From 8e7ec9142f62cb47adcfdc92ba98e448eb1a7469 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 13:50:45 +0300 Subject: [PATCH 01/17] docs: add AGENTS.md guide for git commits and git.tatar Forgejo API releases --- AGENTS.md | 156 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..df81f9c --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,156 @@ +# Инструкция для AI-агентов (Git, коммиты и релизы на git.tatar) + +Этот репозиторий хостится на **Forgejo** (`https://git.tatar/marwy/yandex-music-rs`). +В системе (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-токены Яндекс Музыки. + +--- + +## 1. Коммиты и пуш (`git push`) + +- Ветка по умолчанию: `main`. +- Используй Conventional Commits (`feat: ...`, `fix: ...`, `chore(release): vX.Y.Z`, `docs: ...`). +- На Windows **PowerShell 5.1 не поддерживает `&&`** — разделяй команды через `;` с проверкой `if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }`. +- При добавлении новых shell-скриптов (`*.sh`, `packaging/debian/*`) на Windows обязательно выставляй бит исполняемости в индексе: + ```powershell + git update-index --chmod=+x packaging/build-deb.sh packaging/debian/postinst packaging/debian/postrm + ``` +- Обычный `git push origin main` и `git push origin vX.Y.Z` работают автоматически через системный Git Credential Manager (авторизация уже сохранена). + +--- + +## 2. Сборка релиза `vX.Y.Z` (Windows + Linux) + +1. Обнови версию в `Cargo.toml` (и при необходимости ссылки в `README.md`), закоммить и запушь: + ```powershell + git add Cargo.toml Cargo.lock README.md + git commit -m "chore(release): vX.Y.Z" + git push origin main + ``` +2. **Windows x64** (все ресурсы встроены через `include_bytes!`, получается единый portable `.exe`): + ```powershell + cargo build --release + ``` + Бинарник: `target\release\yandex-music-rs.exe`. +3. **Linux x64 (`.deb` + `.tar.gz`)** через WSL (передавай bash-скрипт через `stdin` в `wsl bash -s`, чтобы Windows не ломал кавычки): + ```powershell + $ver = "0.1.1" + $dist = "D:\YandexMusicRust\target\release-dist-v$ver" + New-Item -ItemType Directory -Force -Path $dist | Out-Null + + Copy-Item -Force "D:\YandexMusicRust\target\release\yandex-music-rs.exe" "$dist\yandex-music-rs-v$ver-windows-x86_64.exe" + + $bashScript = @" + set -euo pipefail + cd /mnt/d/YandexMusicRust + ./packaging/build-deb.sh + TMP=`$(mktemp -d) + cp "`$HOME/.cache/yandex-music-rs-target/release/yandex-music-rs" "`$TMP/yandex-music-rs" + chmod +x "`$TMP/yandex-music-rs" + cp /mnt/d/YandexMusicRust/README.md "`$TMP/README.md" + tar -czf "/mnt/d/YandexMusicRust/target/release-dist-v$ver/yandex-music-rs-v$ver-linux-x86_64.tar.gz" -C "`$TMP" yandex-music-rs README.md + rm -rf "`$TMP" + "@ -replace "`r`n", "`n" + $bashScript | wsl bash -s + + Copy-Item -Force "D:\YandexMusicRust\target\debian\yandex-music-rs_${ver}-1_amd64.deb" "$dist\yandex-music-rs_${ver}-1_amd64.deb" + ``` +4. **Контрольные суммы (`SHA256SUMS.txt`)**: + ```powershell + $files = @( + "yandex-music-rs-v$ver-windows-x86_64.exe", + "yandex-music-rs_${ver}-1_amd64.deb", + "yandex-music-rs-v$ver-linux-x86_64.tar.gz" + ) + $sums = foreach ($f in $files) { + $h = (Get-FileHash -Algorithm SHA256 "$dist\$f").Hash.ToLower() + "$h $f" + } + [System.IO.File]::WriteAllText("$dist\SHA256SUMS.txt", ($sums -join "`n") + "`n", [System.Text.UTF8Encoding]::new($false)) + ``` + +--- + +## 3. Публикация релиза на `git.tatar` через Forgejo API (БЕЗ браузера!) + +1. Создай и запушь аннотированный тег: + ```powershell + git tag -a "v$ver" -m "v$ver" + git push origin "v$ver" + ``` +2. Получи токен из Git Credential Manager (не выводя его в консоль) и создай релиз + загрузи файлы через `curl.exe`: + ```powershell + $ErrorActionPreference = "Stop" + $ver = "0.1.1" + $dist = "D:\YandexMusicRust\target\release-dist-v$ver" + + # Токен из Git Credential Manager (НИКОГДА не печатать!) + $credOut = "protocol=https`nhost=git.tatar`n`n" | git credential fill 2>$null + $token = ($credOut | Where-Object { $_ -like 'password=*' }) -replace '^password=','' + if (-not $token) { throw "No token from git credential fill" } + + $headers = @{ + "Authorization" = "token $token" + "Accept" = "application/json" + } + + # Создание релиза (обязательно UTF-8 bytes, чтобы кириллица не побилась в PowerShell 5.1) + $payloadObj = @{ + tag_name = "v$ver" + target_commitish = "main" + name = "v$ver" + body = "Описание изменений..." + draft = $false + prerelease = $false + } + $payloadBytes = [System.Text.Encoding]::UTF8.GetBytes(($payloadObj | ConvertTo-Json -Depth 5)) + + try { + $release = Invoke-RestMethod -Method Post ` + -Uri "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases" ` + -Headers $headers ` + -ContentType "application/json; charset=utf-8" ` + -Body $payloadBytes + } catch { + # Если релиз для этого тега уже создан — получаем его ID + $release = Invoke-RestMethod -Method Get ` + -Uri "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases/tags/v$ver" ` + -Headers $headers + } + + # Загрузка ассетов через curl.exe (multipart/form-data, поле attachment) + $uploadFiles = @( + "yandex-music-rs-v$ver-windows-x86_64.exe", + "yandex-music-rs_${ver}-1_amd64.deb", + "yandex-music-rs-v$ver-linux-x86_64.tar.gz", + "SHA256SUMS.txt" + ) + foreach ($fname in $uploadFiles) { + $fpath = "$dist\$fname" + $url = "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($fname))" + $resp = & curl.exe -sS -f -X POST -H "Authorization: token $token" -F "attachment=@$fpath" $url + if ($LASTEXITCODE -ne 0) { throw "Upload failed for $fname" } + $asset = $resp | ConvertFrom-Json + Write-Output ("OK: " + $asset.name + " (" + $asset.size + " bytes)") + } + ``` + +> **Совет для PowerShell 5.1 с кириллицей и Markdown:** +> - Для Markdown-текста описания релиза используй **одинарный** here-string `@' ... '@` (в `@" ... "@` обратные кавычки `` ` `` ломают синтаксис!). +> - Если сохраняешь временный `.ps1` скрипт в UTF-8 без BOM, запускай его через чтение в UTF-8, иначе PowerShell 5.1 прочитает его как Windows-1251: +> ```powershell +> $code = [System.IO.File]::ReadAllText("path\to\script.ps1", [System.Text.UTF8Encoding]::new($false)) +> Invoke-Expression $code +> ``` + +--- + +## 4. Другие полезные Forgejo API вызовы + +- Проверить токен: `GET https://git.tatar/api/v1/user` с заголовком `Authorization: token $token` +- Обновить аватар репозитория: `POST https://git.tatar/api/v1/repos/marwy/yandex-music-rs/avatar` с JSON `{ "image": "" }` +- Проверить список релизов: `GET https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases` From e9aa253f723954a7c17b401a8651525ab15a018b Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 14:29:09 +0300 Subject: [PATCH 02/17] feat: 1:1 For You, My Collection, Concerts, Books & Podcasts, WordsCardFullscreen and release v0.1.2 --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 +- src/api/demo_data.rs | 2 + src/api/mod.rs | 984 +++++++++++++++++++++++++--- src/api/models.rs | 61 +- src/app/state.rs | 101 ++- src/views/collection.rs | 1087 ++++++++++++++++++++++++++----- src/views/for_you.rs | 798 +++++++++++++++++++++-- src/views/my_vibe.rs | 311 +++++---- src/views/podcasts_kids.rs | 1249 +++++++++++++++++++++++++++++++----- tests/parity_extended.rs | 381 +++++++++++ 12 files changed, 4393 insertions(+), 593 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c849074..7a8c5c6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6325,7 +6325,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.1" +version = "0.1.2" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index ee4b2c7..a38b710 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.1" +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" diff --git a/README.md b/README.md index cd5873b..b45bb03 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.1-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.1-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.1-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.2-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.1-linux-x86_64.tar.gz` с готовым бинарником. +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.2-linux-x86_64.tar.gz` с готовым бинарником. ## Стек и возможности diff --git a/src/api/demo_data.rs b/src/api/demo_data.rs index d49e0f7..70a3a7c 100644 --- a/src/api/demo_data.rs +++ b/src/api/demo_data.rs @@ -330,6 +330,8 @@ pub fn demo_landing() -> LandingData { vibe_tracks, podcasts, kids_playlists, + rich_new_releases: Vec::new(), + vibe_pick_tabs: Vec::new(), } } diff --git a/src/api/mod.rs b/src/api/mod.rs index 476b289..470b1c4 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -398,6 +398,74 @@ impl YandexApiClient { } } + // Hydrate official 5.129.0 `For You` skeleton (`NEW_RELEASES` + `WAVES` / `SETS_BY_WAVES`) + let skel_ids: &[&str] = if self.has_token() { + &["web_main", "main"] + } else { + &["web_main", "main_nologin"] + }; + let mut main_skeleton: Option = None; + for sid in skel_ids { + if let Ok(sk) = self.fetch_landing_skeleton(sid).await { + if !collect_skeleton_blocks(&sk).is_empty() { + main_skeleton = Some(sk); + break; + } + } + } + if let Some(sk) = main_skeleton { + let blocks = collect_skeleton_blocks(&sk); + for block in blocks { + let btype = block["type"].as_str().unwrap_or("").to_ascii_uppercase(); + let bid = block["id"].as_str().unwrap_or("").to_ascii_lowercase(); + let uri_lc = block["source"]["uri"] + .as_str() + .or_else(|| block["data"]["source"]["uri"].as_str()) + .unwrap_or("") + .to_ascii_lowercase(); + + let is_new_releases = btype.contains("NEW_RELEASES") + || bid.contains("new_releases") + || bid.contains("new-releases") + || uri_lc.contains("new-releases") + || uri_lc.contains("new_releases"); + let is_waves = btype == "WAVES" + || btype.contains("SETS_BY_WAVES") + || bid.contains("waves") + || uri_lc.contains("waves"); + + if is_new_releases && landing.rich_new_releases.is_empty() { + let payload = if let Some(path) = build_skeleton_block_path(block) { + self.get_json(&path).await.ok() + } else { + Some(block.clone()) + }; + if let Some(val) = payload { + let rich = parse_new_releases_block(&val); + if !rich.is_empty() { + if landing.new_releases.is_empty() { + landing.new_releases = + rich.iter().map(|r| r.album.clone()).collect(); + } + landing.rich_new_releases = rich; + } + } + } else if is_waves && landing.vibe_pick_tabs.is_empty() { + let payload = if let Some(path) = build_skeleton_block_path(block) { + self.get_json(&path).await.ok() + } else { + Some(block.clone()) + }; + if let Some(val) = payload { + let tabs = parse_vibe_picks_block(&val); + if !tabs.is_empty() { + landing.vibe_pick_tabs = tabs; + } + } + } + } + } + // Try starting a real 5.128.0 Rotor Session (`POST /rotor/session/new`) if authenticated if self.has_token() { if let Ok(session) = self @@ -441,57 +509,128 @@ impl YandexApiClient { pub async fn fetch_podcast_chart(&self) -> Result> { let res = self.get_json("/chart/podcasts").await?; - let arr = res["podcasts"] - .as_array() - .or_else(|| res["albums"].as_array()) - .or_else(|| res.as_array()); - Ok(arr - .map(|a| a.iter().filter_map(parse_album).collect()) - .unwrap_or_default()) + Ok(extract_non_music_albums(&res)) + } + + /// Official 5.129.0 Books & Podcasts landing (`GET /landing/skeleton/non_music` + block fetches + `/chart/podcasts` fallback). + pub async fn fetch_non_music_landing( + &self, + ) -> Result<(Vec, Vec)> { + let mut sections: Vec = Vec::new(); + let mut flat_albums: Vec = Vec::new(); + let mut seen_album_ids: HashSet = HashSet::new(); + + let skel_res = match self.fetch_landing_skeleton("non_music").await { + Ok(v) => Ok(v), + Err(_) => self.fetch_landing_skeleton("non_music_nologin").await, + }; + + if let Ok(sk) = skel_res { + let blocks = collect_skeleton_blocks(&sk); + let mut fetched_blocks = 0usize; + for (idx, block) in blocks.into_iter().enumerate() { + if fetched_blocks >= 10 { + break; + } + let bid = block["id"] + .as_str() + .map(String::from) + .unwrap_or_else(|| format!("non_music_{}", idx)); + let btype = block["type"].as_str().unwrap_or("").to_string(); + let header_title = block["title"] + .as_str() + .or_else(|| block["data"]["title"].as_str()) + .or_else(|| block["source"]["title"].as_str()) + .unwrap_or("") + .to_string(); + + let payload = if let Some(path) = build_skeleton_block_path(block) { + fetched_blocks += 1; + match self.get_json(&path).await { + Ok(v) => v, + Err(_) => continue, + } + } else if block.get("data").map_or(false, Value::is_object) + || block.get("items").map_or(false, Value::is_array) + { + block.clone() + } else { + continue; + }; + + if let Some(sec) = parse_non_music_block(&bid, &header_title, &btype, &payload) { + for alb in &sec.albums { + if seen_album_ids.insert(alb.id.clone()) { + flat_albums.push(alb.clone()); + } + } + sections.push(sec); + } + } + } + + // Always merge `/chart/podcasts` if flat_albums is empty or no chart section was returned + if let Ok(chart_pods) = self.fetch_podcast_chart().await { + if !chart_pods.is_empty() { + let mut added_any = false; + for alb in &chart_pods { + if seen_album_ids.insert(alb.id.clone()) { + flat_albums.push(alb.clone()); + added_any = true; + } + } + if sections.is_empty() || (added_any && !sections.iter().any(|s| s.block_type.to_ascii_uppercase().contains("CHART"))) { + sections.push(NonMusicSection { + id: "podcast_chart".into(), + title: if self.is_ru_lang() { + "Чарт подкастов".into() + } else { + "Podcasts Chart".into() + }, + block_type: "CHART_ALBUMS".into(), + albums: chart_pods, + playlists: Vec::new(), + }); + } + } + } + + Ok((sections, flat_albums)) + } + + fn is_ru_lang(&self) -> bool { + self.language.to_ascii_lowercase().starts_with("ru") } pub async fn fetch_concerts_feed(&self) -> Result> { - let res = self.get_json("/concerts/feed").await?; - let mut out = Vec::new(); - let list = res["concerts"] - .as_array() - .or_else(|| res["items"].as_array()) - .or_else(|| res.as_array()); - if let Some(arr) = list { - for item in arr { - let c = if item.get("concert").is_some() { - &item["concert"] - } else { - item - }; - if let Some(id) = value_id(&c["id"]) { - out.push(ConcertItem { - id, - title: c["concertTitle"] - .as_str() - .or_else(|| c["title"].as_str()) - .unwrap_or("Concert") - .to_string(), - artist_name: c["artist"]["name"] - .as_str() - .or_else(|| c["artistName"].as_str()) - .unwrap_or("") - .to_string(), - city: c["city"].as_str().unwrap_or("").to_string(), - place: c["place"].as_str().unwrap_or("").to_string(), - date: c["datetime"] - .as_str() - .or_else(|| c["date"].as_str()) - .unwrap_or("") - .to_string(), - cover_uri: c["images"] - .as_array() - .and_then(|a| a.first()) - .and_then(|s| s.as_str()) - .or_else(|| c["artist"]["cover"]["uri"].as_str()) - .map(String::from), - afisha_url: c["afishaUrl"].as_str().map(String::from), - }); + if let Ok(res) = self.get_json("/concerts/feed").await { + let parsed = parse_concerts_feed_response(&res); + if !parsed.is_empty() { + return Ok(parsed); + } + } + + // Automatic fallback: `GET /landing/skeleton/concerts` + concert blocks (`source.uri`) + let sk = self.fetch_landing_skeleton("concerts").await?; + let mut out: Vec = Vec::new(); + let mut seen_ids: HashSet = HashSet::new(); + let mut fetched = 0usize; + for block in collect_skeleton_blocks(&sk) { + if fetched >= 6 { + break; + } + let payload = if let Some(path) = build_skeleton_block_path(block) { + fetched += 1; + match self.get_json(&path).await { + Ok(v) => v, + Err(_) => continue, + } + } else { + block.clone() + }; + for item in parse_concerts_feed_response(&payload) { + if seen_ids.insert(item.id.clone()) { + out.push(item); } } } @@ -1228,7 +1367,7 @@ impl YandexApiClient { .as_array() .map(|arr| { arr.iter() - .take(150) + .take(5000) .filter_map(|t| { let tid = value_id(&t["id"])?; if let Some(aid) = value_id(&t["albumId"]) { @@ -1245,7 +1384,25 @@ impl YandexApiClient { return Ok(Vec::new()); } - self.fetch_tracks_by_ids(&ids).await + // Hydrate ALL liked tracks in batches of 100 (up to 4 concurrent batches) preserving exact order! + let chunks: Vec> = ids.chunks(100).map(|c| c.to_vec()).collect(); + let mut all_tracks: Vec = Vec::with_capacity(ids.len()); + for group in chunks.chunks(4) { + let mut handles = Vec::with_capacity(group.len()); + for chunk in group { + let api = self.clone(); + let batch = chunk.clone(); + handles.push(tokio::spawn(async move { + api.fetch_tracks_by_ids_chunk(&batch).await + })); + } + for h in handles { + if let Ok(Ok(mut batch_tracks)) = h.await { + all_tracks.append(&mut batch_tracks); + } + } + } + Ok(all_tracks) } pub async fn fetch_disliked_track_ids(&self, uid: u64) -> Result> { @@ -1260,6 +1417,22 @@ impl YandexApiClient { /// Primary 5.128.0 batch track hydration: `PUT /tracks/v2/tracks/get-batch`, fallback `POST /tracks` pub async fn fetch_tracks_by_ids(&self, ids: &[String]) -> Result> { + if ids.is_empty() { + return Ok(Vec::new()); + } + if ids.len() <= 100 { + return self.fetch_tracks_by_ids_chunk(ids).await; + } + let mut out = Vec::with_capacity(ids.len()); + for chunk in ids.chunks(100) { + if let Ok(mut batch) = self.fetch_tracks_by_ids_chunk(chunk).await { + out.append(&mut batch); + } + } + Ok(out) + } + + async fn fetch_tracks_by_ids_chunk(&self, ids: &[String]) -> Result> { if ids.is_empty() { return Ok(Vec::new()); } @@ -1635,33 +1808,19 @@ impl YandexApiClient { } pub async fn fetch_bookshelf_liked(&self) -> Result> { - let res = match self - .get_json("/non-music/bookshelf/liked?page=0&pageSize=50") - .await - { - Ok(v) => v, - Err(_) => { - self.get_json("/non-music/bookshelf/recently-played?page=0&pageSize=50") - .await? - } - }; - let arr = res["items"] - .as_array() - .or_else(|| res["albums"].as_array()) - .or_else(|| res["podcasts"].as_array()) - .or_else(|| res.as_array()); - let mut out = Vec::new(); - if let Some(items) = arr { - for item in items { - let node = if item.get("album").is_some() { - &item["album"] - } else if item.get("data").is_some() { - &item["data"] - } else { - item - }; - if let Some(alb) = parse_album(node) { - out.push(alb); + let mut out: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + + // Fetch BOTH recently-played (for "Continue listening") and liked bookshelf items! + for path in [ + "/non-music/bookshelf/recently-played?page=0&pageSize=50", + "/non-music/bookshelf/liked?page=0&pageSize=50", + ] { + if let Ok(res) = self.get_json(path).await { + for alb in extract_non_music_albums(&res) { + if seen.insert(alb.id.clone()) { + out.push(alb); + } } } } @@ -2606,6 +2765,497 @@ fn parse_words_big_card_response(val: &Value) -> Option { Some(WordsBigCard { id, text, actions }) } +// ============================================================================= +// Skeleton, Concerts, Non-Music, NewReleases & Waves Pure Parsers +// ============================================================================= + +fn collect_skeleton_blocks<'a>(skeleton: &'a Value) -> Vec<&'a Value> { + let mut blocks: Vec<&'a Value> = Vec::new(); + let root = skeleton.get("result").unwrap_or(skeleton); + if let Some(arr) = root["blocks"].as_array() { + for b in arr { + blocks.push(b); + if let Some(nested) = b["blocks"].as_array() { + blocks.extend(nested.iter()); + } + } + } + if let Some(tabs) = root["tabs"].as_array() { + for tab in tabs { + if let Some(arr) = tab["blocks"].as_array() { + blocks.extend(arr.iter()); + } + if let Some(arr) = tab["tab"]["blocks"].as_array() { + blocks.extend(arr.iter()); + } + } + } + blocks +} + +fn build_skeleton_block_path(block: &Value) -> Option { + let source = block + .get("source") + .filter(|v| v.is_object()) + .or_else(|| block["data"].get("source").filter(|v| v.is_object()))?; + let raw_uri = source["uri"].as_str().map(str::trim).filter(|s| !s.is_empty())?; + let mut path = if let Some(stripped) = raw_uri.strip_prefix("https://api.music.yandex.net") { + stripped.to_string() + } else if raw_uri.starts_with('/') { + raw_uri.to_string() + } else { + format!("/{}", raw_uri) + }; + let count_web = source["countWeb"] + .as_u64() + .or_else(|| source["count"].as_u64()) + .or_else(|| block["data"]["countWeb"].as_u64()); + if let Some(n) = count_web { + if n > 0 && !path.contains("count=") && !path.contains("limit=") { + let sep = if path.contains('?') { '&' } else { '?' }; + path.push_str(&format!("{}count={}", sep, n)); + } + } + Some(path) +} + +fn parse_album_with_fallback_artists( + album_node: &Value, + artists_fallback: Option<&Value>, +) -> Option { + let mut alb = parse_album(album_node)?; + if alb.artists.is_empty() { + if let Some(arr) = artists_fallback.and_then(Value::as_array) { + alb.artists = arr.iter().filter_map(parse_artist).collect(); + } + } + Some(alb) +} + +fn extract_non_music_albums(res: &Value) -> Vec { + let mut out: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let candidates = [ + res["items"].as_array(), + res["data"]["items"].as_array(), + res["chart"]["albums"].as_array(), + res["albums"].as_array(), + res["podcasts"].as_array(), + res["entities"].as_array(), + res.as_array(), + ]; + for arr in candidates.into_iter().flatten() { + for item in arr { + let item_type = item["type"].as_str().unwrap_or(""); + if item_type.eq_ignore_ascii_case("PLAYLIST_ITEM") { + continue; + } + let parsed = if item["data"]["album"].is_object() { + parse_album_with_fallback_artists( + &item["data"]["album"], + item["data"].get("artists"), + ) + } else if item["album"].is_object() { + parse_album_with_fallback_artists(&item["album"], item.get("artists")) + } else if item["data"].is_object() { + parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) + } else { + parse_album(item) + }; + if let Some(alb) = parsed { + if seen.insert(alb.id.clone()) { + out.push(alb); + } + } + } + } + out +} + +fn parse_non_music_block( + id: &str, + header_title: &str, + block_type: &str, + res: &Value, +) -> Option { + let title = if !header_title.trim().is_empty() { + header_title.trim().to_string() + } else { + res["title"] + .as_str() + .or_else(|| res["data"]["title"].as_str()) + .or_else(|| res["chart"]["title"].as_str()) + .unwrap_or("") + .trim() + .to_string() + }; + + let mut albums: Vec = Vec::new(); + let mut playlists: Vec = Vec::new(); + let mut seen_albums: HashSet = HashSet::new(); + let mut seen_playlists: HashSet = HashSet::new(); + + let lists = [ + res["items"].as_array(), + res["data"]["items"].as_array(), + res["chart"]["albums"].as_array(), + res["albums"].as_array(), + res["podcasts"].as_array(), + res["playlists"].as_array(), + res["entities"].as_array(), + res.as_array(), + ]; + for arr in lists.into_iter().flatten() { + for item in arr { + let item_type = item["type"].as_str().unwrap_or(""); + let is_playlist_item = item_type.eq_ignore_ascii_case("PLAYLIST_ITEM") + || item["data"]["playlist"].is_object() + || item["playlist"].is_object() + || (item.get("kind").is_some() && item.get("owner").is_some()); + + if is_playlist_item { + let pl_node = if item["data"]["playlist"].is_object() { + &item["data"]["playlist"] + } else if item["playlist"].is_object() { + &item["playlist"] + } else if item["data"].is_object() && item["data"].get("kind").is_some() { + &item["data"] + } else { + item + }; + if let Some(pl) = parse_playlist(pl_node) { + let key = format!("{}:{}", pl.owner_uid, pl.kind); + if seen_playlists.insert(key) { + playlists.push(pl); + } + } + continue; + } + + let alb = if item["data"]["album"].is_object() { + parse_album_with_fallback_artists( + &item["data"]["album"], + item["data"].get("artists"), + ) + } else if item["album"].is_object() { + parse_album_with_fallback_artists(&item["album"], item.get("artists")) + } else if item["data"].is_object() { + parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) + } else { + parse_album(item) + }; + if let Some(a) = alb { + if seen_albums.insert(a.id.clone()) { + albums.push(a); + } + } + } + } + + if albums.is_empty() && playlists.is_empty() { + return None; + } + Some(NonMusicSection { + id: id.to_string(), + title, + block_type: block_type.to_string(), + albums, + playlists, + }) +} + +fn parse_concerts_feed_response(res: &Value) -> Vec { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + let list = res["items"] + .as_array() + .or_else(|| res["concerts"].as_array()) + .or_else(|| res["data"]["items"].as_array()) + .or_else(|| res.as_array()); + let Some(arr) = list else { + return out; + }; + + for item in arr { + let data_node = item + .get("data") + .filter(|v| v.is_object()) + .unwrap_or(item); + let c = data_node + .get("concert") + .filter(|v| v.is_object()) + .or_else(|| item.get("concert").filter(|v| v.is_object())) + .unwrap_or(data_node); + + let Some(id) = value_id(&c["id"]).or_else(|| value_id(&item["id"])) else { + continue; + }; + if !seen.insert(id.clone()) { + continue; + } + + let title = c["concertTitle"] + .as_str() + .or_else(|| c["title"].as_str()) + .unwrap_or("Concert") + .to_string(); + let artist_name = c["artist"]["name"] + .as_str() + .or_else(|| c["artistName"].as_str()) + .or_else(|| data_node["artist"]["name"].as_str()) + .unwrap_or("") + .to_string(); + let city = c["city"].as_str().unwrap_or("").to_string(); + let place = c["place"].as_str().unwrap_or("").to_string(); + let date = c["datetime"] + .as_str() + .or_else(|| c["date"].as_str()) + .unwrap_or("") + .to_string(); + let cover_uri = c["cover"]["uri"] + .as_str() + .filter(|s| !s.is_empty()) + .or_else(|| { + c["images"].as_array().and_then(|a| { + a.first() + .and_then(|v| v.as_str().or_else(|| v["uri"].as_str())) + }) + }) + .or_else(|| c["artist"]["cover"]["uri"].as_str()) + .or_else(|| data_node["cover"]["uri"].as_str()) + .map(String::from); + let cover_color = c["cover"]["color"] + .as_str() + .or_else(|| data_node["cover"]["color"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let price_node = data_node + .get("minPrice") + .or_else(|| c.get("minPrice")) + .or_else(|| item.get("minPrice")); + let min_price = price_node.and_then(|p| { + p["value"] + .as_u64() + .or_else(|| p["value"].as_f64().map(|f| f.round() as u64)) + .or_else(|| p.as_u64()) + }); + let currency = price_node + .and_then(|p| p["currency"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let cashback_node = c.get("cashback").or_else(|| data_node.get("cashback")); + let cashback_percent = cashback_node + .and_then(|cb| { + cb["valuePercent"] + .as_u64() + .or_else(|| cb["percent"].as_u64()) + }) + .map(|v| v as u32); + let cashback_title = cashback_node + .and_then(|cb| cb["title"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let event_kind = c["eventInfo"]["type"] + .as_str() + .or_else(|| c["eventType"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + let afisha_url = c["afishaUrl"] + .as_str() + .filter(|s| !s.is_empty()) + .map(String::from) + .or_else(|| { + Some(format!( + "https://afisha.yandex.ru/search?text={}", + urlencoding::encode(&title) + )) + }); + + out.push(ConcertItem { + id, + title, + artist_name, + city, + place, + date, + cover_uri, + afisha_url, + min_price, + currency, + cashback_percent, + cashback_title, + cover_color, + event_kind, + }); + } + out +} + +fn parse_new_releases_block(res: &Value) -> Vec { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + let arr = res["newReleases"] + .as_array() + .or_else(|| res["data"]["newReleases"].as_array()) + .or_else(|| res["items"].as_array()) + .or_else(|| res["data"]["items"].as_array()) + .or_else(|| res["albums"].as_array()) + .or_else(|| res.as_array()); + let Some(items) = arr else { + return out; + }; + + for item in items { + let node = item + .get("data") + .filter(|v| v.is_object()) + .unwrap_or(item); + let album_node = if node["album"].is_object() { + &node["album"] + } else { + node + }; + let Some(album) = parse_album_with_fallback_artists(album_node, node.get("artists")) else { + continue; + }; + if !seen.insert(album.id.clone()) { + continue; + } + let artist_cover_uri = node["artists"] + .as_array() + .and_then(|a| a.first()) + .and_then(|ar| { + ar["cover"]["uri"] + .as_str() + .or_else(|| ar["ogImage"].as_str()) + }) + .filter(|s| !s.is_empty()) + .map(String::from) + .or_else(|| album.artists.first().and_then(|a| a.cover_uri.clone())); + let cover_color = node["cover"]["color"] + .as_str() + .or_else(|| album_node["cover"]["color"].as_str()) + .or_else(|| album_node["derivedColors"]["average"].as_str()) + .or_else(|| node["derivedColors"]["average"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + let release_date = node["releaseDate"] + .as_str() + .or_else(|| album_node["releaseDate"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + out.push(NewReleaseItem { + album, + artist_cover_uri, + cover_color, + release_date, + }); + } + out +} + +fn parse_vibe_picks_block(res: &Value) -> Vec { + let mut tabs = Vec::new(); + let arr = res["waves"] + .as_array() + .or_else(|| res["data"]["waves"].as_array()) + .or_else(|| res["tabs"].as_array()) + .or_else(|| res["data"]["tabs"].as_array()) + .or_else(|| res.as_array()); + let Some(raw_tabs) = arr else { + return tabs; + }; + + for raw_tab in raw_tabs { + let title = raw_tab["title"] + .as_str() + .or_else(|| raw_tab["name"].as_str()) + .unwrap_or("") + .trim() + .to_string(); + let raw_items = raw_tab["items"] + .as_array() + .or_else(|| raw_tab["waves"].as_array()) + .or_else(|| raw_tab["stations"].as_array()); + let Some(items_arr) = raw_items else { + continue; + }; + + let mut parsed_items = Vec::new(); + for raw_item in items_arr { + let obj = raw_item + .get("data") + .filter(|v| v.is_object()) + .or_else(|| raw_item.get("wave").filter(|v| v.is_object())) + .unwrap_or(raw_item); + let Some(item_title) = obj["title"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + else { + continue; + }; + let header = obj["header"] + .as_str() + .or_else(|| obj["subtitle"].as_str()) + .unwrap_or("") + .trim() + .to_string(); + let mut seeds: Vec = obj["seeds"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|s| s.as_str().map(String::from)) + .collect() + }) + .unwrap_or_default(); + if seeds.is_empty() { + if let Some(sid) = obj["stationId"].as_str().filter(|s| !s.is_empty()) { + seeds.push(sid.to_string()); + } + } + let color_hex = obj["colors"]["average"] + .as_str() + .or_else(|| obj["color"].as_str()) + .or_else(|| obj["backgroundColor"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + let background_image_url = obj["backgroundImageUrl"] + .as_str() + .or_else(|| obj["backgroundImageUri"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + let image_url = obj["imageUrl"] + .as_str() + .or_else(|| obj["imageUri"].as_str()) + .filter(|s| !s.is_empty()) + .map(String::from); + + parsed_items.push(VibePickItem { + title: item_title.to_string(), + header, + seeds, + color_hex, + background_image_url, + image_url, + }); + } + + if !parsed_items.is_empty() { + tabs.push(VibePickTab { + title, + items: parsed_items, + }); + } + } + tabs +} + fn parse_writers_field(v: &Value) -> Option { let arr = v.as_array()?; let joined: Vec<&str> = arr @@ -3024,4 +3674,184 @@ mod tests { assert_eq!(big.actions.len(), 1); assert_eq!(big.actions[0].url, "https://genius.com/test"); } + + #[test] + fn test_parse_concerts_feed_nested_data_shape() { + let payload = json!({ + "items": [ + { + "type": "CONCERT", + "data": { + "concert": { + "id": "conc-42", + "concertTitle": "Баста — Большой концерт", + "city": "Москва", + "place": "ВТБ Арена", + "datetime": "2026-11-28T20:00:00+03:00", + "cover": { + "uri": "avatars.yandex.net/get-afisha/1/poster/%%", + "color": "#2A1F3D" + }, + "afishaUrl": "https://afisha.yandex.ru/moscow/concert/basta", + "cashback": { + "title": "Кешбэк 15%", + "valuePercent": 15 + }, + "eventInfo": { "type": "CONCERT" }, + "artist": { "name": "Баста" } + }, + "minPrice": { + "value": 3500, + "currency": "RUB" + } + } + }, + { + "data": { + "concert": { + "id": "conc-99", + "concertTitle": "Indie Night", + "city": "Казань", + "place": "Werk", + "datetime": "2026-12-05T19:00:00+03:00" + } + } + } + ] + }); + + let parsed = parse_concerts_feed_response(&payload); + assert_eq!(parsed.len(), 2); + let first = &parsed[0]; + assert_eq!(first.id, "conc-42"); + assert_eq!(first.title, "Баста — Большой концерт"); + assert_eq!(first.artist_name, "Баста"); + assert_eq!(first.city, "Москва"); + assert_eq!(first.place, "ВТБ Арена"); + assert_eq!(first.min_price, Some(3500)); + assert_eq!(first.currency.as_deref(), Some("RUB")); + assert_eq!(first.cashback_percent, Some(15)); + assert_eq!(first.cashback_title.as_deref(), Some("Кешбэк 15%")); + assert_eq!(first.cover_color.as_deref(), Some("#2A1F3D")); + assert_eq!(first.event_kind.as_deref(), Some("CONCERT")); + assert_eq!( + first.cover_uri.as_deref(), + Some("avatars.yandex.net/get-afisha/1/poster/%%") + ); + + let second = &parsed[1]; + assert_eq!(second.id, "conc-99"); + assert!(second + .afisha_url + .as_deref() + .unwrap_or("") + .starts_with("https://afisha.yandex.ru/search?text=")); + } + + #[test] + fn test_parse_non_music_skeleton_blocks() { + let block_payload = json!({ + "title": "Популярные аудиокниги и подкасты", + "items": [ + { + "type": "NON_MUSIC_ALBUM_ITEM", + "data": { + "album": { + "id": 7001, + "title": "Дюна", + "type": "audiobook", + "trackCount": 24, + "coverUri": "avatars.yandex.net/get-music-content/1/dune/%%" + }, + "artists": [ + { "id": 10, "name": "Фрэнк Герберт" } + ] + } + }, + { + "type": "PLAYLIST_ITEM", + "data": { + "playlist": { + "kind": 1005, + "owner": { "uid": 500, "name": "Редакция" }, + "title": "Лучшие подкасты недели", + "trackCount": 12 + } + } + } + ] + }); + + let sec = parse_non_music_block("nm-1", "", "MIXED_ENTITIES", &block_payload) + .expect("non-music section should parse"); + assert_eq!(sec.title, "Популярные аудиокниги и подкасты"); + assert_eq!(sec.albums.len(), 1); + assert_eq!(sec.albums[0].id, "7001"); + assert_eq!(sec.albums[0].content_type.as_deref(), Some("audiobook")); + assert_eq!(sec.albums[0].artists.len(), 1); + assert_eq!(sec.albums[0].artists[0].name, "Фрэнк Герберт"); + assert_eq!(sec.playlists.len(), 1); + assert_eq!(sec.playlists[0].title, "Лучшие подкасты недели"); + } + + #[test] + fn test_parse_new_releases_and_waves_blocks() { + let nr_payload = json!({ + "newReleases": [ + { + "album": { + "id": 8888, + "title": "Midnight Pulse", + "type": "single", + "coverUri": "avatars.yandex.net/get-music-content/2/mp/%%" + }, + "artists": [ + { + "id": 301, + "name": "Aether", + "cover": { "uri": "avatars.yandex.net/get-music-content/2/aether/%%" } + } + ], + "releaseDate": "2026-11-27", + "cover": { "uri": "avatars.yandex.net/get-music-content/2/mp/%%", "color": "#1E3A8A" } + } + ] + }); + let rich = parse_new_releases_block(&nr_payload); + assert_eq!(rich.len(), 1); + assert_eq!(rich[0].album.id, "8888"); + assert_eq!(rich[0].album.artists[0].name, "Aether"); + assert_eq!( + rich[0].artist_cover_uri.as_deref(), + Some("avatars.yandex.net/get-music-content/2/aether/%%") + ); + assert_eq!(rich[0].cover_color.as_deref(), Some("#1E3A8A")); + assert_eq!(rich[0].release_date.as_deref(), Some("2026-11-27")); + + let waves_payload = json!({ + "waves": [ + { + "title": "по языку", + "items": [ + { + "title": "Английский", + "header": "Моя волна по языку", + "seeds": ["language:english"], + "colors": { "average": "#3B82F6" }, + "backgroundImageUrl": "https://avatars.yandex.net/bg.png", + "imageUrl": "https://avatars.yandex.net/img.png" + } + ] + } + ] + }); + let tabs = parse_vibe_picks_block(&waves_payload); + assert_eq!(tabs.len(), 1); + assert_eq!(tabs[0].title, "по языку"); + assert_eq!(tabs[0].items.len(), 1); + assert_eq!(tabs[0].items[0].title, "Английский"); + assert_eq!(tabs[0].items[0].header, "Моя волна по языку"); + assert_eq!(tabs[0].items[0].seeds, vec!["language:english"]); + assert_eq!(tabs[0].items[0].color_hex.as_deref(), Some("#3B82F6")); + } } diff --git a/src/api/models.rs b/src/api/models.rs index a1c68c3..fca575f 100644 --- a/src/api/models.rs +++ b/src/api/models.rs @@ -184,6 +184,53 @@ pub struct LandingData { pub vibe_tracks: Vec, pub podcasts: Vec, pub kids_playlists: Vec, + #[serde(default)] + pub rich_new_releases: Vec, + #[serde(default)] + pub vibe_pick_tabs: Vec, +} + +/// Rich editorial new release item from `GET /landing/skeleton/web_main` (`NEW_RELEASES`). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct NewReleaseItem { + pub album: AlbumSummary, + #[serde(default)] + pub artist_cover_uri: Option, + #[serde(default)] + pub cover_color: Option, + #[serde(default)] + pub release_date: Option, +} + +/// Single My Vibe wave pick item from `WAVES` / `SETS_BY_WAVES` skeleton block. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VibePickItem { + pub title: String, + pub header: String, + pub seeds: Vec, + #[serde(default)] + pub color_hex: Option, + #[serde(default)] + pub background_image_url: Option, + #[serde(default)] + pub image_url: Option, +} + +/// Category tab inside `More Picks` (`Ещё подборки`) from `WAVES` / `SETS_BY_WAVES`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct VibePickTab { + pub title: String, + pub items: Vec, +} + +/// Section block on the Books & Podcasts (`non_music`) landing page. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct NonMusicSection { + pub id: String, + pub title: String, + pub block_type: String, + pub albums: Vec, + pub playlists: Vec, } #[derive(Debug, Clone)] @@ -264,7 +311,7 @@ pub struct PlayTelemetryEvent { pub batch_id: Option, } -/// Concert item returned by `GET /concerts/feed` +/// Concert item returned by `GET /concerts/feed` or `GET /landing/skeleton/concerts` #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ConcertItem { pub id: String, @@ -275,6 +322,18 @@ pub struct ConcertItem { pub date: String, pub cover_uri: Option, pub afisha_url: Option, + #[serde(default)] + pub min_price: Option, + #[serde(default)] + pub currency: Option, + #[serde(default)] + pub cashback_percent: Option, + #[serde(default)] + pub cashback_title: Option, + #[serde(default)] + pub cover_color: Option, + #[serde(default)] + pub event_kind: Option, } fn default_wheel_item_type() -> String { diff --git a/src/app/state.rs b/src/app/state.rs index 05351f4..652d210 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -248,6 +248,12 @@ pub enum AppAction { title: String, seeds: Vec, }, + StartVibeStation { + title: String, + seeds: Vec, + }, + RefreshConcerts, + RefreshNonMusic, ApplyVibeSettings { mood: Option, activity: Option, @@ -387,6 +393,7 @@ pub(crate) enum ApiEvent { AccountLoaded(Result), LandingLoaded(LandingData), ConcertsLoaded(Vec), + NonMusicLoaded(Vec, Vec), SearchHistoryLoaded(Vec), LikedTracksLoaded(Vec), FavoriteFiltersLoaded(Vec), @@ -474,6 +481,9 @@ pub struct AppState { pub account: Option, pub landing: LandingData, pub concerts: Vec, + pub concerts_loading: bool, + pub non_music_sections: Vec, + pub non_music_loading: bool, pub liked_tracks: Vec, pub liked_ids: HashSet, pub disliked_ids: HashSet, @@ -627,6 +637,9 @@ impl AppState { account: None, landing: LandingData::default(), concerts: Vec::new(), + concerts_loading: false, + non_music_sections: Vec::new(), + non_music_loading: false, liked_tracks: Vec::new(), liked_ids: HashSet::new(), disliked_ids: HashSet::new(), @@ -774,6 +787,9 @@ impl AppState { account, landing, concerts: Vec::new(), + concerts_loading: false, + non_music_sections: Vec::new(), + non_music_loading: false, liked_tracks, liked_ids, disliked_ids: HashSet::new(), @@ -1289,9 +1305,16 @@ impl AppState { let api = self.api.clone(); let tx = self.tx_api.clone(); self.runtime.spawn(async move { - if let Ok(concerts) = api.fetch_concerts_feed().await { - let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); - } + let concerts = api.fetch_concerts_feed().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); + }); + } + { + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums)); }); } { @@ -1637,12 +1660,53 @@ impl AppState { } }); } + Route::Concerts => { + self.detail_loading = false; + if self.concerts.is_empty() && !self.concerts_loading { + self.refresh_concerts(); + } + } + Route::Podcasts => { + self.detail_loading = false; + if self.non_music_sections.is_empty() && !self.non_music_loading { + self.refresh_non_music(); + } + } _ => { self.detail_loading = false; } } } + pub fn refresh_concerts(&mut self) { + self.concerts_loading = true; + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + let concerts = api.fetch_concerts_feed().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::ConcertsLoaded(concerts)); + }); + } + + pub fn refresh_non_music(&mut self) { + self.non_music_loading = true; + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default(); + let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums)); + }); + if self.api.has_token() { + let api = self.api.clone(); + let tx = self.tx_api.clone(); + self.runtime.spawn(async move { + if let Ok(shelf) = api.fetch_bookshelf_liked().await { + let _ = tx.send(ApiEvent::BookshelfLoaded(shelf)); + } + }); + } + } + pub fn launch_oauth_login(&mut self) { self.show_toast(self.i18n().toast_opening_oauth()); let tx = self.tx_api.clone(); @@ -1717,6 +1781,12 @@ impl AppState { self.show_toast(t.toast_welcome(&acc.display_name)); self.account = Some(acc); self.ensure_words_for_current_track(); + if self.concerts.is_empty() && !self.concerts_loading { + self.refresh_concerts(); + } + if self.non_music_sections.is_empty() && !self.non_music_loading { + self.refresh_non_music(); + } } ApiEvent::AccountLoaded(Err(e)) => { self.show_toast(if t.is_ru() { @@ -1726,7 +1796,19 @@ impl AppState { }); } ApiEvent::ConcertsLoaded(concerts) => { - self.concerts = concerts; + self.concerts_loading = false; + if !concerts.is_empty() || self.concerts.is_empty() { + self.concerts = concerts; + } + } + ApiEvent::NonMusicLoaded(sections, albums) => { + self.non_music_loading = false; + if !sections.is_empty() { + self.non_music_sections = sections; + } + if !albums.is_empty() { + self.landing.podcasts = albums; + } } ApiEvent::SearchHistoryLoaded(hist) => { self.config.search_history = hist; @@ -1777,6 +1859,10 @@ impl AppState { self.queue_index = 0; } } + let mut data = data; + if data.podcasts.is_empty() && !self.landing.podcasts.is_empty() { + data.podcasts = self.landing.podcasts.clone(); + } self.landing = data; } ApiEvent::LikedTracksLoaded(tracks) => { @@ -2419,7 +2505,12 @@ impl AppState { } AppAction::ActivateWheelItem(item) => self.activate_wheel_item(item), AppAction::ReshuffleWheel => self.reshuffle_wheel(), - AppAction::StartVibeBySeeds { title, seeds } => self.start_vibe_by_seeds(title, seeds), + AppAction::StartVibeBySeeds { title, seeds } + | AppAction::StartVibeStation { title, seeds } => { + self.start_vibe_by_seeds(title, seeds); + } + AppAction::RefreshConcerts => self.refresh_concerts(), + AppAction::RefreshNonMusic => self.refresh_non_music(), AppAction::ApplyVibeSettings { mood, activity, diff --git a/src/views/collection.rs b/src/views/collection.rs index e4ba9bd..d7653e9 100644 --- a/src/views/collection.rs +++ b/src/views/collection.rs @@ -3,7 +3,7 @@ use crate::app::state::{AppAction, AppState, CollectionTab, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; use crate::engine::scroll::visible_row_range; -use crate::engine::text::{TextAlign, TextStyle}; +use crate::engine::text::{RichSpan, TextAlign, TextStyle}; use crate::engine::theme::{YmPalette, TRACK_ROW_HEIGHT}; use crate::engine::types::{Color, CursorKind, Pos2, Rect, Vec2}; use crate::engine::widgets::{ @@ -14,15 +14,18 @@ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::{EntityContextMenuState, ShellUiState}; -/// Exact Yandex Music Desktop 5.129.0 Collection Page (`pages_api_spec.md` §5): -/// All 7 original tabs: -/// 1. Любимые треки (My Favorites) -/// 2. Плейлисты (with "+ Создать плейлист" card/button + Rename & Delete controls!) -/// 3. Альбомы (Liked albums grid) -/// 4. Исполнители (Liked artists circular grid) -/// 5. Подкасты и книги (Bookshelf / Podcasts grid) -/// 6. Скачанное (Offline downloaded tracks with play & delete from device) -/// 7. История (Listening history) +/// 1-to-1 Official Yandex Music Desktop 5.129.0 `My Collection` (`web_collection`): +/// - Default view (`CollectionTab::Tracks`): clean vertical feed: +/// - Header (`Коллекция` / `My Collection`) + colored subtitle (`У вашей музыки есть цвет`) +/// - Section 1: `❤️ Мне нравится >` transparent header + 2-column × 4-row compact track grid +/// - Section 2: `Любимые исполнители >` horizontal circular artist carousel +/// - Section 3: `Плейлисты >` horizontal carousel starting with `+ Создать плейлист` +/// - Section 4: `Альбомы >` horizontal carousel +/// - Section 5: `Подкасты и книги >` horizontal carousel (when non-empty) +/// - Section 6: `История >` 2-column × 4-row compact track grid (when non-empty) +/// - Section 7: `Скачанное >` 2-column × 4-row compact track grid (when non-empty) +/// - Sub-views (`Artists`, `Playlists`, `Albums`, `PodcastsAndBooks`, `History`, `Downloaded`): +/// clean `← Коллекция` back button + full interactive grid/list with full CRUD & menus. pub fn render_collection( ctx: &mut UiContext, pal: &YmPalette, @@ -40,168 +43,691 @@ pub fn render_collection( let scroll_id = WidgetId::new("collection_scroll"); let scroll_y = ctx.begin_scroll_v(scroll_id, rect, 0.0); - // `views/mod.rs` already insets `inner_r` by (25, 13, 25, 0) let x = rect.left(); let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; - // Page Heading - ctx.draw_text_ellipsis( - t.collection(), - TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), - TextAlign::Left, - ); - y += 58.0; - - // Signature "Мне нравится" / "My Favorites" Hero Banner Card (theme-aware!) - let hero_r = Rect::from_xywh(x, y, avail_w, 120.0); - let hero_resp = ctx.interact(WidgetId::new("col_fav_hero"), hero_r); - let hero_bg = if pal.is_dark { - if hero_resp.hovered { - Color::rgb(0x2A, 0x24, 0x17) - } else { - Color::rgb(0x22, 0x1D, 0x12) - } - } else if hero_resp.hovered { - Color::rgb(0xFF, 0xF2, 0xBC) - } else { - Color::rgb(0xFF, 0xF8, 0xD6) - }; - ctx.dl() - .push_rect_bordered(hero_r, 16.0, hero_bg, 1.0, pal.border_subtle); - - let cov_r = Rect::from_xywh(hero_r.left() + 18.0, hero_r.center_y() - 42.0, 84.0, 84.0); - draw_cover_art(ctx, pal, covers, cov_r, None, "likes", 12.0, false, true); - - let fav_title = t.liked_playlist(); - ctx.draw_text_ellipsis( - fav_title, - TextStyle::headline(26.0, pal.text_bright), - Rect::from_xywh(cov_r.right() + 20.0, hero_r.top() + 28.0, avail_w - 280.0, 32.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - &t.count_tracks(app.liked_tracks.len()), - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(cov_r.right() + 20.0, hero_r.top() + 66.0, avail_w - 280.0, 22.0), - TextAlign::Left, - ); - - let likes_playing = app.is_context_playing("likes"); - let play_btn_label = if likes_playing { t.pause() } else { t.listen() }; - let play_text_w = ctx - .measure_text(play_btn_label, TextStyle::medium(14.0, pal.on_yellow), None) - .x; - let play_btn_w = (play_text_w + 28.0 + 36.0).max(100.0).ceil(); - let play_btn_r = Rect::from_xywh( - hero_r.right() - play_btn_w - 24.0, - hero_r.center_y() - 21.0, - play_btn_w, - 42.0, - ); - let play_resp = crate::engine::widgets::yellow_pill_button_in( - ctx, - pal, - WidgetId::new("col_fav_play"), - play_btn_r, - Some(if likes_playing { - Icon::PauseXxs - } else { - Icon::PlayXxs - }), - play_btn_label, - app.liked_tracks.is_empty(), - ); - if play_resp.clicked && !app.liked_tracks.is_empty() { - actions.push(AppAction::ToggleContextPlay { - tracks: app.liked_tracks.clone(), - context_name: fav_title.into(), - context_key: "likes".into(), - is_vibe: false, - }); - } else if hero_resp.clicked { - actions.push(AppAction::Navigate(Route::LikedTracks)); - } - if hero_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - y += 120.0 + 20.0; - - // All 7 Original Collection Tabs (horizontal scrollable pill bar!) - let tabs_vp = Rect::from_xywh(x, y, avail_w, 42.0); - let tabs_h_id = WidgetId::new("col_tabs_hscroll"); - let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); - let mut tx = x - tabs_sx; - let all_tabs = [ - (CollectionTab::Tracks, t.liked_tracks_tab()), - (CollectionTab::Playlists, t.playlists()), - (CollectionTab::Albums, t.albums()), - (CollectionTab::Artists, t.artists()), - (CollectionTab::PodcastsAndBooks, t.podcasts_and_books()), - (CollectionTab::Downloaded, t.downloaded()), - (CollectionTab::History, t.history()), - ]; - for (tab_kind, label) in all_tabs { - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("col_tab", tab_kind as u8), - Pos2::new(tx, y), - None, - label, - 38.0, - app.collection_tab == tab_kind, + // ------------------------------------------------------------------------- + // DEFAULT VERTICAL OVERVIEW (`CollectionTab::Tracks`) + // ------------------------------------------------------------------------- + if app.collection_tab == CollectionTab::Tracks { + // Header: Bold 34px Headline + official colored subtitle + ctx.draw_text_ellipsis( + t.collection(), + TextStyle::headline(34.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 42.0), + TextAlign::Left, ); - if resp.clicked { - app.collection_tab = tab_kind; - } - tx = r.right() + 8.0; - } - let tabs_total_w = (tx + tabs_sx) - x; - ctx.end_scroll_h(tabs_h_id, pal, tabs_total_w, false); - y += 56.0; + y += 44.0; - // ------------------------------------------------------------------------- - // TAB BODY - // ------------------------------------------------------------------------- - match app.collection_tab { - CollectionTab::Tracks => { - if app.liked_tracks.is_empty() { - ctx.draw_text_wrapped( - if ru { - "Ставьте лайки трекам или войдите в аккаунт Яндекс Музыки — они появятся здесь." - } else { - "Like tracks or sign in to Yandex Music — they will appear here." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 44.0), - Some(2), - TextAlign::Left, - ); - y += 48.0; - } else { - let tracks = app.liked_tracks.clone(); - y = render_virtual_track_list( - ctx, - pal, - covers, - app, - shell, - rect, - x, - y, - avail_w, - &tracks, - "col_liked", - fav_title, - "likes", - current_track_id.as_deref(), - is_playing, - actions, - ); + let pink_accent = Color::rgb(0xE8, 0x3E, 0x8C); + let spans = if ru { + [ + RichSpan::new( + "У вашей музыки есть ", + TextStyle::medium(14.0, pal.text_secondary), + ), + RichSpan::new("цвет", TextStyle::medium(14.0, pink_accent)), + ] + } else { + [ + RichSpan::new( + "Your music has a ", + TextStyle::medium(14.0, pal.text_secondary), + ), + RichSpan::new("color", TextStyle::medium(14.0, pink_accent)), + ] + }; + ctx.draw_rich_text( + &spans, + Rect::from_xywh(x, y, avail_w, 24.0), + Some(1), + TextAlign::Left, + ); + y += 38.0; + + // --------------------------------------------------------------------- + // SECTION 1: ❤️ My Favorites > (transparent header + 2×4 compact grid) + // --------------------------------------------------------------------- + let fav_title = t.liked_playlist(); + { + let hdr_r = Rect::from_xywh(x, y, avail_w.min(460.0), 58.0); + let hdr_resp = ctx.interact(WidgetId::new("col_fav_header"), hdr_r); + + let cov_r = Rect::from_xywh(x, y + 1.0, 56.0, 56.0); + draw_cover_art(ctx, pal, covers, cov_r, None, "likes", 10.0, false, true); + + let tx = cov_r.right() + 14.0; + let title_style = TextStyle::headline( + 22.0, + if hdr_resp.hovered { + pal.text_bright + } else { + pal.text_primary + }, + ); + let title_w = ctx.measure_text(fav_title, title_style, None).x; + ctx.draw_text_ellipsis( + fav_title, + title_style, + Rect::from_xywh(tx, y + 4.0, (avail_w - 110.0).max(120.0), 28.0), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size( + Pos2::new( + (tx + title_w + 14.0).min(x + avail_w - 14.0), + y + 18.0, + ), + Vec2::splat(20.0), + ), + if hdr_resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + ctx.draw_text_ellipsis( + &t.count_tracks(app.liked_tracks.len()), + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(tx, y + 34.0, (avail_w - 90.0).max(120.0), 20.0), + TextAlign::Left, + ); + + if hdr_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if hdr_resp.clicked { + actions.push(AppAction::Navigate(Route::LikedTracks)); } } + y += 58.0 + 16.0; + + if app.liked_tracks.is_empty() { + ctx.draw_text_wrapped( + if ru { + "Ставьте лайки трекам или войдите в аккаунт Яндекс Музыки — они появятся здесь." + } else { + "Like tracks or sign in to Yandex Music — they will appear here." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 40.0), + Some(2), + TextAlign::Left, + ); + y += 48.0; + } else { + let liked_tracks = app.liked_tracks.clone(); + y = render_compact_two_col_track_grid( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &liked_tracks, + "col_ov_fav", + fav_title, + "likes", + current_track_id.as_deref(), + is_playing, + actions, + ); + y += 28.0; + } + + // --------------------------------------------------------------------- + // SECTION 2: Favorite Artists > (horizontal circular carousel) + // --------------------------------------------------------------------- + { + let art_title = if ru { + "Любимые исполнители" + } else { + "Favorite Artists" + }; + let h_id = WidgetId::new("col_ov_artists_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_artists"), + art_title, + x, + y, + avail_w, + Some(h_id), + !app.liked_artists.is_empty(), + ) { + app.collection_tab = CollectionTab::Artists; + } + y += 38.0; + + if app.liked_artists.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Здесь появятся ваши любимые исполнители." + } else { + "Your favorite artists will appear here." + }, + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 22.0), + TextAlign::Left, + ); + y += 34.0; + } else { + let artists = app.liked_artists.clone(); + let card_w = 168.0; + let card_h = card_w + 52.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + for art in artists.iter().take(24) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_art", &art.id), + cr, + &art.name, + t.artist(), + art.cover_uri.as_deref(), + &format!("art_{}", art.id), + true, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "artist".into(), + id: art.id.clone(), + title: art.name.clone(), + subtitle: t.artist().into(), + cover_uri: art.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/artist/{}", art.id), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayArtist { + id: art.id.clone(), + name: art.name.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Artist { + id: art.id.clone(), + name: art.name.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + artists.len().min(24) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + } + + // --------------------------------------------------------------------- + // SECTION 3: Playlists > (horizontal carousel starting with `+ Create`) + // --------------------------------------------------------------------- + { + let h_id = WidgetId::new("col_ov_playlists_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_playlists"), + t.playlists(), + x, + y, + avail_w, + Some(h_id), + true, + ) { + app.collection_tab = CollectionTab::Playlists; + } + y += 38.0; + + let playlists = app.user_playlists.clone(); + let my_uid = app.account.as_ref().map(|a| a.uid.to_string()); + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + // Slot 0: compact `+ Создать плейлист` card + { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let cov_r = Rect::from_xywh(cr.left(), cr.top(), card_w, card_w); + let resp = ctx.interact(WidgetId::new("col_ov_create_pl"), cr); + ctx.dl().push_rect_bordered( + cov_r, + 10.0, + if resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + pal.border_control, + ); + ctx.draw_icon( + Icon::AddXxs, + Rect::from_center_size(cov_r.center(), Vec2::splat(34.0)), + if resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + ctx.draw_text_ellipsis( + t.create_playlist(), + TextStyle::medium(13.5, pal.text_primary), + Rect::from_xywh(cr.left(), cov_r.bottom() + 8.0, card_w, 20.0), + TextAlign::Left, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked { + actions.push(AppAction::OpenCreatePlaylistModal { + initial_track: None, + }); + } + } + cx += card_w + gap; + } + + for 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); + let is_own = pl.kind != "3" + && (pl.owner_uid == "local" + || my_uid.as_deref() == Some(pl.owner_uid.as_str())); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_pl", format!("{}_{}", pl.owner_uid, pl.kind)), + cr, + &pl.title, + &sub, + pl.cover_uri.as_deref(), + &format!("upl_{}_{}", pl.owner_uid, pl.kind), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "playlist".into(), + id: format!("{}:{}", pl.owner_uid, pl.kind), + title: pl.title.clone(), + subtitle: t.playlist().into(), + cover_uri: pl.cover_uri.clone(), + owner_uid: Some(pl.owner_uid.clone()), + is_own_playlist: is_own, + tracks: Vec::new(), + anchor: pos, + share_url: format!( + "https://music.yandex.ru/users/{}/playlists/{}", + pl.owner_uid, pl.kind + ), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayPlaylist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Playlist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + (playlists.len().min(24) + 1) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + + // --------------------------------------------------------------------- + // SECTION 4: Albums > (horizontal carousel) + // --------------------------------------------------------------------- + { + let h_id = WidgetId::new("col_ov_albums_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_albums"), + t.albums(), + x, + y, + avail_w, + Some(h_id), + !app.liked_albums.is_empty(), + ) { + app.collection_tab = CollectionTab::Albums; + } + y += 38.0; + + if app.liked_albums.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Здесь появятся ваши любимые альбомы." + } else { + "Your favorite albums will appear here." + }, + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 22.0), + TextAlign::Left, + ); + y += 34.0; + } else { + let albums = app.liked_albums.clone(); + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + for 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 sub = alb + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(t.album()); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_alb", &alb.id), + cr, + &alb.title, + sub, + alb.cover_uri.as_deref(), + &format!("alb_{}", alb.id), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "album".into(), + id: alb.id.clone(), + title: alb.title.clone(), + subtitle: t.album().into(), + cover_uri: alb.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/album/{}", alb.id), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayAlbum { + id: alb.id.clone(), + title: alb.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + albums.len().min(24) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + } + + // --------------------------------------------------------------------- + // SECTION 5: Podcasts & Audiobooks > (when non-empty) + // --------------------------------------------------------------------- + if !app.bookshelf_items.is_empty() { + let h_id = WidgetId::new("col_ov_books_h"); + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_books"), + t.podcasts_and_books(), + x, + y, + avail_w, + Some(h_id), + true, + ) { + app.collection_tab = CollectionTab::PodcastsAndBooks; + } + y += 38.0; + + let items = app.bookshelf_items.clone(); + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + + for pod in items.iter().take(24) { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let sub = pod + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(if ru { "Подкаст" } else { "Podcast" }); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair("col_ov_pod", &pod.id), + cr, + &pod.title, + sub, + pod.cover_uri.as_deref(), + &format!("pod_{}", pod.id), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "album".into(), + id: pod.id.clone(), + title: pod.title.clone(), + subtitle: sub.to_string(), + cover_uri: pod.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/album/{}", pod.id), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayAlbum { + id: pod.id.clone(), + title: pod.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: pod.id.clone(), + title: pod.title.clone(), + })); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h( + h_id, + pal, + items.len().min(24) as f32 * (card_w + gap), + false, + ); + y += card_h + 26.0; + } + + // --------------------------------------------------------------------- + // SECTION 6: History > (2-col × 4-row compact track grid when non-empty) + // --------------------------------------------------------------------- + if !app.play_history.is_empty() { + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_history"), + t.history(), + x, + y, + avail_w, + None, + false, + ) { + app.collection_tab = CollectionTab::History; + } + y += 38.0; + + let hist = app.play_history.clone(); + y = render_compact_two_col_track_grid( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &hist, + "col_ov_hist", + t.history(), + "history", + current_track_id.as_deref(), + is_playing, + actions, + ); + y += 28.0; + } + + // --------------------------------------------------------------------- + // SECTION 7: Downloaded > (compact preview list when non-empty) + // --------------------------------------------------------------------- + if !app.config.downloaded_tracks.is_empty() { + if draw_section_heading( + ctx, + pal, + WidgetId::new("col_sec_downloaded"), + t.downloaded(), + x, + y, + avail_w, + None, + false, + ) { + app.collection_tab = CollectionTab::Downloaded; + } + y += 38.0; + + let dl = app.config.downloaded_tracks.clone(); + y = render_compact_two_col_track_grid( + ctx, + pal, + covers, + app, + shell, + rect, + x, + y, + avail_w, + &dl, + "col_ov_dl", + t.downloaded_tracks(), + "downloads", + current_track_id.as_deref(), + is_playing, + actions, + ); + y += 16.0; + } + + y += 20.0; + let total_h = y - (rect.top() - scroll_y); + ctx.end_scroll_v(scroll_id, pal, total_h, true); + return; + } + + // ------------------------------------------------------------------------- + // SUB-VIEWS (Back button `← Коллекция` + full grid/list) + // ------------------------------------------------------------------------- + let (back_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("col_sub_back"), + Pos2::new(x, y), + Some(Icon::ArrowLeft), + t.collection(), + 34.0, + false, + ); + if back_resp.clicked { + app.collection_tab = CollectionTab::Tracks; + } + y += 48.0; + + let sub_title = match app.collection_tab { + CollectionTab::Tracks => t.collection(), + CollectionTab::Playlists => t.playlists(), + CollectionTab::Albums => t.albums(), + CollectionTab::Artists => { + if ru { + "Любимые исполнители" + } else { + "Favorite Artists" + } + } + CollectionTab::PodcastsAndBooks => t.podcasts_and_books(), + CollectionTab::Downloaded => t.downloaded(), + CollectionTab::History => t.history(), + }; + ctx.draw_text_ellipsis( + sub_title, + TextStyle::headline(32.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 40.0), + TextAlign::Left, + ); + y += 52.0; + + match app.collection_tab { + CollectionTab::Tracks => {} CollectionTab::Playlists => { let gap = 16.0; @@ -209,7 +735,6 @@ pub fn render_collection( let card_w = ((avail_w - gap * (cols as f32 - 1.0)) / cols as f32).max(132.0); let card_h = card_w + 62.0; - // Total slots = 1 ("+ Create playlist" card) + user_playlists.len() let playlists = app.user_playlists.clone(); let my_uid = app.account.as_ref().map(|a| a.uid.to_string()); @@ -375,11 +900,7 @@ pub fn render_collection( } CollectionTab::Albums => { - let albums = if !app.liked_albums.is_empty() { - app.liked_albums.clone() - } else { - Vec::new() - }; + let albums = app.liked_albums.clone(); if albums.is_empty() { ctx.draw_text_ellipsis( if ru { @@ -627,7 +1148,6 @@ pub fn render_collection( ); y += 48.0; } else { - // Header bar with Play Offline + Clear all downloaded let dl_playing = app.is_context_playing("downloads"); let (play_r, pr) = yellow_pill_button( ctx, @@ -730,6 +1250,231 @@ pub fn render_collection( ctx.end_scroll_v(scroll_id, pal, total_h, true); } +/// Clickable `Section Title >` heading with optional `<` `>` carousel scroll arrows on the right. +#[allow(clippy::too_many_arguments)] +fn draw_section_heading( + ctx: &mut UiContext, + pal: &YmPalette, + id: WidgetId, + title: &str, + x: f32, + y: f32, + avail_w: f32, + h_scroll_id: Option, + show_arrows: bool, +) -> bool { + let style_idle = TextStyle::headline(22.0, pal.text_primary); + let tw = ctx.measure_text(title, style_idle, None).x; + let head_w = (tw + 30.0).min((avail_w - 84.0).max(140.0)); + let head_r = Rect::from_xywh(x, y, head_w, 28.0); + let resp = ctx.interact(id, head_r); + + ctx.draw_text_ellipsis( + title, + TextStyle::headline( + 22.0, + if resp.hovered { + pal.text_bright + } else { + pal.text_primary + }, + ), + Rect::from_xywh(x, y, (head_w - 24.0).max(60.0), 28.0), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size( + Pos2::new(head_r.right() - 10.0, head_r.center_y()), + Vec2::splat(20.0), + ), + if resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + + if let (Some(h_id), true) = (h_scroll_id, show_arrows) { + let right_x = x + avail_w; + let cy = y + 14.0; + let next_r = Rect::from_center_size(Pos2::new(right_x - 15.0, cy), Vec2::splat(30.0)); + let prev_r = Rect::from_center_size(Pos2::new(right_x - 51.0, cy), Vec2::splat(30.0)); + + let (off_x, max_x) = { + let st = ctx.scrolls.get_or_create(h_id); + (st.offset.x, st.max_offset().x) + }; + let can_prev = off_x > 2.0; + let can_next = max_x > 2.0 && off_x < max_x - 2.0; + + let prev_resp = ctx.interact(h_id.with("prev"), prev_r); + let next_resp = ctx.interact(h_id.with("next"), next_r); + + ctx.dl().push_rect_bordered( + prev_r, + 15.0, + if prev_resp.hovered && can_prev { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + pal.border_subtle, + ); + ctx.draw_icon( + Icon::ArrowLeft, + Rect::from_center_size(prev_r.center(), Vec2::splat(16.0)), + if can_prev { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + ctx.dl().push_rect_bordered( + next_r, + 15.0, + if next_resp.hovered && can_next { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + pal.border_subtle, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size(next_r.center(), Vec2::splat(16.0)), + if can_next { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + if (prev_resp.hovered && can_prev) || (next_resp.hovered && can_next) { + ctx.set_cursor(CursorKind::Pointer); + } + if prev_resp.clicked && can_prev { + ctx.scrolls.get_or_create(h_id).scroll_by_x(-552.0); + ctx.request_repaint(); + } + if next_resp.clicked && can_next { + ctx.scrolls.get_or_create(h_id).scroll_by_x(552.0); + ctx.request_repaint(); + } + } + + resp.clicked +} + +/// Official 5.129.0 2-column × 4-row compact track grid (tracks 0..4 left, 4..8 right, 24px gap, 56px row height). +/// Gracefully collapses to 1 column of up to 6 tracks when `avail_w < 660.0`. +#[allow(clippy::too_many_arguments)] +fn render_compact_two_col_track_grid( + ctx: &mut UiContext, + pal: &YmPalette, + covers: &mut CoverCache, + app: &AppState, + shell: &mut ShellUiState, + viewport: Rect, + x: f32, + top_y: f32, + avail_w: f32, + tracks: &[Track], + salt: &str, + context_name: &str, + context_key: &str, + current_track_id: Option<&str>, + is_playing: bool, + actions: &mut Vec, +) -> f32 { + let t = app.i18n(); + let row_h = 56.0; + let two_cols = avail_w >= 660.0; + let col_gap = 24.0; + let max_items = if two_cols { 8 } else { 6 }; + let count = tracks.len().min(max_items); + let rows_per_col = if two_cols { 4 } else { count }; + let col_w = if two_cols { + (avail_w - col_gap) * 0.5 + } else { + avail_w + }; + + for idx in 0..count { + let col = if two_cols { idx / 4 } else { 0 }; + let row = if two_cols { idx % 4 } else { idx }; + let row_r = Rect::from_xywh( + x + col as f32 * (col_w + col_gap), + top_y + row as f32 * row_h, + col_w, + row_h, + ); + if row_r.bottom() < viewport.top() - 40.0 || row_r.top() > viewport.bottom() + 40.0 { + continue; + } + let tr = &tracks[idx]; + let is_curr = current_track_id == Some(tr.id.as_str()); + match track_row( + ctx, + pal, + covers, + WidgetId::from_pair(salt, idx), + row_r, + tr, + TrackRowOptions { + index: None, + show_chart_rank: false, + show_cover: true, + is_current: is_curr, + is_playing: is_curr && is_playing, + is_liked: app.liked_ids.contains(&tr.id), + is_disliked: app.disliked_ids.contains(&tr.id), + is_downloaded: app.is_track_downloaded(&tr.id), + menu_open: shell.is_track_menu_open(&tr.id), + }, + ) { + TrackRowAction::Play => { + actions.push(AppAction::PlayTracks { + tracks: tracks.to_vec(), + start_index: idx, + context_name: context_name.to_string(), + context_key: context_key.to_string(), + is_vibe: false, + }); + } + TrackRowAction::ToggleLike => actions.push(AppAction::ToggleLike(tr.clone())), + TrackRowAction::ToggleDislike => actions.push(AppAction::ToggleDislike(tr.clone())), + TrackRowAction::OpenArtist(id, name) => { + actions.push(AppAction::Navigate(Route::Artist { id, name })); + } + TrackRowAction::OpenAlbum(id) => { + actions.push(AppAction::Navigate(Route::Album { + id, + title: tr + .album_title + .clone() + .unwrap_or_else(|| t.album().into()), + })); + } + TrackRowAction::OpenContextMenu(pos) => { + shell.open_track_menu(tr.clone(), pos); + } + TrackRowAction::None => {} + } + } + + let used_rows = if two_cols { + count.min(rows_per_col) + } else { + count + }; + top_y + used_rows as f32 * row_h +} + #[allow(clippy::too_many_arguments)] fn render_virtual_track_list( ctx: &mut UiContext, diff --git a/src/views/for_you.rs b/src/views/for_you.rs index 3e12343..ec0c6c4 100644 --- a/src/views/for_you.rs +++ b/src/views/for_you.rs @@ -1,3 +1,6 @@ +use std::cell::Cell; + +use crate::api::models::{NewReleaseItem, VibePickItem, VibePickTab}; use crate::app::state::{AppAction, AppState, CollectionTab, ForYouTab, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -9,7 +12,11 @@ use crate::engine::widgets::{ }; use crate::engine::UiContext; use crate::icons::Icon; -use crate::views::overlays::ShellUiState; +use crate::views::overlays::{EntityContextMenuState, ShellUiState}; + +thread_local! { + static FOR_YOU_PICKS_TAB: Cell = const { Cell::new(0) }; +} /// Exact Yandex Music Desktop 5.129.0 "For you and Trends" page (`vibe_wheel_foryou_spec.md` §4): /// - Persistent heading ("Для вас и Тренды" / "For you and Trends") + IN-PLACE switcher tabs ("Для вас" / "Тренды") @@ -496,10 +503,15 @@ pub fn render_for_you( y += card_h + 26.0; } - // 5. "New Releases" - if !app.landing.new_releases.is_empty() { - y = render_new_releases_carousel(ctx, pal, covers, app, x, y, avail_w, "fy_rel", actions); + // 5. "New Releases >" (1-to-1 official `NewRelease` + `NewReleaseCard` circular portrait + colored release card!) + if !app.landing.rich_new_releases.is_empty() || !app.landing.new_releases.is_empty() { + y = render_new_releases_carousel( + ctx, pal, covers, app, shell, rect, x, y, avail_w, "fy_rel", actions, + ); } + + // 6. Official "More Picks" / "Ещё подборки" (`Waves` / `SETS_BY_WAVES`) + y = render_more_picks_section(ctx, pal, app, rect, x, y, avail_w, actions); } ForYouTab::Trends => { @@ -606,12 +618,14 @@ pub fn render_for_you( } // 2. New Releases Carousel - if !app.landing.new_releases.is_empty() { + if !app.landing.rich_new_releases.is_empty() || !app.landing.new_releases.is_empty() { y = render_new_releases_carousel( ctx, pal, covers, app, + shell, + rect, x, y, avail_w, @@ -678,9 +692,162 @@ pub fn render_for_you( } y += 20.0; - let _ = CornerRadii::ZERO; let total_h = y - (rect.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_h, true); + + // Sticky Frosted Top Switcher Bar when scrolled (`scroll_y > 72.0` -> zero impact on `scroll_y == 0` parity!) + if scroll_y > 72.0 { + let fade_in = ((scroll_y - 72.0) / 36.0).clamp(0.0, 1.0); + let bar_r = Rect::from_xywh( + rect.left() - 25.0, + rect.top() - 12.0, + rect.width() + 50.0, + 66.0, + ); + // Subtle atmospheric gradient glow behind the frosted sticky bar + let glow_c = if pal.is_dark { + Color::rgb(0x4E, 0x35, 0x62) + } else { + Color::rgb(0xD8, 0xD2, 0xE8) + }; + ctx.dl().push_gradient_rect( + bar_r, + CornerRadii::top(12.0), + glow_c.with_alpha((54.0 * fade_in).round() as u8), + glow_c.with_alpha(0), + Vec2::new(0.0, 1.0), + ); + let glass_tint = if pal.is_dark { + css_rgba(18, 18, 18, (186.0 * fade_in).round() as u8) + } else { + css_rgba(255, 255, 255, (206.0 * fade_in).round() as u8) + }; + ctx.dl().push_backdrop_blur( + bar_r, + CornerRadii::top(12.0), + 2.0, + glass_tint, + 0.0, + Color::TRANSPARENT, + ); + ctx.dl().push_rect( + Rect::from_xywh(bar_r.left(), bar_r.bottom() - 1.0, bar_r.width(), 1.0), + 0.0, + pal.border_subtle.scale_alpha(fade_in), + ); + + let mut sx = x; + let sy = bar_r.center_y() - 19.0; + for (tab_kind, label) in [ + (ForYouTab::ForYou, t.for_you()), + (ForYouTab::Trends, t.trends()), + ] { + let active = app.for_you_tab == tab_kind; + let tw = ctx + .measure_text(label, TextStyle::bold(14.5, pal.text_primary), None) + .x + + 32.0; + let pr = Rect::from_xywh(sx, sy, tw.max(88.0), 38.0); + let resp = ctx.interact(WidgetId::from_pair("fy_sticky_tab", tab_kind as u8), pr); + if active || resp.hovered { + ctx.dl().push_rect( + pr, + 19.0, + if active { + pal.surface_hover + } else { + pal.surface_secondary + }, + ); + } + ctx.draw_text_ellipsis( + label, + TextStyle::bold( + 14.5, + if active || resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ), + pr, + TextAlign::Center, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked && !active { + actions.push(AppAction::SetForYouTab(tab_kind)); + } + sx = pr.right() + 8.0; + } + } +} + +fn rich_dark_tint(raw: Color) -> Color { + // Rich dark-saturated card tint (~24% lightness) keeping high contrast for white album text + let r = (raw.r as f32 / 255.0).clamp(0.0, 1.0); + let g = (raw.g as f32 / 255.0).clamp(0.0, 1.0); + let b = (raw.b as f32 / 255.0).clamp(0.0, 1.0); + let max_c = r.max(g).max(b); + let min_c = r.min(g).min(b); + let avg = (max_c + min_c) * 0.5; + // Slightly boost chroma then scale luminance into ~0.22..0.28 range + let sat_r = (avg + (r - avg) * 1.25).clamp(0.0, 1.0); + let sat_g = (avg + (g - avg) * 1.25).clamp(0.0, 1.0); + let sat_b = (avg + (b - avg) * 1.25).clamp(0.0, 1.0); + let luma = (0.299 * sat_r + 0.587 * sat_g + 0.114 * sat_b).max(0.01); + let scale = (0.24 / luma).clamp(0.28, 0.95); + Color::rgb( + ((sat_r * scale).clamp(0.08, 0.48) * 255.0).round() as u8, + ((sat_g * scale).clamp(0.08, 0.48) * 255.0).round() as u8, + ((sat_b * scale).clamp(0.08, 0.48) * 255.0).round() as u8, + ) +} + +fn format_release_subtitle(item: &NewReleaseItem, ru: bool) -> String { + let is_single = item + .album + .content_type + .as_deref() + .map_or(false, |ct| ct.eq_ignore_ascii_case("single")) + || (item.album.track_count > 0 && item.album.track_count <= 3); + let kind = if is_single { + if ru { "сингл" } else { "single" } + } else if ru { + "альбом" + } else { + "album" + }; + + if let Some(ref rd) = item.release_date { + let date_part = rd.split('T').next().unwrap_or(rd); + let parts: Vec<&str> = date_part.split('-').collect(); + if parts.len() >= 3 { + if let (Ok(m), Ok(d)) = (parts[1].parse::(), parts[2].parse::()) { + if (1..=12).contains(&m) && d > 0 { + const MONTHS_RU: [&str; 12] = [ + "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", + "сентября", "октября", "ноября", "декабря", + ]; + const MONTHS_EN: [&str; 12] = [ + "January", "February", "March", "April", "May", "June", "July", "August", + "September", "October", "November", "December", + ]; + return if ru { + format!("{} · {} {}", kind, d, MONTHS_RU[m - 1]) + } else { + format!("{} · {} {}", kind, MONTHS_EN[m - 1], d) + }; + } + } + } + } + if let Some(yr) = item.album.year { + format!("{} · {}", kind, yr) + } else { + kind.to_string() + } } #[allow(clippy::too_many_arguments)] @@ -689,6 +856,8 @@ fn render_new_releases_carousel( pal: &YmPalette, covers: &mut CoverCache, app: &AppState, + shell: &mut ShellUiState, + viewport: Rect, x: f32, mut y: f32, avail_w: f32, @@ -696,58 +865,589 @@ fn render_new_releases_carousel( actions: &mut Vec, ) -> f32 { let t = app.i18n(); + let ru = t.is_ru(); + let items: Vec = if !app.landing.rich_new_releases.is_empty() { + app.landing.rich_new_releases.clone() + } else { + app.landing + .new_releases + .iter() + .cloned() + .map(|album| NewReleaseItem { + artist_cover_uri: album.artists.first().and_then(|a| a.cover_uri.clone()), + cover_color: None, + release_date: None, + album, + }) + .collect() + }; + if items.is_empty() { + return y; + } + + let h_id = WidgetId::new(salt); + let card_w = 286.0_f32; + let gap = 18.0_f32; + let portrait_d = 236.0_f32; + let overlap = 56.0_f32; + let bottom_h = 80.0_f32; + let card_h = portrait_d - overlap + bottom_h; // 260.0 + let total_w = items.len() as f32 * (card_w + gap); + + // Header row: "New Releases >" + circular `<` `>` carousel arrows on right + let head_txt = t.new_releases(); + let head_tw = ctx + .measure_text(head_txt, TextStyle::headline(24.0, pal.text_primary), None) + .x; ctx.draw_text_ellipsis( - t.new_releases(), + head_txt, + TextStyle::headline(24.0, pal.text_primary), + Rect::from_xywh(x, y, head_tw + 4.0, 30.0), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size(Pos2::new(x + head_tw + 16.0, y + 15.0), Vec2::splat(22.0)), + pal.text_secondary, + ); + + let (can_left, can_right) = ctx + .scrolls + .get(h_id) + .map(|s| (s.can_scroll_left(), s.can_scroll_right())) + .unwrap_or((false, total_w > avail_w + 10.0)); + let l_btn_c = Pos2::new(x + avail_w - 54.0, y + 15.0); + let r_btn_c = Pos2::new(x + avail_w - 16.0, y + 15.0); + for (c, ic, enabled, is_right) in [ + (l_btn_c, Icon::ArrowLeftXxs, can_left, false), + (r_btn_c, Icon::ArrowRightXxs, can_right, true), + ] { + let br = Rect::from_center_size(c, Vec2::splat(32.0)); + let resp = ctx.interact(WidgetId::from_pair(salt, if is_right { "next" } else { "prev" }), br); + let bg = if enabled && resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }; + ctx.dl().push_circle(c, 16.0, bg); + ctx.draw_icon( + ic, + Rect::from_center_size(c, Vec2::splat(18.0)), + if enabled { + if resp.hovered { pal.text_bright } else { pal.text_primary } + } else { + pal.text_disabled + }, + ); + if enabled && resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if enabled && resp.clicked { + let delta = if is_right { (card_w + gap) * 2.0 } else { -(card_w + gap) * 2.0 }; + ctx.scrolls.scroll_by_x(h_id, delta); + ctx.request_repaint(); + } + } + y += 42.0; + + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + if row_vp.bottom() >= viewport.top() - 120.0 && row_vp.top() <= viewport.bottom() + 120.0 { + let scroll_x = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - scroll_x; + for item in &items { + let alb = &item.album; + let outer_r = Rect::from_xywh(cx, y, card_w, card_h); + if outer_r.right() >= row_vp.left() - 80.0 && outer_r.left() <= row_vp.right() + 80.0 { + // 1. Huge 236x236 circular artist portrait overlapping the bottom card by 56px + let circle_r = Rect::from_xywh( + cx + (card_w - portrait_d) * 0.5, + y, + portrait_d, + portrait_d, + ); + let portrait_uri = item + .artist_cover_uri + .as_deref() + .or(alb.cover_uri.as_deref()); + let (portrait_dom, _) = draw_cover_art( + ctx, + pal, + covers, + circle_r, + portrait_uri, + &format!("nr_art_{}", alb.id), + portrait_d * 0.5, + true, + false, + ); + + // Resolve rich dark-saturated tint from `cover_color` or cover dominant color + let raw_tint = item + .cover_color + .as_deref() + .and_then(Color::from_hex_str) + .or_else(|| { + alb.cover_uri + .as_deref() + .and_then(|u| covers.get_or_fetch(u, 200)) + .map(|(_, dom, _)| dom) + }) + .unwrap_or(portrait_dom); + let card_tint = rich_dark_tint(raw_tint); + + // Smooth lower gradient fade over lower 42% of circular portrait + ctx.push_clip(circle_r, portrait_d * 0.5); + let scrim_h = portrait_d * 0.46; + ctx.dl().push_gradient_rect( + Rect::from_xywh(circle_r.left(), circle_r.bottom() - scrim_h, portrait_d, scrim_h), + 0.0, + card_tint.with_alpha(0), + card_tint.with_alpha(232), + Vec2::new(0.0, 1.0), + ); + ctx.pop_clip(); + + // Bold white centered Artist Name above the card overlap + let artist_name = alb + .artists + .first() + .map(|a| a.name.as_str()) + .unwrap_or(alb.title.as_str()); + let art_lbl_r = Rect::from_xywh( + circle_r.left() + 18.0, + y + portrait_d - overlap - 54.0, + portrait_d - 36.0, + 50.0, + ); + ctx.draw_text_wrapped( + artist_name, + TextStyle::headline(21.0, Color::WHITE).with_line_height(24.0), + art_lbl_r, + Some(2), + TextAlign::Center, + ); + + let port_click_r = Rect::from_xywh(circle_r.left(), circle_r.top(), portrait_d, portrait_d - overlap); + let port_resp = ctx.interact(WidgetId::from_pair(salt, 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, format!("card_{}", alb.id)), card_r); + let card_bg = if card_resp.hovered { + card_tint.lerp(Color::WHITE, 0.08) + } else { + card_tint + }; + ctx.dl().push_shadow( + card_r, + 14.0, + 12.0, + 0.0, + Vec2::new(0.0, 4.0), + css_rgba(0, 0, 0, 72), + ); + ctx.dl().push_rect_bordered( + card_r, + 14.0, + card_bg, + 1.0, + css_rgba(255, 255, 255, 26), + ); + + // Left 62x62 rounded (8px) album cover + let cov_r = Rect::from_xywh(card_r.left() + 9.0, card_r.top() + 9.0, 62.0, 62.0); + draw_cover_art( + ctx, + pal, + covers, + cov_r, + alb.cover_uri.as_deref(), + &format!("nr_alb_{}", alb.id), + 8.0, + false, + false, + ); + + // Right 38x38 crisp white circular Play/Pause button + let play_c = Pos2::new(card_r.right() - 28.0, card_r.center_y()); + let play_r = Rect::from_center_size(play_c, Vec2::splat(38.0)); + let play_resp = ctx.interact(WidgetId::from_pair(salt, format!("play_{}", alb.id)), play_r); + let play_rad = if play_resp.hovered { 20.0 } else { 19.0 }; + ctx.dl().push_circle(play_c, play_rad, Color::WHITE); + let alb_playing = app.is_context_playing(&format!("album:{}", alb.id)); + ctx.draw_icon( + if alb_playing { + Icon::PauseFilledXs + } else { + Icon::PlayFilledXs + }, + Rect::from_center_size(play_c, Vec2::splat(18.0)), + Color::rgb(0x14, 0x14, 0x14), + ); + + // Middle bold white title + muted release subtitle + let tx_l = cov_r.right() + 12.0; + let tx_w = (play_r.left() - tx_l - 8.0).max(40.0); + ctx.draw_text_ellipsis( + &alb.title, + TextStyle::bold(14.5, Color::WHITE), + Rect::from_xywh(tx_l, card_r.top() + 18.0, tx_w, 20.0), + TextAlign::Left, + ); + let sub = format_release_subtitle(item, ru); + ctx.draw_text_ellipsis( + &sub, + TextStyle::medium(12.5, css_rgba(255, 255, 255, 172)), + Rect::from_xywh(tx_l, card_r.top() + 42.0, tx_w, 18.0), + TextAlign::Left, + ); + + if play_resp.hovered || card_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if card_resp.right_clicked { + let pos = ctx + .input + .pointer_pos + .unwrap_or(Pos2::new(card_r.center_x(), card_r.bottom())); + shell.open_entity_menu(EntityContextMenuState { + kind: "album".into(), + id: alb.id.clone(), + title: alb.title.clone(), + subtitle: sub, + cover_uri: alb.cover_uri.clone(), + owner_uid: None, + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!("https://music.yandex.ru/album/{}", alb.id), + }); + } else if play_resp.clicked { + actions.push(AppAction::PlayAlbum { + id: alb.id.clone(), + title: alb.title.clone(), + }); + } else if card_resp.clicked { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); + } else if port_resp.clicked { + if let Some(first) = alb.artists.first() { + actions.push(AppAction::Navigate(Route::Artist { + id: first.id.clone(), + name: first.name.clone(), + })); + } else { + actions.push(AppAction::Navigate(Route::Album { + id: alb.id.clone(), + title: alb.title.clone(), + })); + } + } + } + cx += card_w + gap; + } + ctx.end_scroll_h(h_id, pal, total_w, false); + } + + y + card_h + 34.0 +} + +fn fallback_vibe_pick_tabs(ru: bool) -> Vec { + let mk = |title: &str, header: &str, seed: &str, hex: &str| VibePickItem { + title: title.into(), + header: header.into(), + seeds: vec![seed.into()], + color_hex: Some(hex.into()), + background_image_url: None, + image_url: None, + }; + if ru { + vec![ + VibePickTab { + title: "топ".into(), + items: vec![ + mk("Английский", "Моя волна по языку", "language:english", "#3F68F9"), + mk("Электроника", "Моя волна по жанру", "genre:electronics", "#8341EF"), + mk("Бодрое", "Моя волна по настроению", "mood:energetic", "#FF5C4D"), + mk("Для работы", "Моя волна по занятию", "activity:work", "#0D9488"), + mk("Незнакомое", "Моя волна по характеру", "diversity:discover", "#D97706"), + ], + }, + VibePickTab { + title: "по языку".into(), + items: vec![ + mk("Английский", "Моя волна по языку", "language:english", "#3F68F9"), + mk("Русский", "Моя волна по языку", "language:russian", "#E11D48"), + mk("Без слов", "Моя волна по языку", "language:without-words", "#0F766E"), + ], + }, + VibePickTab { + title: "по жанру".into(), + items: vec![ + mk("Электроника", "Моя волна по жанру", "genre:electronics", "#7C3AED"), + mk("Хип-хоп", "Моя волна по жанру", "genre:hiphop", "#EA580C"), + mk("Рок", "Моя волна по жанру", "genre:rock", "#DC2626"), + mk("Поп", "Моя волна по жанру", "genre:pop", "#DB2777"), + ], + }, + VibePickTab { + title: "по настроению".into(), + items: vec![ + mk("Бодрое", "Моя волна по настроению", "mood:energetic", "#F97316"), + mk("Спокойное", "Моя волна по настроению", "mood:calm", "#2563EB"), + mk("Весёлое", "Моя волна по настроению", "mood:fun", "#EAB308"), + ], + }, + VibePickTab { + title: "по занятию".into(), + items: vec![ + mk("Для работы", "Моя волна по занятию", "activity:work", "#0D9488"), + mk("Тренировка", "Моя волна по занятию", "activity:workout", "#E11D48"), + mk("В дорогу", "Моя волна по занятию", "activity:road-trip", "#4F46E5"), + ], + }, + VibePickTab { + title: "по характеру".into(), + items: vec![ + mk("Незнакомое", "Моя волна по характеру", "diversity:discover", "#8B5CF6"), + mk("Любимое", "Моя волна по характеру", "diversity:favorite", "#EC4899"), + mk("Популярное", "Моя волна по характеру", "diversity:popular", "#059669"), + ], + }, + ] + } else { + vec![ + VibePickTab { + title: "top".into(), + items: vec![ + mk("English", "My Vibe by language", "language:english", "#3F68F9"), + mk("Electronic", "My Vibe by genre", "genre:electronics", "#8341EF"), + mk("Energetic", "My Vibe by mood", "mood:energetic", "#FF5C4D"), + mk("Focus & Work", "My Vibe by activity", "activity:work", "#0D9488"), + mk("Discover", "My Vibe by character", "diversity:discover", "#D97706"), + ], + }, + VibePickTab { + title: "by language".into(), + items: vec![ + mk("English", "My Vibe by language", "language:english", "#3F68F9"), + mk("Russian", "My Vibe by language", "language:russian", "#E11D48"), + mk("Instrumental", "My Vibe by language", "language:without-words", "#0F766E"), + ], + }, + VibePickTab { + title: "by genre".into(), + items: vec![ + mk("Electronic", "My Vibe by genre", "genre:electronics", "#7C3AED"), + mk("Hip-Hop", "My Vibe by genre", "genre:hiphop", "#EA580C"), + mk("Rock", "My Vibe by genre", "genre:rock", "#DC2626"), + mk("Pop", "My Vibe by genre", "genre:pop", "#DB2777"), + ], + }, + VibePickTab { + title: "by mood".into(), + items: vec![ + mk("Energetic", "My Vibe by mood", "mood:energetic", "#F97316"), + mk("Calm", "My Vibe by mood", "mood:calm", "#2563EB"), + mk("Upbeat", "My Vibe by mood", "mood:fun", "#EAB308"), + ], + }, + VibePickTab { + title: "by activity".into(), + items: vec![ + mk("Work", "My Vibe by activity", "activity:work", "#0D9488"), + mk("Workout", "My Vibe by activity", "activity:workout", "#E11D48"), + mk("Road trip", "My Vibe by activity", "activity:road-trip", "#4F46E5"), + ], + }, + VibePickTab { + title: "by character".into(), + items: vec![ + mk("Discover", "My Vibe by character", "diversity:discover", "#8B5CF6"), + mk("Favorites", "My Vibe by character", "diversity:favorite", "#EC4899"), + mk("Popular", "My Vibe by character", "diversity:popular", "#059669"), + ], + }, + ] + } +} + +#[allow(clippy::too_many_arguments)] +fn render_more_picks_section( + ctx: &mut UiContext, + pal: &YmPalette, + app: &AppState, + viewport: Rect, + x: f32, + mut y: f32, + avail_w: f32, + actions: &mut Vec, +) -> f32 { + let ru = app.i18n().is_ru(); + let tabs: Vec = if !app.landing.vibe_pick_tabs.is_empty() { + app.landing.vibe_pick_tabs.clone() + } else { + fallback_vibe_pick_tabs(ru) + }; + if tabs.is_empty() { + return y; + } + + ctx.draw_text_ellipsis( + if ru { "Ещё подборки" } else { "More Picks" }, TextStyle::headline(24.0, pal.text_primary), Rect::from_xywh(x, y, avail_w, 30.0), TextAlign::Left, ); y += 40.0; - let card_w = 164.0; - let card_h = card_w + 54.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let h_id = WidgetId::new(salt); - let scroll_x = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let active_idx = FOR_YOU_PICKS_TAB.with(|c| c.get()).min(tabs.len() - 1); - let releases = app.landing.new_releases.clone(); - let mut cx = x - scroll_x; - for alb in &releases { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { - let art = alb - .artists - .first() - .map(|a| a.name.as_str()) - .unwrap_or(t.album()); - let m = media_card( - ctx, - pal, - covers, - WidgetId::from_pair(salt, &alb.id), - cr, - &alb.title, - art, - alb.cover_uri.as_deref(), - &format!("alb_{}", alb.id), - false, - false, - ); - if m.play_clicked { - actions.push(AppAction::PlayAlbum { - id: alb.id.clone(), - title: alb.title.clone(), - }); - } else if m.clicked { - actions.push(AppAction::Navigate(Route::Album { - id: alb.id.clone(), - title: alb.title.clone(), - })); - } + // Horizontal category filter tabs (`32px` active pill, clean secondary text inactive) + let tabs_vp = Rect::from_xywh(x, y, avail_w, 34.0); + let tabs_h_id = WidgetId::new("fy_picks_tabs_hscroll"); + let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); + let mut tx = x - tabs_sx; + for (idx, tab) in tabs.iter().enumerate() { + let is_act = idx == active_idx; + let style = TextStyle::medium( + 14.0, + if is_act { pal.text_bright } else { pal.text_secondary }, + ); + let tw = ctx.measure_text(&tab.title, style, None).x + 24.0; + let tr = Rect::from_xywh(tx, y, tw.max(52.0), 32.0); + let resp = ctx.interact(WidgetId::from_pair("fy_pick_tab", idx), tr); + if is_act { + ctx.dl().push_rect(tr, 16.0, pal.surface_hover); + } else if resp.hovered { + ctx.dl().push_rect(tr, 16.0, pal.surface_secondary); } - cx += card_w + 16.0; + ctx.draw_text_ellipsis( + &tab.title, + TextStyle::medium( + 14.0, + if is_act || resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ), + tr, + TextAlign::Center, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked { + FOR_YOU_PICKS_TAB.with(|c| c.set(idx)); + } + tx = tr.right() + 8.0; } - let total_w = (releases.len() as f32) * (card_w + 16.0); - ctx.end_scroll_h(h_id, pal, total_w, false); + ctx.end_scroll_h(tabs_h_id, pal, (tx + tabs_sx) - x, false); + y += 46.0; + + // Vibrant gradient-tinted glossy Vibe-Station cards (`260x70`, `radius: 16px`) + const CURATED_PALETTE: &[Color] = &[ + Color::rgb(0x3F, 0x68, 0xF9), + Color::rgb(0x83, 0x41, 0xEF), + Color::rgb(0xE1, 0x3A, 0x52), + Color::rgb(0x0D, 0x94, 0x88), + Color::rgb(0xD9, 0x77, 0x06), + Color::rgb(0xDB, 0x27, 0x77), + ]; + + let card_w = 260.0_f32; + let card_h = 70.0_f32; + let gap = 14.0_f32; + let row_vp = Rect::from_xywh(x, y, avail_w, card_h); + let items = &tabs[active_idx].items; + if row_vp.bottom() >= viewport.top() - 120.0 && row_vp.top() <= viewport.bottom() + 120.0 { + let h_id = WidgetId::from_pair("fy_picks_cards", active_idx); + let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); + let mut cx = x - sx; + for (idx, item) in items.iter().enumerate() { + let cr = Rect::from_xywh(cx, y, card_w, card_h); + if cr.right() >= row_vp.left() - 60.0 && cr.left() <= row_vp.right() + 60.0 { + let resp = ctx.interact(WidgetId::from_pair("fy_pick_card", (active_idx, idx)), cr); + let base_c = item + .color_hex + .as_deref() + .and_then(Color::from_hex_str) + .unwrap_or(CURATED_PALETTE[idx % CURATED_PALETTE.len()]); + let c_left = base_c.lerp(Color::BLACK, if resp.hovered { 0.14 } else { 0.24 }); + let c_right = base_c.lerp(Color::BLACK, if resp.hovered { 0.36 } else { 0.48 }); + ctx.dl() + .push_gradient_rect(cr, 16.0, c_left, c_right, Vec2::new(1.0, 0.4)); + // Subtle glossy top sheen + ctx.dl().push_gradient_rect( + Rect::from_xywh(cr.left(), cr.top(), cr.width(), cr.height() * 0.48), + CornerRadii::top(16.0), + css_rgba(255, 255, 255, if resp.hovered { 42 } else { 28 }), + css_rgba(255, 255, 255, 0), + Vec2::new(0.0, 1.0), + ); + ctx.dl().push_rect_bordered( + cr, + 16.0, + Color::TRANSPARENT, + 1.0, + css_rgba(255, 255, 255, 28), + ); + + // Eyebrow ("Моя волна по языку" / "My Vibe by language") + if !item.header.is_empty() { + ctx.draw_text_ellipsis( + &item.header, + TextStyle::medium(12.0, css_rgba(255, 255, 255, 196)), + Rect::from_xywh(cr.left() + 14.0, cr.top() + 13.0, cr.width() - 28.0, 16.0), + TextAlign::Center, + ); + } + + // Centered bold white `▶` + station title (`17px` Headline) + let title_style = TextStyle::headline(17.0, Color::WHITE); + let tw = ctx + .measure_text(&item.title, title_style, None) + .x + .min(cr.width() - 52.0); + let inner_w = 16.0 + 6.0 + tw; + let tx_start = cr.center_x() - inner_w * 0.5; + let row_y = if item.header.is_empty() { + cr.center_y() + } else { + cr.top() + 45.0 + }; + ctx.draw_icon( + Icon::PlayFilledXs, + Rect::from_center_size(Pos2::new(tx_start + 8.0, row_y), Vec2::splat(14.0)), + Color::WHITE, + ); + ctx.draw_text_ellipsis( + &item.title, + title_style, + Rect::from_xywh(tx_start + 22.0, row_y - 11.0, tw + 4.0, 22.0), + TextAlign::Left, + ); + + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked && !item.seeds.is_empty() { + actions.push(AppAction::StartVibeBySeeds { + title: item.title.clone(), + seeds: item.seeds.clone(), + }); + } + } + cx += card_w + gap; + } + ctx.end_scroll_h(h_id, pal, items.len() as f32 * (card_w + gap), false); + } + y + card_h + 26.0 } diff --git a/src/views/my_vibe.rs b/src/views/my_vibe.rs index d8002bb..7a0c202 100644 --- a/src/views/my_vibe.rs +++ b/src/views/my_vibe.rs @@ -14,8 +14,8 @@ use crate::engine::types::{ css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, Vec2, VIBE_TEXTURE_ID, }; use crate::engine::widgets::{ - draw_cover_art, secondary_pill_button, ym_menu_divider, ym_menu_frame, ym_menu_item, - ym_menu_item_ex, ym_volume_capsule, + draw_cover_art, ym_menu_divider, ym_menu_frame, ym_menu_item, ym_menu_item_ex, + ym_volume_capsule, }; use crate::engine::UiContext; use crate::icons::Icon; @@ -1504,7 +1504,7 @@ pub fn render_my_vibe( // 13. OFFICIAL 5.129.0 `WordsCardFullscreen` (`ZLayer::Modal` when `app.words_big_card_open`) if app.words_big_card_open { - render_words_card_fullscreen(ctx, pal, app, ru, active_words_card.as_ref(), actions); + render_words_card_fullscreen(ctx, pal, covers, app, ru, active_words_card.as_ref(), actions); } } @@ -1664,6 +1664,7 @@ fn render_words_card_popover( fn render_words_card_fullscreen( ctx: &mut UiContext, pal: &YmPalette, + covers: &mut CoverCache, app: &AppState, ru: bool, fallback_card: Option<&WordsCard>, @@ -1714,31 +1715,21 @@ fn render_words_card_fullscreen( should_close = true; } - let col_w = (screen.width() - 96.0).clamp(300.0, 540.0); - let modal_h = (screen.height() - 140.0).clamp(320.0, 580.0); - let content_rect = Rect::from_center_size(screen.center(), Vec2::new(col_w + 48.0, modal_h)); - let col_x = content_rect.center_x() - col_w * 0.5; - let mut y = content_rect.top() + 18.0; - - // Top AI sparkle badge with soft meteor glow - let sp_c = Pos2::new(content_rect.center_x(), y + 20.0); - let meteor_tex = ctx.icons.get_official_meteor_glow(&mut ctx.textures); - let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); - ctx.dl().push_image( - Rect::from_xywh(badge_tl.x - 180.0 * 0.25, badge_tl.y - 180.0 * 0.43, 180.0, 180.0), - meteor_tex, - 0.0, - Color::WHITE.with_alpha(150), + let col_w = (screen.width() - 96.0).clamp(300.0, 560.0); + let col_x = screen.center_x() - col_w * 0.5; + let disclaimer = if ru { + "AI может ошибаться, проверяйте важное" + } else { + "AI may make mistakes, be sure to double-check important information" + }; + let disclaimer_y = screen.bottom() - 38.0; + let content_rect = Rect::from_min_max( + Pos2::new(col_x - 24.0, screen.top() + 92.0), + Pos2::new(col_x + col_w + 24.0, disclaimer_y - 12.0), ); - ctx.draw_icon( - Icon::AiSparkles, - Rect::from_center_size(sp_c, Vec2::splat(28.0)), - pal.text_bright, - ); - y += 64.0; if app.words_big_card_loading { - // 3 subtle animated shimmer bars while `POST /words/big-cards` loads + // 3 subtle animated shimmer bars centered vertically while `POST /words/big-cards` loads let shimmer = 0.5 + 0.5 * ((ctx.input.time as f32) * 3.2).sin(); let a = (28.0 + 36.0 * shimmer).round() as u8; let bar_col = if pal.is_dark { @@ -1746,11 +1737,12 @@ fn render_words_card_fullscreen( } else { css_rgba(0, 0, 0, a) }; + let sy = content_rect.center_y() - 40.0; for (i, frac) in [0.88_f32, 1.0_f32, 0.64_f32].iter().enumerate() { let bw = col_w * frac; let br = Rect::from_xywh( - content_rect.center_x() - bw * 0.5, - y + i as f32 * 30.0, + screen.center_x() - bw * 0.5, + sy + i as f32 * 30.0, bw, 18.0, ); @@ -1773,107 +1765,170 @@ fn render_words_card_fullscreen( .or_else(|| fallback_card.map(|c| c.actions.as_slice())) .unwrap_or(&[]); - let bottom_reserved = if sources.is_empty() { 104.0 } else { 154.0 }; - let text_vp_h = (content_rect.bottom() - y - bottom_reserved).max(120.0); - let text_vp = Rect::from_xywh(col_x, y, col_w, text_vp_h); let text_style = TextStyle::bold(20.0, pal.text_bright).with_line_height(28.0); let measured = ctx.measure_text(full_text, text_style, Some(col_w)); - - let scroll_id = WidgetId::new("wcf_text_scroll"); - let scroll_y = ctx.begin_scroll_v(scroll_id, text_vp, 0.0); - let ty = if measured.y < text_vp_h { - text_vp.center_y() - measured.y * 0.5 + let src_count = sources.len().min(2); + let src_block_h = if src_count > 0 { + 28.0 + src_count as f32 * 46.0 - 8.0 } else { - text_vp.top() - scroll_y + 0.0 }; - ctx.draw_text_wrapped( - full_text, - text_style, - Rect::from_xywh(col_x, ty, col_w, measured.y + 12.0), - None, - TextAlign::Center, - ); - ctx.end_scroll_v(scroll_id, pal, measured.y + 16.0, false); - y = text_vp.bottom() + 16.0; + let fb_block_h = if fallback_card.is_some() { 22.0 + 32.0 } else { 0.0 }; + let max_text_h = (content_rect.height() - src_block_h - fb_block_h - 16.0).max(110.0); + let used_text_h = measured.y.min(max_text_h); + let total_stack_h = used_text_h + src_block_h + fb_block_h; + let mut y = (content_rect.center_y() - total_stack_h * 0.5).max(content_rect.top()); - // Optional source link pills - if !sources.is_empty() { - let mut sx = col_x; - let max_right = col_x + col_w; - for (idx, src) in sources.iter().take(4).enumerate() { - let est_w = (ctx - .measure_text(&src.title, TextStyle::medium(13.5, pal.text_primary), None) - .x - + 50.0) - .clamp(80.0, col_w); - if sx + est_w > max_right && sx > col_x { - break; - } - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("wcf_src", idx), - Pos2::new(sx, y), - Some(Icon::LinkXxs), - &src.title, - 34.0, - false, + // 1. Centered 20px bold story text (scrollable if longer than viewport, ZERO floating sparkle!) + let text_vp = Rect::from_xywh(col_x, y, col_w, used_text_h + 6.0); + if measured.y > max_text_h { + let scroll_id = WidgetId::new("wcf_text_scroll"); + let scroll_y = ctx.begin_scroll_v(scroll_id, text_vp, 0.0); + ctx.draw_text_wrapped( + full_text, + text_style, + Rect::from_xywh(col_x, text_vp.top() - scroll_y, col_w, measured.y + 12.0), + None, + TextAlign::Center, + ); + ctx.end_scroll_v(scroll_id, pal, measured.y + 16.0, false); + } else { + ctx.draw_text_wrapped( + full_text, + text_style, + Rect::from_xywh(col_x, y, col_w, measured.y + 12.0), + None, + TextAlign::Center, + ); + } + y += used_text_h; + + // 2. Centered full-width-fitted source/Alice glass pill(s) (28px below text, NEVER truncates!) + if src_count > 0 { + y += 28.0; + let max_pill_w = (screen.width() - 64.0).min(520.0); + for (idx, src) in sources.iter().take(src_count).enumerate() { + let lbl_style = TextStyle::medium(14.0, pal.text_bright); + let tw = ctx.measure_text(&src.title, lbl_style, None).x; + let pill_w = (tw + 54.0).clamp(160.0, max_pill_w); + let pill_r = Rect::from_xywh( + screen.center_x() - pill_w * 0.5, + y, + pill_w, + 38.0, ); + let resp = ctx.interact(WidgetId::from_pair("wcf_src_pill", idx), pill_r); + let bg = if pal.is_dark { + css_rgba(255, 255, 255, if resp.hovered { 32 } else { 18 }) + } else if resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }; + let border = if pal.is_dark { + css_rgba(255, 255, 255, 28) + } else { + pal.border_subtle + }; + ctx.dl().push_rect_bordered(pill_r, 19.0, bg, 1.0, border); + + // Left 18x18 icon: favicon_url -> Alice purple ring -> LinkRounded + let ic_center = Pos2::new(pill_r.left() + 22.0, pill_r.center_y()); + let ic_rect = Rect::from_center_size(ic_center, Vec2::splat(18.0)); + let mut drew_fav = false; + if let Some(ref fav) = src.favicon_url { + if let Some((tex_id, _, _)) = covers.get_or_fetch(fav, 64) { + ctx.dl().push_image(ic_rect, tex_id, 9.0, Color::WHITE); + drew_fav = true; + } + } + if !drew_fav { + let tl = src.title.to_lowercase(); + if tl.contains("алис") || tl.contains("alice") { + ctx.dl() + .push_circle(ic_center, 9.0, Color::rgb(0x18, 0x13, 0x26)); + ctx.dl().push_circle_stroke( + ic_center, + 8.0, + 2.2, + Color::rgb(0x8B, 0x5C, 0xF6), + ); + ctx.dl() + .push_circle(ic_center, 2.6, Color::rgb(0xC4, 0xB5, 0xFD)); + } else { + ctx.draw_icon( + Icon::LinkRounded, + Rect::from_center_size(ic_center, Vec2::splat(16.0)), + pal.text_bright, + ); + } + } + + ctx.draw_text_ellipsis( + &src.title, + lbl_style, + Rect::from_xywh( + pill_r.left() + 38.0, + pill_r.top(), + (pill_r.width() - 52.0).max(40.0), + pill_r.height(), + ), + TextAlign::Left, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } if resp.clicked && !src.url.is_empty() { actions.push(AppAction::OpenUrl(src.url.clone())); } - sx = r.right() + 8.0; + y += 46.0; } - y += 46.0; + y -= 8.0; } - // Horizontal feedback bar: 👍 More similar replies | 1px divider | 👎 Not cool + // 3. BORDERLESS TEXT-ONLY feedback buttons (22px below source pill, 28px gap, ZERO boxes!) if let Some(card) = fallback_card { + y += 22.0; let like_lbl = if ru { "Больше такого" } else { "More similar replies" }; let dislike_lbl = if ru { "Мимо" } else { "Not cool" }; - let btn_h = 38.0; - let like_w = (ctx - .measure_text(like_lbl, TextStyle::medium(14.0, pal.text_primary), None) - .x - + 54.0) - .max(120.0); - let dislike_w = (ctx - .measure_text(dislike_lbl, TextStyle::medium(14.0, pal.text_primary), None) - .x - + 54.0) - .max(100.0); - let bar_w = like_w + 25.0 + dislike_w; - let bar_x = content_rect.center_x() - bar_w * 0.5; + let muted = if pal.is_dark { + css_rgba(255, 255, 255, 148) + } else { + pal.text_secondary + }; + let lbl_style = TextStyle::medium(14.0, muted); + let like_tw = ctx.measure_text(like_lbl, lbl_style, None).x; + let dislike_tw = ctx.measure_text(dislike_lbl, lbl_style, None).x; + let like_w = 16.0 + 7.0 + like_tw + 8.0; + let dislike_w = 16.0 + 7.0 + dislike_tw + 8.0; + let gap = 28.0_f32; + let total_w = like_w + gap + dislike_w; + let start_x = screen.center_x() - total_w * 0.5; + let btn_h = 32.0; - let like_r = Rect::from_xywh(bar_x, y, like_w, btn_h); + let like_r = Rect::from_xywh(start_x, y, like_w, btn_h); let like_resp = ctx.interact(WidgetId::new("wcf_like"), like_r); - ctx.dl().push_rect( - like_r, - 19.0, - if like_resp.hovered || card.is_liked() { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); let like_fg = if card.is_liked() || like_resp.hovered { pal.text_bright } else { - pal.text_primary + muted }; ctx.draw_icon( Icon::ThumbUpXxs, - Rect::from_center_size(Pos2::new(like_r.left() + 22.0, like_r.center_y()), Vec2::splat(18.0)), + Rect::from_center_size( + Pos2::new(like_r.left() + 10.0, like_r.center_y()), + Vec2::splat(16.0), + ), like_fg, ); ctx.draw_text_ellipsis( like_lbl, TextStyle::medium(14.0, like_fg), - Rect::from_xywh(like_r.left() + 38.0, like_r.top(), like_r.width() - 48.0, like_r.height()), + Rect::from_xywh(like_r.left() + 24.0, like_r.top(), like_tw + 8.0, btn_h), TextAlign::Left, ); if like_resp.hovered { @@ -1891,39 +1946,30 @@ fn render_words_card_fullscreen( }); } - // 1px vertical divider - let div_x = like_r.right() + 12.0; - ctx.dl().push_rect( - Rect::from_xywh(div_x, y + 7.0, 1.0, 24.0), - 0.0, - pal.border_subtle, - ); - - let dislike_r = Rect::from_xywh(div_x + 13.0, y, dislike_w, btn_h); + let dislike_r = Rect::from_xywh(like_r.right() + gap, y, dislike_w, btn_h); let dislike_resp = ctx.interact(WidgetId::new("wcf_dislike"), dislike_r); - ctx.dl().push_rect( - dislike_r, - 19.0, - if dislike_resp.hovered || card.is_disliked() { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); let dislike_fg = if card.is_disliked() || dislike_resp.hovered { pal.text_bright } else { - pal.text_primary + muted }; ctx.draw_icon( Icon::ThumbDownXxs, - Rect::from_center_size(Pos2::new(dislike_r.left() + 22.0, dislike_r.center_y()), Vec2::splat(18.0)), + Rect::from_center_size( + Pos2::new(dislike_r.left() + 10.0, dislike_r.center_y()), + Vec2::splat(16.0), + ), dislike_fg, ); ctx.draw_text_ellipsis( dislike_lbl, TextStyle::medium(14.0, dislike_fg), - Rect::from_xywh(dislike_r.left() + 38.0, dislike_r.top(), dislike_r.width() - 48.0, dislike_r.height()), + Rect::from_xywh( + dislike_r.left() + 24.0, + dislike_r.top(), + dislike_tw + 8.0, + btn_h, + ), TextAlign::Left, ); if dislike_resp.hovered { @@ -1936,24 +1982,25 @@ fn render_words_card_fullscreen( state: "dislike".into(), }); } - y += btn_h + 18.0; } - - // Bottom AI disclaimer - let disclaimer = if ru { - "AI может ошибаться, проверяйте важное" - } else { - "AI may make mistakes, be sure to double-check important information" - }; - ctx.draw_text_wrapped( - disclaimer, - TextStyle::regular(12.5, pal.text_secondary).with_line_height(17.0), - Rect::from_xywh(col_x, y, col_w, 36.0), - Some(2), - TextAlign::Center, - ); } + // 4. Disclaimer pinned cleanly near the bottom (`screen.bottom() - 32.0`) + let disc_col = if pal.is_dark { + css_rgba(255, 255, 255, 96) + } else { + pal.text_secondary + }; + ctx.draw_text_ellipsis( + disclaimer, + TextStyle::regular(12.0, disc_col), + Rect::from_center_size( + Pos2::new(screen.center_x(), screen.bottom() - 32.0), + Vec2::new((screen.width() - 64.0).max(200.0), 22.0), + ), + TextAlign::Center, + ); + if ctx.input.key_pressed(Key::Escape) || ctx.input.clicked_outside_any(&[content_rect, close_r]) { diff --git a/src/views/podcasts_kids.rs b/src/views/podcasts_kids.rs index b349079..43603a4 100644 --- a/src/views/podcasts_kids.rs +++ b/src/views/podcasts_kids.rs @@ -1,4 +1,6 @@ -use crate::api::models::AlbumSummary; +use std::cell::RefCell; + +use crate::api::models::{AlbumSummary, ConcertItem, PlaylistSummary}; use crate::app::state::{AppAction, AppState, Route}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -14,6 +16,10 @@ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::{EntityContextMenuState, ShellUiState}; +thread_local! { + static CONCERT_CITY_FILTER: RefCell> = const { RefCell::new(None) }; +} + fn is_audiobook_item(item: &AlbumSummary) -> bool { item.content_type .as_deref() @@ -23,10 +29,277 @@ fn is_audiobook_item(item: &AlbumSummary) -> bool { }) } -/// Books & Podcasts landing page (100% theme-aware & RU/EN localized): -/// - Category filter tabs (`Все` / `Подкасты` / `Аудиокниги`) -/// - "Продолжить слушать" / "Continue listening" horizontal shelf -/// - Podcasts & Audiobooks grids with right-click context menus +fn is_audiobook_section(id: &str, block_type: &str, title: &str) -> bool { + let low_id = id.to_lowercase(); + let low_bt = block_type.to_lowercase(); + let low_ti = title.to_lowercase(); + low_id.contains("book") + || low_bt.contains("book") + || low_ti.contains("книг") + || low_ti.contains("book") + || low_ti.contains("роман") + || low_ti.contains("фантаст") +} + +fn draw_carousel_arrows( + ctx: &mut UiContext, + pal: &YmPalette, + h_id: WidgetId, + right_x: f32, + center_y: f32, + step: f32, +) { + let next_r = Rect::from_center_size(Pos2::new(right_x - 16.0, center_y), Vec2::splat(30.0)); + let prev_r = Rect::from_center_size(Pos2::new(right_x - 52.0, center_y), Vec2::splat(30.0)); + + let (off_x, max_x) = { + let st = ctx.scrolls.get_or_create(h_id); + (st.offset.x, st.max_offset().x) + }; + let can_prev = off_x > 2.0; + let can_next = max_x > 2.0 && off_x < max_x - 2.0; + + let prev_resp = ctx.interact(h_id.with("prev"), prev_r); + let next_resp = ctx.interact(h_id.with("next"), next_r); + + let prev_bg = if prev_resp.hovered && can_prev { + pal.surface_hover + } else { + pal.surface_secondary + }; + let next_bg = if next_resp.hovered && can_next { + pal.surface_hover + } else { + pal.surface_secondary + }; + + ctx.dl() + .push_rect_bordered(prev_r, 15.0, prev_bg, 1.0, pal.border_subtle); + ctx.draw_icon( + Icon::ArrowLeft, + Rect::from_center_size(prev_r.center(), Vec2::splat(16.0)), + if can_prev { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + + ctx.dl() + .push_rect_bordered(next_r, 15.0, next_bg, 1.0, pal.border_subtle); + ctx.draw_icon( + Icon::ArrowRight, + Rect::from_center_size(next_r.center(), Vec2::splat(16.0)), + if can_next { + pal.text_bright + } else { + pal.text_secondary.scale_alpha(0.35) + }, + ); + + if (prev_resp.hovered && can_prev) || (next_resp.hovered && can_next) { + ctx.set_cursor(CursorKind::Pointer); + } + if prev_resp.clicked && can_prev { + ctx.scrolls.get_or_create(h_id).scroll_by_x(-step); + ctx.request_repaint(); + } + if next_resp.clicked && can_next { + ctx.scrolls.get_or_create(h_id).scroll_by_x(step); + ctx.request_repaint(); + } +} + +fn shimmer_color(pal: &YmPalette, phase: f32) -> Color { + let pulse = 0.5 + 0.5 * phase.sin(); + let base = pal.surface_secondary; + let hi = pal.surface_hover; + let lerp = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * pulse).round() as u8; + Color::from_rgba( + lerp(base.r, hi.r), + lerp(base.g, hi.g), + lerp(base.b, hi.b), + 255, + ) +} + +fn format_price_spaced(price: u64) -> String { + let s = price.to_string(); + let mut out = String::with_capacity(s.len() + s.len() / 3); + for (i, ch) in s.chars().rev().enumerate() { + if i > 0 && i % 3 == 0 { + out.push(' '); + } + out.push(ch); + } + out.chars().rev().collect() +} + +fn currency_symbol(cur: Option<&str>) -> &'static str { + match cur.map(|s| s.to_ascii_uppercase()).as_deref() { + Some("USD") => "$", + Some("EUR") => "€", + Some("KZT") => "₸", + Some("BYN") => "Br", + Some("UZS") => "сум", + _ => "₽", + } +} + +fn format_ticket_label(c: &ConcertItem, ru: bool) -> String { + if let Some(price) = c.min_price.filter(|&p| p > 0) { + let sym = currency_symbol(c.currency.as_deref()); + let formatted = format_price_spaced(price); + if ru { + format!("от {} {}", formatted, sym) + } else { + format!("from {} {}", formatted, sym) + } + } else if ru { + "Билеты".into() + } else { + "Tickets".into() + } +} + +fn format_cashback_label(c: &ConcertItem, ru: bool) -> Option { + if let Some(ref title) = c.cashback_title { + if !title.trim().is_empty() { + return Some(title.trim().to_string()); + } + } + c.cashback_percent.filter(|&p| p > 0).map(|pct| { + if ru { + format!("Кешбэк {}%", pct) + } else { + format!("{}% Cashback", pct) + } + }) +} + +fn month_short(month: u32, ru: bool) -> &'static str { + if ru { + match month { + 1 => "ЯНВ", + 2 => "ФЕВ", + 3 => "МАР", + 4 => "АПР", + 5 => "МАЯ", + 6 => "ИЮН", + 7 => "ИЮЛ", + 8 => "АВГ", + 9 => "СЕН", + 10 => "ОКТ", + 11 => "НОЯ", + 12 => "ДЕК", + _ => "LIVE", + } + } else { + match month { + 1 => "JAN", + 2 => "FEB", + 3 => "MAR", + 4 => "APR", + 5 => "MAY", + 6 => "JUN", + 7 => "JUL", + 8 => "AUG", + 9 => "SEP", + 10 => "OCT", + 11 => "NOV", + 12 => "DEC", + _ => "LIVE", + } + } +} + +fn parse_concert_date_parts(raw: &str, ru: bool) -> (String, String, Option) { + let trimmed = raw.trim(); + // ISO-8601 e.g. "2026-05-15T19:00:00+03:00" or "2026-05-15" + if trimmed.len() >= 10 + && trimmed.as_bytes()[4] == b'-' + && trimmed.as_bytes()[7] == b'-' + { + if let (Ok(m), Ok(d)) = (trimmed[5..7].parse::(), trimmed[8..10].parse::()) { + let time = if trimmed.len() >= 16 + && (trimmed.as_bytes()[10] == b'T' || trimmed.as_bytes()[10] == b' ') + { + let hhmm = &trimmed[11..16]; + if hhmm != "00:00" { + Some(hhmm.to_string()) + } else { + None + } + } else { + None + }; + return (d.to_string(), month_short(m, ru).to_string(), time); + } + } + // DD.MM.YYYY + let dot_parts: Vec<&str> = trimmed.split(['.', ' ', ',']).filter(|s| !s.is_empty()).collect(); + if dot_parts.len() >= 2 { + if let (Ok(d), Ok(m)) = (dot_parts[0].parse::(), dot_parts[1].parse::()) { + if (1..=31).contains(&d) && (1..=12).contains(&m) { + let time = dot_parts + .iter() + .find(|p| p.contains(':') && p.len() >= 4) + .map(|s| s.chars().take(5).collect()); + return (d.to_string(), month_short(m, ru).to_string(), time); + } + } + } + // Human readable e.g. "15 мая, 19:00" or "15 May 20:00" + let tokens: Vec<&str> = trimmed + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|s| !s.is_empty()) + .collect(); + if tokens.len() >= 2 && tokens[0].chars().all(|c| c.is_ascii_digit()) { + let day = tokens[0].to_string(); + let mon: String = tokens[1].chars().take(3).collect::().to_uppercase(); + let time = tokens + .iter() + .skip(2) + .find(|p| p.contains(':')) + .map(|s| s.chars().take(5).collect()); + return (day, mon, time); + } + let fallback = trimmed.chars().take(6).collect::(); + if fallback.is_empty() { + ("•".into(), "LIVE".into(), None) + } else { + (fallback, if ru { "АФИША" } else { "SHOW" }.into(), None) + } +} + +fn draw_cashback_pill(ctx: &mut UiContext, pos_right_or_left: Pos2, align_right: bool, label: &str) -> Rect { + let style = TextStyle::bold(11.5, Color::WHITE); + let tw = ctx.measure_text(label, style, None).x; + let w = (tw + 18.0).ceil(); + let h = 22.0; + let x = if align_right { + pos_right_or_left.x - w + } else { + pos_right_or_left.x + }; + let pill = Rect::from_xywh(x, pos_right_or_left.y, w, h); + ctx.dl().push_gradient_rect( + pill, + 11.0, + Color::rgb(0xFF, 0x3B, 0x7F), + Color::rgb(0x7B, 0x42, 0xFF), + Vec2::new(1.0, 0.0), + ); + ctx.draw_text_ellipsis(label, style, pill, TextAlign::Center); + pill +} + +/// 1-to-1 Official Books & Podcasts (`non_music`) landing page (100% theme-aware & RU/EN localized): +/// - Category filter tabs (`Все` / `Подкасты` / `Аудиокниги` / `Моя полка`) +/// - Animated loading shimmer + Refresh action when empty +/// - "Продолжить слушать" horizontal shelf +/// - Every official skeleton section from `app.non_music_sections` with `<` `>` carousel arrows +/// - Filtered Podcasts, Audiobooks & My Shelf grids with right-click context menus pub fn render_podcasts( ctx: &mut UiContext, pal: &YmPalette, @@ -45,13 +318,34 @@ pub fn render_podcasts( let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; + // Header + Refresh pill + let title_w = (avail_w - 132.0).max(180.0); ctx.draw_text_ellipsis( t.books_and_podcasts(), TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), + Rect::from_xywh(x, y, title_w, 42.0), TextAlign::Left, ); + let refresh_label = if ru { "Обновить" } else { "Refresh" }; + let refresh_tw = ctx + .measure_text(refresh_label, TextStyle::medium(13.5, pal.text_primary), None) + .x; + let refresh_w = (refresh_tw + 28.0).ceil(); + let (ref_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("pod_refresh_top"), + Pos2::new(x + avail_w - refresh_w, y + 4.0), + None, + refresh_label, + 34.0, + false, + ); + if ref_resp.clicked { + actions.push(AppAction::RefreshNonMusic); + } y += 46.0; + ctx.draw_text_ellipsis( if ru { "Шоу, интервью, аудиокниги и новые выпуски каждый день" @@ -64,13 +358,17 @@ pub fn render_podcasts( ); y += 32.0; - // Category filter tabs (All / Podcasts / Audiobooks) + // Category filter tabs (All / Podcasts / Audiobooks / My shelf) let active_tab = shell.podcast_filter_tab; - let mut tx = x; + let tabs_vp = Rect::from_xywh(x, y, avail_w, 40.0); + let tabs_h_id = WidgetId::new("pod_tabs_hscroll"); + let tabs_sx = ctx.begin_scroll_h(tabs_h_id, tabs_vp, 0.0); + let mut tx = x - tabs_sx; for (idx, label) in [ (0u8, t.search_all()), (1u8, if ru { "Подкасты" } else { "Podcasts" }), (2u8, t.audiobooks()), + (3u8, if ru { "Моя полка" } else { "My shelf" }), ] { let (resp, r) = secondary_pill_button( ctx, @@ -87,67 +385,139 @@ pub fn render_podcasts( } tx = r.right() + 8.0; } - y += 52.0; + ctx.end_scroll_h(tabs_h_id, pal, (tx + tabs_sx) - x, false); + y += 54.0; - // Merge bookshelf_items + landing.podcasts cleanly + // Collect deduplicated catalog from bookshelf + landing.podcasts + non_music_sections let mut all_items: Vec = Vec::new(); + let mut audiobook_ids: std::collections::HashSet = std::collections::HashSet::new(); for item in app.bookshelf_items.iter().chain(app.landing.podcasts.iter()) { + if is_audiobook_item(item) { + audiobook_ids.insert(item.id.clone()); + } if !all_items.iter().any(|existing| existing.id == item.id) { all_items.push(item.clone()); } } + for sec in &app.non_music_sections { + let sec_is_book = is_audiobook_section(&sec.id, &sec.block_type, &sec.title); + for alb in &sec.albums { + if sec_is_book || is_audiobook_item(alb) { + audiobook_ids.insert(alb.id.clone()); + } + if !all_items.iter().any(|existing| existing.id == alb.id) { + all_items.push(alb.clone()); + } + } + } - if all_items.is_empty() { - ctx.draw_text_ellipsis( + let has_any_content = !all_items.is_empty() + || app + .non_music_sections + .iter() + .any(|s| !s.albums.is_empty() || !s.playlists.is_empty()); + + if !has_any_content && app.non_music_loading { + ctx.request_repaint(); + let t_sec = app.start_time.elapsed().as_secs_f32() * 3.0; + let card_w = 168.0; + let card_h = card_w + 54.0; + for row_idx in 0..2 { + let head_col = shimmer_color(pal, t_sec + row_idx as f32 * 0.7); + ctx.dl() + .push_rect(Rect::from_xywh(x, y, 210.0, 22.0), 6.0, head_col); + y += 34.0; + let count = ((avail_w + 16.0) / (card_w + 16.0)).floor().clamp(2.0, 6.0) as usize; + for i in 0..count { + let cx = x + i as f32 * (card_w + 16.0); + let col = shimmer_color(pal, t_sec + i as f32 * 0.45 + row_idx as f32 * 0.8); + ctx.dl() + .push_rect(Rect::from_xywh(cx, y, card_w, card_w), 12.0, col); + ctx.dl().push_rect( + Rect::from_xywh(cx, y + card_w + 10.0, card_w * 0.78, 14.0), + 5.0, + col, + ); + ctx.dl().push_rect( + Rect::from_xywh(cx, y + card_w + 30.0, card_w * 0.52, 12.0), + 5.0, + col, + ); + } + y += card_h + 26.0; + } + } else if !has_any_content { + ctx.draw_text_wrapped( if ru { - "Загрузка подкастов и книг…" + "Подкасты и аудиокниги пока не загрузились. Нажмите «Обновить», чтобы повторить запрос." } else { - "Loading podcasts & audiobooks…" + "Podcasts and audiobooks haven't loaded yet. Click Refresh to try again." }, TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), + Rect::from_xywh(x, y, avail_w, 44.0), + Some(2), TextAlign::Left, ); - y += 32.0; + y += 52.0; + let (btn, _) = yellow_pill_button( + ctx, + pal, + WidgetId::new("pod_empty_refresh"), + Pos2::new(x, y), + None, + refresh_label, + 38.0, + false, + ); + if btn.clicked { + actions.push(AppAction::RefreshNonMusic); + } + y += 56.0; } else { - // 1. "Continue listening" horizontal shelf (bookshelf + recently played podcasts/books) - let mut continue_items: Vec = Vec::new(); - for tr in &app.play_history { - if let Some(ref aid) = tr.album_id { - if let Some(found) = all_items.iter().find(|it| &it.id == aid) { - if !continue_items.iter().any(|c| c.id == found.id) { - continue_items.push(found.clone()); - } - } + // Helper to draw a horizontal shelf of albums + playlists with `<` `>` carousel arrows + let draw_shelf = |ctx: &mut UiContext, + covers: &mut CoverCache, + shell: &mut ShellUiState, + actions: &mut Vec, + title: &str, + salt: &str, + albums: &[AlbumSummary], + playlists: &[PlaylistSummary], + start_y: f32| + -> f32 { + let total_cards = albums.len() + playlists.len(); + if total_cards == 0 { + return start_y; } - } - for item in &app.bookshelf_items { - if !continue_items.iter().any(|c| c.id == item.id) { - continue_items.push(item.clone()); - } - } - if continue_items.is_empty() { - continue_items = all_items.iter().take(4).cloned().collect(); - } + let card_w = 168.0; + let card_h = card_w + 54.0; + let gap = 16.0; + let h_id = WidgetId::from_pair("pod_shelf_h", salt); - if active_tab == 0 && !continue_items.is_empty() { + let mut cur_y = start_y; ctx.draw_text_ellipsis( - t.continue_listening(), + title, TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), + Rect::from_xywh(x, cur_y, (avail_w - 80.0).max(160.0), 28.0), TextAlign::Left, ); - y += 38.0; + draw_carousel_arrows( + ctx, + pal, + h_id, + x + avail_w, + cur_y + 14.0, + (card_w + gap) * 3.0, + ); + cur_y += 38.0; - let card_w = 164.0; - let card_h = card_w + 54.0; - let row_vp = Rect::from_xywh(x, y, avail_w, card_h); - let h_id = WidgetId::new("pod_continue_hscroll"); + let row_vp = Rect::from_xywh(x, cur_y, avail_w, card_h); let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); let mut cx = x - sx; - for item in continue_items.iter().take(12) { - let cr = Rect::from_xywh(cx, y, card_w, card_h); - if cr.right() >= row_vp.left() - 20.0 && cr.left() <= row_vp.right() + 20.0 { + + for item in albums { + let cr = Rect::from_xywh(cx, cur_y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { let sub = item .artists .first() @@ -163,12 +533,12 @@ pub fn render_podcasts( ctx, pal, covers, - WidgetId::from_pair("pod_cont", &item.id), + WidgetId::from_pair(salt, format!("a_{}", item.id)), cr, &item.title, sub, item.cover_uri.as_deref(), - &format!("podc_{}", item.id), + &format!("{}_{}", salt, item.id), false, false, ); @@ -197,30 +567,62 @@ pub fn render_podcasts( })); } } - cx += card_w + 16.0; + cx += card_w + gap; } - ctx.end_scroll_h( - h_id, - pal, - continue_items.len().min(12) as f32 * (card_w + 16.0), - false, - ); - y += card_h + 28.0; - } - let mut podcasts_only: Vec = Vec::new(); - let mut audiobooks_only: Vec = Vec::new(); - for item in &all_items { - if is_audiobook_item(item) { - audiobooks_only.push(item.clone()); - } else { - podcasts_only.push(item.clone()); + for pl in playlists { + let cr = Rect::from_xywh(cx, cur_y, card_w, card_h); + if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let sub = pl.description.as_deref().unwrap_or(t.playlist()); + let m = media_card( + ctx, + pal, + covers, + WidgetId::from_pair(salt, format!("p_{}_{}", pl.owner_uid, pl.kind)), + cr, + &pl.title, + sub, + pl.cover_uri.as_deref(), + &format!("{}_pl_{}_{}", salt, pl.owner_uid, pl.kind), + false, + false, + ); + if let Some(pos) = m.right_clicked_pos { + shell.open_entity_menu(EntityContextMenuState { + kind: "playlist".into(), + id: format!("{}:{}", pl.owner_uid, pl.kind), + title: pl.title.clone(), + subtitle: sub.to_string(), + cover_uri: pl.cover_uri.clone(), + owner_uid: Some(pl.owner_uid.clone()), + is_own_playlist: false, + tracks: Vec::new(), + anchor: pos, + share_url: format!( + "https://music.yandex.ru/users/{}/playlists/{}", + pl.owner_uid, pl.kind + ), + }); + } else if m.play_clicked { + actions.push(AppAction::PlayPlaylist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + }); + } else if m.clicked { + actions.push(AppAction::Navigate(Route::Playlist { + owner_uid: pl.owner_uid.clone(), + kind: pl.kind.clone(), + title: pl.title.clone(), + })); + } + } + cx += card_w + gap; } - } - // If API metadata did not tag audiobooks separately, surface bookshelf items in Audiobooks too - if audiobooks_only.is_empty() && !app.bookshelf_items.is_empty() { - audiobooks_only = app.bookshelf_items.clone(); - } + + ctx.end_scroll_h(h_id, pal, total_cards as f32 * (card_w + gap), false); + cur_y + card_h + 28.0 + }; // Helper closure to render a podcast/audiobook grid with right-click context menu let draw_grid = |ctx: &mut UiContext, @@ -233,7 +635,7 @@ pub fn render_podcasts( start_y: f32| -> f32 { let gap = 16.0; - let cols = ((avail_w + gap) / 196.0).floor().clamp(2.0, 6.0) as usize; + let cols = ((avail_w + gap) / 192.0).floor().clamp(2.0, 6.0) as usize; let card_w = ((avail_w - gap * (cols as f32 - 1.0)) / cols as f32).max(140.0); let card_h = card_w + 54.0; for (idx, pod) in items.iter().enumerate() { @@ -304,59 +706,224 @@ pub fn render_podcasts( start_y + rows as f32 * (card_h + 18.0) + 20.0 }; - // 2. Podcasts Section - if (active_tab == 0 || active_tab == 1) && !podcasts_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { "Подкасты" } else { "Podcasts" }, - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - y = draw_grid( - ctx, - covers, - shell, - actions, - &podcasts_only, - "pod_card", - if ru { "Подкаст" } else { "Podcast" }, - y, - ); + let mut podcasts_only: Vec = Vec::new(); + let mut audiobooks_only: Vec = Vec::new(); + for item in &all_items { + if audiobook_ids.contains(&item.id) || is_audiobook_item(item) { + audiobooks_only.push(item.clone()); + } else { + podcasts_only.push(item.clone()); + } + } + if audiobooks_only.is_empty() && !app.bookshelf_items.is_empty() { + audiobooks_only = app.bookshelf_items.clone(); } - // 3. Audiobooks Section - if active_tab == 0 || active_tab == 2 { - ctx.draw_text_ellipsis( - t.audiobooks(), - TextStyle::headline(22.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 28.0), - TextAlign::Left, - ); - y += 38.0; - if audiobooks_only.is_empty() { - ctx.draw_text_ellipsis( - if ru { - "Добавляйте аудиокниги на книжную полку — они появятся здесь." + match active_tab { + 0 => { + // 1. "Continue listening" horizontal shelf + let mut continue_items: Vec = Vec::new(); + for tr in &app.play_history { + if let Some(ref aid) = tr.album_id { + if let Some(found) = all_items.iter().find(|it| &it.id == aid) { + if !continue_items.iter().any(|c| c.id == found.id) { + continue_items.push(found.clone()); + } + } + } + } + for item in &app.bookshelf_items { + if !continue_items.iter().any(|c| c.id == item.id) { + continue_items.push(item.clone()); + } + } + if continue_items.is_empty() { + continue_items = all_items.iter().take(6).cloned().collect(); + } + if !continue_items.is_empty() { + let empty_pl: [PlaylistSummary; 0] = []; + let slice_len = continue_items.len().min(12); + y = draw_shelf( + ctx, + covers, + shell, + actions, + t.continue_listening(), + "pod_continue", + &continue_items[..slice_len], + &empty_pl, + y, + ); + } + + // 2. Render EVERY official skeleton section from `app.non_music_sections` + let sections = app.non_music_sections.clone(); + let mut rendered_sections = 0usize; + for (sidx, sec) in sections.iter().enumerate() { + if sec.albums.is_empty() && sec.playlists.is_empty() { + continue; + } + let sec_title = if sec.title.trim().is_empty() { + if ru { "Подборка" } else { "Selection" } } else { - "Save audiobooks to your bookshelf and they will appear here." - }, - TextStyle::regular(14.0, pal.text_secondary), - Rect::from_xywh(x, y, avail_w, 24.0), + sec.title.as_str() + }; + let salt = format!("nm_sec_{}_{}", sidx, sec.id); + y = draw_shelf( + ctx, + covers, + shell, + actions, + sec_title, + &salt, + &sec.albums, + &sec.playlists, + y, + ); + rendered_sections += 1; + } + + // Fallback grids if skeleton sections weren't returned yet + if rendered_sections == 0 { + if !podcasts_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { "Подкасты" } else { "Podcasts" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + y = draw_grid( + ctx, + covers, + shell, + actions, + &podcasts_only, + "pod_card", + if ru { "Подкаст" } else { "Podcast" }, + y, + ); + } + if !audiobooks_only.is_empty() { + ctx.draw_text_ellipsis( + t.audiobooks(), + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + y = draw_grid( + ctx, + covers, + shell, + actions, + &audiobooks_only, + "book_card", + t.audiobooks(), + y, + ); + } + } + } + 1 => { + ctx.draw_text_ellipsis( + if ru { "Подкасты" } else { "Podcasts" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), TextAlign::Left, ); - y += 32.0; - } else { - y = draw_grid( - ctx, - covers, - shell, - actions, - &audiobooks_only, - "book_card", + y += 38.0; + if podcasts_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Подкасты не найдены." + } else { + "No podcasts found." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), + TextAlign::Left, + ); + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &podcasts_only, + "pod_tab_card", + if ru { "Подкаст" } else { "Podcast" }, + y, + ); + } + } + 2 => { + ctx.draw_text_ellipsis( t.audiobooks(), - y, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, ); + y += 38.0; + if audiobooks_only.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Добавляйте аудиокниги на книжную полку — они появятся здесь." + } else { + "Save audiobooks to your bookshelf and they will appear here." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), + TextAlign::Left, + ); + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &audiobooks_only, + "book_tab_card", + t.audiobooks(), + y, + ); + } + } + _ => { + ctx.draw_text_ellipsis( + if ru { "Моя полка" } else { "My shelf" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + let shelf_items = app.bookshelf_items.clone(); + if shelf_items.is_empty() { + ctx.draw_text_ellipsis( + if ru { + "Сохраняйте любимые подкасты и аудиокниги — они появятся на вашей полке." + } else { + "Save podcasts and audiobooks to see them on your shelf." + }, + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, y, avail_w, 24.0), + TextAlign::Left, + ); + y += 32.0; + } else { + y = draw_grid( + ctx, + covers, + shell, + actions, + &shelf_items, + "shelf_card", + t.audiobooks(), + y, + ); + } } } } @@ -488,7 +1055,11 @@ pub fn render_kids( ctx.end_scroll_v(scroll_id, pal, total_h, true); } -/// Real Concerts Feed powered by `GET /concerts/feed`. +/// 1-to-1 Official Concerts Page (`ConcertsPage` + `ConcertCard_root__fcR9B`): +/// - City filter pills ("Все города" + unique cities) +/// - Animated shimmer while loading + Refresh action when empty +/// - Top Featured Concerts 3-card poster grid with frosted date badge + Plus cashback pill + price CTA +/// - Upcoming Concerts Feed with 68x74 date block, 60x60 cover, metadata + cashback pill, and price/tickets CTA pub fn render_concerts( ctx: &mut UiContext, pal: &YmPalette, @@ -507,13 +1078,34 @@ pub fn render_concerts( let avail_w = (rect.width() - 6.0).max(320.0); let mut y = rect.top() + 8.0 - scroll_y; + // Header + Refresh button + let refresh_label = if ru { "Обновить" } else { "Refresh" }; + let refresh_tw = ctx + .measure_text(refresh_label, TextStyle::medium(13.5, pal.text_primary), None) + .x; + let refresh_w = (refresh_tw + 28.0).ceil(); + ctx.draw_text_ellipsis( t.concerts(), TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(x, y, avail_w, 42.0), + Rect::from_xywh(x, y, (avail_w - refresh_w - 16.0).max(160.0), 42.0), TextAlign::Left, ); + let (ref_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("concerts_refresh_top"), + Pos2::new(x + avail_w - refresh_w, y + 4.0), + None, + refresh_label, + 34.0, + false, + ); + if ref_resp.clicked { + actions.push(AppAction::RefreshConcerts); + } y += 46.0; + ctx.draw_text_ellipsis( if ru { "Афиша ближайших выступлений любимых исполнителей" @@ -524,19 +1116,128 @@ pub fn render_concerts( Rect::from_xywh(x, y, avail_w, 22.0), TextAlign::Left, ); - y += 38.0; + y += 32.0; - if app.concerts.is_empty() { + let concerts = app.concerts.clone(); + + // Collect unique cities for filter pills + let mut cities: Vec = Vec::new(); + for c in &concerts { + let city = c.city.trim(); + if !city.is_empty() && !cities.iter().any(|existing| existing == city) { + cities.push(city.to_string()); + } + } + + let mut selected_city = CONCERT_CITY_FILTER.with(|cell| cell.borrow().clone()); + if let Some(ref sc) = selected_city { + if !cities.iter().any(|c| c == sc) { + selected_city = None; + CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = None); + } + } + + if !cities.is_empty() { + let pills_vp = Rect::from_xywh(x, y, avail_w, 40.0); + let pills_h_id = WidgetId::new("concerts_city_pills"); + let sx = ctx.begin_scroll_h(pills_h_id, pills_vp, 0.0); + let mut px = x - sx; + + let all_label = if ru { "Все города" } else { "All cities" }; + let (all_resp, all_r) = secondary_pill_button( + ctx, + pal, + WidgetId::new("concerts_city_all"), + Pos2::new(px, y), + None, + all_label, + 34.0, + selected_city.is_none(), + ); + if all_resp.clicked { + selected_city = None; + CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = None); + } + px = all_r.right() + 8.0; + + for (ci, city) in cities.iter().enumerate() { + let is_active = selected_city.as_deref() == Some(city.as_str()); + let (c_resp, c_r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("concerts_city", ci), + Pos2::new(px, y), + None, + city, + 34.0, + is_active, + ); + if c_resp.clicked { + selected_city = Some(city.clone()); + CONCERT_CITY_FILTER.with(|cell| *cell.borrow_mut() = Some(city.clone())); + } + px = c_r.right() + 8.0; + } + ctx.end_scroll_h(pills_h_id, pal, (px + sx) - x, false); + y += 50.0; + } + + let filtered: Vec<&ConcertItem> = concerts + .iter() + .filter(|c| match selected_city.as_deref() { + Some(city) => c.city.trim() == city, + None => true, + }) + .collect(); + + if concerts.is_empty() && app.concerts_loading { + ctx.request_repaint(); + let t_sec = app.start_time.elapsed().as_secs_f32() * 3.0; + + // 3 featured shimmer poster cards + let gap = 16.0; + let f_cols = if avail_w >= 860.0 { + 3usize + } else if avail_w >= 560.0 { + 2 + } else { + 1 + }; + let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).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, 210.0), + 16.0, + col, + ); + } + y += 236.0; + + // 4 shimmer feed rows + for i in 0..4 { + let col = shimmer_color(pal, t_sec + 1.2 + i as f32 * 0.45); + ctx.dl() + .push_rect(Rect::from_xywh(x, y, avail_w, 92.0), 14.0, col); + y += 104.0; + } + } else if filtered.is_empty() { let msg = if app.account.is_none() { if ru { "Войдите в аккаунт Яндекс ID, чтобы видеть персональную афишу концертов." } else { "Sign in with Yandex ID to see personalized upcoming concerts." } + } else if selected_city.is_some() { + if ru { + "В выбранном городе ближайших концертов не найдено." + } else { + "No upcoming concerts found in the selected city." + } } else if ru { - "Ближайшие концерты не найдены или ещё загружаются." + "Ближайшие концерты не найдены. Попробуйте обновить афишу." } else { - "No upcoming concerts found or still loading." + "No upcoming concerts found. Try refreshing the feed." }; ctx.draw_text_wrapped( msg, @@ -545,13 +1246,193 @@ pub fn render_concerts( Some(2), TextAlign::Left, ); - y += 48.0; + y += 50.0; + let (btn, _) = yellow_pill_button( + ctx, + pal, + WidgetId::new("concerts_empty_refresh"), + Pos2::new(x, y), + None, + refresh_label, + 38.0, + false, + ); + if btn.clicked { + actions.push(AppAction::RefreshConcerts); + } + y += 54.0; } else { - let concerts = app.concerts.clone(); - for (idx, c) in concerts.iter().enumerate() { - let cr = Rect::from_xywh(x, y, avail_w, 94.0); + // --------------------------------------------------------------------- + // 1. TOP FEATURED CONCERTS GRID (first up to 3 concerts) + // --------------------------------------------------------------------- + let featured_count = filtered.len().min(3); + let gap = 16.0; + let f_cols = if avail_w >= 860.0 { + featured_count.min(3) + } else if avail_w >= 560.0 { + featured_count.min(2) + } else { + 1 + } + .max(1); + let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).clamp(240.0, 440.0); + let f_h = 216.0; + + ctx.draw_text_ellipsis( + if ru { "Рекомендуем" } else { "Featured" }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + + for (i, c) in filtered.iter().take(featured_count).enumerate() { + let col = i % f_cols; + let row = i / f_cols; + let cr = Rect::from_xywh( + x + col as f32 * (f_w + gap), + y + row as f32 * (f_h + gap), + f_w, + f_h, + ); if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { - let resp = ctx.interact(WidgetId::from_pair("concert_card", idx), cr); + let resp = ctx.interact(WidgetId::from_pair("concert_feat", i), cr); + + // Full-bleed cover poster + draw_cover_art( + ctx, + pal, + covers, + cr, + c.cover_uri.as_deref(), + &c.id, + 16.0, + false, + false, + ); + + // Rich dark bottom gradient scrim for legible white text on any artwork + ctx.dl().push_gradient_rect( + cr, + 16.0, + Color::from_rgba(12, 12, 16, if resp.hovered { 32 } else { 52 }), + Color::from_rgba(10, 10, 14, 232), + Vec2::new(0.0, 1.0), + ); + ctx.dl().push_rect_bordered( + cr, + 16.0, + Color::TRANSPARENT, + 1.0, + Color::from_rgba(255, 255, 255, if resp.hovered { 48 } else { 24 }), + ); + + // Top-left frosted date pill + let (day_s, mon_s, time_opt) = parse_concert_date_parts(&c.date, ru); + let date_chip = format!("{} {}", day_s, mon_s); + let date_style = TextStyle::bold(12.0, Color::WHITE); + let dtw = ctx.measure_text(&date_chip, date_style, None).x; + let date_r = Rect::from_xywh(cr.left() + 14.0, cr.top() + 14.0, (dtw + 20.0).ceil(), 26.0); + ctx.dl().push_rect_bordered( + date_r, + 13.0, + Color::from_rgba(14, 14, 18, 188), + 1.0, + Color::from_rgba(255, 255, 255, 36), + ); + ctx.draw_text_ellipsis(&date_chip, date_style, date_r, TextAlign::Center); + + // Top-right Plus cashback pill + if let Some(cb) = format_cashback_label(c, ru) { + draw_cashback_pill(ctx, Pos2::new(cr.right() - 14.0, cr.top() + 16.0), true, &cb); + } + + // Bottom-right price/tickets yellow CTA + let ticket_label = format_ticket_label(c, ru); + let btn_style = TextStyle::bold(12.5, pal.on_yellow); + let btn_w = (ctx.measure_text(&ticket_label, btn_style, None).x + 24.0) + .clamp(88.0, 144.0) + .ceil(); + let btn_r = Rect::from_xywh( + cr.right() - btn_w - 14.0, + cr.bottom() - 48.0, + btn_w, + 34.0, + ); + ctx.dl().push_rect(btn_r, 17.0, pal.yellow); + ctx.draw_text_ellipsis(&ticket_label, btn_style, btn_r, TextAlign::Center); + + // Bottom-left title + venue + let heading = if c.artist_name.is_empty() { + c.title.clone() + } else if c.title.is_empty() || c.title == c.artist_name { + c.artist_name.clone() + } else { + format!("{} · {}", c.artist_name, c.title) + }; + let info_w = (btn_r.left() - cr.left() - 24.0).max(90.0); + ctx.draw_text_ellipsis( + &heading, + TextStyle::bold(17.0, Color::WHITE), + Rect::from_xywh(cr.left() + 14.0, cr.bottom() - 56.0, info_w, 24.0), + TextAlign::Left, + ); + let mut meta_parts: Vec<&str> = Vec::new(); + if !c.city.is_empty() { + meta_parts.push(c.city.as_str()); + } + if !c.place.is_empty() { + meta_parts.push(c.place.as_str()); + } + let time_str = time_opt.as_deref().unwrap_or(""); + if !time_str.is_empty() { + meta_parts.push(time_str); + } + ctx.draw_text_ellipsis( + &meta_parts.join(" · "), + TextStyle::regular(12.5, Color::from_rgba(255, 255, 255, 210)), + Rect::from_xywh(cr.left() + 14.0, cr.bottom() - 31.0, info_w, 18.0), + TextAlign::Left, + ); + + if resp.hovered && c.afisha_url.is_some() { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked { + if let Some(ref url) = c.afisha_url { + actions.push(AppAction::OpenUrl(url.clone())); + } + } + } + } + let f_rows = featured_count.div_ceil(f_cols); + y += f_rows as f32 * (f_h + gap) + 18.0; + + // --------------------------------------------------------------------- + // 2. UPCOMING CONCERTS FEED (`ConcertCard_root__fcR9B`) + // --------------------------------------------------------------------- + let feed_items = if filtered.len() > 3 { + &filtered[3..] + } else { + &filtered[..] + }; + + ctx.draw_text_ellipsis( + if ru { + "Ближайшие концерты" + } else { + "Upcoming concerts" + }, + TextStyle::headline(22.0, pal.text_bright), + Rect::from_xywh(x, y, avail_w, 28.0), + TextAlign::Left, + ); + y += 38.0; + + for (idx, c) in feed_items.iter().enumerate() { + let cr = Rect::from_xywh(x, y, avail_w, 96.0); + if cr.bottom() >= rect.top() - 40.0 && cr.top() <= rect.bottom() + 40.0 { + let resp = ctx.interact(WidgetId::from_pair("concert_feed_row", idx), cr); ctx.dl().push_rect_bordered( cr, 14.0, @@ -563,7 +1444,32 @@ pub fn render_concerts( 1.0, pal.border_subtle, ); - let cov_r = Rect::from_xywh(cr.left() + 14.0, cr.top() + 14.0, 66.0, 66.0); + + // Left 68x74 rounded Date Block (big bold day + short uppercase month) + let (day_s, mon_s, time_opt) = parse_concert_date_parts(&c.date, ru); + let date_r = Rect::from_xywh(cr.left() + 12.0, cr.center_y() - 37.0, 68.0, 74.0); + ctx.dl().push_rect_bordered( + date_r, + 11.0, + pal.bg_content, + 1.0, + pal.border_subtle, + ); + ctx.draw_text_ellipsis( + &day_s, + TextStyle::headline(24.0, pal.text_bright), + Rect::from_xywh(date_r.left() + 4.0, date_r.top() + 12.0, date_r.w - 8.0, 30.0), + TextAlign::Center, + ); + ctx.draw_text_ellipsis( + &mon_s, + TextStyle::bold(11.5, pal.text_secondary), + Rect::from_xywh(date_r.left() + 4.0, date_r.top() + 44.0, date_r.w - 8.0, 18.0), + TextAlign::Center, + ); + + // 60x60 thumbnail + let cov_r = Rect::from_xywh(date_r.right() + 14.0, cr.center_y() - 30.0, 60.0, 60.0); draw_cover_art( ctx, pal, @@ -576,6 +1482,40 @@ pub fn render_concerts( false, ); + // Right CTA button (128x38) + let ticket_label = format_ticket_label(c, ru); + let btn_w = 128.0; + let btn_r = Rect::from_xywh( + cr.right() - btn_w - 16.0, + cr.center_y() - 19.0, + btn_w, + 38.0, + ); + if c.afisha_url.is_some() { + ctx.dl().push_rect(btn_r, 19.0, pal.yellow); + ctx.draw_text_ellipsis( + &ticket_label, + TextStyle::bold(13.0, pal.on_yellow), + btn_r, + TextAlign::Center, + ); + } else { + ctx.dl().push_rect_bordered( + btn_r, + 19.0, + pal.surface_hover, + 1.0, + pal.border_subtle, + ); + ctx.draw_text_ellipsis( + &ticket_label, + TextStyle::medium(13.0, pal.text_secondary), + btn_r, + TextAlign::Center, + ); + } + + // Middle info column: title + city/place/time + Plus cashback pill let heading = if c.artist_name.is_empty() { c.title.clone() } else if c.title.is_empty() || c.title == c.artist_name { @@ -584,37 +1524,42 @@ pub fn render_concerts( format!("{} · {}", c.artist_name, c.title) }; let text_x = cov_r.right() + 16.0; - let text_w = (cr.right() - text_x - 136.0).max(100.0); + let text_w = (btn_r.left() - text_x - 14.0).max(100.0); + let cashback = format_cashback_label(c, ru); + + let title_y = if cashback.is_some() { + cr.top() + 13.0 + } else { + cr.top() + 21.0 + }; ctx.draw_text_ellipsis( &heading, TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(text_x, cr.top() + 20.0, text_w, 24.0), - TextAlign::Left, - ); - let meta: Vec<&str> = [c.date.as_str(), c.city.as_str(), c.place.as_str()] - .into_iter() - .filter(|s| !s.is_empty()) - .collect(); - ctx.draw_text_ellipsis( - &meta.join(" · "), - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(text_x, cr.top() + 50.0, text_w, 20.0), + Rect::from_xywh(text_x, title_y, text_w, 24.0), TextAlign::Left, ); - if c.afisha_url.is_some() { - let btn_r = Rect::from_center_size( - Pos2::new(cr.right() - 68.0, cr.center_y()), - Vec2::new(108.0, 34.0), - ); - ctx.dl().push_rect(btn_r, 17.0, pal.yellow); - ctx.draw_text_ellipsis( - if ru { "Билеты" } else { "Tickets" }, - TextStyle::bold(13.0, pal.on_yellow), - btn_r, - TextAlign::Center, - ); + let mut meta: Vec<&str> = Vec::new(); + if !c.city.is_empty() { + meta.push(c.city.as_str()); } + if !c.place.is_empty() { + meta.push(c.place.as_str()); + } + if let Some(ref tm) = time_opt { + meta.push(tm.as_str()); + } + ctx.draw_text_ellipsis( + &meta.join(" · "), + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(text_x, title_y + 26.0, text_w, 20.0), + TextAlign::Left, + ); + + if let Some(cb) = cashback { + draw_cashback_pill(ctx, Pos2::new(text_x, title_y + 49.0), false, &cb); + } + if resp.hovered && c.afisha_url.is_some() { ctx.set_cursor(CursorKind::Pointer); } @@ -624,7 +1569,7 @@ pub fn render_concerts( } } } - y += 104.0; + y += 106.0; } } diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index fc00273..a963dd9 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -1863,3 +1863,384 @@ fn test_ext_16_yandex_id_popup_and_words_card_visual_parity() { ); } } + +#[test] +fn test_ext_17_for_you_collection_concerts_words_fullscreen() { + use yandex_music_rs::api::models::{ + AlbumSummary, ConcertItem, NewReleaseItem, VibePickItem, VibePickTab, WordsBigCard, + WordsCard, WordsCardSource, + }; + use yandex_music_rs::engine::WidgetId; + + let rt = tokio::runtime::Runtime::new().unwrap(); + let mut vk = HeadlessVulkanRenderer::new(NATIVE_W, NATIVE_H).expect("Vulkan init failed"); + let out_dir = output_dir(); + let _ = std::fs::create_dir_all(&out_dir); + + // 1. Official `For You` scrolled down: sticky frosted header + circular NewReleases + More Picks (`for_you_new_releases_picks.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::ForYou, + ThemeMode::Dark, + Language::En, + 0.0, + ); + let mk_album = |id: &str, title: &str, artist: &str| AlbumSummary { + id: id.into(), + title: title.into(), + year: Some(2026), + cover_uri: None, + artists: vec![ArtistSummary { + id: format!("art_{id}"), + name: artist.into(), + cover_uri: None, + genres: vec![], + }], + track_count: 12, + genre: Some("electronic".into()), + is_explicit: false, + content_type: Some("album".into()), + }; + shell.app.landing.rich_new_releases = vec![ + NewReleaseItem { + album: mk_album("nr1", "Neon Horizon", "SALUKI"), + artist_cover_uri: None, + cover_color: Some("#3B4CA8".into()), + release_date: Some("2026-11-20".into()), + }, + NewReleaseItem { + album: mk_album("nr2", "Velvet Pulse", "Mirele"), + artist_cover_uri: None, + cover_color: Some("#7B2D5F".into()), + release_date: Some("2026-11-18".into()), + }, + NewReleaseItem { + album: mk_album("nr3", "Night Drive", "SLAVA MARLOW"), + artist_cover_uri: None, + cover_color: Some("#1E6B52".into()), + release_date: Some("2026-11-15".into()), + }, + NewReleaseItem { + album: mk_album("nr4", "Solar Flare", "OG BLESS"), + artist_cover_uri: None, + cover_color: Some("#8F4A1E".into()), + release_date: Some("2026-11-12".into()), + }, + ]; + shell.app.landing.vibe_pick_tabs = vec![ + VibePickTab { + title: "Mood".into(), + items: vec![ + VibePickItem { + title: "Energetic".into(), + header: "Vibe".into(), + seeds: vec!["mood:energetic".into()], + color_hex: Some("#D94E2A".into()), + background_image_url: None, + image_url: None, + }, + VibePickItem { + title: "Night Focus".into(), + header: "Vibe".into(), + seeds: vec!["mood:calm".into()], + color_hex: Some("#2F55A4".into()), + background_image_url: None, + image_url: None, + }, + VibePickItem { + title: "Dreamy Synth".into(), + header: "Vibe".into(), + seeds: vec!["genre:electronic".into()], + color_hex: Some("#7C3AED".into()), + background_image_url: None, + image_url: None, + }, + ], + }, + VibePickTab { + title: "Activity".into(), + items: vec![VibePickItem { + title: "Workout".into(), + header: "Vibe".into(), + seeds: vec!["activity:workout".into()], + color_hex: Some("#0F766E".into()), + background_image_url: None, + image_url: None, + }], + }, + VibePickTab { + title: "Genres".into(), + items: vec![], + }, + ]; + + // Warm up layout so scroll content height is computed, then scroll to show New Releases + More Picks + sticky switcher + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + shell + .ui + .scrolls + .jump_to_y(WidgetId::new("foryou_page_scroll"), 860.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.032); + let img = render_single_frame(&mut vk, &mut shell, 0.048); + let _ = img.save(out_dir.join("for_you_new_releases_picks.png")); + + // Verify colored NewRelease cards / More Picks cards rendered non-flat rich pixels in content card + let mut colored_px = 0usize; + for y in 110..680 { + for x in 250..1240 { + let [r, g, b] = img.get_pixel(x, y).0; + let max_c = r.max(g).max(b); + let min_c = r.min(g).min(b); + if max_c.saturating_sub(min_c) >= 24 { + colored_px += 1; + } + } + } + assert!( + colored_px > 5_000, + "[for_you_new_releases_picks] Expected colored New Releases / More Picks cards, found only {} chromatic px", + colored_px + ); + } + + // 2. Official `My Collection` vertical feed (`my_collection_official.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::Collection, + ThemeMode::Dark, + Language::En, + 0.0, + ); + let extra_tracks = [ + ("c_1", "MONTAGEM TENTA", "KYOR", 141_000), + ("c_2", "Midnight Sun", "SuperSolar", 184_000), + ("c_3", "BANG A RANG", "GSTRNM", 100_000), + ("c_4", "BOSS BITCH TEKK", "wharoxmane", 107_000), + ("c_5", "Neon Rain", "Mirele", 192_000), + ("c_6", "Skyline Pulse", "SALUKI", 168_000), + ("c_7", "Electric Horizon", "SLAVA MARLOW", 155_000), + ("c_8", "Deep Focus", "OG BLESS", 210_000), + ]; + shell.app.liked_tracks = extra_tracks + .iter() + .map(|(id, title, art, dur)| Track { + id: (*id).into(), + title: (*title).into(), + version: None, + artists: vec![ArtistSummary { + id: format!("ca_{id}"), + name: (*art).into(), + cover_uri: None, + genres: vec![], + }], + album_id: Some(format!("calb_{id}")), + album_title: Some((*title).into()), + duration_ms: *dur, + cover_uri: None, + is_explicit: false, + has_lossless: true, + has_lyrics: true, + chart_position: None, + chart_progress: None, + preview_url: None, + r128_i: None, + r128_tp: None, + derived_average_hex: None, + derived_accent_hex: None, + }) + .collect(); + shell.app.liked_artists = ["SALUKI", "Mirele", "KYOR", "SuperSolar", "GSTRNM", "OG BLESS"] + .iter() + .enumerate() + .map(|(i, name)| ArtistSummary { + id: format!("la_{i}"), + name: (*name).into(), + cover_uri: None, + genres: vec![], + }) + .collect(); + + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + let img = render_single_frame(&mut vk, &mut shell, 0.032); + let _ = img.save(out_dir.join("my_collection_official.png")); + + // Verify pink-magenta colored "color" word in subtitle + crimson 3D heart icon present, + // and ZERO old yellow-bordered My Favorites hero card! + let mut pink_subtitle_px = 0usize; + for y in 75..125 { + for x in 250..520 { + let [r, g, b] = img.get_pixel(x, y).0; + if r > 170 && b > 100 && (r as u16) > (g as u16) + 50 { + pink_subtitle_px += 1; + } + } + } + assert!( + pink_subtitle_px >= 15, + "[my_collection_official] Expected magenta-colored subtitle word 'color', found {} px", + pink_subtitle_px + ); + } + + // 3. Official `ConcertsPage` (`concerts_official.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::Concerts, + ThemeMode::Dark, + Language::Ru, + 0.0, + ); + shell.app.concerts = vec![ + ConcertItem { + id: "con_1".into(), + title: "SALUKI — Большой сольный концерт".into(), + artist_name: "SALUKI".into(), + city: "Москва".into(), + place: "VK Stadium".into(), + date: "14 дек, 20:00".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(2500), + currency: Some("RUB".into()), + cashback_percent: Some(15), + cashback_title: Some("Кешбэк 15%".into()), + cover_color: Some("#4C2A85".into()), + event_kind: Some("concert".into()), + }, + ConcertItem { + id: "con_2".into(), + title: "Mirele — Акустический вечер".into(), + artist_name: "Mirele".into(), + city: "Санкт-Петербург".into(), + place: "A2 Green Concert".into(), + date: "21 дек, 19:30".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(1900), + currency: Some("RUB".into()), + cashback_percent: Some(10), + cashback_title: None, + cover_color: Some("#1D5B79".into()), + event_kind: Some("concert".into()), + }, + ConcertItem { + id: "con_3".into(), + title: "SLAVA MARLOW — Live Tour".into(), + artist_name: "SLAVA MARLOW".into(), + city: "Казань".into(), + place: "Korston Club Hotel".into(), + date: "28 дек, 20:00".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(2200), + currency: Some("RUB".into()), + cashback_percent: Some(20), + cashback_title: None, + cover_color: Some("#8C2F39".into()), + event_kind: Some("concert".into()), + }, + ConcertItem { + id: "con_4".into(), + title: "Электрофорез — Зимний сет".into(), + artist_name: "Электрофорез".into(), + city: "Москва".into(), + place: "Урбан".into(), + date: "5 янв, 20:00".into(), + cover_uri: None, + afisha_url: Some("https://afisha.yandex.ru".into()), + min_price: Some(1700), + currency: Some("RUB".into()), + cashback_percent: Some(10), + cashback_title: None, + cover_color: Some("#2D4F1E".into()), + event_kind: Some("concert".into()), + }, + ]; + + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + let img = render_single_frame(&mut vk, &mut shell, 0.032); + let _ = img.save(out_dir.join("concerts_official.png")); + + // Verify Top 3 colored poster cards + upcoming feed rendered cleanly + let mut poster_chromatic_px = 0usize; + 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 { + poster_chromatic_px += 1; + } + } + } + assert!( + poster_chromatic_px > 10_000, + "[concerts_official] Expected Top 3 concert poster cards + cashback pills, found {} chromatic px", + poster_chromatic_px + ); + } + + // 4. Official `WordsCardFullscreen` (`words_fullscreen_official.png`) + { + let mut shell = make_base_shell( + rt.handle().clone(), + vk.gpu_name.clone(), + Route::MyVibe, + ThemeMode::Dark, + Language::Ru, + 108.0, + ); + shell.app.words_cards.insert( + "t_1".into(), + WordsCard { + id: "wc_fs_1".into(), + track_id: "t_1".into(), + text: "MONTAGEM TENTA сочетает бразильский фонк и жёсткие хардстайл-кики.".into(), + tags: vec!["FACT".into()], + action: None, + actions: vec![], + big_card_ids: vec!["bc_1".into()], + feedback_state: None, + }, + ); + shell.app.words_big_card_open = true; + shell.app.words_big_card_loading = false; + shell.app.words_big_card = Some(WordsBigCard { + id: "bc_1".into(), + text: "MONTAGEM TENTA (Hardstyle) — взрывной кроссовер бразильского фонка и европейского хардстайла с плотным саб-басом и стремительным ритмом.".into(), + actions: vec![WordsCardSource { + title: "Обсудить с Алисой AI".into(), + url: "https://alice.yandex.ru".into(), + favicon_url: None, + }], + }); + + let _ = render_single_frame(&mut vk, &mut shell, 0.0); + let _ = render_single_frame(&mut vk, &mut shell, 0.016); + let img = render_single_frame(&mut vk, &mut shell, 0.032); + let _ = img.save(out_dir.join("words_fullscreen_official.png")); + + // Verify purple Alice ring (#8B5CF6) rendered inside the centered source pill + let mut alice_purple_px = 0usize; + for y in 360..600 { + for x in 560..960 { + let [r, g, b] = img.get_pixel(x, y).0; + if b > 160 && r > 90 && (b as u16) > (g as u16) + 50 { + alice_purple_px += 1; + } + } + } + assert!( + alice_purple_px >= 15, + "[words_fullscreen_official] Expected purple Alice AI icon inside source pill, found {} px", + alice_purple_px + ); + } +} From 8b0276616004630309e54f37bc99daed90c477d5 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 14:36:18 +0300 Subject: [PATCH 03/17] fix: eliminate white window flash on startup with hidden init and dark Win32 brush --- src/main.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index afd9149..ca96fe6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -135,7 +135,8 @@ fn build_window_attrs(init_w: f64, init_h: f64) -> WindowAttributes { .with_inner_size(LogicalSize::new(init_w, init_h)) .with_min_inner_size(LogicalSize::new(768.0, 650.0)) .with_decorations(false) // Custom frameless 32px Yandex TitleBar! - .with_resizable(true); + .with_resizable(true) + .with_visible(false); // Stay hidden until DWM + first pure-black/splash frame is presented! #[cfg(target_os = "linux")] { use winit::platform::wayland::WindowAttributesExtWayland; @@ -628,6 +629,17 @@ impl ApplicationHandler for AppRunner { self.window_focused = true; self.window_occluded = false; self.last_frame_hash = None; + + // Present the first theme-matched + splash frame into the swapchain BEFORE making the + // window visible so there is zero white OS/DWM flash on startup! + // (On Linux/Wayland where an unmapped window may report 0x0, skip pre-render and reveal.) + let init_size = window.inner_size(); + if init_size.width > 0 && init_size.height > 0 { + self.render(event_loop); + self.last_frame_hash = None; + } + window.set_visible(true); + window.focus_window(); window.request_redraw(); } @@ -880,6 +892,76 @@ fn apply_win11_dwm_style(window: &Window, is_dark: bool) { &round as *const _ as *const _, std::mem::size_of::() as u32, ); + // DWMWA_CAPTION_COLOR (35): pure black in dark mode, pure white in light mode + const DWMWA_CAPTION_COLOR: u32 = 35; + let caption_color: u32 = if is_dark { 0x0000_0000 } else { 0x00FF_FFFF }; + DwmSetWindowAttribute( + hwnd, + DWMWA_CAPTION_COLOR, + &caption_color as *const _ as *const _, + std::mem::size_of::() as u32, + ); + + // Replace Win32 class background brush (BLACK_BRUSH=4 / WHITE_BRUSH=0) & prime + // the client backing surface so Win32 never flashes white before or during resize. + #[repr(C)] + struct WinRect { + left: i32, + top: i32, + right: i32, + bottom: i32, + } + #[link(name = "gdi32")] + extern "system" { + fn GetStockObject(i: i32) -> *mut std::ffi::c_void; + } + #[link(name = "user32")] + extern "system" { + #[cfg(target_pointer_width = "64")] + fn SetClassLongPtrW( + hwnd: *mut std::ffi::c_void, + index: i32, + new_long: isize, + ) -> isize; + #[cfg(target_pointer_width = "32")] + fn SetClassLongW( + hwnd: *mut std::ffi::c_void, + index: i32, + new_long: i32, + ) -> i32; + fn GetClientRect(hwnd: *mut std::ffi::c_void, rect: *mut WinRect) -> i32; + fn GetDC(hwnd: *mut std::ffi::c_void) -> *mut std::ffi::c_void; + fn FillRect( + hdc: *mut std::ffi::c_void, + rect: *const WinRect, + hbr: *mut std::ffi::c_void, + ) -> i32; + fn ReleaseDC(hwnd: *mut std::ffi::c_void, hdc: *mut std::ffi::c_void) -> i32; + } + const WHITE_BRUSH: i32 = 0; + const BLACK_BRUSH: i32 = 4; + const GCLP_HBRBACKGROUND: i32 = -10; + let brush = GetStockObject(if is_dark { BLACK_BRUSH } else { WHITE_BRUSH }); + if !brush.is_null() { + #[cfg(target_pointer_width = "64")] + SetClassLongPtrW(hwnd, GCLP_HBRBACKGROUND, brush as isize); + #[cfg(target_pointer_width = "32")] + SetClassLongW(hwnd, GCLP_HBRBACKGROUND, brush as i32); + + let mut rc = WinRect { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + if GetClientRect(hwnd, &mut rc) != 0 { + let hdc = GetDC(hwnd); + if !hdc.is_null() { + FillRect(hdc, &rc, brush); + ReleaseDC(hwnd, hdc); + } + } + } } } } From 84d9c6756cb6120adc71dc6c57cc4a08311daee4 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 14:37:52 +0300 Subject: [PATCH 04/17] docs: require permanent Forgejo PAT (provider=generic) and pre-flight auth check in AGENTS.md --- AGENTS.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index df81f9c..cb3d43d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,35 @@ # Инструкция для AI-агентов (Git, коммиты и релизы на git.tatar) Этот репозиторий хостится на **Forgejo** (`https://git.tatar/marwy/yandex-music-rs`). -В системе (Windows Credential Manager) уже сохранён рабочий токен для `https://git.tatar` (`git:https://git.tatar`). +Авторизация на `https://git.tatar` должна храниться в Windows Credential Manager как **бессрочный Personal Access Token (PAT)** с `credential.https://git.tatar.provider = generic` (НЕ через OAuth-окно GCM — OAuth-токен Forgejo протухает через ~1 час, после чего `git push` удаляет запись из Credential Manager). > **ВАЖНО:** > 1. **НИКОГДА не используй браузер** для создания релизов, загрузки ассетов или настройки репозитория на `git.tatar` — браузер не авторизован и упрётся в страницу логина. Все операции с `git.tatar` выполняются через **Forgejo REST API v1** с токеном из `git credential fill`. > 2. **НИКОГДА не печатай токен** в stdout, логи, файлы или ответы пользователю. > 3. **НИКОГДА не коммить** `target/`, `original_yandex_music/`, `Yandex_Music_*.exe`, локальные `.deb`/`.exe`/`.tar.gz` и личные OAuth-токены Яндекс Музыки. +> 4. **Перед `git push` проверяй токен без интерактива** (`$env:GCM_INTERACTIVE = "never"` + `GET https://git.tatar/api/v1/user`): если токен отсутствует или истёк (401), не вешай `git push` на невидимом окне GCM — сразу попроси пользователя сохранить бессрочный PAT из `https://git.tatar/user/settings/applications` (см. раздел 0). + +--- + +## 0. Первичная настройка бессрочного токена (делается пользователем 1 раз) + +Если токен отсутствует или протух (401), пользователь создаёт **Access Token** на `https://git.tatar/user/settings/applications` (права: `write:repository`, `read:user`) и сохраняет его один раз: + +```powershell +git config --global credential.https://git.tatar.provider generic +"protocol=https`nhost=git.tatar`nusername=marwy`npassword=`n" | git credential approve +``` + +Проверка из агента (никогда не выводить `$token`, всегда ставить `GCM_INTERACTIVE=never`): + +```powershell +$env:GCM_INTERACTIVE = "never" +$credOut = "protocol=https`nhost=git.tatar`n`n" | git credential fill 2>$null +$token = ($credOut | Where-Object { $_ -like 'password=*' }) -replace '^password=','' +if (-not $token) { throw "No token in Credential Manager (need PAT for git.tatar)" } +$u = Invoke-RestMethod -Uri "https://git.tatar/api/v1/user" -Headers @{ Authorization = "token $token" } +Write-Output ("AUTH_OK: " + $u.login) +``` --- From bd16a9c703c976d484c97b7e524399109d549ad5 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 14:39:41 +0300 Subject: [PATCH 05/17] fix: use neutral dark/light popover styling for hover tooltips --- src/engine/mod.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 7dea5c8..2a284a4 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -117,7 +117,8 @@ 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_sz = self.measure_text(&label, TextStyle::medium(12.0, Color::WHITE), None); + let text_style = TextStyle::medium(12.0, pal.text_primary); + let text_sz = self.measure_text(&label, text_style, None); let tip_w = text_sz.x + pad_x * 2.0; let tip_h = 26.0; let screen = self.input.screen_size; @@ -132,15 +133,16 @@ 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), 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, - ); + .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); self.set_layer(prev); } From 19ceef9f74ba1298a109e9ace1db4ca314b7445d Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 17:05:07 +0300 Subject: [PATCH 06/17] docs: enforce immutable releases and tags rule in AGENTS.md --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index cb3d43d..71a710f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ > 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`), чтобы у клиентов никогда не было разных бинарников под одним номером версии и автообновление работало корректно. --- From 0b2561503f8f8c4d5cbec2e32abb24bded2d3325 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 17:25:15 +0300 Subject: [PATCH 07/17] perf(linux): cut OpenGL RSS via isolated auth/Vulkan helpers, malloc_trim, 1024 atlas (v0.1.3) --- Cargo.lock | 2 +- Cargo.toml | 20 +++++++++-- README.md | 8 ++--- packaging/build-deb.sh | 7 +++- src/bin/yandex_music_auth.rs | 3 ++ src/engine/text.rs | 2 +- src/main.rs | 38 +++++++++++++++++++- src/native/mod.rs | 49 +++++++++++++++++++------ src/telemetry.rs | 69 ++++++++++++++++++++++++++++++++++-- 9 files changed, 175 insertions(+), 23 deletions(-) create mode 100644 src/bin/yandex_music_auth.rs diff --git a/Cargo.lock b/Cargo.lock index 7a8c5c6..f6bd874 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6325,7 +6325,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.2" +version = "0.1.3" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index a38b710..f9a987d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,22 @@ [package] name = "yandex-music-rs" -version = "0.1.2" +version = "0.1.3" 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" @@ -68,8 +81,8 @@ windows-sys = { version = "0.59", features = [ ] } [target.'cfg(target_os = "linux")'.dependencies] -wry = { version = "0.51", default-features = false, features = ["os-webview"] } -gtk = "0.18" +wry = { version = "0.51", default-features = false, features = ["os-webview"], optional = true } +gtk = { version = "0.18", optional = true } [build-dependencies] naga = { version = "24", features = ["wgsl-in", "spv-out"] } @@ -94,6 +107,7 @@ recommends = "libvulkan1, mesa-vulkan-drivers, libgl1, libegl1" maintainer-scripts = "packaging/debian" assets = [ ["target/release/yandex-music-rs", "usr/bin/", "755"], + ["target/release/yandex-music-auth", "usr/bin/", "755"], ["assets/icons/app_icon.png", "usr/share/pixmaps/yandex-music-rs.png", "644"], ["assets/icons/app_48.png", "usr/share/icons/hicolor/48x48/apps/yandex-music-rs.png", "644"], ["packaging/icons/64x64.png", "usr/share/icons/hicolor/64x64/apps/yandex-music-rs.png", "644"], diff --git a/README.md b/README.md index b45bb03..52e3451 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.2-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.2-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.3-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.3-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.2-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.3-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.2-linux-x86_64.tar.gz` с готовым бинарником. +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.3-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности diff --git a/packaging/build-deb.sh b/packaging/build-deb.sh index da914ef..8b2664e 100755 --- a/packaging/build-deb.sh +++ b/packaging/build-deb.sh @@ -13,5 +13,10 @@ else fi cd "$PROJECT_DIR" -cargo deb --output "$PROJECT_DIR/target/debian/" +# 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/" ls -lh "$PROJECT_DIR/target/debian/"*.deb diff --git a/src/bin/yandex_music_auth.rs b/src/bin/yandex_music_auth.rs new file mode 100644 index 0000000..142d8cd --- /dev/null +++ b/src/bin/yandex_music_auth.rs @@ -0,0 +1,3 @@ +fn main() { + yandex_music_rs::native::run_auth_webview_subprocess(); +} diff --git a/src/engine/text.rs b/src/engine/text.rs index fe6ff44..3c578c2 100644 --- a/src/engine/text.rs +++ b/src/engine/text.rs @@ -13,7 +13,7 @@ use crate::engine::types::{ Color, DisplayList, Pos2, Rect, Vec2, GLYPH_ATLAS_TEXTURE_ID, }; -const ATLAS_SIZE: u32 = 2048; +const ATLAS_SIZE: u32 = 1024; /// The 4 official Yandex Music 5.129.0 font roles loaded from `assets/fonts/`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/src/main.rs b/src/main.rs index ca96fe6..3de1b03 100644 --- a/src/main.rs +++ b/src/main.rs @@ -169,6 +169,32 @@ 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! @@ -413,7 +439,12 @@ 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 { @@ -561,7 +592,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 VulkanContext::has_hardware_vulkan() { + if has_hardware_vulkan_isolated() { match init_vulkan_backend(event_loop, init_w, init_h) { Ok(pair) => pair, Err(vk_err) => { @@ -1028,6 +1059,11 @@ fn acquire_single_instance_lock() -> bool { } fn main() { + // Isolated Vulkan HW probe subprocess (keeps libvulkan_lvp / libLLVM out of main Linux RSS) + if std::env::args().any(|a| a == "--probe-vulkan") { + std::process::exit(if VulkanContext::has_hardware_vulkan() { 0 } else { 1 }); + } + // Isolated zero-resident-RAM WebView2 OAuth subprocess (exits immediately after login!) if std::env::args().any(|a| a == "--auth-webview") { run_auth_webview_subprocess(); diff --git a/src/native/mod.rs b/src/native/mod.rs index 3e97f70..e44da3f 100644 --- a/src/native/mod.rs +++ b/src/native/mod.rs @@ -451,13 +451,9 @@ mod imp { mod imp { use super::NativeEvent; use crate::api::models::Track; - use crate::api::signing::extract_oauth_token; - use crate::api::YANDEX_OAUTH_URL; - use gtk::prelude::*; - use std::io::{BufRead, BufReader, Write}; + use std::io::{BufRead, BufReader}; use std::process::{Command, Stdio}; use winit::window::Window; - use wry::{WebViewBuilder, WebViewBuilderExtUnix}; const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:"; @@ -480,8 +476,17 @@ mod imp { winit::window::Icon::from_rgba(img.into_raw(), w, h).ok() } - /// Entry point for the short-lived `--auth-webview` subprocess on Linux (GTK3 + WebKitGTK). + /// 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")] 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"); @@ -554,14 +559,38 @@ mod imp { gtk::main(); } - /// Spawn the isolated `--auth-webview` subprocess and return the captured OAuth token. + #[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. pub fn spawn_auth_webview_subprocess() -> anyhow::Result { let exe = std::env::current_exe()?; - let mut child = Command::new(exe) - .arg("--auth-webview") + 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") .stdout(Stdio::piped()) .stderr(Stdio::null()) - .spawn()?; + .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"); + }; let stdout = child .stdout diff --git a/src/telemetry.rs b/src/telemetry.rs index 2df9633..1f5995f 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -61,7 +61,17 @@ impl PerfTelemetry { } } - #[cfg(not(windows))] + #[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"))))] pub fn trim_working_set() {} #[cfg(windows)] @@ -86,7 +96,62 @@ impl PerfTelemetry { } } - #[cfg(not(windows))] + #[cfg(target_os = "linux")] + pub fn sample_memory(&mut self) { + fn parse_kb_line(line: &str, prefix: &str) -> Option { + let rest = line.strip_prefix(prefix)?; + rest.split_whitespace().next()?.parse::().ok() + } + + if let Ok(rollup) = std::fs::read_to_string("/proc/self/smaps_rollup") { + let mut rss_kb: Option = None; + let mut pss_kb: Option = None; + let mut priv_clean_kb: u64 = 0; + let mut priv_dirty_kb: u64 = 0; + let mut has_priv = false; + for line in rollup.lines() { + if let Some(v) = parse_kb_line(line, "Rss:") { + rss_kb = Some(v); + } else if let Some(v) = parse_kb_line(line, "Pss:") { + pss_kb = Some(v); + } else if let Some(v) = parse_kb_line(line, "Private_Clean:") { + priv_clean_kb = v; + has_priv = true; + } else if let Some(v) = parse_kb_line(line, "Private_Dirty:") { + priv_dirty_kb = v; + has_priv = true; + } + } + if let Some(rss) = rss_kb { + self.working_set_mb = rss as f32 / 1024.0; + let priv_kb = if has_priv { + priv_clean_kb.saturating_add(priv_dirty_kb) + } else { + pss_kb.unwrap_or(rss) + }; + self.private_mb = priv_kb as f32 / 1024.0; + return; + } + } + + if let Ok(status) = std::fs::read_to_string("/proc/self/status") { + let mut rss_kb: Option = None; + let mut anon_kb: Option = None; + for line in status.lines() { + if let Some(v) = parse_kb_line(line, "VmRSS:") { + rss_kb = Some(v); + } else if let Some(v) = parse_kb_line(line, "RssAnon:") { + anon_kb = Some(v); + } + } + if let Some(rss) = rss_kb { + self.working_set_mb = rss as f32 / 1024.0; + self.private_mb = anon_kb.unwrap_or(rss) as f32 / 1024.0; + } + } + } + + #[cfg(not(any(windows, target_os = "linux")))] pub fn sample_memory(&mut self) { self.working_set_mb = 28.0; self.private_mb = 22.0; From f06338241068798dbb81d73d1ca0b4e0240c2978 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 18:11:16 +0300 Subject: [PATCH 08/17] chore(release): v0.1.4 - 1:1 SyncLyrics, scroll isolation, object-fit cover, Concerts icon, friends' likes & duplicate-title albums --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 +- .../icons/navigationConcerts_selected_xs.svg | 6 +- src/api/demo_data.rs | 11 + src/api/mod.rs | 457 ++++++++++++++---- src/api/models.rs | 22 + src/app/state.rs | 94 +++- src/covers.rs | 39 +- src/engine/mod.rs | 22 + src/engine/scroll.rs | 2 +- src/engine/text.rs | 62 +++ src/engine/widgets.rs | 51 +- src/views/collection.rs | 41 +- src/views/detail.rs | 16 +- src/views/for_you.rs | 27 +- src/views/overlays.rs | 391 ++++++++++----- src/views/podcasts_kids.rs | 11 +- src/views/search.rs | 32 +- src/views/sidebar.rs | 4 +- tests/parity_extended.rs | 275 ++++++++++- 21 files changed, 1287 insertions(+), 288 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f6bd874..2384686 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6325,7 +6325,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.3" +version = "0.1.4" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index f9a987d..7a0d324 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.3" +version = "0.1.4" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" diff --git a/README.md b/README.md index 52e3451..5a4182e 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.3-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.3-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.4-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.4-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.3-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.4-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.3-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.4-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности diff --git a/assets/icons/navigationConcerts_selected_xs.svg b/assets/icons/navigationConcerts_selected_xs.svg index 5216578..06aacdc 100644 --- a/assets/icons/navigationConcerts_selected_xs.svg +++ b/assets/icons/navigationConcerts_selected_xs.svg @@ -1,3 +1,3 @@ - - - \ No newline at end of file + + + diff --git a/src/api/demo_data.rs b/src/api/demo_data.rs index 70a3a7c..9de951a 100644 --- a/src/api/demo_data.rs +++ b/src/api/demo_data.rs @@ -92,6 +92,7 @@ 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 & Эндшпиль")], @@ -103,6 +104,7 @@ 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")], @@ -114,6 +116,7 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_3".into(), title: "Зеркала и эхо".into(), + version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a3", "Три дня дождя")], @@ -125,6 +128,7 @@ 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")], @@ -136,6 +140,7 @@ 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")], @@ -147,6 +152,7 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "rel_6".into(), title: "Тихий океан".into(), + version: None, year: Some(2026), cover_uri: None, artists: vec![artist("a6", "Баста")], @@ -234,6 +240,7 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_1".into(), title: "Подкаст «Запуск завтра»".into(), + version: None, year: Some(2026), cover_uri: None, artists: vec![artist("p1", "Самат Галимов")], @@ -245,6 +252,7 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_2".into(), title: "Дневники Лоры Палны".into(), + version: None, year: Some(2026), cover_uri: None, artists: vec![artist("p2", "Студия Терменвокс")], @@ -256,6 +264,7 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_3".into(), title: "Краткая история времени".into(), + version: None, year: Some(2025), cover_uri: None, artists: vec![artist("p3", "Стивен Хокинг (Аудиокнига)")], @@ -267,6 +276,7 @@ pub fn demo_landing() -> LandingData { AlbumSummary { id: "pod_4".into(), title: "Хоббит, или Туда и обратно".into(), + version: None, year: Some(2025), cover_uri: None, artists: vec![artist("p4", "Дж. Р. Р. Толкин")], @@ -557,6 +567,7 @@ pub fn demo_lyrics(track: &Track) -> TrackLyrics { is_synced: true, lines, writers: Some("Яндекс Музыка Rust (Демо-режим)".into()), + major: None, } } diff --git a/src/api/mod.rs b/src/api/mod.rs index 470b1c4..4534a9b 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -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_likes = false; + let mut seen_keys: HashSet<(String, String)> = HashSet::new(); let arr = res["pins"].as_array().or_else(|| res.as_array()); if let Some(items) = arr { for item in items { @@ -679,30 +679,37 @@ impl YandexApiClient { match kind { "playlist" | "playlist_item" | "liked_playlist_item" | "personal_playlist_item" => { if let Some(pl) = parse_playlist(data) { - 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; + // 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 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: 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 - }, + id: pin_id, + kind: pin_kind, + title, subtitle: if ru { "Плейлист".into() } else { "Playlist".into() }, - cover_uri: if is_likes { None } else { pl.cover_uri }, + cover_uri: if is_system_likes { None } else { pl.cover_uri }, owner_uid: Some(pl.owner_uid), }); } @@ -1739,74 +1746,186 @@ impl YandexApiClient { Ok(out) } - pub async fn fetch_liked_albums(&self, uid: u64) -> Result> { - 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); + pub async fn fetch_albums_by_ids(&self, ids: &[String]) -> Result> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let mut out = Vec::with_capacity(ids.len()); + let mut seen = HashSet::new(); + for chunk in ids.chunks(100) { + let joined = chunk.join(","); + if let Ok(res) = self + .post_form("/albums", &[("album-ids", joined)]) + .await + { + let arr = res.as_array().or_else(|| res["albums"].as_array()); + if let Some(items) = arr { + for item in items { + if let Some(alb) = parse_album(item) { + if seen.insert(alb.id.clone()) { + out.push(alb); + } + } + } } } } Ok(out) } - pub async fn fetch_liked_artists(&self, uid: u64) -> Result> { - 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); + pub async fn fetch_artists_by_ids(&self, ids: &[String]) -> Result> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let mut out = Vec::with_capacity(ids.len()); + let mut seen = HashSet::new(); + for chunk in ids.chunks(100) { + let joined = chunk.join(","); + if let Ok(res) = self + .post_form("/artists", &[("artist-ids", joined)]) + .await + { + let arr = res.as_array().or_else(|| res["artists"].as_array()); + if let Some(items) = arr { + for item in items { + if let Some(art) = parse_artist(item) { + if seen.insert(art.id.clone()) { + out.push(art); + } + } + } } } } Ok(out) } + pub async fn fetch_liked_albums(&self, uid: u64) -> Result> { + let mut out: Vec = Vec::new(); + let mut seen_ids: HashSet = HashSet::new(); + let mut bare_ids: Vec = Vec::new(); + let mut seen_bare: HashSet = HashSet::new(); + + for page in 0..5u32 { + let path = format!( + "/users/{}/likes/albums/page?rich=true&metaType=music&page={}&pageSize=100", + uid, page + ); + let Ok(res) = self.get_json(&path).await else { + break; + }; + let (raw_count, page_albs, page_bare) = parse_liked_albums_entries(&res); + for alb in page_albs { + if seen_ids.insert(alb.id.clone()) { + out.push(alb); + } + } + for bid in page_bare { + if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { + bare_ids.push(bid); + } + } + if raw_count < 100 { + break; + } + } + + // Fallback if `/likes/albums/page` failed or returned nothing + if out.is_empty() && bare_ids.is_empty() { + if let Ok(res) = self + .get_json(&format!("/users/{}/likes/albums?rich=true", uid)) + .await + { + let (_, page_albs, page_bare) = parse_liked_albums_entries(&res); + for alb in page_albs { + if seen_ids.insert(alb.id.clone()) { + out.push(alb); + } + } + for bid in page_bare { + if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { + bare_ids.push(bid); + } + } + } + } + + if !bare_ids.is_empty() { + if let Ok(hydrated) = self.fetch_albums_by_ids(&bare_ids).await { + for alb in hydrated { + if seen_ids.insert(alb.id.clone()) { + out.push(alb); + } + } + } + } + + Ok(out) + } + + pub async fn fetch_liked_artists(&self, uid: u64) -> Result> { + let mut out: Vec = Vec::new(); + let mut seen_ids: HashSet = HashSet::new(); + let mut bare_ids: Vec = Vec::new(); + let mut seen_bare: HashSet = HashSet::new(); + + for page in 0..5u32 { + let path = format!( + "/users/{}/likes/artists/page?page={}&pageSize=100", + uid, page + ); + let Ok(res) = self.get_json(&path).await else { + break; + }; + let (raw_count, page_arts, page_bare) = parse_liked_artists_entries(&res); + for art in page_arts { + if seen_ids.insert(art.id.clone()) { + out.push(art); + } + } + for bid in page_bare { + if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { + bare_ids.push(bid); + } + } + if raw_count < 100 { + break; + } + } + + // Fallback if `/likes/artists/page` failed or returned empty! + if out.is_empty() && bare_ids.is_empty() { + if let Ok(res) = self + .get_json(&format!("/users/{}/likes/artists", uid)) + .await + { + let (_, page_arts, page_bare) = parse_liked_artists_entries(&res); + for art in page_arts { + if seen_ids.insert(art.id.clone()) { + out.push(art); + } + } + for bid in page_bare { + if !seen_ids.contains(&bid) && seen_bare.insert(bid.clone()) { + bare_ids.push(bid); + } + } + } + } + + if !bare_ids.is_empty() { + if let Ok(hydrated) = self.fetch_artists_by_ids(&bare_ids).await { + for art in hydrated { + if seen_ids.insert(art.id.clone()) { + out.push(art); + } + } + } + } + + Ok(out) + } + pub async fn fetch_bookshelf_liked(&self) -> Result> { let mut out: Vec = Vec::new(); let mut seen: HashSet = HashSet::new(); @@ -1967,10 +2086,7 @@ impl YandexApiClient { .as_array() .map(|a| a.iter().filter_map(parse_track).collect()) .unwrap_or_default(); - let albums = res["albums"] - .as_array() - .map(|a| a.iter().filter_map(parse_album).collect()) - .unwrap_or_default(); + let albums = parse_artist_detail_albums(&res); let similar_artists = res["similarArtists"] .as_array() .map(|a| a.iter().filter_map(parse_artist).collect()) @@ -2478,6 +2594,7 @@ impl YandexApiClient { is_synced: false, lines, writers, + major: None, }); } } @@ -2515,6 +2632,11 @@ 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!( @@ -2533,6 +2655,7 @@ impl YandexApiClient { is_synced: parsed_synced && format == "LRC", lines, writers, + major, }) } @@ -3310,9 +3433,103 @@ fn parse_artist(v: &Value) -> Option { }) } +fn parse_liked_albums_entries(res: &Value) -> (usize, Vec, Vec) { + let arr = res["albums"] + .as_array() + .or_else(|| res["items"].as_array()) + .or_else(|| res["library"]["albums"].as_array()) + .or_else(|| res.as_array()); + let Some(items) = arr else { + return (0, Vec::new(), Vec::new()); + }; + let mut albs = Vec::new(); + let mut bare_ids = Vec::new(); + for item in items { + let parsed = if item["data"]["album"].is_object() { + parse_album_with_fallback_artists(&item["data"]["album"], item["data"].get("artists")) + } else if item["album"].is_object() { + parse_album_with_fallback_artists(&item["album"], item.get("artists")) + } else if item["data"].is_object() { + parse_album_with_fallback_artists(&item["data"], item["data"].get("artists")) + } else { + parse_album(item) + }; + if let Some(alb) = parsed { + albs.push(alb); + } else if let Some(bid) = value_id(&item["id"]) + .or_else(|| value_id(&item["album"]["id"])) + .or_else(|| value_id(&item["data"]["id"])) + { + bare_ids.push(bid); + } + } + (items.len(), albs, bare_ids) +} + +fn parse_liked_artists_entries(res: &Value) -> (usize, Vec, Vec) { + let arr = res["artists"] + .as_array() + .or_else(|| res["items"].as_array()) + .or_else(|| res["library"]["artists"].as_array()) + .or_else(|| res.as_array()); + let Some(items) = arr else { + return (0, Vec::new(), Vec::new()); + }; + let mut arts = Vec::new(); + let mut bare_ids = Vec::new(); + for item in items { + let node = if item["data"]["artist"].is_object() { + &item["data"]["artist"] + } else if item["artist"].is_object() { + &item["artist"] + } else if item["data"].is_object() { + &item["data"] + } else { + item + }; + if let Some(art) = parse_artist(node) { + arts.push(art); + } else if let Some(bid) = value_id(&node["id"]).or_else(|| value_id(&item["id"])) { + bare_ids.push(bid); + } + } + (items.len(), arts, bare_ids) +} + +fn parse_artist_detail_albums(res: &Value) -> Vec { + let mut out = Vec::new(); + let mut seen_ids = HashSet::new(); + for key in ["albums", "alsoAlbums", "discography"] { + if let Some(arr) = res[key].as_array() { + for item in arr { + if let Some(alb) = parse_album(item) { + if seen_ids.insert(alb.id.clone()) { + out.push(alb); + } + } + if let Some(dups) = item["duplicates"].as_array() { + for dup in dups { + if let Some(alb) = parse_album(dup) { + if seen_ids.insert(alb.id.clone()) { + out.push(alb); + } + } + } + } + } + } + } + out +} + fn parse_album(v: &Value) -> Option { let title = v["title"].as_str()?.to_string(); let id = value_id(&v["id"])?; + let version = v["version"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(String::from); let year = v["year"].as_u64().map(|y| y as u32); let cover_uri = v["coverUri"] .as_str() @@ -3334,6 +3551,7 @@ fn parse_album(v: &Value) -> Option { Some(AlbumSummary { id, title, + version, year, cover_uri, artists, @@ -3854,4 +4072,79 @@ 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"]); + } } diff --git a/src/api/models.rs b/src/api/models.rs index fca575f..67344a5 100644 --- a/src/api/models.rs +++ b/src/api/models.rs @@ -24,6 +24,8 @@ pub struct ArtistSummary { pub struct AlbumSummary { pub id: String, pub title: String, + #[serde(default)] + pub version: Option, pub year: Option, pub cover_uri: Option, pub artists: Vec, @@ -35,6 +37,24 @@ pub struct AlbumSummary { pub content_type: Option, } +impl AlbumSummary { + /// Display title including edition/version (e.g. `"Album (Deluxe)"`) when `version` is non-empty + /// and not already present in `title`, so duplicate-title editions stay clearly distinguishable. + pub fn full_title(&self) -> String { + match self + .version + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + { + Some(ver) if !self.title.to_lowercase().contains(&ver.to_lowercase()) => { + format!("{} ({})", self.title, ver) + } + _ => self.title.clone(), + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Track { pub id: String, @@ -158,6 +178,8 @@ pub struct TrackLyrics { pub is_synced: bool, pub lines: Vec, pub writers: Option, + #[serde(default)] + pub major: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/src/app/state.rs b/src/app/state.rs index 652d210..fb5e30e 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -1461,8 +1461,24 @@ 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 { - let _ = tx_c.send(ApiEvent::UserPlaylistsLoaded(pls)); + 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)); } }); } @@ -1779,7 +1795,10 @@ 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(); @@ -1901,20 +1920,8 @@ impl AppState { self.bookshelf_items = items; } ApiEvent::PinsLoaded(mut pins) => { - 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 - }); + let my_uid = self.account.as_ref().map(|a| a.uid); + normalize_pins(&mut pins, my_uid, t.is_ru()); self.config.pinned_items = pins; self.save_config(); } @@ -3039,6 +3046,26 @@ 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, my_uid: Option, ru: bool) { + if let Some(uid) = my_uid { + let my_likes_id = format!("{}:3", uid); + let likes_title = if ru { "Мне нравится" } else { "My Favorites" }; + for p in pins.iter_mut() { + if p.kind == "playlist" && p.id == my_likes_id { + p.id = "likes".into(); + p.kind = "likes".into(); + p.cover_uri = None; + p.title = likes_title.into(); + } + } + } + let mut seen: HashSet<(String, String)> = HashSet::new(); + pins.retain(|p| seen.insert((p.kind.clone(), p.id.clone()))); +} + #[cfg(test)] mod tests { use super::*; @@ -3054,4 +3081,41 @@ 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")); + } } diff --git a/src/covers.rs b/src/covers.rs index 4407d93..06a9534 100644 --- a/src/covers.rs +++ b/src/covers.rs @@ -16,6 +16,8 @@ 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, } @@ -148,6 +150,8 @@ impl CoverCache { texture_id: tex_id, dominant_color: dom, hue, + width: width as u32, + height: height as u32, last_used_frame: frame_id, }, ); @@ -175,6 +179,8 @@ impl CoverCache { texture_id: tex_id, dominant_color: dom, hue, + width: width as u32, + height: height as u32, last_used_frame: frame_id, }, ); @@ -208,6 +214,8 @@ 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, }, ); @@ -246,6 +254,17 @@ 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; } @@ -253,7 +272,13 @@ 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)); + return Some(( + entry.texture_id, + entry.dominant_color, + entry.hue, + entry.width, + entry.height, + )); } // Cross-resolution mipmap reuse: if a higher-resolution variant is already cached, @@ -272,7 +297,13 @@ 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)); + return Some(( + entry.texture_id, + entry.dominant_color, + entry.hue, + entry.width, + entry.height, + )); } if self.in_flight.contains(&hi_url) { return None; @@ -335,7 +366,9 @@ fn decode_and_analyze(bytes: &[u8], target_px: u32) -> Option<(u32, u32, Vec let (ow, oh) = (dyn_img.width(), dyn_img.height()); let max_dim = target_px.max(128); if ow > max_dim || oh > max_dim { - dyn_img = dyn_img.resize_exact(max_dim, max_dim, image::imageops::FilterType::Lanczos3); + // 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); } let rgba = dyn_img.to_rgba8(); let (w, h) = rgba.dimensions(); diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 2a284a4..3a071ba 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -368,6 +368,28 @@ impl UiContext { .draw_text_wrapped(dl, &mut self.textures, text, style, rect, max_lines, align) } + /// Draw wrapped multi-line text vertically centered inside `rect` and uniformly scaled + /// around `rect.center()` by `scale` (CSS `transform: scale(...)` without wrap-jump). + pub fn draw_text_wrapped_scaled( + &mut self, + text: &str, + style: TextStyle, + rect: Rect, + scale: f32, + align: TextAlign, + ) -> Vec2 { + let dl = &mut self.layers[self.current_layer.index()]; + self.text.draw_text_wrapped_scaled( + dl, + &mut self.textures, + text, + style, + rect, + scale, + align, + ) + } + pub fn draw_rich_text( &mut self, spans: &[RichSpan<'_>], diff --git a/src/engine/scroll.rs b/src/engine/scroll.rs index 9755e10..c8f5c22 100644 --- a/src/engine/scroll.rs +++ b/src/engine/scroll.rs @@ -135,7 +135,7 @@ impl ScrollState { if horizontal { let dx = if input.wheel_delta.x.abs() > 0.01 { -input.wheel_delta.x - } else if !vertical || input.modifiers.shift { + } else if input.modifiers.shift { -input.wheel_delta.y } else { 0.0 diff --git a/src/engine/text.rs b/src/engine/text.rs index 3c578c2..22053a0 100644 --- a/src/engine/text.rs +++ b/src/engine/text.rs @@ -452,6 +452,68 @@ impl TextEngine { size } + /// Draw wrapped multi-line text vertically centered inside `rect` and uniformly scaled + /// around `rect.center()` by `scale` (1-to-1 CSS `transform: scale(...)` with zero wrap-jump + /// or fractional-size glyph atlas churn). + #[allow(clippy::too_many_arguments)] + pub fn draw_text_wrapped_scaled( + &mut self, + dl: &mut DisplayList, + textures: &mut TextureRegistry, + text: &str, + style: TextStyle, + rect: Rect, + scale: f32, + align: TextAlign, + ) -> Vec2 { + if text.is_empty() || style.color.a == 0 || rect.w <= 1.0 || scale <= 0.001 { + return Vec2::ZERO; + } + let (key, size) = self.get_or_shape(text, style, Some(rect.w), None, false, align); + let origin = Pos2::new(rect.x, rect.center_y() - size.y * 0.5); + if (scale - 1.0).abs() < 0.0005 { + self.emit_cached_buffer(dl, textures, key, origin, style.color, None); + return size; + } + let Some((buffer, _)) = self.shape_cache.get(&key) else { + return size; + }; + + let dpi = self.scale_factor; + let inv_dpi = 1.0 / dpi; + let origin_px = (origin.x * dpi).round(); + let center = rect.center(); + + let mut glyphs_to_draw = Vec::with_capacity(64); + for run in buffer.layout_runs() { + let baseline_py = ((origin.y + run.line_y) * dpi).floor(); + for glyph in run.glyphs.iter() { + let phys = glyph.physical((0.0, 0.0), dpi); + glyphs_to_draw.push((phys, baseline_py)); + } + } + for (phys, baseline_py) in glyphs_to_draw { + if let Some(entry) = self.atlas.get_or_insert( + phys.cache_key, + &mut self.font_system, + &mut self.swash_cache, + textures, + ) { + let gx = (origin_px + (phys.x + entry.left) as f32) * inv_dpi; + let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_dpi; + let gw = entry.width as f32 * inv_dpi; + let gh = entry.height as f32 * inv_dpi; + + let sx = center.x + (gx - center.x) * scale; + let sy = center.y + (gy - center.y) * scale; + let sw = gw * scale; + let sh = gh * scale; + dl.push_glyph(Rect::from_xywh(sx, sy, sw, sh), entry.uv, style.color); + } + } + size + } + /// Draw multi-span rich text (e.g. clickable `SeparatedArtists` or `Title + Version`) inside `rect`. /// Returns screen-space bounding `Rect`s for every span whose `metadata != 0` so callers can /// perform exact per-span hover & click hit-testing! diff --git a/src/engine/widgets.rs b/src/engine/widgets.rs index b440305..e07daed 100644 --- a/src/engine/widgets.rs +++ b/src/engine/widgets.rs @@ -374,7 +374,32 @@ pub fn draw_plus_badge( (resp, rect) } -/// Draw cover artwork with SDF rounded-rect / circular clip: +/// 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: /// - 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. @@ -399,9 +424,10 @@ 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().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); + 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); return (dom, hue); } } @@ -428,9 +454,10 @@ pub fn draw_cover_art( } if let Some(u) = uri { - 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); + 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); return (dom, hue); } } @@ -1101,8 +1128,9 @@ 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, _, _)) = covers.get_or_fetch(u, 200) { - ctx.dl().push_image(card_r, tex_id, 6.0, Color::WHITE); + 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); drew_tex = true; } } @@ -1181,8 +1209,9 @@ 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, _, _)) = covers.get_or_fetch(u, 400) { - ctx.dl().push_image(img_r, tex_id, 8.0, Color::WHITE); + 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); has_photo = true; } } diff --git a/src/views/collection.rs b/src/views/collection.rs index d7653e9..c81e35b 100644 --- a/src/views/collection.rs +++ b/src/views/collection.rs @@ -352,7 +352,7 @@ pub fn render_collection( cx += card_w + gap; } - for pl in playlists.iter().take(24) { + for (idx, pl) in playlists.iter().take(60).enumerate() { let cr = Rect::from_xywh(cx, y, card_w, card_h); if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { let sub = t.count_tracks(pl.track_count as usize); @@ -363,14 +363,17 @@ pub fn render_collection( ctx, pal, covers, - WidgetId::from_pair("col_ov_pl", format!("{}_{}", pl.owner_uid, pl.kind)), + WidgetId::from_pair( + "col_ov_pl", + (idx, format!("{}_{}", pl.owner_uid, pl.kind)), + ), cr, &pl.title, &sub, pl.cover_uri.as_deref(), &format!("upl_{}_{}", pl.owner_uid, pl.kind), false, - false, + pl.kind == "3" && pl.cover_uri.is_none(), ); if let Some(pos) = m.right_clicked_pos { shell.open_entity_menu(EntityContextMenuState { @@ -407,7 +410,7 @@ pub fn render_collection( ctx.end_scroll_h( h_id, pal, - (playlists.len().min(24) + 1) as f32 * (card_w + gap), + (playlists.len().min(60) + 1) as f32 * (card_w + gap), false, ); y += card_h + 26.0; @@ -454,9 +457,10 @@ pub fn render_collection( let sx = ctx.begin_scroll_h(h_id, row_vp, 0.0); let mut cx = x - sx; - for alb in albums.iter().take(24) { + for (idx, alb) in albums.iter().take(60).enumerate() { let cr = Rect::from_xywh(cx, y, card_w, card_h); if cr.right() >= row_vp.left() - 24.0 && cr.left() <= row_vp.right() + 24.0 { + let alb_title = alb.full_title(); let sub = alb .artists .first() @@ -466,9 +470,9 @@ pub fn render_collection( ctx, pal, covers, - WidgetId::from_pair("col_ov_alb", &alb.id), + WidgetId::from_pair("col_ov_alb", (idx, &alb.id)), cr, - &alb.title, + &alb_title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -479,7 +483,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, @@ -491,12 +495,12 @@ pub fn render_collection( } else if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, })); } } @@ -505,7 +509,7 @@ pub fn render_collection( ctx.end_scroll_h( h_id, pal, - albums.len().min(24) as f32 * (card_w + gap), + albums.len().min(60) as f32 * (card_w + gap), false, ); y += card_h + 26.0; @@ -793,7 +797,7 @@ pub fn render_collection( continue; } let sub = t.count_tracks(pl.track_count as usize); - let wid = WidgetId::from_pair("col_pl", format!("{}_{}", pl.owner_uid, pl.kind)); + let wid = WidgetId::from_pair("col_pl", (i, format!("{}_{}", pl.owner_uid, pl.kind))); let m = media_card( ctx, pal, @@ -805,7 +809,7 @@ pub fn render_collection( pl.cover_uri.as_deref(), &format!("upl_{}_{}", pl.owner_uid, pl.kind), false, - false, + pl.kind == "3" && pl.cover_uri.is_none(), ); // Own playlists (not Liked kind=3) get quick Rename & Delete action icons on hover! @@ -928,6 +932,7 @@ 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() @@ -937,9 +942,9 @@ pub fn render_collection( ctx, pal, covers, - WidgetId::from_pair("col_alb", &alb.id), + WidgetId::from_pair("col_alb", (idx, &alb.id)), cr, - &alb.title, + &alb_title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -950,7 +955,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, @@ -962,12 +967,12 @@ pub fn render_collection( } else if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, })); } } diff --git a/src/views/detail.rs b/src/views/detail.rs index 6deb089..260a7a0 100644 --- a/src/views/detail.rs +++ b/src/views/detail.rs @@ -144,6 +144,7 @@ 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(), @@ -156,7 +157,7 @@ pub fn render_detail( pl_cov, p_seed, false, - false, + is_likes_art, "playlist", p_id, Some(owner_uid), @@ -902,9 +903,10 @@ 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 alb in art_detail.albums.iter().take(16) { + for (idx, alb) in art_detail.albums.iter().take(48).enumerate() { 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()) @@ -913,9 +915,9 @@ pub fn render_detail( ctx, pal, covers, - WidgetId::from_pair("art_alb", &alb.id), + WidgetId::from_pair("art_alb", (idx, &alb.id)), cr, - &alb.title, + &alb_title, &yr, alb.cover_uri.as_deref(), &format!("artalb_{}", alb.id), @@ -925,12 +927,12 @@ pub fn render_detail( if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, })); } } @@ -939,7 +941,7 @@ pub fn render_detail( ctx.end_scroll_h( h_id, pal, - art_detail.albums.len().min(16) as f32 * (card_w + 16.0), + art_detail.albums.len().min(48) as f32 * (card_w + 16.0), false, ); } diff --git a/src/views/for_you.rs b/src/views/for_you.rs index ec0c6c4..5890b7d 100644 --- a/src/views/for_you.rs +++ b/src/views/for_you.rs @@ -465,7 +465,7 @@ pub fn render_for_you( let playlists = app.landing.personal_playlists.clone(); let mut cx = x - scroll_x; - for pl in &playlists { + for (idx, pl) in playlists.iter().enumerate() { 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,7 +473,10 @@ pub fn render_for_you( ctx, pal, covers, - WidgetId::from_pair("fy_pl", format!("{}_{}", pl.owner_uid, pl.kind)), + WidgetId::from_pair( + "fy_pl", + (idx, format!("{}_{}", pl.owner_uid, pl.kind)), + ), cr, &pl.title, sub, @@ -652,14 +655,17 @@ pub fn render_for_you( let playlists = app.landing.popular_playlists.clone(); let mut cx = x - scroll_x; - for pl in &playlists { + for (idx, pl) in playlists.iter().enumerate() { 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", format!("{}_{}", pl.owner_uid, pl.kind)), + WidgetId::from_pair( + "tr_pl", + (idx, format!("{}_{}", pl.owner_uid, pl.kind)), + ), cr, &pl.title, &pl.owner_name, @@ -954,8 +960,9 @@ 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 item in &items { + for (idx, item) in items.iter().enumerate() { let alb = &item.album; + let alb_title = alb.full_title(); let outer_r = Rect::from_xywh(cx, y, card_w, card_h); if outer_r.right() >= row_vp.left() - 80.0 && outer_r.left() <= row_vp.right() + 80.0 { // 1. Huge 236x236 circular artist portrait overlapping the bottom card by 56px @@ -1012,7 +1019,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, @@ -1028,14 +1035,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, format!("port_{}", alb.id)), port_click_r); + let port_resp = ctx.interact(WidgetId::from_pair(salt, (idx, format!("port_{}", alb.id))), port_click_r); if port_resp.hovered { ctx.set_cursor(CursorKind::Pointer); } // 2. Bottom 80px colored rounded release card (`radius: 14px`) let card_r = Rect::from_xywh(cx, y + portrait_d - overlap, card_w, bottom_h); - let card_resp = ctx.interact(WidgetId::from_pair(salt, format!("card_{}", alb.id)), card_r); + let card_resp = ctx.interact(WidgetId::from_pair(salt, (idx, format!("card_{}", alb.id))), card_r); let card_bg = if card_resp.hovered { card_tint.lerp(Color::WHITE, 0.08) } else { @@ -1074,7 +1081,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, format!("play_{}", alb.id)), play_r); + let play_resp = ctx.interact(WidgetId::from_pair(salt, (idx, format!("play_{}", alb.id))), play_r); let play_rad = if play_resp.hovered { 20.0 } else { 19.0 }; ctx.dl().push_circle(play_c, play_rad, Color::WHITE); let alb_playing = app.is_context_playing(&format!("album:{}", alb.id)); @@ -1092,7 +1099,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, diff --git a/src/views/overlays.rs b/src/views/overlays.rs index eea7cde..1cd5781 100644 --- a/src/views/overlays.rs +++ b/src/views/overlays.rs @@ -80,6 +80,8 @@ pub struct ShellUiState { pub queue_drag: Option, pub fs_lyrics_scroll_y: f32, pub fs_lyrics_manual_until: f64, + pub fs_lyrics_upper_until: f64, + pub fs_lyrics_last_mouse: Option, pub fs_lyrics_track_id: String, } @@ -640,37 +642,9 @@ pub fn render_fullscreen_player( ctx.register_blocker(screen); ctx.dl().push_rect(screen, 0.0, bg_color); - // Top-right circular `v` collapse button (`FullscreenPlayerDesktop_closeButton`) - let close_r = Rect::from_center_size( - Pos2::new(screen.right() - 44.0, screen.top() + 56.0), - Vec2::splat(40.0), - ); - let close_resp = ctx.interact(WidgetId::new("fs_close"), close_r); - ctx.dl().push_circle( - close_r.center(), - if close_resp.hovered { 21.0 } else { 20.0 }, - if close_resp.hovered { - css_rgba(255, 255, 255, 36) - } else { - css_rgba(255, 255, 255, 22) - }, - ); - ctx.draw_icon( - Icon::ArrowDown, - Rect::from_center_size(close_r.center(), Vec2::splat(24.0)), - Color::WHITE, - ); - if close_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - ctx.show_tooltip(close_r, i18n.close()); - } - if close_resp.clicked { - actions.push(AppAction::SetFullscreen(false)); - } - - let Some(tr) = track else { - return; - }; + // Render track player + 50/50 split BEFORE top-right `v` collapse button so + // SyncLyrics top gradient fade mask never slices over `FullscreenPlayerDesktop_closeButton`! + if let Some(tr) = track { // Mutually exclusive right split modes (SyncLyrics OR PlayQueue) WITHOUT closing fullscreen! let is_split = app.fullscreen_lyrics_open || app.fullscreen_queue_open; @@ -692,7 +666,8 @@ pub fn render_fullscreen_player( let cx_center = screen.center_x(); let cx_left = screen.left() + screen.width() * 0.25; let cx = cx_center + (cx_left - cx_center) * split_t; - let cov_cy = screen.center_y() - 36.0; + // Center the entire (poster + 110px info) block symmetrically around `screen.center_y()` + let cov_cy = screen.center_y() - 55.0; let cov_r = Rect::from_center_size(Pos2::new(cx, cov_cy), Vec2::splat(cov_sz)); // Soft cover elevation shadow @@ -956,7 +931,7 @@ pub fn render_fullscreen_player( } // Below Cover: Clickable Track Title + Explicit + Individually Clickable Artists - let title_y = cov_r.bottom() + 20.0; + let title_y = cov_r.bottom() + 24.0; let meta_w = cov_sz.max(320.0); let full_title = tr.full_title(); let measured_tw = ctx @@ -1003,7 +978,7 @@ pub fn render_fullscreen_player( } // Individually clickable artists below title (`SeparatedArtists`)! - let art_r = Rect::from_center_size(Pos2::new(cx, title_y + 34.0), Vec2::new(meta_w, 22.0)); + let art_r = Rect::from_xywh(cx - meta_w * 0.5, title_y + 26.0, meta_w, 22.0); if let Some((aid, aname)) = separated_artists( ctx, pal, @@ -1020,7 +995,7 @@ pub fn render_fullscreen_player( } // Progress bar (`ChangeTimecode`: 4px `#E6E6E6` fill/thumb + hover timecodes + smooth drag seek) - let bar_y = title_y + 64.0; + let bar_y = cov_r.bottom() + 86.0; let bar_hit = Rect::from_center_size(Pos2::new(cx, bar_y), Vec2::new(cov_sz, 22.0)); let bar_resp = ctx.interact(WidgetId::new("fs_progress"), bar_hit); let bar_r = Rect::from_center_size(Pos2::new(cx, bar_y), Vec2::new(cov_sz, 4.0)); @@ -1090,13 +1065,24 @@ pub fn render_fullscreen_player( ctx.dl().push_circle(Pos2::new(fill_x, bar_y), 6.0, fill_col); } - // Right-Half 50/50 Animated Pane: SyncLyrics OR PlayQueue! + // Right-Half 50/50 Animated Pane (`FullscreenPlayerDesktopContent_additionalContent`): SyncLyrics OR PlayQueue! if split_t > 0.02 { - let right_rect = Rect::from_min_max( - Pos2::new(screen.left() + screen.width() * 0.48, screen.top() + 56.0), - Pos2::new(screen.right() - 48.0, screen.bottom() - 40.0), - ); + let indent = if screen.width() > 1060.0 { + 44.0 + } else if screen.width() > 960.0 { + 20.0 + } else { + 10.0 + }; + let right_left = screen.left() + screen.width() * 0.50 - indent; + let right_right = (right_left + screen.width() * 0.50).min(screen.right()); + let right_bottom = screen.bottom() - (screen.height() * 0.09).max(56.0); + if app.fullscreen_queue_open { + let right_rect = Rect::from_min_max( + Pos2::new(right_left, screen.top() + 56.0), + Pos2::new((right_right - 48.0).max(right_left + 120.0), right_bottom), + ); ctx.draw_text_ellipsis( i18n.queue(), TextStyle::headline(22.0, Color::WHITE.with_alpha_f32(split_t)), @@ -1119,12 +1105,17 @@ pub fn render_fullscreen_player( actions, ); } else { + let lyr_rect = Rect::from_min_max( + Pos2::new(right_left, screen.top() + 32.0), + Pos2::new(right_right, right_bottom), + ); render_fullscreen_sync_lyrics( ctx, app.current_lyrics.as_ref(), tr, position_ms, - right_rect, + is_playing, + lyr_rect, bg_color, split_t, ru, @@ -1133,13 +1124,41 @@ pub fn render_fullscreen_player( ); } } - // Bottom-right Volume / Mute button with upward 44×216 `ym_volume_capsule` hover popover! - // Smoothly shifts into the left player column when `split_t > 0` so neither the button nor - // its upward popover ever collides with `right_rect` (SyncLyrics / Queue split pane). - let vol_x_centered = screen.right() - 44.0; - let vol_x_split = (screen.left() + screen.width() * 0.48 - 34.0).max(screen.left() + 44.0); - let vol_x = vol_x_centered + (vol_x_split - vol_x_centered) * split_t; - let vol_center = Pos2::new(vol_x, screen.bottom() - 44.0); + } // end `if let Some(tr) = track` + + // Top-right circular `v` collapse button (`FullscreenPlayerDesktop_closeButton`, z-index: header) + let close_r = Rect::from_center_size( + Pos2::new(screen.right() - 44.0, screen.top() + 56.0), + Vec2::splat(40.0), + ); + let close_resp = ctx.interact(WidgetId::new("fs_close"), close_r); + ctx.dl().push_circle( + close_r.center(), + if close_resp.hovered { 21.0 } else { 20.0 }, + if close_resp.hovered { + css_rgba(255, 255, 255, 36) + } else { + css_rgba(255, 255, 255, 22) + }, + ); + ctx.draw_icon( + Icon::ArrowDown, + Rect::from_center_size(close_r.center(), Vec2::splat(24.0)), + Color::WHITE, + ); + if close_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + ctx.show_tooltip(close_r, i18n.close()); + } + if close_resp.clicked { + actions.push(AppAction::SetFullscreen(false)); + } + + if track.is_none() { + return; + } + // Bottom-right Volume / Mute button anchored cleanly at bottom-right aligned with top-right `v`! + let vol_center = Pos2::new(screen.right() - 44.0, screen.bottom() - 40.0); let vol_btn_r = Rect::from_center_size(vol_center, Vec2::splat(40.0)); let vol_resp = ctx.interact(WidgetId::new("fs_vol_btn"), vol_btn_r); let vol_val = app.config.volume; @@ -1207,12 +1226,19 @@ pub fn render_fullscreen_player( }); } +/// 1-to-1 Official `SyncLyrics` (`83ceed5f9f3f6e01.css` + `9631.422e0bf38581fe75.js`): +/// - `40vh` active anchor, `32px` Swiper spacing, `base_sz` `(2.5vw clamped 32..48px)`, `scale(1.2)` active line +/// - `INTRO` 4 staggered pulsing dots + `PREPARE` `3/2/1` countdown slot above line 0 +/// - `withVisibleUpperLyrics` (3s on mouse move) & `withVisibleScrolledLyrics` (3s on wheel scroll) +/// - Exact opacity ladder (`1.0` active, `0.30` next, `0.10` upcoming / upper-visible, `0.0` hidden past) +/// - Official `SyncLyricsFooter` (`Авторы:` / `Writers:` + `Источник:` / `Source:`) + `80px` top/bottom fades #[allow(clippy::too_many_arguments)] fn render_fullscreen_sync_lyrics( ctx: &mut UiContext, lyrics: Option<&TrackLyrics>, track: &Track, position_ms: u64, + is_playing: bool, lyr_rect: Rect, bg_color: Color, split_t: f32, @@ -1224,6 +1250,8 @@ fn render_fullscreen_sync_lyrics( shell.fs_lyrics_track_id = track.id.clone(); shell.fs_lyrics_scroll_y = 0.0; shell.fs_lyrics_manual_until = 0.0; + shell.fs_lyrics_upper_until = 0.0; + shell.fs_lyrics_last_mouse = None; } let Some(lyr) = lyrics.filter(|l| !l.lines.is_empty()) else { @@ -1241,52 +1269,85 @@ fn render_fullscreen_sync_lyrics( return; }; - let active_idx = if lyr.is_synced { - lyr.lines - .iter() - .rposition(|l| l.time_ms <= position_ms) - .unwrap_or(0) + let screen = ctx.screen_rect(); + let screen_w = screen.width(); + let base_sz = (screen_w * 0.025).clamp(32.0, 48.0).round(); + let active_sz = (base_sz * 1.2).round(); + let base_lh = (base_sz * 1.25).round(); + let active_lh = (active_sz * 1.25).round(); + let max_line_w = (lyr_rect.width() * 0.80).max(200.0); + let line_gap = 32.0f32; // exact Swiper `spaceBetween: 32` + + // Exact `--sync-lyrics-scroller-inset-top-vh: 40vh` anchor + let anchor_y = (screen.top() + screen.height() * 0.40) + .clamp(lyr_rect.top() + 48.0, lyr_rect.bottom() - 80.0); + + // Exact state machine: INTRO / PREPARE / PLAYING + let start_ms = lyr.lines.first().map_or(0, |l| l.time_ms); + let is_prepare = lyr.is_synced + && start_ms >= 3000 + && position_ms < start_ms + && (start_ms - position_ms) <= 3000; + let is_intro = lyr.is_synced && start_ms > 0 && position_ms < start_ms && !is_prepare; + let active_idx: Option = if lyr.is_synced && !is_intro && !is_prepare { + lyr.lines.iter().rposition(|l| l.time_ms <= position_ms) } else { - usize::MAX + None }; - let screen_w = ctx.screen_rect().width(); - let base_sz = (screen_w * 0.022).clamp(24.0, 32.0); - let active_sz = base_sz * 1.15; - let max_line_w = (lyr_rect.width() - 48.0).max(200.0); - - // Pre-measure lines + // Pre-measure every line at fixed `base_sz` / `base_lh` (zero wrap-jumping during `scale(1.2)`) + let measure_style = TextStyle::headline(base_sz, Color::WHITE).with_line_height(base_lh); let mut line_heights = Vec::with_capacity(lyr.lines.len()); let mut line_y = Vec::with_capacity(lyr.lines.len()); let mut cur_y = 0.0f32; - for (i, line) in lyr.lines.iter().enumerate() { - let is_active = i == active_idx; - let sz = if is_active { active_sz } else { base_sz }; + for line in &lyr.lines { let txt = if line.text.trim().is_empty() { "• • •" } else { line.text.as_str() }; - let measured = ctx.measure_text(txt, TextStyle::headline(sz, Color::WHITE), Some(max_line_w)); - let h = measured.y.max(sz * 1.25); + let measured = ctx.measure_text(txt, measure_style, Some(max_line_w)); + let h = measured.y.max(base_lh); line_y.push(cur_y + h * 0.5); line_heights.push(h); - cur_y += h + 22.0; + cur_y += h + line_gap; } let total_h = cur_y; + let counter_y = -(line_gap + 22.0); + let min_scroll = if is_intro || is_prepare { counter_y } else { 0.0 }; let now_t = ctx.input.time; let dt = ctx.input.dt; + + // Mouse movement (`> 2px`) reveals past upper lines for 3s (`withVisibleUpperLyrics`) + if let Some(pos) = ctx.input.pointer_pos { + if let Some(prev) = shell.fs_lyrics_last_mouse { + if pos.distance(prev) > 2.0 { + shell.fs_lyrics_upper_until = now_t + 3.0; + shell.fs_lyrics_last_mouse = Some(pos); + } + } else { + shell.fs_lyrics_last_mouse = Some(pos); + } + } + + // Wheel scroll enters manual browse mode for 3s (`withVisibleScrolledLyrics`) let wheel_dy = if ctx.is_hovered(lyr_rect) { ctx.input.wheel_delta.y } else { 0.0 }; if wheel_dy.abs() > 0.25 { - shell.fs_lyrics_scroll_y = (shell.fs_lyrics_scroll_y - wheel_dy).clamp(0.0, total_h.max(0.0)); + shell.fs_lyrics_scroll_y = (shell.fs_lyrics_scroll_y - wheel_dy).clamp(min_scroll, total_h.max(0.0)); shell.fs_lyrics_manual_until = now_t + 3.0; - } else if lyr.is_synced && active_idx < line_y.len() && now_t >= shell.fs_lyrics_manual_until { - let target_y = line_y[active_idx]; + } else if lyr.is_synced && now_t >= shell.fs_lyrics_manual_until { + let target_y = if is_intro || is_prepare { + counter_y + } else if let Some(act) = active_idx { + line_y[act] + } else { + 0.0 + }; let alpha = 1.0 - (-dt * 7.5).exp(); shell.fs_lyrics_scroll_y += (target_y - shell.fs_lyrics_scroll_y) * alpha; if (target_y - shell.fs_lyrics_scroll_y).abs() > 0.4 { @@ -1295,82 +1356,190 @@ fn render_fullscreen_sync_lyrics( } let manual_scrolled = now_t < shell.fs_lyrics_manual_until; - let center_y = lyr_rect.center_y(); + let upper_visible = now_t < shell.fs_lyrics_upper_until; let lyr_cx = lyr_rect.center_x(); ctx.push_clip(lyr_rect, 0.0); + + // Counter / Loader slot above line 0 (`INTRO`: 4 staggered pulsing dots; `PREPARE`: "3"/"2"/"1") + if is_intro || is_prepare { + let cy_screen = anchor_y + (counter_y - shell.fs_lyrics_scroll_y); + if cy_screen >= lyr_rect.top() - 40.0 && cy_screen <= lyr_rect.bottom() + 40.0 { + if is_prepare { + let rem_ms = start_ms.saturating_sub(position_ms); + let digit = ((rem_ms.saturating_sub(1)) / 1000 + 1).clamp(1, 3); + ctx.draw_text_ellipsis( + &digit.to_string(), + TextStyle::headline(base_sz, Color::WHITE.with_alpha_f32(0.50 * split_t)), + Rect::from_center_size(Pos2::new(lyr_cx, cy_screen), Vec2::new(80.0, base_lh)), + TextAlign::Center, + ); + } else { + let spacing = 20.0f32; + let start_x = lyr_cx - spacing * 1.5; + for k in 0..4 { + let (dy, dot_a) = if is_playing { + let phase = (now_t as f32 * 4.2 - k as f32 * 0.55).sin(); + (-phase.max(0.0) * 6.0, (0.30 + 0.55 * (phase * 0.5 + 0.5)) * split_t) + } else { + (0.0, 0.35 * split_t) + }; + ctx.dl().push_circle( + Pos2::new(start_x + k as f32 * spacing, cy_screen + dy), + 5.5, + Color::WHITE.with_alpha_f32(dot_a), + ); + } + if is_playing { + ctx.request_repaint(); + } + } + } + } + for (i, line) in lyr.lines.iter().enumerate() { - let y_screen = center_y + (line_y[i] - shell.fs_lyrics_scroll_y); + let y_screen = anchor_y + (line_y[i] - shell.fs_lyrics_scroll_y); let h = line_heights[i]; - if y_screen + h * 0.5 < lyr_rect.top() - 40.0 || y_screen - h * 0.5 > lyr_rect.bottom() + 40.0 { + let is_active = !manual_scrolled && active_idx == Some(i); + + let target_op: f32 = if !lyr.is_synced || manual_scrolled { + 1.0 + } else if is_intro || is_prepare { + if i == 0 { 0.30 } else { 0.10 } + } else if let Some(act) = active_idx { + if i == act { + 1.0 + } else if i == act + 1 { + 0.30 + } else if i > act + 1 { + 0.10 + } else if upper_visible { + 0.10 + } else { + 0.0 + } + } else { + 0.10 + }; + + let op_t = ctx.animate_f32(WidgetId::from_pair("fs_lyr_op", i), target_op, 0.45); + let act_t = ctx.animate_bool(WidgetId::from_pair("fs_lyr_act", i), is_active, 0.45); + + if y_screen + h * 0.65 < lyr_rect.top() - 48.0 + || y_screen - h * 0.65 > lyr_rect.bottom() + 48.0 + { continue; } - let is_active = i == active_idx; - let is_next = active_idx != usize::MAX && i == active_idx + 1; - let hit_r = Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h + 12.0)); + let line_visible = op_t > 0.02 || manual_scrolled || upper_visible || !lyr.is_synced; + let hit_r = Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h + 14.0)); let resp = ctx.interact(WidgetId::from_pair("fs_lyr_ln", i), hit_r); - let act_t = ctx.animate_bool(WidgetId::from_pair("fs_lyr_act", i), is_active, 0.35); let hov_t = ctx.animate_bool( WidgetId::from_pair("fs_lyr_hov", i), - resp.hovered && lyr.is_synced, + resp.hovered && lyr.is_synced && line_visible, 0.18, ); - let base_alpha = if !lyr.is_synced || manual_scrolled { - 0.90f32 - } else if is_next { - 0.34 - } else { - 0.16 - }; - let alpha = (base_alpha + (1.0 - base_alpha) * act_t) - .max(0.90 * hov_t) - * split_t; - let sz = base_sz + (active_sz - base_sz) * act_t; - let col = Color::WHITE.with_alpha_f32(alpha); - let txt = if line.text.trim().is_empty() { - "• • •" - } else { - line.text.as_str() - }; + let alpha = op_t.max(0.85 * hov_t) * split_t; + if alpha > 0.005 { + let col = Color::WHITE.with_alpha_f32(alpha); + let txt = if line.text.trim().is_empty() { + "• • •" + } else { + line.text.as_str() + }; - let draw_r = Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h + 6.0)); - ctx.draw_text_wrapped(txt, TextStyle::headline(sz, col), draw_r, None, TextAlign::Center); + if act_t < 0.01 { + ctx.draw_text_wrapped_scaled( + txt, + TextStyle::headline(base_sz, col).with_line_height(base_lh), + Rect::from_center_size(Pos2::new(lyr_cx, y_screen), Vec2::new(max_line_w, h)), + 1.0, + TextAlign::Center, + ); + } else { + let sc = (1.0 + 0.2 * act_t) / 1.2; + ctx.draw_text_wrapped_scaled( + txt, + TextStyle::headline(active_sz, col).with_line_height(active_lh), + Rect::from_center_size( + Pos2::new(lyr_cx, y_screen), + Vec2::new(max_line_w * 1.2, h * 1.2), + ), + sc, + TextAlign::Center, + ); + } + } - if lyr.is_synced { + if lyr.is_synced && line_visible { if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } if resp.clicked { - actions.push(AppAction::SeekMs(line.time_ms)); + actions.push(AppAction::SeekMs(line.time_ms.saturating_add(10))); shell.fs_lyrics_manual_until = 0.0; } } } - // Writers footer - if let Some(ref writers) = lyr.writers { - let fy = center_y + (total_h + 24.0 - shell.fs_lyrics_scroll_y); - if fy >= lyr_rect.top() - 40.0 && fy <= lyr_rect.bottom() + 40.0 { + // Official `SyncLyricsFooter`: Writers + Source (`major`) attribution at `0.50` alpha + let has_writers = lyr.writers.as_deref().map_or(false, |s| !s.trim().is_empty()); + let has_major = lyr.major.as_deref().map_or(false, |s| !s.trim().is_empty()); + if has_writers || has_major { + let footer_pad_top = (screen_w * 0.0625).clamp(48.0, 96.0); + let footer_sz = (screen_w * 0.0125).clamp(15.0, 20.0); + let footer_col = Color::WHITE.with_alpha_f32(0.50 * split_t); + let footer_style = TextStyle::medium(footer_sz, footer_col); + let mut fy = anchor_y + (total_h + footer_pad_top - shell.fs_lyrics_scroll_y); + + if let Some(ref writers) = lyr.writers.as_deref().filter(|s| !s.trim().is_empty()) { let txt = if ru { format!("Авторы: {}", writers) } else { format!("Writers: {}", writers) }; - ctx.draw_text_wrapped( - &txt, - TextStyle::regular(14.0, Color::WHITE.with_alpha_f32(0.5 * split_t)), - Rect::from_center_size(Pos2::new(lyr_cx, fy), Vec2::new(max_line_w, 40.0)), - Some(2), - TextAlign::Center, - ); + let mh = ctx + .measure_text(&txt, footer_style, Some(max_line_w)) + .y + .max(footer_sz * 1.35); + if fy + mh >= lyr_rect.top() - 40.0 && fy <= lyr_rect.bottom() + 40.0 { + ctx.draw_text_wrapped( + &txt, + footer_style, + Rect::from_xywh(lyr_cx - max_line_w * 0.5, fy, max_line_w, mh + 4.0), + Some(3), + TextAlign::Center, + ); + } + fy += mh + 8.0; + } + + if let Some(ref major) = lyr.major.as_deref().filter(|s| !s.trim().is_empty()) { + let txt = if ru { + format!("Источник: {}", major) + } else { + format!("Source: {}", major) + }; + let mh = ctx + .measure_text(&txt, footer_style, Some(max_line_w)) + .y + .max(footer_sz * 1.35); + if fy + mh >= lyr_rect.top() - 40.0 && fy <= lyr_rect.bottom() + 40.0 { + ctx.draw_text_wrapped( + &txt, + footer_style, + Rect::from_xywh(lyr_cx - max_line_w * 0.5, fy, max_line_w, mh + 4.0), + Some(2), + TextAlign::Center, + ); + } } } - // Smooth top & bottom gradient fade masks into `bg_color` - let fade_h = 84.0f32.min(lyr_rect.height() * 0.22); + // Official `80px` (`5rem`) top & bottom gradient fade masks into `bg_color` + let fade_h = 80.0f32.min(lyr_rect.height() * 0.25); let bg_clear = bg_color.with_alpha(0); ctx.dl().push_gradient_rect( Rect::from_xywh(lyr_rect.left(), lyr_rect.top(), lyr_rect.width(), fade_h), diff --git a/src/views/podcasts_kids.rs b/src/views/podcasts_kids.rs index 43603a4..94a8ce9 100644 --- a/src/views/podcasts_kids.rs +++ b/src/views/podcasts_kids.rs @@ -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 + // 3 featured shimmer poster cards (matching official 0.963 TopConcertsCarousel aspect ratio) let gap = 16.0; let f_cols = if avail_w >= 860.0 { 3usize @@ -1203,16 +1203,17 @@ pub fn render_concerts( } else { 1 }; - let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).max(220.0); + let f_w = ((avail_w - gap * (f_cols as f32 - 1.0)) / f_cols as f32).clamp(240.0, 440.0); + let f_h = (f_w / 0.963).clamp(240.0, 320.0); for i in 0..f_cols { let col = shimmer_color(pal, t_sec + i as f32 * 0.55); ctx.dl().push_rect( - Rect::from_xywh(x + i as f32 * (f_w + gap), y, f_w, 210.0), + Rect::from_xywh(x + i as f32 * (f_w + gap), y, f_w, f_h), 16.0, col, ); } - y += 236.0; + y += f_h + 26.0; // 4 shimmer feed rows for i in 0..4 { @@ -1276,7 +1277,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 = 216.0; + let f_h = (f_w / 0.963).clamp(240.0, 320.0); ctx.draw_text_ellipsis( if ru { "Рекомендуем" } else { "Featured" }, diff --git a/src/views/search.rs b/src/views/search.rs index 77e10ce..9f059aa 100644 --- a/src/views/search.rs +++ b/src/views/search.rs @@ -339,8 +339,9 @@ 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, @@ -726,8 +727,9 @@ 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 alb in res.albums.iter().take(12) { + for (idx, alb) in res.albums.iter().take(12).enumerate() { let cr = Rect::from_xywh(cx, y, card_w, card_h); + let alb_title = alb.full_title(); let sub = alb .artists .first() @@ -737,9 +739,9 @@ pub fn render_search( ctx, pal, covers, - WidgetId::from_pair("s_alb", &alb.id), + WidgetId::from_pair("s_alb", (idx, &alb.id)), cr, - &alb.title, + &alb_title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -749,12 +751,12 @@ pub fn render_search( if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, })); } cx += card_w + 16.0; @@ -776,6 +778,7 @@ 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() @@ -785,9 +788,9 @@ pub fn render_search( ctx, pal, covers, - WidgetId::from_pair("s_alb_grid", &alb.id), + WidgetId::from_pair("s_alb_grid", (idx, &alb.id)), cr, - &alb.title, + &alb_title, sub, alb.cover_uri.as_deref(), &format!("alb_{}", alb.id), @@ -797,12 +800,12 @@ pub fn render_search( if m.play_clicked { actions.push(AppAction::PlayAlbum { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, }); } else if m.clicked { actions.push(AppAction::Navigate(Route::Album { id: alb.id.clone(), - title: alb.title.clone(), + title: alb_title, })); } } @@ -831,13 +834,16 @@ 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 pl in res.playlists.iter().take(12) { + for (idx, pl) in res.playlists.iter().take(12).enumerate() { let cr = Rect::from_xywh(cx, y, card_w, card_h); let m = media_card( ctx, pal, covers, - WidgetId::from_pair("s_pl", format!("{}_{}", pl.owner_uid, pl.kind)), + WidgetId::from_pair( + "s_pl", + (idx, format!("{}_{}", pl.owner_uid, pl.kind)), + ), cr, &pl.title, &pl.owner_name, @@ -889,7 +895,7 @@ pub fn render_search( covers, WidgetId::from_pair( "s_pl_grid", - format!("{}_{}", pl.owner_uid, pl.kind), + (idx, format!("{}_{}", pl.owner_uid, pl.kind)), ), cr, &pl.title, diff --git a/src/views/sidebar.rs b/src/views/sidebar.rs index 0e7f8c4..b8943a3 100644 --- a/src/views/sidebar.rs +++ b/src/views/sidebar.rs @@ -287,6 +287,8 @@ 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, @@ -296,7 +298,7 @@ pub fn render_sidebar( &pin.id, 4.0, is_circle, - pin.kind == "likes", + is_likes_art, ); // Hover Play/Pause overlay on ALL pinned items (playlists, albums, favorites, artists & waves!) diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index a963dd9..09950e7 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -1890,6 +1890,7 @@ 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 { @@ -2170,9 +2171,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 colored poster cards + upcoming feed rendered cleanly + // Verify Top 3 poster cards (aspect 0.963, h~320px) + cashback pills + yellow price CTAs rendered cleanly let mut poster_chromatic_px = 0usize; - for y in 160..420 { + for y in 160..540 { for x in 250..1240 { let [r, g, b] = img.get_pixel(x, y).0; if r.max(g).max(b).saturating_sub(r.min(g).min(b)) >= 20 { @@ -2244,3 +2245,273 @@ 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 + ); + } +} From ee65d23b2affe2f43535132d5019e16b2594278a Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 18:35:49 +0300 Subject: [PATCH 09/17] chore(release): v0.1.5 - Linux ksni tray, 1:1 sidebar collapse button, zero-overhead Linux RAM tuning --- Cargo.lock | 334 +++++++++++++++++++++++++++++++++++++++++- Cargo.toml | 3 +- README.md | 8 +- src/covers.rs | 11 +- src/engine/text.rs | 21 ++- src/main.rs | 18 +++ src/native/mod.rs | 257 +++++++++++++++++++++++++++++++- src/views/overlays.rs | 2 +- src/views/sidebar.rs | 78 ++++++---- 9 files changed, 684 insertions(+), 48 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2384686..5ee0bbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -186,6 +186,15 @@ 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" @@ -224,6 +233,18 @@ 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" @@ -236,6 +257,28 @@ 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" @@ -849,6 +892,15 @@ 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" @@ -1085,6 +1137,33 @@ 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" @@ -1139,12 +1218,38 @@ 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" @@ -1333,6 +1438,19 @@ 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" @@ -2350,6 +2468,21 @@ 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" @@ -3195,6 +3328,16 @@ 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" @@ -3229,6 +3372,12 @@ 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" @@ -3252,6 +3401,12 @@ 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" @@ -4211,6 +4366,17 @@ 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" @@ -4265,6 +4431,16 @@ 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" @@ -4817,6 +4993,19 @@ 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" @@ -4979,8 +5168,10 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys 0.61.2", ] @@ -5150,9 +5341,21 @@ 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" @@ -5204,6 +5407,17 @@ 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" @@ -5348,6 +5562,17 @@ 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" @@ -6325,7 +6550,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.4" +version = "0.1.5" dependencies = [ "aes", "anyhow", @@ -6347,6 +6572,7 @@ dependencies = [ "hex", "hmac", "image", + "ksni", "log", "lru", "md-5", @@ -6400,6 +6626,71 @@ 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" @@ -6527,3 +6818,44 @@ checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ "zune-core 0.5.3", ] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.5", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.10", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.10", + "winnow 1.0.5", +] diff --git a/Cargo.toml b/Cargo.toml index 7a0d324..5b31b31 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.4" +version = "0.1.5" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" @@ -81,6 +81,7 @@ 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 } diff --git a/README.md b/README.md index 5a4182e..9cd5716 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.4-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.4-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.5-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.5-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.4-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.5-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.4-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.5-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности diff --git a/src/covers.rs b/src/covers.rs index 06a9534..d69996b 100644 --- a/src/covers.rs +++ b/src/covers.rs @@ -7,9 +7,16 @@ use std::sync::Arc; use crate::engine::textures::TextureRegistry; use crate::engine::types::{Color, TextureId}; -/// Hard minimum LRU cover cache capacity so even dense pages (Artist/Collection + sidebar + player) -/// can never thrash or flicker visible avatars/covers. +/// 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))))] 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 { diff --git a/src/engine/text.rs b/src/engine/text.rs index 22053a0..1507d18 100644 --- a/src/engine/text.rs +++ b/src/engine/text.rs @@ -332,8 +332,25 @@ impl TextEngine { db.set_sans_serif_family(&ys_text_family); - // Load system fallback fonts for rare symbols / emoji / CJK - db.load_system_fonts(); + // 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(); + } let font_system = FontSystem::new_with_locale_and_db("ru-RU".to_string(), db); diff --git a/src/main.rs b/src/main.rs index 3de1b03..7f44916 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1058,7 +1058,25 @@ 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 }); diff --git a/src/native/mod.rs b/src/native/mod.rs index e44da3f..dadd154 100644 --- a/src/native/mod.rs +++ b/src/native/mod.rs @@ -451,22 +451,267 @@ 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 std::process::{Command, Stdio}; + use std::sync::Arc; use winit::window::Window; const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:"; - pub struct NativeDesktop; + struct LinuxTray { + tx: Sender, + icons: Arc>, + is_ru: bool, + window_visible: bool, + is_playing: bool, + track_summary: String, + } + + impl ksni::Tray for LinuxTray { + fn id(&self) -> String { + "yandex-music-rs".into() + } + + fn category(&self) -> ksni::Category { + ksni::Category::ApplicationStatus + } + + fn title(&self) -> String { + if self.is_ru { + "Яндекс Музыка".into() + } else { + "Yandex Music".into() + } + } + + fn icon_name(&self) -> String { + "yandex-music-rs".into() + } + + fn icon_pixmap(&self) -> Vec { + (*self.icons).clone() + } + + fn tool_tip(&self) -> ksni::ToolTip { + ksni::ToolTip { + icon_name: "yandex-music-rs".into(), + icon_pixmap: Vec::new(), + title: self.title(), + description: self.track_summary.clone(), + } + } + + fn activate(&mut self, _x: i32, _y: i32) { + let _ = self.tx.send(NativeEvent::ToggleWindow); + } + + fn menu(&self) -> Vec> { + use ksni::menu::*; + let toggle_label = if self.window_visible { + if self.is_ru { "Скрыть" } else { "Hide" } + } else if self.is_ru { + "Показать" + } else { + "Show" + }; + let play_label = if self.is_playing { + if self.is_ru { "Пауза" } else { "Pause" } + } else if self.is_ru { + "Играть" + } else { + "Play" + }; + let ver_label = if self.is_ru { + format!("Яндекс Музыка {}", env!("CARGO_PKG_VERSION")) + } else { + format!("Yandex Music {}", env!("CARGO_PKG_VERSION")) + }; + + vec![ + StandardItem { + label: toggle_label.into(), + activate: Box::new(|this: &mut Self| { + let _ = this.tx.send(NativeEvent::ToggleWindow); + }), + ..Default::default() + } + .into(), + StandardItem { + label: if self.is_ru { + "Проверить обновления".into() + } else { + "Check updates".into() + }, + activate: Box::new(|this: &mut Self| { + let _ = this.tx.send(NativeEvent::CheckUpdates); + }), + ..Default::default() + } + .into(), + MenuItem::Separator, + StandardItem { + label: play_label.into(), + activate: Box::new(|this: &mut Self| { + let _ = this.tx.send(NativeEvent::TogglePlay); + }), + ..Default::default() + } + .into(), + StandardItem { + label: if self.is_ru { + "Предыдущий трек".into() + } else { + "Previous song".into() + }, + activate: Box::new(|this: &mut Self| { + let _ = this.tx.send(NativeEvent::Prev); + }), + ..Default::default() + } + .into(), + StandardItem { + label: if self.is_ru { + "Следующий трек".into() + } else { + "Next song".into() + }, + activate: Box::new(|this: &mut Self| { + let _ = this.tx.send(NativeEvent::Next); + }), + ..Default::default() + } + .into(), + MenuItem::Separator, + SubMenu { + label: if self.is_ru { + "О приложении".into() + } else { + "About the app".into() + }, + submenu: vec![StandardItem { + label: ver_label, + enabled: false, + ..Default::default() + } + .into()], + ..Default::default() + } + .into(), + MenuItem::Separator, + StandardItem { + label: if self.is_ru { + "Закрыть приложение".into() + } else { + "Close app".into() + }, + activate: Box::new(|this: &mut Self| { + let _ = this.tx.send(NativeEvent::QuitApp); + }), + ..Default::default() + } + .into(), + ] + } + } + + fn decode_ksni_icon(png_bytes: &[u8]) -> Option { + let img = image::load_from_memory(png_bytes).ok()?.to_rgba8(); + let (w, h) = img.dimensions(); + let mut data = img.into_raw(); + for px in data.chunks_exact_mut(4) { + px.rotate_right(1); // RGBA -> ARGB32 network byte order (SNI spec) + } + Some(ksni::Icon { + width: w as i32, + height: h as i32, + data, + }) + } + + pub struct NativeDesktop { + handle: Option>, + rx: Receiver, + last_playing: Option, + last_track_id: Option, + } + + impl Drop for NativeDesktop { + fn drop(&mut self) { + if let Some(ref handle) = self.handle { + handle.shutdown(); + } + } + } + impl NativeDesktop { - pub fn new(_window: &Window, _is_ru: bool) -> Self { - Self + 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 set_window_visible_label(&self, _visible: bool) {} + + 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 poll_events(&self) -> Vec { - Vec::new() + 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; + }); + } } - pub fn sync_playback(&mut self, _track: Option<&Track>, _is_playing: bool, _pos_ms: u64) {} } pub fn load_window_icon() -> Option { diff --git a/src/views/overlays.rs b/src/views/overlays.rs index 1cd5781..7ceebc3 100644 --- a/src/views/overlays.rs +++ b/src/views/overlays.rs @@ -3812,7 +3812,7 @@ impl SplashPlayer { /// Spawns a bounded 4-frame background WebP decoder selecting `splash_dark.webp` on `#000` /// or `splash_light.webp` on `#FFF` to match official Yandex Music 5.129.0 SplashScreen 1-to-1! pub fn spawn(is_dark: bool) -> Self { - let (tx, rx) = crossbeam_channel::bounded::(4); + let (tx, rx) = crossbeam_channel::bounded::(1); std::thread::Builder::new() .name("ym-splash-decode".into()) .spawn(move || { diff --git a/src/views/sidebar.rs b/src/views/sidebar.rs index b8943a3..c14f13a 100644 --- a/src/views/sidebar.rs +++ b/src/views/sidebar.rs @@ -80,42 +80,58 @@ pub fn render_sidebar( } } - // 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 { + // 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 { pal.surface_hover } else { pal.surface_secondary - }, - ); - 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 { + } + .scale_alpha(col_vis); + let icon_col = if col_resp.hovered { pal.text_primary } else { - pal.text_secondary - }, - ); - if col_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if col_resp.clicked { - actions.push(AppAction::ToggleSidebarCollapse); - } + 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); + } + }); } // 2. Navigation Items (exact 5.129.0 order + optional Kids section) From 41c30f9c35b277397d3828a70612ca9db6f20eda Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 19:29:32 +0300 Subject: [PATCH 10/17] feat: official crossfade, concurrent downloads, changelog, and 1-to-1 settings/EQ --- src/api/demo_data.rs | 10 + src/api/mod.rs | 99 ++- src/api/models.rs | 43 +- src/app/i18n.rs | 40 ++ src/app/playback.rs | 264 ++++++- src/app/state.rs | 416 +++++++++-- src/audio/dsp.rs | 229 ++++++- src/audio/mod.rs | 501 ++++++++++++-- src/config.rs | 3 + src/engine/widgets.rs | 98 ++- src/views/collection.rs | 4 + src/views/detail.rs | 32 +- src/views/for_you.rs | 2 + src/views/mod.rs | 120 +++- src/views/my_vibe.rs | 8 +- src/views/overlays.rs | 1329 ++++++++++++++++++++++++++++++++---- src/views/podcasts_kids.rs | 4 + src/views/search.rs | 2 + src/views/settings.rs | 1132 +++++++++++++++--------------- src/views/sidebar.rs | 30 +- tests/common/mod.rs | 1 + tests/parity_extended.rs | 69 ++ 22 files changed, 3572 insertions(+), 864 deletions(-) diff --git a/src/api/demo_data.rs b/src/api/demo_data.rs index 9de951a..2a20ae1 100644 --- a/src/api/demo_data.rs +++ b/src/api/demo_data.rs @@ -366,6 +366,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_2".into(), @@ -386,6 +387,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_3".into(), @@ -406,6 +408,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_4".into(), @@ -426,6 +429,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_5".into(), @@ -446,6 +450,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_6".into(), @@ -466,6 +471,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_7".into(), @@ -486,6 +492,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_8".into(), @@ -506,6 +513,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_9".into(), @@ -526,6 +534,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, Track { id: "demo_10".into(), @@ -546,6 +555,7 @@ pub fn demo_chart_tracks() -> Vec { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }, ] } diff --git a/src/api/mod.rs b/src/api/mod.rs index 4534a9b..03dfd2b 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -2515,15 +2515,62 @@ impl YandexApiClient { quality: AudioQuality, cache_dir: &Path, ) -> Result { + let never_cancel = std::sync::atomic::AtomicBool::new(false); + self.download_track_to_cache_with_progress(track, quality, cache_dir, &never_cancel, |_| {}) + .await + } + + /// Streaming variant of `download_track_to_cache` reporting throttled `0.0..=1.0` progress + /// and aborting immediately if `cancel` is signaled. + pub async fn download_track_to_cache_with_progress( + &self, + track: &Track, + quality: AudioQuality, + cache_dir: &Path, + cancel: &std::sync::atomic::AtomicBool, + mut on_progress: F, + ) -> Result { + use std::sync::atomic::Ordering; + + if cancel.load(Ordering::Relaxed) { + return Err(anyhow!("Download cancelled")); + } let stream = self.resolve_track_stream(&track.id, quality).await?; - let resp = self.http.get(&stream.url).send().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?; if !resp.status().is_success() { return Err(anyhow!( "Offline download HTTP {}", resp.status().as_u16() )); } - let mut bytes = resp.bytes().await?.to_vec(); + + 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")); + } + 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")); @@ -2537,12 +2584,13 @@ impl YandexApiClient { } else { "mp3" }; - std::fs::create_dir_all(cache_dir)?; + tokio::fs::create_dir_all(cache_dir).await?; 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)); - std::fs::write(&part_path, &bytes)?; - std::fs::rename(&part_path, &final_path)?; + tokio::fs::write(&part_path, &bytes).await?; + tokio::fs::rename(&part_path, &final_path).await?; + on_progress(1.0); Ok(final_path) } @@ -3621,6 +3669,15 @@ fn parse_track(v: &Value) -> Option { .as_str() .or_else(|| v["derivedColors"]["waveText"].as_str()) .map(String::from); + let fade = v.get("fade").and_then(|f| { + let tf = TrackFade { + in_start: f["inStart"].as_f64()? as f32, + in_stop: f["inStop"].as_f64()? as f32, + out_start: f["outStart"].as_f64()? as f32, + out_stop: f["outStop"].as_f64()? as f32, + }; + tf.is_valid().then_some(tf) + }); Some(Track { id, @@ -3641,6 +3698,7 @@ fn parse_track(v: &Value) -> Option { r128_tp, derived_average_hex, derived_accent_hex, + fade, }) } @@ -4147,4 +4205,35 @@ mod tests { assert_eq!(parsed_arts[1].name, "Artist Two"); assert_eq!(bare_art_ids, vec!["22"]); } + + #[test] + fn test_parse_track_fade_metadata() { + let valid = json!({ + "id": 12345, + "title": "Crossfade Track", + "durationMs": 210000, + "artists": [{ "id": 1, "name": "Artist" }], + "fade": { + "inStart": 0.25, + "inStop": 4.5, + "outStart": 203.0, + "outStop": 208.5 + } + }); + let tr = parse_track(&valid).expect("valid track"); + let f = tr.fade.expect("valid fade parsed"); + assert!((f.in_start - 0.25).abs() < 1e-4); + assert!((f.in_stop - 4.5).abs() < 1e-4); + assert!((f.out_start - 203.0).abs() < 1e-4); + assert!((f.out_stop - 208.5).abs() < 1e-4); + + let invalid = json!({ + "id": 12346, + "title": "Bad Fade", + "durationMs": 180000, + "fade": { "inStart": 10.0, "inStop": 5.0, "outStart": 4.0, "outStop": 3.0 } + }); + let tr_bad = parse_track(&invalid).expect("track parses"); + assert!(tr_bad.fade.is_none()); + } } diff --git a/src/api/models.rs b/src/api/models.rs index 67344a5..a3aa702 100644 --- a/src/api/models.rs +++ b/src/api/models.rs @@ -55,7 +55,7 @@ impl AlbumSummary { } } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Track { pub id: String, pub title: String, @@ -82,6 +82,27 @@ pub struct Track { pub derived_average_hex: Option, #[serde(default)] pub derived_accent_hex: Option, + /// Official Yandex Music track transition points in seconds (`track.fade`) + #[serde(default)] + pub fade: Option, +} + +/// Official Yandex Music track transition points in seconds (`track.fade`). +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct TrackFade { + pub in_start: f32, + pub in_stop: f32, + pub out_start: f32, + pub out_stop: f32, +} + +impl TrackFade { + pub fn is_valid(&self) -> bool { + self.in_start >= 0.0 + && self.in_stop >= self.in_start + && self.out_start > self.in_stop + && self.out_stop > self.out_start + } } impl Track { @@ -534,3 +555,23 @@ pub struct WordsBigCard { pub text: String, pub actions: Vec, } + +/// Release changelog entry fetched from Forgejo releases API (or built-in fallback). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReleaseNoteEntry { + pub tag: String, + pub version: String, + pub name: String, + pub date: String, + pub body: String, + pub html_url: String, +} + +/// Available application update metadata for `NotificationUpdate` & Settings card. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpdateInfo { + pub version: String, + pub html_url: String, + pub date: String, + pub body: String, +} diff --git a/src/app/i18n.rs b/src/app/i18n.rs index be19907..49a9a00 100644 --- a/src/app/i18n.rs +++ b/src/app/i18n.rs @@ -804,6 +804,46 @@ 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) diff --git a/src/app/playback.rs b/src/app/playback.rs index 10a1999..08469a8 100644 --- a/src/app/playback.rs +++ b/src/app/playback.rs @@ -21,6 +21,7 @@ impl AppState { if idx >= self.queue.len() { return; } + self.invalidate_preload(); self.queue_index = idx; let track = self.queue[idx].clone(); @@ -74,6 +75,7 @@ impl AppState { track.duration_ms, track.r128_i, track.r128_tp, + track.fade, ); self.fetch_lyrics_async(&track); self.ensure_words_for_current_track(); @@ -92,6 +94,7 @@ 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 { @@ -104,6 +107,7 @@ impl AppState { duration_ms: dur, r128_i, r128_tp, + fade, result, }); }); @@ -114,6 +118,150 @@ impl AppState { } } + pub(crate) fn peek_next_queue_index(&self) -> Option { + if self.queue.is_empty() || self.repeat == RepeatMode::One { + return None; + } + if self.queue_index + 1 < self.queue.len() { + Some(self.queue_index + 1) + } else if self.repeat == RepeatMode::All || self.is_vibe_active { + Some(0) + } else { + None + } + } + + pub fn invalidate_preload(&mut self) { + self.preloaded_next_track_id = None; + self.audio.clear_preload(); + } + + pub(crate) fn maybe_preload_next_track(&mut self) { + if !self.is_audio_playing() || self.is_buffering() || self.preloaded_next_track_id.is_some() { + return; + } + let dur_ms = self.duration_ms(); + if dur_ms < 8_000 { + return; + } + let pos_ms = self.position_ms(); + let curr_fade = self.current_track().and_then(|tr| tr.fade); + let transition_ms = if self.config.crossfade_enabled { + if self.config.crossfade_secs > 0.1 { + dur_ms.saturating_sub((self.config.crossfade_secs * 1000.0) as u64) + } else if let Some(f) = curr_fade { + ((f.out_start * 1000.0) as u64).min(dur_ms) + } else { + dur_ms.saturating_sub(3_500) + } + } else { + dur_ms + }; + if pos_ms + 15_000 < transition_ms { + return; + } + let Some(next_idx) = self.peek_next_queue_index() else { + return; + }; + let next_track = self.queue[next_idx].clone(); + self.preloaded_next_track_id = Some(next_track.id.clone()); + + let cache_dir = AppConfig::offline_cache_dir(); + if let Some(local_path) = find_offline_track_file(&next_track.id, &cache_dir) { + let ext = local_path + .extension() + .and_then(|e| e.to_str()) + .unwrap_or("mp3") + .to_lowercase(); + let (codec_label, bitrate_kbps) = match ext.as_str() { + "flac" => ("FLAC (Offline)".to_string(), 1000), + "m4a" => ("AAC (Offline)".to_string(), 320), + _ => ("MP3 (Offline)".to_string(), 320), + }; + let stream = ResolvedStream { + url: format!("file://{}", local_path.display()), + codec_label, + bitrate_kbps, + decrypt_key_hex: None, + gain_applied: false, + }; + self.audio.preload_next( + next_track.id, + stream, + next_track.duration_ms, + next_track.r128_i, + next_track.r128_tp, + next_track.fade, + ); + return; + } + + if self.api.has_token() { + let api = self.api.clone(); + let tx = self.tx_api.clone(); + let tid = next_track.id.clone(); + let dur = next_track.duration_ms; + let r128_i = next_track.r128_i; + let r128_tp = next_track.r128_tp; + let fade = next_track.fade; + let quality = self.config.audio_quality; + self.runtime.spawn(async move { + let result = api + .resolve_track_stream(&tid, quality) + .await + .map_err(|e| e.to_string()); + let _ = tx.send(ApiEvent::NextStreamPreloaded { + track_id: tid, + duration_ms: dur, + r128_i, + r128_tp, + fade, + result, + }); + }); + } + } + + pub(crate) fn on_seamless_transition_to(&mut self, next_track_id: &str) { + self.preloaded_next_track_id = None; + let pos_sec = self.duration_ms() as f64 / 1000.0; + let outgoing = self.current_track().cloned(); + self.send_play_telemetry("finish"); + if self.is_vibe_active { + self.send_rotor_feedback(RotorFeedbackKind::TrackFinished, outgoing.as_ref(), Some(pos_sec)); + } + + if let Some(next_idx) = self + .peek_next_queue_index() + .filter(|&i| self.queue.get(i).map_or(false, |tr| tr.id == next_track_id)) + .or_else(|| self.queue.iter().position(|tr| tr.id == next_track_id)) + { + self.queue_index = next_idx; + } + + let Some(track) = self.current_track().cloned() else { + return; + }; + self.current_play_id = generate_request_id(); + self.play_start_iso = iso8601_now(); + self.play_seeked = false; + self.play_paused = false; + self.play_from_cache = find_offline_track_file(&track.id, &AppConfig::offline_cache_dir()).is_some(); + self.last_play_heartbeat = Instant::now(); + + if self.is_vibe_active { + self.send_rotor_feedback(RotorFeedbackKind::TrackStarted, Some(&track), None); + self.maybe_prefetch_rotor_batch(); + } + self.play_history.retain(|t| t.id != track.id); + self.play_history.insert(0, track.clone()); + self.play_history.truncate(50); + + self.send_play_telemetry("start"); + self.fetch_lyrics_async(&track); + self.ensure_words_for_current_track(); + } + fn fetch_lyrics_async(&mut self, track: &Track) { self.current_lyrics = None; self.fetch_lyrics_for_track(track); @@ -338,6 +486,7 @@ 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); @@ -378,6 +527,7 @@ 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); @@ -391,6 +541,7 @@ impl AppState { } pub fn clear_queue(&mut self) { + self.invalidate_preload(); self.queue.clear(); self.unshuffled_queue.clear(); self.queue_index = 0; @@ -399,11 +550,13 @@ 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 @@ -456,6 +609,7 @@ 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 { @@ -484,6 +638,7 @@ 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, @@ -1612,21 +1767,58 @@ impl AppState { !tracks.is_empty() && tracks.iter().all(|t| self.downloaded_track_ids.contains(&t.id)) } + pub fn track_download_progress(&self, track_id: &str) -> f32 { + self.downloading_track_progress + .get(track_id) + .copied() + .unwrap_or(0.0) + } + pub fn download_progress_pct(&self) -> Option { if self.downloading_track_ids.is_empty() || self.download_batch_total == 0 { return None; } - let 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) + let in_flight: f32 = self.downloading_track_progress.values().sum(); + let total = self.download_batch_total.max(1) as f32; + let frac = ((self.download_batch_done as f32 + in_flight) / total).clamp(0.0, 0.99); + Some((frac * 100.0).round().clamp(0.0, 99.0) as u8) + } + + pub fn tracks_download_progress_pct(&self, tracks: &[Track]) -> Option { + if tracks.is_empty() || self.downloading_track_ids.is_empty() { + return None; + } + let mut active_count = 0usize; + let mut completed_count = 0usize; + let mut in_flight = 0.0f32; + for tr in tracks { + if self.downloaded_track_ids.contains(&tr.id) { + completed_count += 1; + } else if self.downloading_track_ids.contains(&tr.id) { + active_count += 1; + in_flight += self.track_download_progress(&tr.id); + } + } + if active_count == 0 { + return None; + } + let denom = (completed_count + active_count).max(1) as f32; + let frac = ((completed_count as f32 + in_flight) / denom).clamp(0.0, 0.99); + Some((frac * 100.0).round().clamp(0.0, 99.0) as u8) } 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()); } @@ -1641,8 +1833,11 @@ 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(); @@ -1654,8 +1849,15 @@ 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(&track, quality, &cache_dir) + .download_track_to_cache_with_progress(&track, quality, &cache_dir, &cancel, |p| { + let _ = tx_prog.send(ApiEvent::TrackDownloadProgress { + track_id: tid.clone(), + progress: p, + }); + }) .await .map_err(|e| e.to_string()); if cancel.load(Ordering::Relaxed) { @@ -1672,7 +1874,11 @@ impl AppState { self.show_toast(self.i18n().toast_sign_in_required()); return; } - self.download_cancel.store(false, Ordering::SeqCst); + if self.downloading_track_ids.is_empty() { + self.download_cancel.store(false, Ordering::SeqCst); + self.download_batch_succeeded = 0; + self.download_batch_failed = 0; + } let to_download: Vec = tracks .into_iter() .filter(|tr| !self.is_track_downloaded(&tr.id) && !self.is_track_downloading(&tr.id)) @@ -1682,6 +1888,7 @@ 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; } @@ -1690,20 +1897,52 @@ 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 res = api - .download_track_to_cache(&track, quality, &cache_dir) - .await - .map_err(|e| e.to_string()); + let Ok(permit) = sem.clone().acquire_owned().await else { + break; + }; if cancel.load(Ordering::Relaxed) { - let _ = remove_offline_track_file(&track.id, &cache_dir); + drop(permit); break; } - let _ = tx.send(ApiEvent::TrackDownloaded { track, result: res }); + 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 }); + }); } }); } @@ -1956,6 +2195,7 @@ mod tests { r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, } } diff --git a/src/app/state.rs b/src/app/state.rs index fb5e30e..1c10953 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -348,6 +348,8 @@ pub enum AppAction { SetVibeModalOpen(bool), SetLoginModalOpen(bool), SetEqPopoverOpen(bool), + SetEqualizerModalOpen(bool), + SetShortcutsModalOpen(bool), OpenTrackDetailModal(Track), CloseTrackDetailModal, OpenWordsBigCard { @@ -360,6 +362,10 @@ pub enum AppAction { state: String, }, DismissOverlays, + OpenReleaseNotesModal, + CloseReleaseNotesModal, + DismissUpdateNotification, + InstallUpdate, // Account, Settings & Lifecycle SetTheme(ThemeMode), @@ -367,6 +373,7 @@ pub enum AppAction { ToggleLanguage, SetAudioQuality(AudioQuality), SetNormalizeLoudness(bool), + SetCrossfadeEnabled(bool), SetCrossfadeSecs(f32), SetAiContentReduction(bool), SetChildMode(bool), @@ -422,6 +429,15 @@ pub(crate) enum ApiEvent { duration_ms: u64, r128_i: Option, r128_tp: Option, + fade: Option, + result: Result, + }, + NextStreamPreloaded { + track_id: String, + duration_ms: u64, + r128_i: Option, + r128_tp: Option, + fade: Option, result: Result, }, LyricsLoaded(TrackLyrics), @@ -449,11 +465,18 @@ pub(crate) enum ApiEvent { revision: Result, toast_msg: String, }, + TrackDownloadProgress { + track_id: String, + progress: f32, + }, TrackDownloaded { track: Track, result: Result, }, - UpdateCheckFinished(Result, String>), + ReleasesLoaded { + result: Result, String>, + user_initiated: bool, + }, } // ============================================================================= @@ -503,8 +526,12 @@ pub struct AppState { // Offline cache & download tracking pub downloaded_track_ids: HashSet, pub downloading_track_ids: HashSet, + pub downloading_track_progress: HashMap, pub download_batch_total: usize, pub download_batch_done: usize, + pub download_batch_succeeded: usize, + pub download_batch_failed: usize, + pub download_config_dirty_count: usize, pub download_cancel: Arc, // Page-specific states @@ -534,6 +561,7 @@ pub struct AppState { pub vibe_prefetching: bool, pub shuffle: bool, pub repeat: RepeatMode, + pub preloaded_next_track_id: Option, pub current_lyrics: Option, pub modal_lyrics: Option, @@ -572,6 +600,8 @@ pub struct AppState { pub vibe_modal_open: bool, pub login_modal_open: bool, pub eq_popover_open: bool, + pub equalizer_modal_open: bool, + pub shortcuts_modal_open: bool, pub playlist_modal: PlaylistModalState, pub track_detail_modal: Option, pub token_input: String, @@ -584,7 +614,11 @@ pub struct AppState { pub clear_cover_cache_requested: bool, pub cover_cache_capacity_dirty: bool, pub pending_clipboard_text: Option, - pub available_update: Option<(String, String)>, + pub available_update: Option, + pub releases: Vec, + pub releases_loading: bool, + pub release_notes_modal_open: bool, + pub update_notification_dismissed: bool, pub persist_enabled: bool, } @@ -597,6 +631,7 @@ impl AppState { config.eq_enabled, config.eq_bands_db, config.normalize_loudness, + config.crossfade_enabled, config.crossfade_secs, ); let mut api = YandexApiClient::new(config.oauth_token.clone()); @@ -655,8 +690,12 @@ 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, @@ -682,6 +721,7 @@ 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(), @@ -714,6 +754,8 @@ 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(), @@ -725,6 +767,10 @@ 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, }; @@ -805,8 +851,12 @@ 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, @@ -832,6 +882,7 @@ 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(), @@ -864,6 +915,8 @@ 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(), @@ -875,6 +928,10 @@ 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, } } @@ -1238,59 +1295,141 @@ impl AppState { }) } - /// 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); + /// Built-in offline fallback release notes so `ReleaseNotesModal` is always populated immediately. + pub fn builtin_fallback_releases() -> Vec { + vec![ + ReleaseNoteEntry { + tag: format!("v{}", APP_VERSION), + version: APP_VERSION.to_string(), + name: format!("v{}", APP_VERSION), + date: "2026-11-27".to_string(), + body: "## Что нового\n- Плавные переходы между страницами, шторкой очереди, полноэкранным плеером и модалками\n- Быстрое параллельное скачивание треков с круговым индикатором прогресса без спама уведомлениями\n- Встроенный список изменений («Что нового?») и уведомление о доступном обновлении как в оригинале".to_string(), + html_url: "https://git.tatar/marwy/yandex-music-rs/releases/latest".to_string(), + }, + ReleaseNoteEntry { + tag: "v0.1.5".to_string(), + version: "0.1.5".to_string(), + name: "v0.1.5".to_string(), + date: "2026-11-27".to_string(), + body: "- Нативный системный трей Linux (StatusNotifierItem через `ksni` без GTK/libappindicator)\n- Кнопка сворачивания левой панели 1-в-1 как в Яндекс Музыке 5.129.0\n- Оптимизации памяти без потери производительности GPU-рендера".to_string(), + html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v0.1.5".to_string(), + }, + ReleaseNoteEntry { + tag: "v0.1.4".to_string(), + version: "0.1.4".to_string(), + name: "v0.1.4".to_string(), + date: "2026-11-27".to_string(), + body: "- Полноэкранный плеер 1-в-1 и синхронизированный текст песен (SyncLyrics)\n- Отображение плейлистов «Мне нравится» друзей с сердечками на обложках\n- Корректное кадрирование обложек `object-fit: cover` и изолированный скролл каруселей".to_string(), + html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v0.1.4".to_string(), + }, + ] + } + + /// Fetch release changelog + check for newer versions from Forgejo releases API. + pub fn fetch_releases_and_updates(&mut self, user_initiated: bool) { + if self.releases_loading && !user_initiated { + return; } - self.show_toast(self.i18n().toast_checking_updates()); + self.releases_loading = true; let tx = self.tx_api.clone(); self.runtime.spawn(async move { - 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"; + const RELEASES_API: &str = + "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases?limit=15"; + const RELEASES_WEB: &str = + "https://git.tatar/marwy/yandex-music-rs/releases"; let client = reqwest::Client::builder() .timeout(Duration::from_secs(6)) .user_agent(format!("yandex-music-rs/{}", APP_VERSION)) .build(); let res = match client { - Ok(http) => match http.get(LATEST_RELEASE_API).send().await { + Ok(http) => match http.get(RELEASES_API).send().await { Ok(resp) if resp.status().is_success() => { - match resp.json::().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) + match resp.json::>().await { + Ok(arr) => { + let mut entries = Vec::new(); + for val in arr { + if val["draft"].as_bool().unwrap_or(false) { + continue; + } + let tag = val["tag_name"] + .as_str() + .map(str::trim) + .unwrap_or("") + .to_string(); + let version = tag.trim_start_matches(['v', 'V']).to_string(); + if version.is_empty() { + continue; + } + let name = val["name"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(&tag) + .to_string(); + let raw_date = val["published_at"] + .as_str() + .or_else(|| val["created_at"].as_str()) + .unwrap_or(""); + let date = raw_date + .split('T') + .next() + .unwrap_or("") + .trim() + .to_string(); + let body = val["body"] + .as_str() + .unwrap_or("") + .trim() + .to_string(); + let html_url = val["html_url"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(RELEASES_WEB) + .to_string(); + entries.push(ReleaseNoteEntry { + tag, + version, + name, + date, + body, + html_url, + }); } + Ok(entries) } Err(e) => Err(e.to_string()), } } - Ok(resp) if resp.status().as_u16() == 404 => Ok(None), + Ok(resp) if resp.status().as_u16() == 404 => Ok(Vec::new()), Ok(resp) => Err(format!("HTTP {}", resp.status().as_u16())), Err(e) => Err(e.to_string()), }, Err(e) => Err(e.to_string()), }; - let _ = tx.send(ApiEvent::UpdateCheckFinished(res)); + let _ = tx.send(ApiEvent::ReleasesLoaded { + result: res, + user_initiated, + }); }); } - pub fn bootstrap_api(&self) { + /// 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); + } // 1. Landing data + Concerts + Metatags { let api = self.api.clone(); @@ -1753,10 +1892,15 @@ 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 { @@ -2013,13 +2157,14 @@ 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); + .load_stream(track_id, stream, duration_ms, r128_i, r128_tp, fade); } Err(e) => { log::warn!("Stream resolve failed: {}", e); @@ -2034,6 +2179,37 @@ 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()) { @@ -2244,17 +2420,24 @@ 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 } => { - self.downloading_track_ids.remove(&track.id); - if self.download_batch_total > 0 { + 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.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 { @@ -2267,30 +2450,74 @@ impl AppState { .any(|tr| tr.id == track.id) { self.config.downloaded_tracks.insert(0, track.clone()); - self.save_config(); + self.download_config_dirty_count += 1; + if self.download_config_dirty_count >= 10 { + self.save_config(); + self.download_config_dirty_count = 0; + } } - self.show_toast(t.toast_track_downloaded(&track.title)); + self.download_batch_succeeded += 1; } Err(e) => { log::warn!("Offline download failed for {}: {}", track.id, e); - self.show_toast(t.toast_download_error()); + 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()); + } } } } - 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()); - } - }, } } @@ -2751,6 +2978,12 @@ 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 @@ -2794,10 +3027,31 @@ 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 @@ -2838,6 +3092,11 @@ 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); @@ -3118,4 +3377,49 @@ mod tests { assert_eq!(pins[1].id, "2002:3"); assert_eq!(pins[1].owner_uid.as_deref(), Some("2002")); } + + #[test] + fn test_download_batch_no_per_track_toast_spam() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let mut app = AppState::new_visual_test( + rt.handle().clone(), + "test-gpu".into(), + Route::LikedTracks, + AppConfig::default(), + LandingData::default(), + None, + Vec::new(), + Vec::new(), + 0, + 0, + 0.0, + ); + + for i in 1..=3 { + let tid = format!("dl_t{}", i); + app.downloading_track_ids.insert(tid.clone()); + app.downloading_track_progress.insert(tid.clone(), 0.5); + app.download_batch_total += 1; + } + for i in 1..=3 { + let tid = format!("dl_t{}", i); + let tr = Track { + id: tid.clone(), + title: format!("Track {}", i), + ..Default::default() + }; + let _ = app.tx_api.send(ApiEvent::TrackDownloaded { + track: tr, + result: Ok(PathBuf::from(format!("/tmp/{}.mp3", tid))), + }); + } + assert!(app.poll_async_events()); + assert!( + app.toast.is_none(), + "Successful track downloads must NOT spam per-track toasts" + ); + assert_eq!(app.downloaded_track_ids.len(), 3); + assert!(app.downloading_track_ids.is_empty()); + assert_eq!(app.download_batch_total, 0); + } } diff --git a/src/audio/dsp.rs b/src/audio/dsp.rs index a4ff06a..776656c 100644 --- a/src/audio/dsp.rs +++ b/src/audio/dsp.rs @@ -1,28 +1,140 @@ use std::f32::consts::PI; pub const EQ_FREQS: [f32; 10] = [ - 32.0, 64.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0, + 60.0, 170.0, 310.0, 600.0, 1000.0, 3000.0, 6000.0, 12000.0, 14000.0, 16000.0, ]; pub const EQ_LABELS: [&str; 10] = [ - "32", "64", "125", "250", "500", "1k", "2k", "4k", "8k", "16k", + "60", "170", "310", "600", "1k", "3k", "6k", "12k", "14k", "16k", ]; pub struct EqPreset { - pub name: &'static str, + pub name_ru: &'static str, + pub name_en: &'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: "Плоский", 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] }, + 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: "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: "Concert", + 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: "Party", + 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 Music", + 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], + }, ]; +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" + } +} + #[derive(Clone, Copy)] struct Biquad { b0: f32, @@ -51,13 +163,17 @@ 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.b0 = 1.0; - self.b1 = 0.0; - self.b2 = 0.0; - self.a1 = 0.0; - self.a2 = 0.0; + self.set_identity(); return; } let a = 10.0f32.powf(gain_db / 40.0); @@ -79,6 +195,58 @@ 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; @@ -115,7 +283,13 @@ impl Equalizer10Band { if self.gains_db != gains_db { self.gains_db = gains_db; for i in 0..10 { - self.bands[i].set_peaking(self.sample_rate, EQ_FREQS[i], 1.41, gains_db[i]); + 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]); + } } } } @@ -178,3 +352,26 @@ 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), "Свой"); + + let mut eq = Equalizer10Band::new(48_000.0); + eq.update(true, 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()); + } + } +} diff --git a/src/audio/mod.rs b/src/audio/mod.rs index e5cc967..0c68225 100644 --- a/src/audio/mod.rs +++ b/src/audio/mod.rs @@ -16,7 +16,7 @@ use symphonia::core::meta::MetadataOptions; use symphonia::core::probe::Hint; use symphonia::core::units::Time; -use crate::api::models::ResolvedStream; +use crate::api::models::{ResolvedStream, TrackFade}; use crate::api::signing::decrypt_encraw_at_offset; use dsp::{AudioEnergyAnalyzer, Equalizer10Band}; @@ -31,8 +31,21 @@ pub enum AudioCommand { duration_ms: u64, r128_i: Option, r128_tp: Option, + fade: Option, seek_seq: u64, }, + PreloadNext { + track_id: String, + stream: ResolvedStream, + duration_ms: u64, + r128_i: Option, + r128_tp: Option, + fade: Option, + preload_gen: u64, + }, + ClearPreload { + preload_gen: u64, + }, Play, Pause, Stop { @@ -53,6 +66,7 @@ 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, @@ -61,6 +75,7 @@ pub struct SharedAudioState { pub active_codec: Mutex, pub output_device_name: Mutex, pub last_error: Mutex>, + pub crossfaded_track_id: Mutex>, } impl SharedAudioState { @@ -70,6 +85,7 @@ impl SharedAudioState { eq_enabled: bool, eq_bands: [f32; 10], normalize_loudness: bool, + crossfade_enabled: bool, crossfade_secs: f32, ) -> Self { Self { @@ -84,6 +100,7 @@ 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()), @@ -92,6 +109,7 @@ impl SharedAudioState { 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), } } @@ -144,6 +162,7 @@ pub fn compute_r128_gain( pub struct AudioEngine { tx_cmd: Sender, pub state: Arc, + preload_gen: AtomicU64, } impl AudioEngine { @@ -153,6 +172,7 @@ impl AudioEngine { eq_enabled: bool, eq_bands: [f32; 10], normalize_loudness: bool, + crossfade_enabled: bool, crossfade_secs: f32, ) -> Self { let state = Arc::new(SharedAudioState::new( @@ -161,6 +181,7 @@ impl AudioEngine { eq_enabled, eq_bands, normalize_loudness, + crossfade_enabled, crossfade_secs, )); let (tx_cmd, rx_cmd) = unbounded(); @@ -171,16 +192,24 @@ impl AudioEngine { .spawn(move || run_audio_worker(rx_cmd, state_bg)) .expect("Failed to spawn audio thread"); - Self { tx_cmd, state } + Self { + tx_cmd, + state, + preload_gen: AtomicU64::new(0), + } } /// Silent, thread-free audio engine for deterministic headless visual tests. 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_bands, true, 0.0, + volume, muted, eq_enabled, eq_bands, true, false, 0.0, )); let (tx_cmd, _rx_cmd) = unbounded(); - Self { tx_cmd, state } + Self { + tx_cmd, + state, + preload_gen: AtomicU64::new(0), + } } pub fn load_stream( @@ -190,7 +219,10 @@ impl AudioEngine { duration_ms: u64, r128_i: Option, r128_tp: Option, + fade: Option, ) { + self.preload_gen.fetch_add(1, Ordering::SeqCst); + *self.state.crossfaded_track_id.lock() = None; let seek_seq = { let _guard = self.state.position_lock.lock(); let seq = self.state.seek_seq.fetch_add(1, Ordering::SeqCst) + 1; @@ -218,10 +250,39 @@ impl AudioEngine { duration_ms, r128_i, r128_tp, + fade, seek_seq, }); } + pub fn preload_next( + &self, + track_id: String, + stream: ResolvedStream, + duration_ms: u64, + r128_i: Option, + r128_tp: Option, + fade: Option, + ) { + let gen = self.preload_gen.fetch_add(1, Ordering::SeqCst) + 1; + let _ = self.tx_cmd.send(AudioCommand::PreloadNext { + track_id, + stream, + duration_ms, + r128_i, + r128_tp, + fade, + preload_gen: gen, + }); + } + + pub fn clear_preload(&self) { + let gen = self.preload_gen.fetch_add(1, Ordering::SeqCst) + 1; + let _ = self + .tx_cmd + .send(AudioCommand::ClearPreload { preload_gen: gen }); + } + pub fn play(&self) { self.state.is_playing.store(true, Ordering::SeqCst); let _ = self.tx_cmd.send(AudioCommand::Play); @@ -243,6 +304,8 @@ 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; @@ -285,6 +348,10 @@ 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 @@ -299,6 +366,10 @@ impl AudioEngine { pub fn take_track_finished(&self) -> bool { self.state.track_finished.swap(false, Ordering::SeqCst) } + + pub fn take_crossfaded_track_id(&self) -> Option { + self.state.crossfaded_track_id.lock().take() + } } // ============================================================================= @@ -437,6 +508,20 @@ struct ActiveStreamDecoder { min_report_frames: u64, total_frames: u64, eof: bool, + meta_track_id: String, + duration_ms: u64, + codec_label: String, + r128_i: Option, + r128_tp: Option, + gain_applied: bool, + fade: Option, + fade_in_window: Option<(u64, u64)>, +} + +struct OutgoingCrossfade { + dec: ActiveStreamDecoder, + start_frame: u64, + stop_frame: u64, } impl ActiveStreamDecoder { @@ -734,9 +819,115 @@ fn open_streaming_decoder( min_report_frames: 0, total_frames, eof: false, + meta_track_id: String::new(), + duration_ms: fallback_duration_ms, + codec_label: format!("{} {} kbps", stream.codec_label, stream.bitrate_kbps), + r128_i: None, + r128_tp: None, + gain_applied: stream.gain_applied, + fade: None, + fade_in_window: None, }) } +#[inline] +fn deck_gain(dec: &ActiveStreamDecoder, normalize: bool) -> f32 { + compute_r128_gain(normalize, dec.gain_applied, dec.r128_i, dec.r128_tp) +} + +#[inline] +fn fade_out_gain(t: f32) -> f32 { + (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).cos() +} + +#[inline] +fn fade_in_gain(t: f32) -> f32 { + (t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin() +} + +pub(crate) fn compute_crossfade_out_window( + fade: Option, + total_frames: u64, + device_rate: u32, + crossfade_enabled: bool, + crossfade_secs: f32, +) -> Option<(u64, u64)> { + let rate = device_rate.max(1) as u64; + if !crossfade_enabled || total_frames < rate * 4 { + return None; + } + if crossfade_secs > 0.1 { + let cf = ((crossfade_secs.clamp(0.5, 12.0) * rate as f32) as u64).min(total_frames / 3); + return Some((total_frames.saturating_sub(cf), total_frames)); + } + if let Some(f) = fade.filter(|f| f.is_valid()) { + let min_start = total_frames / 2; + let out_start = ((f.out_start * rate as f32) as u64).clamp(min_start, total_frames); + let mut out_stop = ((f.out_stop * rate as f32) as u64).clamp(out_start, total_frames); + let min_dur = rate / 2; + let max_dur = rate * 12; + if out_stop.saturating_sub(out_start) < min_dur { + out_stop = (out_start + min_dur).min(total_frames); + } + if out_stop.saturating_sub(out_start) > max_dur { + out_stop = (out_start + max_dur).min(total_frames); + } + if out_stop > out_start + 100 { + return Some((out_start, out_stop)); + } + } + let cf = ((3.5 * rate as f32) as u64).min(total_frames / 3); + Some((total_frames.saturating_sub(cf), total_frames)) +} + +pub(crate) fn compute_crossfade_in_window( + fade: Option, + total_frames: u64, + device_rate: u32, + crossfade_enabled: bool, + crossfade_secs: f32, +) -> Option<(u64, u64)> { + let rate = device_rate.max(1) as u64; + if !crossfade_enabled || total_frames < rate * 4 { + return None; + } + if crossfade_secs > 0.1 { + let cf = ((crossfade_secs.clamp(0.5, 12.0) * rate as f32) as u64).min(total_frames / 3); + return Some((0, cf)); + } + if let Some(f) = fade.filter(|f| f.is_valid()) { + let in_start = ((f.in_start * rate as f32) as u64).min(total_frames / 3); + let mut in_stop = ((f.in_stop * rate as f32) as u64).clamp(in_start, total_frames / 2); + let min_dur = rate / 2; + let max_dur = rate * 12; + if in_stop.saturating_sub(in_start) < min_dur { + in_stop = (in_start + rate * 3).min(total_frames / 2); + } + if in_stop.saturating_sub(in_start) > max_dur { + in_stop = (in_start + max_dur).min(total_frames / 2); + } + if in_stop > in_start + 100 { + return Some((in_start, in_stop)); + } + } + let cf = ((3.5 * rate as f32) as u64).min(total_frames / 3); + Some((0, cf)) +} + +fn next_stereo_frame(dec: &mut ActiveStreamDecoder) -> Option<(f32, f32)> { + if dec.pending_idx + 1 >= dec.pending.len() && !dec.decode_next_packet() { + return None; + } + if dec.pending_idx + 1 >= dec.pending.len() { + return None; + } + let l = dec.pending[dec.pending_idx]; + let r = dec.pending[dec.pending_idx + 1]; + dec.pending_idx += 2; + dec.played_frames += 1; + Some((l, r)) +} + /// Atomically publish decoder playback position ONLY if no newer `seek_ms` / `load_stream` / `stop` /// has occurred since `applied_seek_seq`. Prevents stale decoder frames from teleporting the seek bar /// back to the pre-seek position! @@ -831,8 +1022,7 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc 0.0 } }; - let track_gain = state_cb.track_gain(); - let gain = vol * track_gain; + let gain = vol; let eq_on = state_cb.eq_enabled.load(Ordering::Relaxed); if let Some(bands) = state_cb.eq_bands.try_lock() { @@ -898,10 +1088,25 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc .ok(); let mut active: Option = None; + let mut outgoing: Option = None; + let mut preloaded: Option = None; + let mut latest_preload_gen: u64 = 0; + let (tx_preloaded, rx_preloaded) = + crossbeam_channel::unbounded::<(u64, ActiveStreamDecoder)>(); let mut applied_seek_seq: u64 = 0; let mut flush_wait_iters: u8 = 0; loop { + while let Ok((gen, dec)) = rx_preloaded.try_recv() { + if gen == latest_preload_gen { + if let Some(old) = preloaded.replace(dec) { + old.abort(); + } + } else { + dec.abort(); + } + } + let mut raw_cmds = Vec::new(); while let Ok(cmd) = rx_cmd.try_recv() { raw_cmds.push(cmd); @@ -911,15 +1116,24 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc for cmd in non_seeks { match cmd { AudioCommand::LoadStream { + track_id, stream, duration_ms, r128_i, r128_tp, + fade, .. } => { if let Some(old) = active.take() { old.abort(); } + if let Some(old_out) = outgoing.take() { + old_out.dec.abort(); + } + if let Some(old_pre) = preloaded.take() { + old_pre.abort(); + } + latest_preload_gen = latest_preload_gen.wrapping_add(1); flush_rb.store(true, Ordering::Release); flush_wait_iters = 0; state.is_buffering.store(true, Ordering::SeqCst); @@ -935,13 +1149,18 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc if let Some(ref rt) = rt { match open_streaming_decoder(rt.handle(), &stream, device_rate, duration_ms) { - Ok(dec) => { + Ok(mut 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); } @@ -955,6 +1174,42 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc } state.is_buffering.store(false, Ordering::SeqCst); } + AudioCommand::PreloadNext { + track_id, + stream, + duration_ms, + r128_i, + r128_tp, + fade, + preload_gen, + } => { + latest_preload_gen = preload_gen; + if let Some(old_pre) = preloaded.take() { + old_pre.abort(); + } + if let Some(ref rt) = rt { + let handle = rt.handle().clone(); + let tx_p = tx_preloaded.clone(); + rt.spawn_blocking(move || { + if let Ok(mut dec) = + open_streaming_decoder(&handle, &stream, device_rate, duration_ms) + { + dec.meta_track_id = track_id; + dec.duration_ms = duration_ms; + dec.r128_i = r128_i; + dec.r128_tp = r128_tp; + dec.fade = fade; + let _ = tx_p.send((preload_gen, dec)); + } + }); + } + } + AudioCommand::ClearPreload { preload_gen } => { + latest_preload_gen = preload_gen; + if let Some(old_pre) = preloaded.take() { + old_pre.abort(); + } + } AudioCommand::Play => { state.is_playing.store(true, Ordering::SeqCst); } @@ -966,6 +1221,13 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc if let Some(old) = active.take() { old.abort(); } + if let Some(old_out) = outgoing.take() { + old_out.dec.abort(); + } + if let Some(old_pre) = preloaded.take() { + old_pre.abort(); + } + latest_preload_gen = latest_preload_gen.wrapping_add(1); flush_rb.store(true, Ordering::Release); flush_wait_iters = 0; } @@ -976,7 +1238,11 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc if let Some((ms, seq)) = pending_seek { flush_rb.store(true, Ordering::Release); flush_wait_iters = 0; + if let Some(old_out) = outgoing.take() { + old_out.dec.abort(); + } if let Some(ref mut dec) = active { + dec.fade_in_window = None; if dec.seek_ms(ms) { dec.played_frames = (ms * device_rate as u64) / 1000; dec.min_report_frames = dec.played_frames; @@ -1003,38 +1269,150 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc } let mut pushed_any = false; - if let Some(ref mut dec) = active { - let cf_frames = (state.crossfade_secs() * device_rate as f32) as u64; + 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() { 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; } - if dec.pending_idx >= dec.pending.len() && !dec.decode_next_packet() { - 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); } - 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); + + // 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 _ = prod.try_push(pair[0] * env); - let _ = prod.try_push(pair[1] * env); - dec.played_frames += 1; + + 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; } - dec.pending_idx += avail; + + 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; + } + } + break; + } + + let dec = active.as_ref().unwrap(); let buffered_frames = if _cpal_stream.is_some() { (prod.occupied_len() / 2) as u64 } else { @@ -1049,24 +1427,29 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc pushed_any = true; } - // Keep audible playback position smoothly updating while CPAL drains the ring buffer. if !pushed_any && _cpal_stream.is_some() && !flush_rb.load(Ordering::Acquire) { - 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 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); + } } - if dec.eof - && dec.pending_idx >= dec.pending.len() - && applied_seek_seq == state.seek_seq.load(Ordering::Acquire) - { + 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) + }) { 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(); + } } } @@ -1149,4 +1532,36 @@ mod tests { assert!(!publish_decoder_position_ms(&engine.state, 0, 45_200)); assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 0); } + + #[test] + fn test_crossfade_windows_and_equal_power_curves() { + let rate = 48_000u32; + let total = 200 * rate as u64; + let smart = TrackFade { + in_start: 0.5, + in_stop: 4.5, + out_start: 194.0, + out_stop: 199.0, + }; + assert_eq!( + compute_crossfade_out_window(Some(smart), total, rate, false, 0.0), + None + ); + let out_auto = compute_crossfade_out_window(Some(smart), total, rate, true, 0.0).unwrap(); + assert_eq!(out_auto, (194 * rate as u64, 199 * rate as u64)); + let in_auto = compute_crossfade_in_window(Some(smart), total, rate, true, 0.0).unwrap(); + assert_eq!(in_auto, (rate as u64 / 2, (4.5 * rate as f32) as u64)); + + // Fallback when track has no `fade` metadata + let out_fb = compute_crossfade_out_window(None, total, rate, true, 0.0).unwrap(); + assert_eq!(out_fb.1 - out_fb.0, (3.5 * rate as f32) as u64); + + // Manual duration override + let out_man = compute_crossfade_out_window(Some(smart), total, rate, true, 6.0).unwrap(); + assert_eq!(out_man.1 - out_man.0, 6 * rate as u64); + + // Equal-power crossfade preserves constant power at midpoint (0.5^2 + 0.5^2 -> 1.0) + let p_mid = fade_out_gain(0.5).powi(2) + fade_in_gain(0.5).powi(2); + assert!((p_mid - 1.0).abs() < 1e-5); + } } diff --git a/src/config.rs b/src/config.rs index 45cae2b..eee290f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -154,6 +154,8 @@ pub struct AppConfig { pub eq_enabled: bool, 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, @@ -206,6 +208,7 @@ impl Default for AppConfig { eq_enabled: false, eq_bands_db: [0.0; 10], normalize_loudness: true, + crossfade_enabled: true, crossfade_secs: 0.0, ai_content_reduction: false, child_mode: false, diff --git a/src/engine/widgets.rs b/src/engine/widgets.rs index e07daed..646aeff 100644 --- a/src/engine/widgets.rs +++ b/src/engine/widgets.rs @@ -512,6 +512,8 @@ 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, } @@ -526,6 +528,8 @@ impl Default for TrackRowOptions { is_liked: false, is_disliked: false, is_downloaded: false, + is_downloading: false, + download_progress: 0.0, menu_open: false, } } @@ -694,8 +698,13 @@ pub fn track_row( pal.text_secondary }; - // 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 }; + // 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 + }; 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 @@ -729,7 +738,17 @@ pub fn track_row( ); badge_x += 22.0; } - if opts.is_downloaded { + 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 { ctx.draw_icon( Icon::Downloaded, Rect::from_center_size(Pos2::new(badge_x + 8.0, title_rect.center_y()), Vec2::splat(16.0)), @@ -1799,3 +1818,76 @@ pub fn draw_playing_eq_bars( ctx.request_repaint_after(std::time::Duration::from_millis(40)); } } + +/// Smooth circular progress ring matching official Yandex Music 5.129.0 `CircleProgress` (`68254`). +pub fn draw_circular_progress_ring( + ctx: &mut UiContext, + center: Pos2, + radius: f32, + stroke_w: f32, + progress: f32, + track_color: Color, + progress_color: Color, +) { + use std::f32::consts::{FRAC_PI_2, TAU}; + + ctx.dl() + .push_circle_stroke(center, radius, stroke_w, track_color); + + let frac = progress.clamp(0.0, 1.0); + let (start_angle, sweep) = if frac < 0.03 { + if ctx.input.time > 0.001 { + ctx.request_repaint_after(std::time::Duration::from_millis(24)); + } + ((ctx.input.time as f32 * 3.2) - FRAC_PI_2, 0.24 * TAU) + } else { + (-FRAC_PI_2, frac * TAU) + }; + + let segments = ((sweep / TAU) * 32.0).ceil().max(4.0) as usize; + let step = sweep / segments as f32; + for i in 0..segments { + let a0 = start_angle + i as f32 * step; + let a1 = start_angle + (i + 1) as f32 * step; + let p0 = Pos2::new(center.x + radius * a0.cos(), center.y + radius * a0.sin()); + let p1 = Pos2::new(center.x + radius * a1.cos(), center.y + radius * a1.sin()); + ctx.dl().push_line(p0, p1, stroke_w, progress_color); + } +} + +/// Official Yandex Music 5.129.0 `DownloadingProgress` (`79262` / `63298c27abf81dc6.css:210-218`): +/// yellow circular progress ring with optional centered `close` (`×`) cancel icon. +pub fn draw_downloading_progress( + ctx: &mut UiContext, + pal: &YmPalette, + center: Pos2, + size: f32, + progress: f32, + with_cancel_icon: bool, + hovered: bool, +) { + let stroke_w = if size >= 22.0 { 2.2 } else { 1.8 }; + let radius = ((size - stroke_w) * 0.5).max(3.0); + draw_circular_progress_ring( + ctx, + center, + radius, + stroke_w, + progress, + pal.border_control, + pal.yellow, + ); + if with_cancel_icon { + let icon_sz = (size * 0.42).clamp(8.0, 12.0); + let tint = if hovered { + pal.text_bright + } else { + pal.text_primary + }; + ctx.draw_icon( + Icon::Close, + Rect::from_center_size(center, Vec2::splat(icon_sz)), + tint, + ); + } +} diff --git a/src/views/collection.rs b/src/views/collection.rs index c81e35b..2016195 100644 --- a/src/views/collection.rs +++ b/src/views/collection.rs @@ -1439,6 +1439,8 @@ 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), }, ) { @@ -1522,6 +1524,8 @@ fn render_virtual_track_list( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), + is_downloading: app.is_track_downloading(&tr.id), + download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { diff --git a/src/views/detail.rs b/src/views/detail.rs index 260a7a0..623f241 100644 --- a/src/views/detail.rs +++ b/src/views/detail.rs @@ -632,12 +632,18 @@ pub fn render_detail( .any(|tr| app.is_track_downloading(&tr.id)); if any_downloading { - let pct = app.download_progress_pct().unwrap_or(0); + let pct = app + .tracks_download_progress_pct(&raw_tracks) + .or_else(|| app.download_progress_pct()) + .unwrap_or(0); let label = format!("{}%", pct); - let btn_w = 78.0; + 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 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_bordered( + ctx.dl().push_rect( dl_r, 20.0, if resp.hovered { @@ -645,18 +651,20 @@ pub fn render_detail( } else { pal.surface_secondary }, - 1.5, - pal.yellow, ); - 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, + 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_text_ellipsis( &label, - TextStyle::bold(13.0, pal.text_primary), - Rect::from_xywh(dl_r.left() + 34.0, dl_r.top(), 40.0, dl_r.height()), + 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()), TextAlign::Left, ); if resp.hovered { @@ -824,6 +832,8 @@ 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), }, ) { diff --git a/src/views/for_you.rs b/src/views/for_you.rs index 5890b7d..68b21be 100644 --- a/src/views/for_you.rs +++ b/src/views/for_you.rs @@ -579,6 +579,8 @@ 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), }, ) { diff --git a/src/views/mod.rs b/src/views/mod.rs index d356813..b98ef1f 100644 --- a/src/views/mod.rs +++ b/src/views/mod.rs @@ -23,9 +23,10 @@ use crate::vulkan::vibe_renderer::VibePushConstants; use overlays::{ render_delete_playlist_confirm_modal, render_entity_context_menu, render_eq_popover, - 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, + 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, }; use player_bar::render_player_bar; use sidebar::render_sidebar; @@ -246,9 +247,46 @@ impl YandexMusicShell { ); } - // 3. Optional Right Slide-Over Drawer (Queue / Sync Lyrics; hidden when Fullscreen is open) + // 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!) 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 { @@ -256,13 +294,14 @@ 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_w - LAYOUT_GAP, + screen.right() - drawer_shift, content_top, drawer_w, (content_bottom - content_top).max(40.0), ); - if show_side_drawer { + if drawer_ease > 0.01 { render_right_drawer( &mut self.ui, &pal, @@ -279,7 +318,7 @@ impl YandexMusicShell { let vibe_rect = Rect::from_xywh( nav_w, screen.top(), - (screen.width() - nav_w - if show_side_drawer { drawer_w + LAYOUT_GAP * 2.0 } else { 0.0 }) + (screen.width() - nav_w - if drawer_ease > 0.01 { drawer_shift + LAYOUT_GAP } else { 0.0 }) .max(100.0), screen.height(), ); @@ -292,8 +331,15 @@ 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 show_side_drawer { + let content_right = if drawer_ease > 0.01 { drawer_rect.left() - LAYOUT_GAP } else { screen.right() - LAYOUT_GAP @@ -343,7 +389,13 @@ impl YandexMusicShell { ); // Exact inner content rect (+25px horizontal, +12px top so inner y stays 45.0 with +1px card_top) - let inner_r = outer_r.inset(25.0, 12.0, 25.0, 0.0); + 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(), + ); self.ui.push_clip(outer_r, CONTENT_RADIUS); match self.app.route.clone() { Route::MyVibe => {} @@ -450,11 +502,32 @@ 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 — sits below Popovers/Modals/Titlebar!) - if self.app.fullscreen_open { + // 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 { render_fullscreen_player( &mut self.ui, &pal, @@ -467,7 +540,7 @@ impl YandexMusicShell { // 6. Floating Popovers & Context Menus (ZLayer::Popover) if self.app.eq_popover_open { - render_eq_popover(&mut self.ui, &pal, &self.app, &mut actions); + render_eq_popover(&mut self.ui, &pal, &self.app, &mut self.shell, &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); @@ -490,6 +563,15 @@ 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); } + if self.app.release_notes_modal_open { + render_release_notes_modal(&mut self.ui, &pal, &self.app, &mut actions); + } + if self.app.equalizer_modal_open { + render_equalizer_modal(&mut self.ui, &pal, &self.app, &mut self.shell, &mut actions); + } + if self.app.shortcuts_modal_open { + render_shortcuts_modal(&mut self.ui, &pal, &self.app, &mut actions); + } // 8. Transparent 32px Floating TitleBar (ZLayer::Titlebar) let win_cmd = render_titlebar( @@ -500,10 +582,20 @@ impl YandexMusicShell { self.app.fullscreen_open, ); - // 9. Floating Toast (when splash is done) + // 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); + } + } if self.splash.is_none() { if let Some(msg) = self.app.current_toast().map(String::from) { - render_toast(&mut self.ui, &pal, &msg); + let extra_offset = if show_upd_notif { 64.0 } else { 0.0 }; + render_toast_with_offset(&mut self.ui, &pal, &msg, extra_offset); } } diff --git a/src/views/my_vibe.rs b/src/views/my_vibe.rs index 7a0c202..889d5fd 100644 --- a/src/views/my_vibe.rs +++ b/src/views/my_vibe.rs @@ -1110,10 +1110,10 @@ pub fn render_my_vibe( } } - // 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 { + // 9. BOTTOM-RIGHT VERSION BADGE (`APP_VERSION` = `0.1.5`, or `0.1.5 → {ver}` when update available!) + let (ver_label, ver_col) = if let Some(ref upd) = app.available_update { ( - format!("{} → {}", APP_VERSION, new_ver), + format!("{} → {}", APP_VERSION, upd.version), if pal.is_dark { pal.yellow } else { @@ -1148,7 +1148,7 @@ pub fn render_my_vibe( ctx.set_cursor(CursorKind::Pointer); } if ver_resp.clicked { - actions.push(AppAction::CheckForUpdates); + actions.push(AppAction::OpenReleaseNotesModal); } // 10. LEFT CURVED-ARC WHEEL CAROUSEL (`WheelDesktop` exact math from `vibe_wheel_foryou_spec.md` §2.1) diff --git a/src/views/overlays.rs b/src/views/overlays.rs index 7ceebc3..a43e08c 100644 --- a/src/views/overlays.rs +++ b/src/views/overlays.rs @@ -2,15 +2,19 @@ use std::time::Instant; use crossbeam_channel::Receiver; -use crate::api::models::{format_ms, Track, TrackLyrics}; +use crate::api::models::{format_ms, Track, TrackLyrics, UpdateInfo}; +use crate::app::i18n::APP_VERSION; +use crate::app::state::is_newer_version; use crate::app::{AppAction, AppState, PlaylistModalState, RepeatMode, RightDrawerTab, Route}; -use crate::audio::dsp::{EQ_LABELS, EQ_PRESETS}; +use crate::audio::dsp::{active_eq_preset_name, EQ_LABELS, EQ_PRESETS}; +use crate::config::AudioQuality; use crate::covers::CoverCache; +use crate::engine::text::RichSpan; use crate::engine::textures::{premultiply_rgba_srgb, TextureRegistry}; use crate::engine::widgets::{ - draw_cover_art, icon_button, secondary_pill_button, separated_artists, text_input_widget, - yellow_pill_button, ym_menu_frame, ym_menu_item, ym_menu_item_ex, ym_vertical_slider, - ym_volume_capsule, TextInputOptions, + draw_cover_art, draw_downloading_progress, icon_button, secondary_pill_button, + separated_artists, text_input_widget, yellow_pill_button, ym_menu_frame, ym_menu_item, + ym_menu_item_ex, ym_vertical_slider, ym_volume_capsule, TextInputOptions, }; use crate::engine::{ css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, TextAlign, TextStyle, TextureId, @@ -83,6 +87,11 @@ pub struct ShellUiState { pub fs_lyrics_upper_until: f64, pub fs_lyrics_last_mouse: Option, pub fs_lyrics_track_id: String, + pub last_route: Option, + pub route_transition_start: f64, + pub last_drawer_tab: Option, + pub fs_slide_dy: f32, + pub eq_presets_dropdown_open: bool, } impl ShellUiState { @@ -197,7 +206,12 @@ pub fn render_right_drawer( ) { let i18n = app.i18n(); let ru = i18n.is_ru(); - let tab = app.right_drawer; + let tab = if app.right_drawer != RightDrawerTab::None { + shell.last_drawer_tab = Some(app.right_drawer); + app.right_drawer + } else { + shell.last_drawer_tab.unwrap_or(RightDrawerTab::Queue) + }; ctx.with_layer(ZLayer::Drawer, |ctx| { ctx.register_blocker(rect); @@ -606,7 +620,15 @@ pub fn render_fullscreen_player( shell: &mut ShellUiState, actions: &mut Vec, ) { - let screen = ctx.screen_rect(); + let mut screen = ctx.screen_rect(); + if shell.fs_slide_dy.abs() > 0.5 { + screen = Rect::from_xywh( + screen.left(), + screen.top() + shell.fs_slide_dy, + screen.width(), + screen.height(), + ); + } let i18n = app.i18n(); let ru = i18n.is_ru(); let track = app.current_track(); @@ -1672,9 +1694,35 @@ pub fn render_track_context_menu( } y += row_h; - // 3. Download / Delete from device + // 3. Download / Downloading / Delete from device (`TrackContextMenuDownloadItem`) + let is_downloading = app.is_track_downloading(&tr.id); let r = Rect::from_xywh(inner.x, y, inner.w, row_h); - if ym_menu_item( + if is_downloading { + let dl_resp = ctx.interact(WidgetId::new("tcm_dl"), r); + if dl_resp.hovered { + ctx.dl().push_rect(r, 8.0, pal.surface_hover); + ctx.set_cursor(CursorKind::Pointer); + } + draw_downloading_progress( + ctx, + pal, + Pos2::new(r.left() + 18.0, r.center_y()), + 20.0, + app.track_download_progress(&tr.id), + true, + dl_resp.hovered, + ); + ctx.draw_text_ellipsis( + i18n.stop_download(), + TextStyle::medium(13.5, pal.text_primary), + Rect::from_xywh(r.left() + 38.0, r.top(), (r.width() - 46.0).max(40.0), r.height()), + TextAlign::Left, + ); + if dl_resp.clicked { + actions.push(AppAction::CancelDownload); + close_menu = true; + } + } else if ym_menu_item( ctx, pal, WidgetId::new("tcm_dl"), @@ -3606,15 +3654,33 @@ pub fn render_eq_popover( ctx: &mut UiContext, pal: &YmPalette, app: &AppState, + shell: &mut ShellUiState, actions: &mut Vec, ) { - let ru = app.i18n().is_ru(); + let i18n = app.i18n(); + let ru = i18n.is_ru(); let screen = ctx.screen_rect(); - let pop_w = 436.0; - let pop_h = 248.0; + let anim_t = if app.fixed_vibe_time.is_some() { + 1.0 + } else { + let raw = ctx.animate_bool(WidgetId::new("ym_quality_popover_anim"), true, 0.16); + let u = 1.0 - raw; + 1.0 - u * u * u + }; + let eq_expand_t = if app.fixed_vibe_time.is_some() { + if app.config.eq_enabled { 1.0 } else { 0.0 } + } else { + ctx.animate_bool(WidgetId::new("ym_quality_eq_expand"), app.config.eq_enabled, 0.18) + }; + + let pop_w = (screen.width() - 32.0).clamp(320.0, 430.0); + let base_h = 286.0; + let eq_extra_h = 256.0 * eq_expand_t; + let pop_h = (base_h + eq_extra_h).min((screen.height() - PLAYER_BAR_HEIGHT - 56.0).max(280.0)); + let slide_dy = (1.0 - anim_t) * 14.0; let pop_r = Rect::from_xywh( - (screen.right() - pop_w - 20.0).max(8.0), - (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 26.0).max(36.0), + (screen.right() - pop_w - 20.0).max(16.0), + (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 22.0 + slide_dy).max(40.0), pop_w, pop_h, ); @@ -3622,135 +3688,149 @@ pub fn render_eq_popover( let mut enabled = app.config.eq_enabled; let mut bands = app.config.eq_bands_db; let mut changed = false; + let mut dropdown_rect: Option = None; ctx.with_layer(ZLayer::Popover, |ctx| { ctx.register_blocker(pop_r); ctx.dl() - .push_shadow(pop_r, 16.0, 22.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); - ctx.dl() - .push_backdrop_blur(pop_r, 16.0, 2.0, pal.bg_menu, 1.0, pal.border_control); - - let inner = pop_r.shrink(14.0); - - // Header: Title + Enabled toggle + Close `×` - ctx.draw_text_ellipsis( - if ru { "Эквалайзер" } else { "Equalizer" }, - TextStyle::bold(15.0, pal.text_bright), - Rect::from_xywh(inner.x, inner.y, 120.0, 24.0), - TextAlign::Left, - ); - - let tog_r = Rect::from_xywh(inner.x + 126.0, inner.y, 110.0, 24.0); - let tog_resp = ctx.interact(WidgetId::new("eq_enable_tog"), tog_r); - let box_r = Rect::from_xywh(tog_r.x, tog_r.center_y() - 8.0, 16.0, 16.0); + .push_shadow(pop_r, 16.0, 24.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); ctx.dl().push_rect_bordered( - box_r, - 4.0, - if enabled { pal.yellow } else { Color::TRANSPARENT }, - 1.5, - if enabled { pal.yellow } else { pal.input_border }, + pop_r, + 16.0, + pal.bg_popover, + 1.0, + pal.border_subtle, ); - if enabled { - ctx.draw_icon( - Icon::CheckXxs, - Rect::from_center_size(box_r.center(), Vec2::splat(13.0)), - pal.on_yellow, - ); - } + + // Header: `"Настройки звука"` + circular Close `×` (`QualitySettings_headerWithCloseButton`) + let hdr_r = Rect::from_xywh(pop_r.left() + 20.0, pop_r.top() + 16.0, pop_w - 40.0, 32.0); ctx.draw_text_ellipsis( - if ru { "Включён" } else { "Enabled" }, - TextStyle::medium(12.5, pal.text_primary), - Rect::from_xywh(box_r.right() + 6.0, tog_r.y, 84.0, 24.0), + i18n.sound_settings(), + TextStyle::headline(18.0, pal.text_bright), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); - if tog_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if tog_resp.clicked { - enabled = !enabled; - changed = true; - } - if icon_button( ctx, - WidgetId::new("eq_close_btn"), - Rect::from_xywh(inner.right() - 24.0, inner.y, 24.0, 24.0), + WidgetId::new("qs_close_btn"), + Rect::from_xywh(hdr_r.right() - 28.0, hdr_r.top() + 2.0, 28.0, 28.0), Icon::Close, - 12.0, + 13.0, pal.text_secondary, pal.text_bright, pal.surface_hover, false, - app.i18n().close(), + i18n.close(), ) .clicked { + shell.eq_presets_dropdown_open = false; actions.push(AppAction::SetEqPopoverOpen(false)); } - // Preset chips row - let mut px = inner.x; - let py = inner.y + 32.0; - for (pi, preset) in EQ_PRESETS.iter().take(5).enumerate() { - let lbl_w = ctx - .measure_text(preset.name, TextStyle::medium(11.5, pal.text_primary), None) - .x - + 16.0; - let pr = Rect::from_xywh(px, py, lbl_w, 24.0); - let presp = ctx.interact(WidgetId::from_pair("eq_preset", pi), pr); - ctx.dl().push_rect( - pr, - 12.0, - if presp.hovered { pal.chip_hover } else { pal.chip_bg }, - ); - ctx.draw_text_ellipsis( - preset.name, - TextStyle::medium(11.5, pal.text_primary), - pr, - TextAlign::Center, - ); - if presp.hovered { + // 3 Official Quality Options (`QualitySettings_item`) + let mut y = hdr_r.bottom() + 10.0; + let qualities = [ + ( + AudioQuality::Lossless, + if ru { "Максимальное" } else { "Maximum" }, + if ru { + "Звук без потерь в формате FLAC (если доступно)" + } else { + "Lossless FLAC audio when available" + }, + ), + ( + AudioQuality::High, + if ru { "Оптимальное" } else { "Optimal" }, + if ru { + "Высокое качество звука (320 кбит/с)" + } else { + "High audio quality (320 kbps)" + }, + ), + ( + AudioQuality::Standard, + if ru { "Экономичное" } else { "Efficient" }, + if ru { + "Стабильное звучание при медленном интернете" + } else { + "Stable playback on slower connections" + }, + ), + ]; + + for (q, title, sub) in qualities { + let row_r = Rect::from_xywh(pop_r.left() + 10.0, y, pop_w - 20.0, 54.0); + let resp = ctx.interact(WidgetId::from_pair("qs_qual", q as u8), row_r); + let active = app.config.audio_quality == q; + if resp.hovered { + ctx.dl().push_rect(row_r, 10.0, pal.surface_hover); ctx.set_cursor(CursorKind::Pointer); } - if presp.clicked { - enabled = true; - bands = preset.gains; - changed = true; - } - px += lbl_w + 6.0; - } - - // 10 vertical band sliders - let band_top = py + 34.0; - let band_h = (inner.bottom() - band_top - 22.0).max(80.0); - let col_w = inner.w / 10.0; - for i in 0..10 { - let bx = inner.x + i as f32 * col_w; - let sr = Rect::from_xywh(bx + 4.0, band_top, col_w - 8.0, band_h); - let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); - let sresp = ym_vertical_slider( - ctx, - pal, - WidgetId::from_pair("eq_band", i), - sr, - norm, - false, - if enabled { pal.yellow } else { pal.text_primary }, - ); - if let Some(v) = sresp.value { - bands[i] = (v * 24.0 - 12.0).clamp(-12.0, 12.0); - enabled = true; - changed = true; - } + let txt_x = row_r.left() + 12.0; + let txt_w = (row_r.width() - 46.0).max(80.0); ctx.draw_text_ellipsis( - EQ_LABELS[i], - TextStyle::bold(10.0, pal.text_secondary), - Rect::from_xywh(bx, band_top + band_h + 4.0, col_w, 16.0), - TextAlign::Center, + title, + TextStyle::bold(14.5, pal.text_bright), + Rect::from_xywh(txt_x, row_r.top() + 8.0, txt_w, 19.0), + TextAlign::Left, ); + ctx.draw_text_ellipsis( + sub, + TextStyle::regular(12.0, pal.text_secondary), + Rect::from_xywh(txt_x, row_r.top() + 28.0, txt_w, 17.0), + TextAlign::Left, + ); + if active { + ctx.draw_icon( + Icon::CheckXxs, + Rect::from_center_size( + Pos2::new(row_r.right() - 18.0, row_r.center_y()), + Vec2::splat(16.0), + ), + pal.text_bright, + ); + } + if resp.clicked && !active { + actions.push(AppAction::SetAudioQuality(q)); + } + y += 56.0; } - if ctx.input.clicked_outside(pop_r) { + // Hairline divider before Equalizer section + y += 6.0; + ctx.dl().push_rect( + Rect::from_xywh(pop_r.left() + 20.0, y, pop_w - 40.0, 1.0), + 0.0, + pal.border_subtle, + ); + y += 14.0; + + // Inline Official Equalizer (`Equalizer_header` + expandable `EqualizerPresets` & 10 bands) + let eq_area = Rect::from_min_max( + Pos2::new(pop_r.left() + 20.0, y), + Pos2::new(pop_r.right() - 20.0, pop_r.bottom() - 16.0), + ); + dropdown_rect = render_equalizer_body( + ctx, + pal, + eq_area, + if ru { "Эквалайзер" } else { "Equalizer" }, + ru, + &mut enabled, + &mut bands, + &mut changed, + &mut shell.eq_presets_dropdown_open, + eq_expand_t > 0.15, + "qs_eq", + ); + + let clicked_in_dd = dropdown_rect + .and_then(|dr| ctx.input.pointer_pos.map(|p| dr.contains(p))) + .unwrap_or(false); + if ctx.input.clicked_outside(pop_r) && !clicked_in_dd { + shell.eq_presets_dropdown_open = false; actions.push(AppAction::SetEqPopoverOpen(false)); } }); @@ -3760,18 +3840,543 @@ pub fn render_eq_popover( } } +/// 1-to-1 Official `EqualizerModal` (`Equalizer_modal__yW0lz`, `430px` centered modal). +pub fn render_equalizer_modal( + ctx: &mut UiContext, + pal: &YmPalette, + app: &AppState, + shell: &mut ShellUiState, + actions: &mut Vec, +) { + let i18n = app.i18n(); + let ru = i18n.is_ru(); + let anim_t = if app.fixed_vibe_time.is_some() { + 1.0 + } else { + let raw = ctx.animate_bool(WidgetId::new("ym_eq_modal_anim"), true, 0.18); + let u = 1.0 - raw; + 1.0 - u * u * u + }; + let screen = ctx.screen_rect(); + let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); + let modal_h = 376.0; + let slide_dy = (1.0 - anim_t) * 14.0; + let modal_r = Rect::from_center_size( + Pos2::new(screen.center_x(), screen.center_y() + slide_dy), + Vec2::new(modal_w, modal_h), + ); + + let mut enabled = app.config.eq_enabled; + let mut bands = app.config.eq_bands_db; + let mut changed = false; + + ctx.with_layer(ZLayer::Modal, |ctx| { + ctx.register_blocker(screen); + ctx.dl().push_rect( + screen, + 0.0, + Color::rgba(0, 0, 0, (150.0 * anim_t).round() as u8), + ); + ctx.dl() + .push_shadow(modal_r, 16.0, 32.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); + ctx.dl() + .push_rect_bordered(modal_r, 16.0, pal.bg_popover, 1.0, pal.border_subtle); + + let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); + ctx.draw_text_ellipsis( + if ru { "Эквалайзер" } else { "Equalizer" }, + TextStyle::headline(20.0, pal.text_bright), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), + TextAlign::Left, + ); + if icon_button( + ctx, + WidgetId::new("eq_modal_close"), + Rect::from_xywh(hdr_r.right() - 30.0, hdr_r.top() + 1.0, 30.0, 30.0), + Icon::Close, + 15.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + i18n.close(), + ) + .clicked + { + shell.eq_presets_dropdown_open = false; + actions.push(AppAction::SetEqualizerModalOpen(false)); + } + + let eq_area = Rect::from_min_max( + Pos2::new(modal_r.left() + 20.0, hdr_r.bottom() + 18.0), + Pos2::new(modal_r.right() - 20.0, modal_r.bottom() - 20.0), + ); + let dd_rect = render_equalizer_body( + ctx, + pal, + eq_area, + if ru { + "Включить эквалайзер" + } else { + "Enable equalizer" + }, + ru, + &mut enabled, + &mut bands, + &mut changed, + &mut shell.eq_presets_dropdown_open, + true, + "em_eq", + ); + + let clicked_in_dd = dd_rect + .and_then(|dr| ctx.input.pointer_pos.map(|p| dr.contains(p))) + .unwrap_or(false); + if ctx.input.clicked_outside(modal_r) && !clicked_in_dd { + shell.eq_presets_dropdown_open = false; + actions.push(AppAction::SetEqualizerModalOpen(false)); + } + }); + + if changed { + actions.push(AppAction::UpdateEq { enabled, bands }); + } +} + +/// Shared official Yandex Music 5.129.0 Equalizer UI (`8711fa44496b8e09.css:136-299`): +/// Toggle header + Preset selector dropdown (18 presets) + `+12 / 0 / -12 dB` scale + 10 bands (`60`..`16k`). +#[allow(clippy::too_many_arguments)] +fn render_equalizer_body( + ctx: &mut UiContext, + pal: &YmPalette, + area: Rect, + toggle_title: &str, + ru: bool, + enabled: &mut bool, + bands: &mut [f32; 10], + changed: &mut bool, + dropdown_open: &mut bool, + show_sliders: bool, + salt: &str, +) -> Option { + // 1. Header row: Title + official Pill Toggle (`40×22`) + let hdr_r = Rect::from_xywh(area.left(), area.top(), area.width(), 28.0); + ctx.draw_text_ellipsis( + toggle_title, + TextStyle::bold(15.0, pal.text_bright), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 56.0, hdr_r.height()), + TextAlign::Left, + ); + let sw_r = Rect::from_xywh(hdr_r.right() - 42.0, hdr_r.center_y() - 11.0, 42.0, 22.0); + let sw_resp = ctx.interact(WidgetId::new(salt).with("toggle"), sw_r); + ctx.dl().push_rect( + sw_r, + 11.0, + if *enabled { + pal.yellow + } else { + pal.surface_hover + }, + ); + let knob_x = if *enabled { sw_r.right() - 11.0 } else { sw_r.left() + 11.0 }; + ctx.dl().push_circle( + Pos2::new(knob_x, sw_r.center_y()), + 8.5, + if *enabled { Color::rgb(0x19, 0x19, 0x19) } else { pal.text_bright }, + ); + if sw_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if sw_resp.clicked { + *enabled = !*enabled; + *changed = true; + if !*enabled { + *dropdown_open = false; + } + } + + if !show_sliders { + return None; + } + + let mut y = hdr_r.bottom() + 14.0; + let is_custom_or_modified = bands.iter().any(|&b| b.abs() >= 0.15); + + // 2. Preset selector button (`EqualizerPresets_root`) + optional Reset button + let reset_w = if is_custom_or_modified { 86.0 } else { 0.0 }; + let sel_w = (area.width() - if is_custom_or_modified { reset_w + 8.0 } else { 0.0 }).max(140.0); + let sel_r = Rect::from_xywh(area.left(), y, sel_w, 38.0); + let sel_resp = ctx.interact(WidgetId::new(salt).with("preset_sel"), sel_r); + ctx.dl().push_rect_bordered( + sel_r, + 12.0, + if sel_resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }, + 1.0, + if *dropdown_open { + pal.border_control + } else { + pal.border_subtle + }, + ); + let preset_lbl = active_eq_preset_name(bands, ru); + let label_col = if *enabled { + pal.text_bright + } else { + pal.text_disabled + }; + ctx.draw_text_ellipsis( + preset_lbl, + TextStyle::medium(13.5, label_col), + Rect::from_xywh(sel_r.left() + 14.0, sel_r.top(), sel_r.width() - 42.0, sel_r.height()), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowDown, + Rect::from_center_size(Pos2::new(sel_r.right() - 18.0, sel_r.center_y()), Vec2::splat(16.0)), + if *enabled { + pal.text_secondary + } else { + pal.text_disabled + }, + ); + if sel_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if sel_resp.clicked { + *dropdown_open = !*dropdown_open; + } + + if is_custom_or_modified { + let rst_r = Rect::from_xywh(sel_r.right() + 8.0, y, reset_w, 38.0); + let rst_resp = ctx.interact(WidgetId::new(salt).with("preset_rst"), rst_r); + ctx.dl().push_rect( + rst_r, + 12.0, + if rst_resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }, + ); + ctx.draw_text_ellipsis( + if ru { "Сбросить" } else { "Reset" }, + TextStyle::medium(12.5, pal.text_primary), + rst_r, + TextAlign::Center, + ); + if rst_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if rst_resp.clicked { + *bands = [0.0; 10]; + *changed = true; + *dropdown_open = false; + } + } + + y += 50.0; + + // 3. Left dB Scale (`+12 dB`, `0 dB`, `-12 dB`) + 10 Vertical Band Sliders (`9rem` = `144px`) + let scale_w = 42.0; + let sliders_h = 136.0; + let lbl_col = if *enabled { + pal.text_secondary + } else { + pal.text_disabled + }; + ctx.draw_text_ellipsis( + "+12 dB", + TextStyle::regular(11.0, lbl_col), + Rect::from_xywh(area.left(), y, scale_w, 16.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + "0 dB", + TextStyle::regular(11.0, lbl_col), + Rect::from_xywh(area.left(), y + sliders_h * 0.5 - 8.0, scale_w, 16.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + "-12 dB", + TextStyle::regular(11.0, lbl_col), + Rect::from_xywh(area.left(), y + sliders_h - 16.0, scale_w, 16.0), + TextAlign::Left, + ); + + let grid_x = area.left() + scale_w + 4.0; + let grid_w = (area.width() - scale_w - 4.0).max(160.0); + // Subtle 0 dB center reference line + ctx.dl().push_rect( + Rect::from_xywh(grid_x, (y + sliders_h * 0.5).round(), grid_w, 1.0), + 0.0, + pal.border_subtle, + ); + + let col_w = grid_w / 10.0; + let fill_col = if *enabled { + pal.yellow + } else { + pal.text_disabled + }; + for i in 0..10 { + let bx = grid_x + i as f32 * col_w; + let sr = Rect::from_xywh(bx + 2.0, y, (col_w - 4.0).max(18.0), sliders_h); + let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); + let sresp = ym_vertical_slider( + ctx, + pal, + WidgetId::new(salt).with("band").with(i), + sr, + norm, + false, + fill_col, + ); + if sresp.hovered || sresp.dragging { + ctx.show_tooltip(sr, format!("{:+.1} dB", bands[i])); + } + if let Some(v) = sresp.value { + let db = ((v * 24.0 - 12.0) * 2.0).round() * 0.5; + let clamped = db.clamp(-12.0, 12.0); + if (clamped - bands[i]).abs() >= 0.25 { + bands[i] = clamped; + *enabled = true; + *changed = true; + } + } + ctx.draw_text_ellipsis( + EQ_LABELS[i], + TextStyle::medium(11.0, lbl_col), + Rect::from_xywh(bx, y + sliders_h + 6.0, col_w, 16.0), + TextAlign::Center, + ); + } + + // 4. Floating Presets Dropdown (`EqualizerPresets_container`) rendered ON TOP of sliders! + if *dropdown_open { + let dd_h = 240.0f32.min((ctx.screen_rect().bottom() - sel_r.bottom() - 20.0).max(140.0)); + let dd_r = Rect::from_xywh(sel_r.left(), sel_r.bottom() + 6.0, sel_r.width(), dd_h); + ctx.register_blocker(dd_r); + ctx.dl() + .push_shadow(dd_r, 12.0, 20.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); + ctx.dl() + .push_rect_bordered(dd_r, 12.0, pal.bg_popover, 1.0, pal.border_control); + + let dd_scroll_id = WidgetId::new(salt).with("dd_scroll"); + let dd_inner = dd_r.shrink2(Vec2::new(6.0, 6.0)); + let scroll_y = ctx.begin_scroll_v(dd_scroll_id, dd_inner, 0.0); + let mut dy = dd_inner.top() - scroll_y; + let row_h = 36.0; + let cur_name = active_eq_preset_name(bands, ru); + + for (pi, preset) in EQ_PRESETS.iter().enumerate() { + let pname = preset.name(ru); + let rr = Rect::from_xywh(dd_inner.left(), dy, dd_inner.width() - 8.0, row_h); + let rresp = ctx.interact(WidgetId::new(salt).with("dd_item").with(pi), rr); + let is_cur = pname == cur_name; + if rresp.hovered { + ctx.dl().push_rect(rr, 8.0, pal.surface_hover); + ctx.set_cursor(CursorKind::Pointer); + } + ctx.draw_text_ellipsis( + pname, + TextStyle::medium(13.5, if is_cur { pal.text_bright } else { pal.text_primary }), + Rect::from_xywh(rr.left() + 10.0, rr.top(), rr.width() - 36.0, rr.height()), + TextAlign::Left, + ); + if is_cur { + ctx.draw_icon( + Icon::CheckXxs, + Rect::from_center_size(Pos2::new(rr.right() - 14.0, rr.center_y()), Vec2::splat(15.0)), + pal.yellow, + ); + } + if rresp.clicked { + *bands = preset.gains; + *enabled = true; + *changed = true; + *dropdown_open = false; + } + dy += row_h; + } + let total_dd_h = dy - (dd_inner.top() - scroll_y); + ctx.end_scroll_v(dd_scroll_id, pal, total_dd_h, true); + + if ctx.input.clicked_outside(dd_r) && !sel_resp.clicked { + *dropdown_open = false; + } + return Some(dd_r); + } + + None +} + +/// 1-to-1 Official `ShortcutsModal` (`29c95960ed6ac633.css:137-238`, `settings/page.js:1076-1175`). +pub fn render_shortcuts_modal( + ctx: &mut UiContext, + pal: &YmPalette, + app: &AppState, + actions: &mut Vec, +) { + let i18n = app.i18n(); + let ru = i18n.is_ru(); + let anim_t = if app.fixed_vibe_time.is_some() { + 1.0 + } else { + let raw = ctx.animate_bool(WidgetId::new("ym_shortcuts_modal_anim"), true, 0.18); + let u = 1.0 - raw; + 1.0 - u * u * u + }; + let screen = ctx.screen_rect(); + let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); + let modal_h = (screen.height() - 84.0).clamp(320.0, 560.0); + let slide_dy = (1.0 - anim_t) * 14.0; + let modal_r = Rect::from_center_size( + Pos2::new(screen.center_x(), screen.center_y() + slide_dy), + Vec2::new(modal_w, modal_h), + ); + + ctx.with_layer(ZLayer::Modal, |ctx| { + ctx.register_blocker(screen); + ctx.dl().push_rect( + screen, + 0.0, + Color::rgba(0, 0, 0, (150.0 * anim_t).round() as u8), + ); + ctx.dl() + .push_shadow(modal_r, 16.0, 32.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); + ctx.dl() + .push_rect_bordered(modal_r, 16.0, pal.bg_popover, 1.0, pal.border_subtle); + + let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); + ctx.draw_text_ellipsis( + if ru { "Горячие клавиши" } else { "Keyboard shortcuts" }, + TextStyle::headline(20.0, pal.text_bright), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), + TextAlign::Left, + ); + if icon_button( + ctx, + WidgetId::new("sc_modal_close"), + Rect::from_xywh(hdr_r.right() - 30.0, hdr_r.top() + 1.0, 30.0, 30.0), + Icon::Close, + 15.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + i18n.close(), + ) + .clicked + { + actions.push(AppAction::SetShortcutsModalOpen(false)); + } + + let shortcuts: &[(&str, &str, &[&str])] = &[ + ("Пауза / Воспроизведение", "Play / Pause", &["K"]), + ("Включить или выключить звук", "Mute / Unmute", &["M"]), + ("Прибавить громкость", "Increase volume", &["↑"]), + ("Уменьшить громкость", "Decrease volume", &["↓"]), + ("Нравится", "Like", &["F"]), + ("Не нравится", "Dislike", &["D"]), + ("Следующий трек", "Next track", &["N"]), + ("Предыдущий трек", "Previous track", &["P"]), + ("Перемотка вперёд", "Seek forward", &["→", "L"]), + ("Перемотка назад", "Seek backward", &["←", "J"]), + ("Повтор трека или очереди", "Repeat", &["R"]), + ("Перемешать", "Shuffle", &["S"]), + ("Полноэкранный плеер", "Fullscreen player", &["W"]), + ("Закрыть", "Close", &["Esc"]), + ]; + + let scroll_r = Rect::from_min_max( + Pos2::new(modal_r.left() + 20.0, hdr_r.bottom() + 18.0), + Pos2::new(modal_r.right() - 16.0, modal_r.bottom() - 20.0), + ); + let scroll_id = WidgetId::new("shortcuts_modal_scroll"); + let scroll_y = ctx.begin_scroll_v(scroll_id, scroll_r, 0.0); + let mut y = scroll_r.top() - scroll_y; + let or_word = if ru { "или" } else { "or" }; + let or_w = ctx + .measure_text(or_word, TextStyle::regular(12.5, pal.text_secondary), None) + .x + + 12.0; + + for (label_ru, label_en, keys) in shortcuts { + let row_h = 34.0; + let mut right_x = scroll_r.right() - 6.0; + for (ki, key) in keys.iter().rev().enumerate() { + let kw = (ctx + .measure_text(key, TextStyle::medium(12.5, pal.text_bright), None) + .x + + 16.0) + .max(32.0); + let kr = Rect::from_xywh(right_x - kw, y + 4.0, kw, 26.0); + ctx.dl().push_rect_bordered( + kr, + 6.0, + pal.surface_hover, + 1.0, + pal.border_control, + ); + ctx.draw_text_ellipsis( + key, + TextStyle::medium(12.5, pal.text_bright), + kr, + TextAlign::Center, + ); + right_x = kr.left() - 6.0; + if ki + 1 < keys.len() { + let or_r = Rect::from_xywh(right_x - or_w, y, or_w, row_h); + ctx.draw_text_ellipsis( + or_word, + TextStyle::regular(12.5, pal.text_secondary), + or_r, + TextAlign::Center, + ); + right_x = or_r.left() - 6.0; + } + } + let text_w = (right_x - scroll_r.left() - 10.0).max(100.0); + ctx.draw_text_ellipsis( + if ru { label_ru } else { label_en }, + TextStyle::regular(14.0, pal.text_bright), + Rect::from_xywh(scroll_r.left(), y, text_w, row_h), + TextAlign::Left, + ); + y += row_h + 4.0; + } + let total_h = y - (scroll_r.top() - scroll_y); + ctx.end_scroll_v(scroll_id, pal, total_h, true); + + if ctx.input.clicked_outside(modal_r) { + actions.push(AppAction::SetShortcutsModalOpen(false)); + } + }); +} + // ============================================================================= // 7. Floating Toast Notification // ============================================================================= pub fn render_toast(ctx: &mut UiContext, pal: &YmPalette, msg: &str) { + render_toast_with_offset(ctx, pal, msg, 0.0); +} + +pub fn render_toast_with_offset(ctx: &mut UiContext, pal: &YmPalette, msg: &str, extra_bottom_offset: f32) { let screen = ctx.screen_rect(); let max_w = (screen.width() - 64.0).min(520.0); let text_sz = ctx.measure_text(msg, TextStyle::medium(13.5, pal.text_bright), Some(max_w - 32.0)); let w = (text_sz.x + 36.0).clamp(160.0, max_w); let h = (text_sz.y + 20.0).max(40.0); let rect = Rect::from_center_size( - Pos2::new(screen.center_x(), screen.bottom() - PLAYER_BAR_HEIGHT - 44.0), + Pos2::new( + screen.center_x(), + screen.bottom() - PLAYER_BAR_HEIGHT - 44.0 - extra_bottom_offset, + ), Vec2::new(w, h), ); @@ -3789,6 +4394,498 @@ pub fn render_toast(ctx: &mut UiContext, pal: &YmPalette, msg: &str) { }); } +/// 1-to-1 Official `NotificationUpdate` (`28bcd8bd8493d95a.css:1-15` + `5eace9426adf24a8.css:12-23`): +/// Frosted floating bottom bar with available version text, `"Что нового?"` button, +/// yellow `"Обновить"` CTA button (`min-width: 112px`), and dismiss `×`. +pub fn render_update_notification( + ctx: &mut UiContext, + pal: &YmPalette, + app: &AppState, + upd: &UpdateInfo, + actions: &mut Vec, +) { + let i18n = app.i18n(); + let anim_t = if app.fixed_vibe_time.is_some() { + 1.0 + } else { + let raw = ctx.animate_bool(WidgetId::new("ym_update_notif_anim"), true, 0.24); + let u = 1.0 - raw; + 1.0 - u * u * u + }; + let screen = ctx.screen_rect(); + let bottom_margin = if matches!(app.route, Route::MyVibe) { + 26.0 + } else { + PLAYER_BAR_HEIGHT + 22.0 + }; + let bar_w = (screen.width() - 64.0).clamp(430.0, 560.0); + let bar_h = 54.0; + let slide_dy = (1.0 - anim_t) * 26.0; + let rect = Rect::from_xywh( + (screen.center_x() - bar_w * 0.5).round(), + (screen.bottom() - bottom_margin - bar_h + slide_dy).round(), + bar_w, + bar_h, + ); + + ctx.with_layer(ZLayer::Titlebar, |ctx| { + ctx.register_blocker(rect); + ctx.dl() + .push_shadow(rect, 16.0, 22.0, 0.0, Vec2::new(0.0, 4.0), pal.shadow_menu); + ctx.dl().push_backdrop_blur( + rect, + 16.0, + 2.5, + pal.bg_popover.with_alpha(235), + 1.0, + pal.border_control, + ); + + // Left: Yellow status dot + `"Доступна версия vX.Y.Z"` + let dot_pos = Pos2::new(rect.left() + 20.0, rect.center_y()); + ctx.dl().push_circle(dot_pos, 4.0, pal.yellow); + + let close_sz = 28.0; + let close_r = Rect::from_xywh( + rect.right() - close_sz - 10.0, + rect.center_y() - close_sz * 0.5, + close_sz, + close_sz, + ); + let upd_lbl = i18n.update_btn(); + let on_yellow = Color::rgb(0x19, 0x19, 0x19); + let upd_txt_w = ctx + .measure_text(upd_lbl, TextStyle::bold(13.5, on_yellow), None) + .x; + let upd_w = (upd_txt_w + 32.0).max(114.0).ceil(); + let upd_r = Rect::from_xywh( + close_r.left() - upd_w - 8.0, + rect.center_y() - 18.0, + upd_w, + 36.0, + ); + let wn_lbl = i18n.whats_new(); + let wn_txt_w = ctx + .measure_text(wn_lbl, TextStyle::medium(12.5, pal.text_primary), None) + .x; + let wn_w = (wn_txt_w + 22.0).max(88.0).ceil(); + let wn_r = Rect::from_xywh( + upd_r.left() - wn_w - 8.0, + rect.center_y() - 16.0, + wn_w, + 32.0, + ); + + let text_x = rect.left() + 34.0; + let text_w = (wn_r.left() - text_x - 10.0).max(80.0); + let msg = i18n.update_available_banner(&upd.version); + ctx.draw_text_ellipsis( + &msg, + TextStyle::medium(14.0, pal.text_bright), + Rect::from_xywh(text_x, rect.top(), text_w, rect.height()), + TextAlign::Left, + ); + + // Secondary "Что нового?" pill + let wn_resp = ctx.interact(WidgetId::new("upd_notif_changelog"), wn_r); + if wn_resp.hovered { + ctx.dl().push_rect(wn_r, 16.0, pal.surface_hover); + ctx.set_cursor(CursorKind::Pointer); + } else { + ctx.dl().push_rect(wn_r, 16.0, pal.surface_secondary); + } + ctx.draw_text_ellipsis( + wn_lbl, + TextStyle::medium(12.5, pal.text_primary), + wn_r, + TextAlign::Center, + ); + if wn_resp.clicked { + actions.push(AppAction::OpenReleaseNotesModal); + } + + // Primary yellow "Обновить" button (`min-width: 7.875rem`) + let upd_resp = ctx.interact(WidgetId::new("upd_notif_install"), upd_r); + ctx.dl().push_rect( + upd_r, + 18.0, + if upd_resp.hovered { + pal.yellow_hover + } else { + pal.yellow + }, + ); + ctx.draw_text_ellipsis( + upd_lbl, + TextStyle::bold(13.5, on_yellow), + upd_r, + TextAlign::Center, + ); + if upd_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if upd_resp.clicked { + actions.push(AppAction::InstallUpdate); + } + + // Dismiss × button + if icon_button( + ctx, + WidgetId::new("upd_notif_close"), + close_r, + Icon::Close, + 14.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + "", + ) + .clicked + { + actions.push(AppAction::DismissUpdateNotification); + } + }); +} + +/// 1-to-1 Official `ReleaseNotesModal` (`28bcd8bd8493d95a.css:16-100`, `7956-fd3a458349d8bd97.js:490-525`). +pub fn render_release_notes_modal( + ctx: &mut UiContext, + pal: &YmPalette, + app: &AppState, + actions: &mut Vec, +) { + let i18n = app.i18n(); + let ru = i18n.is_ru(); + let anim_t = if app.fixed_vibe_time.is_some() { + 1.0 + } else { + let raw = ctx.animate_bool(WidgetId::new("ym_release_notes_modal_anim"), true, 0.18); + let u = 1.0 - raw; + 1.0 - u * u * u + }; + let screen = ctx.screen_rect(); + let modal_w = (screen.width() - 48.0).clamp(320.0, 460.0); + let modal_h = (screen.height() - 84.0).clamp(320.0, 500.0); + let slide_dy = (1.0 - anim_t) * 14.0; + let modal_r = Rect::from_center_size( + Pos2::new(screen.center_x(), screen.center_y() + slide_dy), + Vec2::new(modal_w, modal_h), + ); + + ctx.with_layer(ZLayer::Modal, |ctx| { + ctx.register_blocker(screen); + ctx.dl().push_rect( + screen, + 0.0, + Color::rgba(0, 0, 0, (150.0 * anim_t).round() as u8), + ); + ctx.dl() + .push_shadow(modal_r, 16.0, 32.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); + ctx.dl() + .push_rect_bordered(modal_r, 16.0, pal.bg_popover, 1.0, pal.border_subtle); + + // Header (`padding: 16px`, title + circular close ×) + let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 14.0, modal_w - 40.0, 34.0); + ctx.draw_text_ellipsis( + i18n.whats_new(), + TextStyle::headline(20.0, pal.text_bright), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), + TextAlign::Left, + ); + let close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top() + 1.0, 32.0, 32.0); + if icon_button( + ctx, + WidgetId::new("rn_modal_close"), + close_r, + Icon::Close, + 16.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + "", + ) + .clicked + { + actions.push(AppAction::CloseReleaseNotesModal); + } + + let mut content_top = hdr_r.bottom() + 10.0; + + // Optional update banner inside modal if newer version is available + if let Some(ref upd) = app.available_update { + let banner_r = Rect::from_xywh(modal_r.left() + 20.0, content_top, modal_w - 40.0, 48.0); + ctx.dl().push_rect_bordered( + banner_r, + 12.0, + pal.surface_secondary, + 1.0, + pal.yellow.with_alpha(120), + ); + let on_yellow = Color::rgb(0x19, 0x19, 0x19); + let btn_lbl = i18n.update_btn(); + let btn_w = (ctx + .measure_text(btn_lbl, TextStyle::bold(13.0, on_yellow), None) + .x + + 24.0) + .max(94.0) + .ceil(); + let btn_r = Rect::from_xywh( + banner_r.right() - btn_w - 8.0, + banner_r.center_y() - 16.0, + btn_w, + 32.0, + ); + let upd_resp = ctx.interact(WidgetId::new("rn_modal_upd_btn"), btn_r); + ctx.dl().push_rect( + btn_r, + 16.0, + if upd_resp.hovered { + pal.yellow_hover + } else { + pal.yellow + }, + ); + ctx.draw_text_ellipsis( + btn_lbl, + TextStyle::bold(13.0, on_yellow), + btn_r, + TextAlign::Center, + ); + if upd_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if upd_resp.clicked { + actions.push(AppAction::InstallUpdate); + } + ctx.draw_text_ellipsis( + &i18n.update_available_banner(&upd.version), + TextStyle::bold(13.5, pal.text_bright), + Rect::from_xywh( + banner_r.left() + 14.0, + banner_r.top(), + (btn_r.left() - banner_r.left() - 22.0).max(60.0), + banner_r.height(), + ), + TextAlign::Left, + ); + content_top = banner_r.bottom() + 12.0; + } + + // Scrollable list of release notes + let scroll_r = Rect::from_min_max( + Pos2::new(modal_r.left() + 20.0, content_top), + Pos2::new(modal_r.right() - 12.0, modal_r.bottom() - 16.0), + ); + let scroll_id = WidgetId::new("release_notes_scroll"); + let scroll_y = ctx.begin_scroll_v(scroll_id, scroll_r, 0.0); + let body_w = (scroll_r.width() - 16.0).max(160.0); + let mut y = scroll_r.top() - scroll_y; + + if app.releases.is_empty() { + let empty_msg = if ru { + "Список изменений пуст" + } else { + "No release notes available" + }; + ctx.draw_text_ellipsis( + empty_msg, + TextStyle::regular(13.5, pal.text_secondary), + Rect::from_xywh(scroll_r.left(), y + 12.0, body_w, 22.0), + TextAlign::Left, + ); + y += 40.0; + } else { + for (idx, entry) in app.releases.iter().enumerate() { + // Version heading + badge + date + let ver_text = if entry.name.is_empty() { + format!("v{}", entry.version) + } else { + entry.name.clone() + }; + let ver_style = TextStyle::bold(15.5, pal.text_bright); + let ver_w = ctx.measure_text(&ver_text, ver_style, None).x.min(body_w * 0.65); + ctx.draw_text_ellipsis( + &ver_text, + ver_style, + Rect::from_xywh(scroll_r.left(), y, ver_w + 4.0, 22.0), + TextAlign::Left, + ); + + let is_current = entry.version == APP_VERSION; + let is_newer = is_newer_version(&entry.version, APP_VERSION); + if is_current || is_newer { + let badge_txt = if is_newer { + i18n.new_version_badge() + } else { + i18n.current_version_badge() + }; + let badge_col = if is_newer { Color::rgb(0x19, 0x19, 0x19) } else { pal.text_primary }; + let badge_bg = if is_newer { pal.yellow } else { pal.surface_secondary }; + let bw = ctx + .measure_text(badge_txt, TextStyle::bold(11.0, badge_col), None) + .x + + 14.0; + let br = Rect::from_xywh(scroll_r.left() + ver_w + 10.0, y + 2.0, bw, 18.0); + ctx.dl().push_rect(br, 9.0, badge_bg); + ctx.draw_text_ellipsis( + badge_txt, + TextStyle::bold(11.0, badge_col), + br, + TextAlign::Center, + ); + } + + if !entry.date.is_empty() { + ctx.draw_text_ellipsis( + &entry.date, + TextStyle::regular(12.5, pal.text_secondary), + Rect::from_xywh(scroll_r.left(), y + 1.0, body_w, 20.0), + TextAlign::Right, + ); + } + y += 28.0; + + // Markdown release notes lines + for raw_line in entry.body.lines() { + let line = raw_line.trim(); + if line.is_empty() || line == "---" || line == "***" { + continue; + } + if let Some(heading) = line + .strip_prefix("### ") + .or_else(|| line.strip_prefix("## ")) + .or_else(|| line.strip_prefix("# ")) + { + let clean = heading.trim(); + let h_style = TextStyle::bold(13.5, pal.text_bright); + let sz = ctx.measure_text(clean, h_style, Some(body_w)); + let lh = (sz.y + 4.0).max(20.0); + ctx.draw_text_wrapped( + clean, + h_style, + Rect::from_xywh(scroll_r.left(), y, body_w, lh), + None, + TextAlign::Left, + ); + y += lh + 4.0; + } else if let Some(bullet) = line + .strip_prefix("- ") + .or_else(|| line.strip_prefix("* ")) + { + let item_x = scroll_r.left() + 14.0; + let item_w = (body_w - 14.0).max(100.0); + ctx.dl().push_circle(Pos2::new(scroll_r.left() + 5.0, y + 9.0), 2.0, pal.text_secondary); + let spans = parse_release_note_spans(bullet.trim(), pal); + let plain: String = spans.iter().map(|s| s.text).collect(); + let sz = ctx.measure_text( + &plain, + TextStyle::regular(13.5, pal.text_primary), + Some(item_w), + ); + let lh = (sz.y + 4.0).max(20.0); + ctx.draw_rich_text( + &spans, + Rect::from_xywh(item_x, y, item_w, lh), + None, + TextAlign::Left, + ); + y += lh + 4.0; + } else { + let spans = parse_release_note_spans(line, pal); + let plain: String = spans.iter().map(|s| s.text).collect(); + let sz = ctx.measure_text( + &plain, + TextStyle::regular(13.5, pal.text_primary), + Some(body_w), + ); + let lh = (sz.y + 4.0).max(20.0); + ctx.draw_rich_text( + &spans, + Rect::from_xywh(scroll_r.left(), y, body_w, lh), + None, + TextAlign::Left, + ); + y += lh + 4.0; + } + } + + if idx + 1 < app.releases.len() { + y += 8.0; + ctx.dl().push_rect( + Rect::from_xywh(scroll_r.left(), y, body_w, 1.0), + 0.0, + pal.border_subtle, + ); + y += 14.0; + } else { + y += 8.0; + } + } + } + + let total_h = y - (scroll_r.top() - scroll_y); + ctx.end_scroll_v(scroll_id, pal, total_h, true); + + if ctx.input.clicked_outside(modal_r) { + actions.push(AppAction::CloseReleaseNotesModal); + } + }); +} + +fn parse_release_note_spans<'a>(line: &'a str, pal: &YmPalette) -> Vec> { + let mut spans = Vec::new(); + let mut rest = line; + let code_col = if pal.is_dark { pal.yellow } else { pal.outline_selected }; + while !rest.is_empty() { + let next_bold = rest.find("**"); + let next_code = rest.find('`'); + let next = match (next_bold, next_code) { + (Some(b), Some(c)) => Some((b <= c, b.min(c))), + (Some(b), None) => Some((true, b)), + (None, Some(c)) => Some((false, c)), + (None, None) => None, + }; + match next { + None => { + spans.push(RichSpan::new(rest, TextStyle::regular(13.5, pal.text_primary))); + break; + } + Some((is_bold, idx)) => { + if idx > 0 { + spans.push(RichSpan::new( + &rest[..idx], + TextStyle::regular(13.5, pal.text_primary), + )); + } + let delim = if is_bold { "**" } else { "`" }; + let after = &rest[idx + delim.len()..]; + if let Some(end) = after.find(delim) { + let inner = &after[..end]; + let style = if is_bold { + TextStyle::bold(13.5, pal.text_bright) + } else { + TextStyle::medium(13.0, code_col) + }; + spans.push(RichSpan::new(inner, style)); + rest = &after[end + delim.len()..]; + } else { + spans.push(RichSpan::new( + &rest[idx..], + TextStyle::regular(13.5, pal.text_primary), + )); + break; + } + } + } + } + if spans.is_empty() { + spans.push(RichSpan::new(line, TextStyle::regular(13.5, pal.text_primary))); + } + spans +} + // ============================================================================= // 8. Theme-Aware Streaming Animated Splash Screen (`splash_dark.webp` / `splash_light.webp`) // ============================================================================= diff --git a/src/views/podcasts_kids.rs b/src/views/podcasts_kids.rs index 94a8ce9..ef8bfee 100644 --- a/src/views/podcasts_kids.rs +++ b/src/views/podcasts_kids.rs @@ -1676,6 +1676,8 @@ 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), }, ) { @@ -2011,6 +2013,8 @@ pub fn render_metatag_detail( is_liked: app.liked_ids.contains(&tr.id), is_disliked: app.disliked_ids.contains(&tr.id), is_downloaded: app.is_track_downloaded(&tr.id), + is_downloading: app.is_track_downloading(&tr.id), + download_progress: app.track_download_progress(&tr.id), menu_open: shell.is_track_menu_open(&tr.id), }, ) { diff --git a/src/views/search.rs b/src/views/search.rs index 9f059aa..81ac659 100644 --- a/src/views/search.rs +++ b/src/views/search.rs @@ -572,6 +572,8 @@ 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), }, ) { diff --git a/src/views/settings.rs b/src/views/settings.rs index 26f8ff7..97b18aa 100644 --- a/src/views/settings.rs +++ b/src/views/settings.rs @@ -1,29 +1,23 @@ use crate::app::i18n::APP_VERSION; use crate::app::state::{AppAction, AppState}; -use crate::audio::dsp::{EQ_LABELS, EQ_PRESETS}; +use crate::audio::dsp::active_eq_preset_name; use crate::config::{AudioQuality, Language, ThemeMode}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; use crate::engine::text::{TextAlign, TextStyle}; use crate::engine::theme::YmPalette; -use crate::engine::types::{CursorKind, Pos2, Rect}; +use crate::engine::types::{Color, CursorKind, Pos2, Rect, Vec2}; use crate::engine::widgets::{ - secondary_pill_button, text_input_widget, yellow_pill_button, ym_slider, ym_vertical_slider, - TextInputOptions, + draw_cover_art, draw_plus_avatar_ring, secondary_pill_button, secondary_pill_button_in, + text_input_widget, yellow_pill_button, ym_slider, TextInputOptions, }; use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::ShellUiState; -/// Authentic Yandex Music Desktop 5.129.0 Settings Page: -/// - Account (Yandex ID / OAuth) -/// - Appearance & Language (3-way System / Dark / Light theme selector + RU/EN + Close to tray) -/// - Sound (Audio quality, Loudness normalization, Crossfade) -/// - 10-band Equalizer (Enable, Presets, 10 vertical band sliders) -/// - Recommendations & Content (Less AI, Show Kids section) -/// - Keyboard shortcuts -/// - About 5.129.0 (Update check & Clear cover cache) -/// 100% `YmPalette` theme-aware & 100% localized RU/EN! +/// 1-to-1 Official Yandex Music Desktop 5.129.0 `SettingsPage` (`Settings_root__FVVrn`, `379bcce309ec9c74.css`): +/// Clean borderless list of `SettingsListButtonItem` (title + description + `arrowRight` chevron) +/// and `SettingsListToggleItem` (title + description + right pill toggle), `max-width: 520px`. pub fn render_settings( ctx: &mut UiContext, pal: &YmPalette, @@ -38,68 +32,71 @@ pub fn render_settings( let scroll_id = WidgetId::new("settings_scroll"); let scroll_y = ctx.begin_scroll_v(scroll_id, rect, 0.0); - // `views/mod.rs` already insets `inner_r` by (25, 13, 25, 0) - let content_x = rect.left(); - let content_w = (rect.width() - 8.0).clamp(320.0, 960.0); + // `views/mod.rs` already insets `inner_r` by (25, 12, 25, 0) + let x = rect.left(); + let col_w = (rect.width() - 12.0).clamp(320.0, 520.0); let mut y = rect.top() + 8.0 - scroll_y; // Page Heading ctx.draw_text_ellipsis( t.settings(), - TextStyle::headline(34.0, pal.text_bright), - Rect::from_xywh(content_x, y, content_w, 42.0), + TextStyle::headline(32.0, pal.text_bright), + Rect::from_xywh(x, y, col_w, 40.0), TextAlign::Left, ); - y += 58.0; + y += 56.0; // ------------------------------------------------------------------------- - // 1. Account (Yandex ID) + // 1. Account (Compact Yandex ID strip — clean borderless row + hairline) // ------------------------------------------------------------------------- - let acc_h = if app.account.is_some() { 112.0 } else { 196.0 }; - let acc_inner = draw_settings_card( - ctx, - pal, - Rect::from_xywh(content_x, y, content_w, acc_h), - if ru { - "Аккаунт Яндекс ID" - } else { - "Yandex ID Account" - }, - ); if let Some(ref acc) = app.account { + let av_sz = 44.0; + let av_r = Rect::from_xywh(x, y + 2.0, av_sz, av_sz); + if acc.has_plus { + draw_plus_avatar_ring(ctx, av_r.center(), av_sz * 0.5 + 2.5, 2.0); + } + draw_cover_art( + ctx, + pal, + covers, + av_r, + acc.avatar_uri.as_deref(), + "set_avatar", + av_sz * 0.5, + true, + false, + ); let sign_out_lbl = t.sign_out(); let measured_w = ctx - .measure_text(sign_out_lbl, TextStyle::bold(14.0, pal.text_primary), None) + .measure_text(sign_out_lbl, TextStyle::bold(13.5, pal.text_primary), None) .x; - let btn_w = (measured_w + 54.0).max(112.0).ceil(); - let text_w = (acc_inner.width() - btn_w - 16.0).max(120.0); - let row_y = acc_inner.top(); + let btn_w = (measured_w + 46.0).max(102.0).ceil(); + let txt_x = av_r.right() + 14.0; + let txt_w = (col_w - (av_sz + 14.0) - btn_w - 12.0).max(100.0); + ctx.draw_text_ellipsis( &acc.display_name, TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(acc_inner.left(), row_y, text_w, 22.0), + Rect::from_xywh(txt_x, y + 3.0, txt_w, 22.0), TextAlign::Left, ); let plan = if acc.has_plus { - if ru { - "Яндекс Плюс активен" - } else { - "Yandex Plus active" - } + if ru { "Яндекс Плюс" } else { "Yandex Plus" } } else if ru { "Базовый тариф" } else { "Free plan" }; - let meta = format!("@{} · UID {} · {}", acc.login, acc.uid, plan); + let meta = format!("@{} · {}", acc.login, plan); ctx.draw_text_ellipsis( &meta, TextStyle::regular(13.0, pal.text_secondary), - Rect::from_xywh(acc_inner.left(), row_y + 24.0, text_w, 20.0), + Rect::from_xywh(txt_x, y + 26.0, txt_w, 18.0), TextAlign::Left, ); - let logout_r = Rect::from_xywh(acc_inner.right() - btn_w, row_y + 4.0, btn_w, 38.0); - let resp = crate::engine::widgets::secondary_pill_button_in( + + let logout_r = Rect::from_xywh(x + col_w - btn_w, y + 6.0, btn_w, 36.0); + let resp = secondary_pill_button_in( ctx, pal, WidgetId::new("set_logout"), @@ -111,26 +108,13 @@ pub fn render_settings( if resp.clicked { actions.push(AppAction::Logout); } + y += 62.0; } else { - let mut cy = acc_inner.top(); - ctx.draw_text_wrapped( - if ru { - "Войдите через Яндекс ID, чтобы слушать свою коллекцию, «Мою волну» и Lossless FLAC." - } else { - "Sign in with Yandex ID to access your collection, My Vibe, and Lossless FLAC." - }, - TextStyle::regular(13.5, pal.text_secondary), - Rect::from_xywh(acc_inner.left(), cy, acc_inner.width(), 36.0), - Some(2), - TextAlign::Left, - ); - cy += 36.0; - let (oauth_resp, _) = yellow_pill_button( ctx, pal, WidgetId::new("set_oauth_btn"), - Pos2::new(acc_inner.left(), cy), + Pos2::new(x, y), Some(Icon::Plus), if ru { "Войти через Яндекс ID" @@ -143,10 +127,10 @@ pub fn render_settings( if oauth_resp.clicked { actions.push(AppAction::OpenOAuthBrowser); } - cy += 50.0; + y += 48.0; - let input_w = (acc_inner.width() - 130.0).clamp(180.0, 420.0); - let input_r = Rect::from_xywh(acc_inner.left(), cy, input_w, 38.0); + let input_w = (col_w - 118.0).clamp(180.0, 400.0); + let input_r = Rect::from_xywh(x, y, input_w, 36.0); let mut token_copy = app.token_input.clone(); let ti = text_input_widget( ctx, @@ -156,15 +140,15 @@ pub fn render_settings( &mut token_copy, TextInputOptions { placeholder: if ru { - "Вставьте OAuth-токен (y0_...) или URL" + "OAuth-токен (y0_...) или URL" } else { - "Paste OAuth token (y0_...) or redirect URL" + "OAuth token (y0_...) or redirect URL" }, leading_icon: None, show_clear_button: true, hide_placeholder_when_unfocused: false, transparent_bg: false, - font_size: 13.5, + font_size: 13.0, pill: true, }, ); @@ -175,213 +159,134 @@ pub fn render_settings( ctx, pal, WidgetId::new("set_token_submit"), - Pos2::new(input_r.right() + 10.0, cy), + Pos2::new(input_r.right() + 10.0, y), Some(Icon::CheckXxs), t.log_in(), - 38.0, + 36.0, !token_copy.trim().is_empty(), ); if (sub_resp.clicked || ti.submitted) && !token_copy.trim().is_empty() { actions.push(AppAction::SubmitOAuthToken(token_copy)); } + y += 50.0; } - y += acc_h + 14.0; + + ctx.dl() + .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); + y += 18.0; // ------------------------------------------------------------------------- - // 2. Appearance & Language (3-way System / Dark / Light + RU/EN + Tray) + // 2. Official Settings List (`Settings_root`, 24px vertical spacing) // ------------------------------------------------------------------------- - let app_h = 204.0; - let app_inner = draw_settings_card( + + // 2a. Sound quality (`QualitySettingsModal` trigger) + let qual_sub = match app.config.audio_quality { + AudioQuality::Lossless => { + if ru { + "Максимальное · FLAC без потерь" + } else { + "Maximum · Lossless FLAC" + } + } + AudioQuality::High => { + if ru { + "Оптимальное · 320 кбит/с" + } else { + "Optimal · 320 kbps" + } + } + AudioQuality::Standard => { + if ru { + "Экономичное" + } else { + "Efficient" + } + } + }; + if settings_button_item( ctx, pal, - Rect::from_xywh(content_x, y, content_w, app_h), + WidgetId::new("set_quality_btn"), + x, + &mut y, + col_w, + t.sound_settings(), + Some(qual_sub), + None, + ) { + actions.push(AppAction::SetEqPopoverOpen(true)); + } + + // 2b. Equalizer (`EqualizerModal` trigger) + let eq_sub = if app.config.eq_enabled { + let preset_name = active_eq_preset_name(&app.config.eq_bands_db, ru); if ru { - "Оформление и интерфейс" + format!("Включён · {}", preset_name) } else { - "Appearance & Language" - }, - ); - { - let mut cy = app_inner.top(); - ctx.draw_text_ellipsis( - t.appearance(), - TextStyle::medium(13.0, pal.text_secondary), - Rect::from_xywh(app_inner.left(), cy, app_inner.width(), 18.0), - TextAlign::Left, - ); - cy += 24.0; - - let mut tx = app_inner.left(); - for (mode, icon, label) in [ - (ThemeMode::System, Icon::ThemeSystemXxs, t.theme_system()), - (ThemeMode::Dark, Icon::ThemeDarkXxs, t.theme_dark()), - (ThemeMode::Light, Icon::ThemeLightXxs, t.theme_light()), - ] { - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("set_theme", mode as u8), - Pos2::new(tx, cy), - Some(icon), - label, - 38.0, - app.config.theme == mode, - ); - if resp.clicked { - actions.push(AppAction::SetTheme(mode)); - } - tx = r.right() + 10.0; + format!("Enabled · {}", preset_name) } - cy += 50.0; - - // Language selector - let mut lx = app_inner.left(); - for (lang, label) in [(Language::Ru, "Русский"), (Language::En, "English")] { - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("set_lang", lang as u8), - Pos2::new(lx, cy), - Some(Icon::ProfileGlobeXxs), - label, - 36.0, - app.config.language == lang, - ); - if resp.clicked { - actions.push(AppAction::SetLanguage(lang)); - } - lx = r.right() + 10.0; - } - cy += 48.0; - - // Close to tray toggle - if let Some(next) = settings_toggle_row( - ctx, - pal, - WidgetId::new("set_close_to_tray"), - Rect::from_xywh(app_inner.left(), cy, app_inner.width(), 32.0), - if ru { - "Сворачивать в системный трей при закрытии окна" - } else { - "Minimize to system tray on close" - }, - app.config.close_to_tray, - ) { - actions.push(AppAction::SetCloseToTray(next)); - } - } - y += app_h + 14.0; - - // ------------------------------------------------------------------------- - // 3. Sound (Audio quality, Loudness normalization, Crossfade) - // ------------------------------------------------------------------------- - let sound_inner_w = (content_w - 36.0).max(100.0); - let mut q_rows = 1usize; - let mut sim_qx = 0.0_f32; - for q in [ - AudioQuality::Lossless, - AudioQuality::High, - AudioQuality::Standard, - ] { - let lbl = q.label_for(app.config.language); - let btn_w = (ctx - .measure_text(lbl, TextStyle::bold(14.0, pal.text_primary), None) - .x - + 36.0) - .min(260.0); - if sim_qx + btn_w > sound_inner_w && sim_qx > 0.0 { - q_rows += 1; - sim_qx = 0.0; - } - sim_qx += btn_w + 8.0; - } - let sound_h = 196.0 + (q_rows.saturating_sub(1) as f32) * 44.0; - let sound_inner = draw_settings_card( + } else if ru { + "Выключен".to_string() + } else { + "Disabled".to_string() + }; + if settings_button_item( ctx, pal, - Rect::from_xywh(content_x, y, content_w, sound_h), - if ru { "Звук" } else { "Sound" }, - ); - { - let mut cy = sound_inner.top(); - ctx.draw_text_ellipsis( + WidgetId::new("set_eq_btn"), + x, + &mut y, + col_w, + if ru { "Эквалайзер" } else { "Equalizer" }, + Some(&eq_sub), + None, + ) { + actions.push(AppAction::SetEqualizerModalOpen(true)); + } + + // 2c. Crossfade between tracks (toggle + optional duration override) + let cf_sub = if app.config.crossfade_enabled { + if app.config.crossfade_secs < 0.1 { if ru { - "Качество звука" + Some("Авто (умные точки Яндекс Музыки)".to_string()) } else { - "Audio quality" - }, - TextStyle::medium(13.0, pal.text_secondary), - Rect::from_xywh(sound_inner.left(), cy, sound_inner.width(), 18.0), - TextAlign::Left, - ); - cy += 24.0; - - let mut qx = sound_inner.left(); - for q in [ - AudioQuality::Lossless, - AudioQuality::High, - AudioQuality::Standard, - ] { - let lbl = q.label_for(app.config.language); - let measured = ctx - .measure_text(lbl, TextStyle::bold(14.0, pal.text_primary), None) - .x - + 36.0; - let btn_w = measured.min(260.0); - if qx + btn_w > sound_inner.right() && qx > sound_inner.left() { - qx = sound_inner.left(); - cy += 44.0; + Some("Auto (Yandex Music smart fade)".to_string()) } - let r = Rect::from_xywh(qx, cy, btn_w, 38.0); - let resp = crate::engine::widgets::secondary_pill_button_in( - ctx, - pal, - WidgetId::from_pair("set_quality", q as u8), - r, - None, - lbl, - app.config.audio_quality == q, - ); - if resp.clicked { - actions.push(AppAction::SetAudioQuality(q)); - } - qx = r.right() + 8.0; - } - cy += 50.0; - - if let Some(next) = settings_toggle_row( - ctx, - pal, - WidgetId::new("set_loudness"), - Rect::from_xywh(sound_inner.left(), cy, sound_inner.width(), 32.0), - if ru { - "Выравнивание громкости (EBU R128)" - } else { - "Loudness normalization (EBU R128)" - }, - app.config.normalize_loudness, - ) { - actions.push(AppAction::SetNormalizeLoudness(next)); - } - cy += 40.0; - - let cf_label = if ru { - format!("Плавные переходы между треками: {:.0} с", app.config.crossfade_secs) + } else if ru { + Some(format!("Длительность: {:.0} с", app.config.crossfade_secs)) } else { - format!("Crossfade between tracks: {:.0} s", app.config.crossfade_secs) + Some(format!("Duration: {:.0} s", app.config.crossfade_secs)) + } + } else { + None + }; + if let Some(next) = settings_toggle_item( + ctx, + pal, + WidgetId::new("set_crossfade_toggle"), + x, + &mut y, + col_w, + if ru { + "Плавные переходы между треками" + } else { + "Crossfade between tracks" + }, + cf_sub.as_deref(), + app.config.crossfade_enabled, + ) { + actions.push(AppAction::SetCrossfadeEnabled(next)); + } + if app.config.crossfade_enabled { + y -= 10.0; + let sl_label = if app.config.crossfade_secs < 0.1 { + if ru { "Авто" } else { "Auto" }.to_string() + } else if ru { + format!("{:.0} с", app.config.crossfade_secs) + } else { + format!("{:.0} s", app.config.crossfade_secs) }; - ctx.draw_text_ellipsis( - &cf_label, - TextStyle::regular(14.0, pal.text_primary), - Rect::from_xywh(sound_inner.left(), cy, 310.0, 26.0), - TextAlign::Left, - ); - let slider_r = Rect::from_xywh( - sound_inner.left() + 320.0, - cy, - (sound_inner.width() - 330.0).clamp(120.0, 280.0), - 26.0, - ); + let slider_r = Rect::from_xywh(x, y, (col_w - 64.0).max(160.0), 22.0); let sr = ym_slider( ctx, pal, @@ -392,395 +297,457 @@ pub fn render_settings( true, true, ); + ctx.draw_text_ellipsis( + &sl_label, + TextStyle::medium(12.5, pal.text_secondary), + Rect::from_xywh(slider_r.right() + 10.0, y, 54.0, 22.0), + TextAlign::Right, + ); if let Some(v) = sr.value { let secs = (v * 12.0).round(); if (secs - app.config.crossfade_secs).abs() >= 0.5 { actions.push(AppAction::SetCrossfadeSecs(secs)); } } + y += 40.0; } - y += sound_h + 14.0; - // ------------------------------------------------------------------------- - // 4. 10-Band Equalizer (dynamic height so wrapped EQ presets never clip or break) - // ------------------------------------------------------------------------- - let eq_inner_w = (content_w - 36.0).max(100.0); - let mut eq_preset_rows = 1usize; - let mut sim_px = 0.0_f32; - for preset in EQ_PRESETS.iter() { - let pw = (ctx - .measure_text(preset.name, TextStyle::bold(14.0, pal.text_primary), None) - .x - + 32.0) - .max(54.0); - if sim_px + pw > eq_inner_w && sim_px > 0.0 { - eq_preset_rows += 1; - sim_px = 0.0; - } - sim_px += pw + 6.0; - } - let eq_h = 266.0 + (eq_preset_rows.saturating_sub(1) as f32) * 38.0; - let eq_inner = draw_settings_card( + // 2d. Loudness normalization (EBU R128) + if let Some(next) = settings_toggle_item( ctx, pal, - Rect::from_xywh(content_x, y, content_w, eq_h), - if ru { "Эквалайзер" } else { "Equalizer" }, - ); - { - let mut enabled = app.config.eq_enabled; - let mut bands = app.config.eq_bands_db; - let mut changed = false; - let mut cy = eq_inner.top(); - - if let Some(next) = settings_toggle_row( - ctx, - pal, - WidgetId::new("set_eq_enable"), - Rect::from_xywh(eq_inner.left(), cy, eq_inner.width(), 30.0), - if ru { - "Включить 10-полосный эквалайзер" - } else { - "Enable 10-band equalizer" - }, - enabled, - ) { - enabled = next; - changed = true; - } - cy += 38.0; - - // Presets rows (wrap cleanly across multiple lines — NO truncation!) - let mut px = eq_inner.left(); - for (idx, preset) in EQ_PRESETS.iter().enumerate() { - let pw = (ctx - .measure_text(preset.name, TextStyle::bold(14.0, pal.text_primary), None) - .x - + 32.0) - .max(54.0); - if px + pw > eq_inner.right() && px > eq_inner.left() { - px = eq_inner.left(); - cy += 38.0; - } - let is_match = enabled - && bands - .iter() - .zip(preset.gains.iter()) - .all(|(a, b)| (a - b).abs() < 0.2); - let r = Rect::from_xywh(px, cy, pw, 30.0); - let resp = crate::engine::widgets::secondary_pill_button_in( - ctx, - pal, - WidgetId::from_pair("set_eq_preset", idx), - r, - None, - preset.name, - is_match, - ); - if resp.clicked { - enabled = true; - bands = preset.gains; - changed = true; - } - px = r.right() + 6.0; - } - cy += 42.0; - - // 10 vertical band sliders - let col_w = (eq_inner.width() / 10.0).min(64.0); - for i in 0..10 { - let bx = eq_inner.left() + i as f32 * col_w; - ctx.draw_text_ellipsis( - &format!("{:+.0}", bands[i]), - TextStyle::regular(11.5, pal.text_secondary), - Rect::from_xywh(bx, cy, col_w, 16.0), - TextAlign::Center, - ); - let sl_r = Rect::from_xywh(bx + col_w * 0.5 - 14.0, cy + 20.0, 28.0, 96.0); - let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); - let sr = ym_vertical_slider( - ctx, - pal, - WidgetId::from_pair("set_eq_band", i), - sl_r, - norm, - false, - if enabled { pal.yellow } else { pal.text_primary }, - ); - if let Some(v) = sr.value { - let db = ((v * 24.0) - 12.0).round().clamp(-12.0, 12.0); - if (db - bands[i]).abs() >= 0.5 { - bands[i] = db; - enabled = true; - changed = true; - } - } - ctx.draw_text_ellipsis( - EQ_LABELS[i], - TextStyle::bold(11.5, pal.text_primary), - Rect::from_xywh(bx, cy + 120.0, col_w, 16.0), - TextAlign::Center, - ); - } - - if changed { - actions.push(AppAction::UpdateEq { enabled, bands }); - } - } - y += eq_h + 14.0; - - // ------------------------------------------------------------------------- - // 5. Recommendations & Content (Less AI, Kids toggle) - // ------------------------------------------------------------------------- - let rec_h = 132.0; - let rec_inner = draw_settings_card( - ctx, - pal, - Rect::from_xywh(content_x, y, content_w, rec_h), + WidgetId::new("set_loudness"), + x, + &mut y, + col_w, if ru { - "Рекомендации и разделы" + "Выравнивание громкости" } else { - "Recommendations & Content" + "Loudness normalization" }, - ); - { - let mut cy = rec_inner.top(); - if let Some(next) = settings_toggle_row( - ctx, - pal, - WidgetId::new("set_ai_red"), - Rect::from_xywh(rec_inner.left(), cy, rec_inner.width(), 32.0), - if ru { - "Меньше ИИ — реже показывать музыку, созданную с помощью ИИ" - } else { - "Less AI — reduce AI-generated music in recommendations" - }, - app.config.ai_content_reduction, - ) { - actions.push(AppAction::SetAiContentReduction(next)); - } - cy += 40.0; - if let Some(next) = settings_toggle_row( - ctx, - pal, - WidgetId::new("set_child_mode"), - Rect::from_xywh(rec_inner.left(), cy, rec_inner.width(), 32.0), - if ru { - "Показывать раздел «Детям»" - } else { - "Show «For Kids» section" - }, - app.config.child_mode, - ) { - actions.push(AppAction::SetChildMode(next)); - } + Some(if ru { + "Автоматически выравнивать громкость треков (EBU R128)" + } else { + "Automatically normalize track volume (EBU R128)" + }), + app.config.normalize_loudness, + ) { + actions.push(AppAction::SetNormalizeLoudness(next)); } - y += rec_h + 14.0; - // ------------------------------------------------------------------------- - // 6. Keyboard Shortcuts - // ------------------------------------------------------------------------- - let shortcuts: &[(&str, &str, &str)] = &[ - ("Space / K", "Пауза / Воспроизведение", "Play / Pause"), - ("N / P", "Следующий / Предыдущий трек", "Next / Previous track"), - ("← / → (J / L)", "Перемотка ±2 сек", "Seek ±2 sec"), - ("↑ / ↓", "Громкость ±5%", "Volume ±5%"), - ("M", "Выключить / включить звук", "Mute / Unmute"), - ("F / D", "Нравится / Не нравится", "Like / Dislike"), - ("R / S", "Повтор / Перемешать", "Repeat / Shuffle"), - ("W", "Полноэкранный плеер", "Fullscreen player"), - ("Ctrl + F / Ctrl + L", "Поиск / Текст песни", "Search / Lyrics"), - ]; - let sc_h = 62.0 + shortcuts.len() as f32 * 26.0; - let sc_inner = draw_settings_card( + // 2e. Less AI + if let Some(next) = settings_toggle_item( ctx, pal, - Rect::from_xywh(content_x, y, content_w, sc_h), + WidgetId::new("set_ai_red"), + x, + &mut y, + col_w, + if ru { "Меньше ИИ" } else { "Less AI" }, + Some(if ru { + "В рекомендациях будет реже встречаться музыка, созданная с помощью ИИ" + } else { + "AI-generated music will appear less frequently in recommendations" + }), + app.config.ai_content_reduction, + ) { + actions.push(AppAction::SetAiContentReduction(next)); + } + + // 2f. Kids section toggle + if let Some(next) = settings_toggle_item( + ctx, + pal, + WidgetId::new("set_child_mode"), + x, + &mut y, + col_w, + if ru { + "Показывать раздел «Детям»" + } else { + "Show «For Kids» section" + }, + None, + app.config.child_mode, + ) { + actions.push(AppAction::SetChildMode(next)); + } + + // 2g. Minimize to tray + if let Some(next) = settings_toggle_item( + ctx, + pal, + WidgetId::new("set_close_to_tray"), + x, + &mut y, + col_w, + if ru { + "Сворачивать в трей при закрытии" + } else { + "Minimize to system tray on close" + }, + None, + app.config.close_to_tray, + ) { + actions.push(AppAction::SetCloseToTray(next)); + } + + // 2h. Clear cover cache + let cache_sub = if ru { + format!("В кэше: {} обложек", covers.len()) + } else { + format!("Cached items: {}", covers.len()) + }; + if settings_button_item( + ctx, + pal, + WidgetId::new("set_clear_cache"), + x, + &mut y, + col_w, + if ru { + "Очистить кэш обложек" + } else { + "Clear cover cache" + }, + Some(&cache_sub), + None, + ) { + actions.push(AppAction::ClearCoverCache); + } + + // 2i. Keyboard shortcuts (`ShortcutsModal` trigger) + if settings_button_item( + ctx, + pal, + WidgetId::new("set_shortcuts_btn"), + x, + &mut y, + col_w, if ru { "Горячие клавиши" } else { "Keyboard shortcuts" }, - ); - { - let mut cy = sc_inner.top(); - for (keys, desc_ru, desc_en) in shortcuts { - ctx.draw_text_ellipsis( - keys, - TextStyle::bold(13.0, pal.text_bright), - Rect::from_xywh(sc_inner.left(), cy, 175.0, 22.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - if ru { *desc_ru } else { *desc_en }, - TextStyle::regular(13.0, pal.text_secondary), - Rect::from_xywh(sc_inner.left() + 185.0, cy, sc_inner.width() - 185.0, 22.0), - TextAlign::Left, - ); - cy += 26.0; - } + None, + None, + ) { + actions.push(AppAction::SetShortcutsModalOpen(true)); } - y += sc_h + 14.0; + + // 2j. Appearance & Language (compact official pill selectors) + ctx.draw_text_ellipsis( + t.appearance(), + TextStyle::bold(16.0, pal.text_bright), + Rect::from_xywh(x, y, col_w, 22.0), + TextAlign::Left, + ); + y += 30.0; + let mut tx = x; + for (mode, icon, label) in [ + (ThemeMode::System, Icon::ThemeSystemXxs, t.theme_system()), + (ThemeMode::Dark, Icon::ThemeDarkXxs, t.theme_dark()), + (ThemeMode::Light, Icon::ThemeLightXxs, t.theme_light()), + ] { + let (resp, r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("set_theme", mode as u8), + Pos2::new(tx, y), + Some(icon), + label, + 34.0, + app.config.theme == mode, + ); + if resp.clicked { + actions.push(AppAction::SetTheme(mode)); + } + tx = r.right() + 8.0; + } + y += 46.0; + + ctx.draw_text_ellipsis( + if ru { "Язык" } else { "Language" }, + TextStyle::bold(16.0, pal.text_bright), + Rect::from_xywh(x, y, col_w, 22.0), + TextAlign::Left, + ); + y += 30.0; + let mut lx = x; + for (lang, label) in [(Language::Ru, "Русский"), (Language::En, "English")] { + let (resp, r) = secondary_pill_button( + ctx, + pal, + WidgetId::from_pair("set_lang", lang as u8), + Pos2::new(lx, y), + Some(Icon::ProfileGlobeXxs), + label, + 34.0, + app.config.language == lang, + ); + if resp.clicked { + actions.push(AppAction::SetLanguage(lang)); + } + lx = r.right() + 8.0; + } + y += 52.0; + + ctx.dl() + .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); + y += 18.0; // ------------------------------------------------------------------------- - // 7. About & Updates (`git.tatar/marwy/yandex-music-rs`) & Cache + // 3. About & Updates (`ReleaseNotesModal` + Update CTA) // ------------------------------------------------------------------------- - let about_h = 172.0; - let about_inner = draw_settings_card( + let about_sub = if let Some(ref upd) = app.available_update { + format!("v{} · {}", APP_VERSION, t.update_available_banner(&upd.version)) + } else if ru { + format!("Версия {} · {}", APP_VERSION, t.up_to_date_badge()) + } else { + format!("Version {} · {}", APP_VERSION, t.up_to_date_badge()) + }; + let about_badge_col = if app.available_update.is_some() { + Some(pal.yellow) + } else { + None + }; + if settings_button_item( ctx, pal, - Rect::from_xywh(content_x, y, content_w, about_h), + WidgetId::new("set_about_btn"), + x, + &mut y, + col_w, if ru { "О приложении" } else { "About" }, - ); - { - let mut cy = about_inner.top(); - let ver_str = if ru { - format!("yandex-music-rs · Версия {}", APP_VERSION) - } else { - format!("yandex-music-rs · Version {}", APP_VERSION) - }; - ctx.draw_text_ellipsis( - &ver_str, - TextStyle::medium(14.0, pal.text_primary), - Rect::from_xywh(about_inner.left(), cy, about_inner.width(), 22.0), - TextAlign::Left, - ); - cy += 24.0; - let repo_label = "git.tatar/marwy/yandex-music-rs"; - let repo_w = ctx - .measure_text(repo_label, TextStyle::medium(13.0, pal.text_secondary), None) - .x - + 8.0; - let repo_r = Rect::from_xywh(about_inner.left(), cy, repo_w.min(about_inner.width()), 20.0); - let repo_resp = ctx.interact(WidgetId::new("set_repo_link"), repo_r); - ctx.draw_text_ellipsis( - repo_label, - TextStyle::medium( - 13.0, - if repo_resp.hovered { - pal.text_bright - } else if pal.is_dark { - pal.yellow - } else { - pal.outline_selected - }, - ), - repo_r, - TextAlign::Left, - ); - if repo_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if repo_resp.clicked { - actions.push(AppAction::OpenUrl( - "https://git.tatar/marwy/yandex-music-rs".into(), - )); - } - cy += 22.0; - let cache_str = if ru { - format!("Кэш обложек: {} шт.", covers.len()) - } else { - format!("Cover cache: {} items", covers.len()) - }; - ctx.draw_text_ellipsis( - &cache_str, - TextStyle::regular(12.5, pal.text_secondary), - Rect::from_xywh(about_inner.left(), cy, about_inner.width(), 20.0), - TextAlign::Left, - ); - cy += 28.0; + Some(&about_sub), + about_badge_col, + ) { + actions.push(AppAction::OpenReleaseNotesModal); + } - let upd_label = if let Some((ref new_ver, _)) = app.available_update { - if ru { - format!("Обновить до {}", new_ver) - } else { - format!("Update to {}", new_ver) - } - } else if ru { - "Проверить обновления".to_string() - } else { - "Check for updates".to_string() - }; - let (upd_resp, upd_r) = secondary_pill_button( - ctx, - pal, - WidgetId::new("set_check_updates"), - Pos2::new(about_inner.left(), cy), - None, - &upd_label, - 36.0, - app.available_update.is_some(), + if let Some(ref upd) = app.available_update { + let banner_r = Rect::from_xywh(x, y - 6.0, col_w, 54.0); + ctx.dl().push_rect_bordered( + banner_r, + 12.0, + pal.surface_secondary, + 1.0, + pal.yellow.with_alpha(120), ); - if upd_resp.clicked { - actions.push(AppAction::CheckForUpdates); - } - let (clr_resp, _) = secondary_pill_button( + let (dl_resp, dl_r) = yellow_pill_button( ctx, pal, - WidgetId::new("set_clear_cache"), - Pos2::new(upd_r.right() + 10.0, cy), + WidgetId::new("set_install_update"), + Pos2::new(banner_r.right() - 184.0, banner_r.center_y() - 17.0), None, - if ru { - "Очистить кэш обложек" - } else { - "Clear cover cache" - }, - 36.0, + t.download_update(), + 34.0, false, ); - if clr_resp.clicked { - actions.push(AppAction::ClearCoverCache); + let _ = dl_r; + if dl_resp.clicked { + actions.push(AppAction::InstallUpdate); } + let title_line = t.update_available_banner(&upd.version); + let sub_line = if upd.date.is_empty() { + t.whats_new().to_string() + } else { + upd.date.clone() + }; + let txt_w = (banner_r.width() - 208.0).max(100.0); + ctx.draw_text_ellipsis( + &title_line, + TextStyle::bold(13.5, pal.text_bright), + Rect::from_xywh(banner_r.left() + 14.0, banner_r.top() + 9.0, txt_w, 18.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + &sub_line, + TextStyle::regular(12.0, pal.text_secondary), + Rect::from_xywh(banner_r.left() + 14.0, banner_r.top() + 28.0, txt_w, 16.0), + TextAlign::Left, + ); + y += 62.0; } - y += about_h + 28.0; + + // Footer action pills: Check updates + What's new + Repo link + let (chk_resp, chk_r) = secondary_pill_button( + ctx, + pal, + WidgetId::new("set_check_updates"), + Pos2::new(x, y), + None, + if ru { + "Проверить обновления" + } else { + "Check for updates" + }, + 34.0, + false, + ); + if chk_resp.clicked { + actions.push(AppAction::CheckForUpdates); + } + let (wn_resp, _) = secondary_pill_button( + ctx, + pal, + WidgetId::new("set_whats_new"), + Pos2::new(chk_r.right() + 10.0, y), + None, + t.whats_new(), + 34.0, + false, + ); + if wn_resp.clicked { + actions.push(AppAction::OpenReleaseNotesModal); + } + y += 44.0; + + let repo_label = "git.tatar/marwy/yandex-music-rs"; + let repo_w = ctx + .measure_text(repo_label, TextStyle::medium(12.5, pal.text_secondary), None) + .x + + 8.0; + let repo_r = Rect::from_xywh(x, y, repo_w.min(col_w), 20.0); + let repo_resp = ctx.interact(WidgetId::new("set_repo_link"), repo_r); + ctx.draw_text_ellipsis( + repo_label, + TextStyle::medium( + 12.5, + if repo_resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ), + repo_r, + TextAlign::Left, + ); + if repo_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if repo_resp.clicked { + actions.push(AppAction::OpenUrl( + "https://git.tatar/marwy/yandex-music-rs".into(), + )); + } + y += 38.0; let total_content_h = y - (rect.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_content_h, true); } -/// Renders a theme-aware settings section card and returns its inner body `Rect` below the heading. -fn draw_settings_card(ctx: &mut UiContext, pal: &YmPalette, rect: Rect, heading: &str) -> Rect { - ctx.dl() - .push_rect_bordered(rect, 14.0, pal.surface_secondary, 1.0, pal.border_subtle); - let inner_x = rect.left() + 18.0; - let inner_w = (rect.width() - 36.0).max(100.0); - ctx.draw_text_ellipsis( - heading, - TextStyle::bold(16.0, pal.text_bright), - Rect::from_xywh(inner_x, rect.top() + 16.0, inner_w, 22.0), - TextAlign::Left, - ); - Rect::from_xywh( - inner_x, - rect.top() + 46.0, - inner_w, - (rect.height() - 62.0).max(0.0), - ) -} - -/// Interactive pill toggle switch row (100% theme-aware). Returns `Some(new_val)` when toggled. -fn settings_toggle_row( +/// Official `SettingsListButtonItem` (`29c95960ed6ac633.css:74-119`): +/// Borderless row with bold 16px title, optional 13px subtitle, and right-aligned `arrowRight` chevron +/// that glides +4px right on hover. +#[allow(clippy::too_many_arguments)] +fn settings_button_item( ctx: &mut UiContext, pal: &YmPalette, id: WidgetId, - rect: Rect, - label: &str, + x: f32, + y: &mut f32, + w: f32, + title: &str, + description: Option<&str>, + dot_color: Option, +) -> bool { + let row_h = if description.is_some() { 44.0 } else { 28.0 }; + let hit_r = Rect::from_xywh(x - 8.0, *y - 4.0, w + 16.0, row_h + 8.0); + let resp = ctx.interact(id, hit_r); + let hover_t = ctx.animate_bool(id.with("hov"), resp.hovered, 0.14); + + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if hover_t > 0.01 { + ctx.dl() + .push_rect(hit_r, 10.0, pal.surface_hover.with_alpha_f32(hover_t * 0.5)); + } + + let text_w = (w - 32.0).max(80.0); + ctx.draw_text_ellipsis( + title, + TextStyle::bold(16.0, pal.text_bright), + Rect::from_xywh(x, *y, text_w, 22.0), + TextAlign::Left, + ); + if let Some(desc) = description { + ctx.draw_text_ellipsis( + desc, + TextStyle::medium(13.0, pal.text_secondary), + Rect::from_xywh(x, *y + 23.0, text_w, 18.0), + TextAlign::Left, + ); + } + + if let Some(dc) = dot_color { + ctx.dl() + .push_circle(Pos2::new(x + w - 34.0, *y + row_h * 0.5), 4.0, dc); + } + + let chev_x = x + w - 12.0 + hover_t * 4.0; + ctx.draw_icon( + Icon::MenuArrowXxs, + Rect::from_center_size(Pos2::new(chev_x, *y + row_h * 0.5), Vec2::splat(16.0)), + if resp.hovered { + pal.text_bright + } else { + pal.text_secondary + }, + ); + + *y += row_h + 20.0; + resp.clicked +} + +/// Official `SettingsListToggleItem` (`29c95960ed6ac633.css:120-136`): +/// Borderless row with bold 16px title, optional wrapped 13px subtitle, and right-aligned pill toggle. +#[allow(clippy::too_many_arguments)] +fn settings_toggle_item( + ctx: &mut UiContext, + pal: &YmPalette, + id: WidgetId, + x: f32, + y: &mut f32, + w: f32, + title: &str, + description: Option<&str>, checked: bool, ) -> Option { - let resp = ctx.interact(id, rect); + let text_w = (w - 60.0).max(100.0); + let desc_h = description.map_or(0.0, |d| { + ctx.measure_text(d, TextStyle::medium(13.0, pal.text_secondary), Some(text_w)) + .y + .max(18.0) + + 4.0 + }); + let row_h = (22.0 + desc_h).max(28.0); + let hit_r = Rect::from_xywh(x - 8.0, *y - 4.0, w + 16.0, row_h + 8.0); + let resp = ctx.interact(id, hit_r); let anim = ctx.animate_bool(id.with("tog"), checked, 0.18); ctx.draw_text_ellipsis( - label, - TextStyle::regular(14.0, pal.text_primary), - Rect::from_xywh(rect.left(), rect.top(), (rect.width() - 56.0).max(40.0), rect.height()), + title, + TextStyle::bold(16.0, pal.text_bright), + Rect::from_xywh(x, *y, text_w, 22.0), TextAlign::Left, ); + if let Some(desc) = description { + ctx.draw_text_wrapped( + desc, + TextStyle::medium(13.0, pal.text_secondary), + Rect::from_xywh(x, *y + 24.0, text_w, desc_h), + None, + TextAlign::Left, + ); + } let sw_w = 42.0; let sw_h = 24.0; let sw_r = Rect::from_xywh( - rect.right() - sw_w, - rect.center_y() - sw_h * 0.5, + x + w - sw_w, + *y + 11.0 - sw_h * 0.5, sw_w, sw_h, ); @@ -799,6 +766,7 @@ fn settings_toggle_row( if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } + *y += row_h + 20.0; if resp.clicked { Some(!checked) } else { diff --git a/src/views/sidebar.rs b/src/views/sidebar.rs index c14f13a..4eceeea 100644 --- a/src/views/sidebar.rs +++ b/src/views/sidebar.rs @@ -708,7 +708,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 * 4.0 } else { 44.0 * 2.0 }; + let group1_h = 54.0 + if logged_in { 44.0 * 5.0 } else { 44.0 * 3.0 }; let sep_h = 13.0; // 6px top + 1px line + 6px bottom let group2_h = 44.0; let group3_h = if logged_in { sep_h + 44.0 * 2.0 } else { 0.0 }; @@ -1121,6 +1121,34 @@ 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, diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 064b905..37d343b 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -211,6 +211,7 @@ fn make_track( r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, } } diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index 09950e7..ea89e0c 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -133,6 +133,7 @@ fn make_base_shell( r128_tp: None, derived_average_hex: None, derived_accent_hex: None, + fade: None, }; let track2 = Track { id: "t_2".into(), @@ -158,6 +159,7 @@ 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( @@ -2053,6 +2055,7 @@ 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"] @@ -2515,3 +2518,69 @@ fn test_ext_18_qa_sync_lyrics_scroll_concerts_duplicate_albums() { ); } } + +#[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.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.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); + } +} From b7cfde1f6b6113c8e686779383905c568c16400f Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 19:32:20 +0300 Subject: [PATCH 11/17] chore(release): v0.1.6 --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ee0bbc..3b2d5f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6550,7 +6550,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.5" +version = "0.1.6" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 5b31b31..4d113ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.5" +version = "0.1.6" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" diff --git a/README.md b/README.md index 9cd5716..f915417 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.5-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.5-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.6-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.6-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.5-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.6-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.5-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.6-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности From b315b212a44cd88d575a8478197565737b697c72 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 19:54:12 +0300 Subject: [PATCH 12/17] fix: 1-to-1 official equalizer, settings, animations, and click-outside dismissal --- src/app/state.rs | 13 +- src/audio/dsp.rs | 38 +- src/audio/mod.rs | 28 +- src/config.rs | 9 +- src/engine/input.rs | 74 +++ src/views/mod.rs | 80 ++- src/views/overlays.rs | 1006 +++++++++++++++++++++++--------------- src/views/settings.rs | 235 ++++----- tests/parity_extended.rs | 2 + 9 files changed, 928 insertions(+), 557 deletions(-) diff --git a/src/app/state.rs b/src/app/state.rs index 1c10953..6e69f38 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -380,6 +380,7 @@ pub enum AppAction { SetCloseToTray(bool), UpdateEq { enabled: bool, + preamp: f32, bands: [f32; 10], }, SetMaxCoverCache(usize), @@ -629,6 +630,7 @@ impl AppState { config.volume, config.muted, config.eq_enabled, + config.eq_preamp, config.eq_bands_db, config.normalize_loudness, config.crossfade_enabled, @@ -803,6 +805,7 @@ 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); @@ -3127,10 +3130,16 @@ impl AppState { self.config.close_to_tray = v; self.save_config(); } - AppAction::UpdateEq { enabled, bands } => { + AppAction::UpdateEq { + enabled, + preamp, + bands, + } => { + let preamp = preamp.clamp(0.5, 1.5); self.config.eq_enabled = enabled; + self.config.eq_preamp = preamp; self.config.eq_bands_db = bands; - self.audio.set_eq(enabled, bands); + self.audio.set_eq(enabled, preamp, bands); self.save_config(); } AppAction::SetMaxCoverCache(cap) => { diff --git a/src/audio/dsp.rs b/src/audio/dsp.rs index 776656c..66d8a34 100644 --- a/src/audio/dsp.rs +++ b/src/audio/dsp.rs @@ -38,12 +38,12 @@ pub const EQ_PRESETS: &[EqPreset] = &[ }, EqPreset { name_ru: "Клубная музыка", - name_en: "Club Music", + 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", + 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 { @@ -62,8 +62,8 @@ pub const EQ_PRESETS: &[EqPreset] = &[ 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: "Speakers", + 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 { @@ -73,12 +73,12 @@ pub const EQ_PRESETS: &[EqPreset] = &[ }, EqPreset { name_ru: "Концерт", - name_en: "Concert", + 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: "Party", + 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 { @@ -102,13 +102,13 @@ pub const EQ_PRESETS: &[EqPreset] = &[ 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 Music", + 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", + 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 { @@ -129,9 +129,9 @@ pub fn active_eq_preset_name(bands: &[f32; 10], ru: bool) -> &'static str { } } if ru { - "Свой" + "Своя настройка" } else { - "Custom" + "Custom settings" } } @@ -264,6 +264,7 @@ impl Biquad { pub struct Equalizer10Band { bands: [Biquad; 10], enabled: bool, + preamp: f32, sample_rate: f32, gains_db: [f32; 10], } @@ -273,13 +274,15 @@ 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, gains_db: [f32; 10]) { + pub fn update(&mut self, enabled: bool, preamp: f32, 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 { @@ -299,6 +302,8 @@ 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); } @@ -364,14 +369,19 @@ mod tests { 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], true), "Своя настройка"); + assert_eq!(active_eq_preset_name(&[1.2; 10], false), "Custom settings"); let mut eq = Equalizer10Band::new(48_000.0); - eq.update(true, EQ_PRESETS[5].gains); + eq.update(true, 1.25, EQ_PRESETS[5].gains); for i in 0..1024 { let s = (i as f32 * 0.1).sin() * 0.5; let (l, r) = eq.process(s, -s); assert!(l.is_finite() && r.is_finite()); } + let mut eq_pre = Equalizer10Band::new(48_000.0); + eq_pre.update(true, 0.5, [0.0; 10]); + let (pl, pr) = eq_pre.process(0.4, -0.4); + assert!((pl - 0.2).abs() < 1e-4 && (pr + 0.2).abs() < 1e-4); } } diff --git a/src/audio/mod.rs b/src/audio/mod.rs index 0c68225..bf28cdd 100644 --- a/src/audio/mod.rs +++ b/src/audio/mod.rs @@ -71,6 +71,7 @@ pub struct SharedAudioState { pub energy_bits: AtomicU32, pub bass_bits: AtomicU32, pub eq_enabled: AtomicBool, + pub eq_preamp_bits: AtomicU32, pub eq_bands: Mutex<[f32; 10]>, pub active_codec: Mutex, pub output_device_name: Mutex, @@ -83,6 +84,7 @@ impl SharedAudioState { volume: f32, muted: bool, eq_enabled: bool, + eq_preamp: f32, eq_bands: [f32; 10], normalize_loudness: bool, crossfade_enabled: bool, @@ -105,6 +107,7 @@ impl SharedAudioState { 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()), @@ -170,6 +173,7 @@ impl AudioEngine { volume: f32, muted: bool, eq_enabled: bool, + eq_preamp: f32, eq_bands: [f32; 10], normalize_loudness: bool, crossfade_enabled: bool, @@ -179,6 +183,7 @@ impl AudioEngine { volume, muted, eq_enabled, + eq_preamp, eq_bands, normalize_loudness, crossfade_enabled, @@ -200,9 +205,15 @@ impl AudioEngine { } /// Silent, thread-free audio engine for deterministic headless visual tests. - pub fn new_headless(volume: f32, muted: bool, eq_enabled: bool, eq_bands: [f32; 10]) -> Self { + pub fn new_headless( + volume: f32, + muted: bool, + eq_enabled: bool, + eq_preamp: f32, + eq_bands: [f32; 10], + ) -> Self { let state = Arc::new(SharedAudioState::new( - volume, muted, eq_enabled, eq_bands, true, false, 0.0, + volume, muted, eq_enabled, eq_preamp, eq_bands, true, false, 0.0, )); let (tx_cmd, _rx_cmd) = unbounded(); Self { @@ -358,8 +369,11 @@ impl AudioEngine { .store(secs.clamp(0.0, 12.0).to_bits(), Ordering::Relaxed); } - pub fn set_eq(&self, enabled: bool, bands: [f32; 10]) { + pub fn set_eq(&self, enabled: bool, preamp: f32, 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; } @@ -1025,8 +1039,10 @@ fn run_audio_worker(rx_cmd: Receiver, state: Arc let gain = vol; 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, *bands); + eq.update(eq_on, preamp, *bands); } if !playing { @@ -1465,7 +1481,7 @@ mod tests { #[test] fn seek_seq_prevents_stale_decoder_position_overwrite() { - let engine = AudioEngine::new_headless(0.8, false, false, [0.0; 10]); + let engine = AudioEngine::new_headless(0.8, false, false, 1.0, [0.0; 10]); // Initial playback at seq 0 publishes normally. assert!(publish_decoder_position_ms(&engine.state, 0, 30_000)); @@ -1524,7 +1540,7 @@ mod tests { #[test] fn stop_bumps_seek_seq_preventing_old_decoder_overwrite() { - let engine = AudioEngine::new_headless(0.8, false, false, [0.0; 10]); + let engine = AudioEngine::new_headless(0.8, false, false, 1.0, [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); diff --git a/src/config.rs b/src/config.rs index eee290f..02bda70 100644 --- a/src/config.rs +++ b/src/config.rs @@ -152,7 +152,9 @@ pub struct AppConfig { pub muted: bool, pub sidebar_collapsed: bool, pub eq_enabled: bool, - pub eq_bands_db: [f32; 10], // 32, 64, 125, 250, 500, 1k, 2k, 4k, 8k, 16k Hz + #[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 normalize_loudness: bool, #[serde(default = "default_true")] pub crossfade_enabled: bool, @@ -195,6 +197,10 @@ fn default_true() -> bool { true } +fn default_eq_preamp() -> f32 { + 1.0 +} + impl Default for AppConfig { fn default() -> Self { Self { @@ -206,6 +212,7 @@ 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, diff --git a/src/engine/input.rs b/src/engine/input.rs index 659dac3..6018b59 100644 --- a/src/engine/input.rs +++ b/src/engine/input.rs @@ -554,6 +554,36 @@ 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) } @@ -694,3 +724,47 @@ impl Animator { self.values.clear(); } } + +#[cfg(test)] +mod tests { + use super::*; + use winit::dpi::PhysicalPosition; + + #[test] + fn test_consume_clicked_outside_prevents_trigger_reopen_on_release() { + let mut input = InputState::new(); + let screen = Vec2::new(1280.0, 800.0); + let trigger_id = WidgetId::new("pb_r_eq"); + let trigger_r = Rect::from_xywh(1000.0, 740.0, 36.0, 36.0); + let pop_r = Rect::from_xywh(800.0, 400.0, 430.0, 300.0); + + // Frame 1: Mouse down on the underlying trigger button while popover is open. + input.begin_frame(screen, 1.0, 1.0); + input.handle_winit_event(&WindowEvent::CursorMoved { + device_id: unsafe { std::mem::zeroed() }, + position: PhysicalPosition::new(1018.0, 758.0), + }); + input.handle_winit_event(&WindowEvent::MouseInput { + device_id: unsafe { std::mem::zeroed() }, + state: ElementState::Pressed, + button: MouseButton::Left, + }); + + let press_resp = input.interact(trigger_id, ZLayer::Base, trigger_r, None); + assert!(!press_resp.clicked); + assert!(input.consume_clicked_outside(pop_r)); + assert!(input.active_id.is_none()); + input.end_frame(); + + // Frame 2: Mouse up over the same trigger button — MUST NOT fire clicked! + input.begin_frame(screen, 1.0, 1.05); + input.handle_winit_event(&WindowEvent::MouseInput { + device_id: unsafe { std::mem::zeroed() }, + state: ElementState::Released, + button: MouseButton::Left, + }); + let rel_resp = input.interact(trigger_id, ZLayer::Base, trigger_r, None); + assert!(!rel_resp.clicked); + input.end_frame(); + } +} diff --git a/src/views/mod.rs b/src/views/mod.rs index b98ef1f..9c67299 100644 --- a/src/views/mod.rs +++ b/src/views/mod.rs @@ -539,8 +539,38 @@ impl YandexMusicShell { } // 6. Floating Popovers & Context Menus (ZLayer::Popover) - if self.app.eq_popover_open { - render_eq_popover(&mut self.ui, &pal, &self.app, &mut self.shell, &mut actions); + 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.18, + )) + }; + let eq_expand_t = if self.app.fixed_vibe_time.is_some() { + if self.app.config.eq_enabled { 1.0 } else { 0.0 } + } else { + ease_out(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, + ); } 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); @@ -563,14 +593,48 @@ 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); } - if self.app.release_notes_modal_open { - render_release_notes_modal(&mut self.ui, &pal, &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); } - if self.app.equalizer_modal_open { - render_equalizer_modal(&mut self.ui, &pal, &self.app, &mut self.shell, &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, + ); } - if self.app.shortcuts_modal_open { - render_shortcuts_modal(&mut self.ui, &pal, &self.app, &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) diff --git a/src/views/overlays.rs b/src/views/overlays.rs index a43e08c..c1fd5d1 100644 --- a/src/views/overlays.rs +++ b/src/views/overlays.rs @@ -14,7 +14,7 @@ use crate::engine::textures::{premultiply_rgba_srgb, TextureRegistry}; use crate::engine::widgets::{ draw_cover_art, draw_downloading_progress, icon_button, secondary_pill_button, separated_artists, text_input_widget, yellow_pill_button, ym_menu_frame, ym_menu_item, - ym_menu_item_ex, ym_vertical_slider, ym_volume_capsule, TextInputOptions, + ym_menu_item_ex, ym_volume_capsule, SliderResponse, TextInputOptions, }; use crate::engine::{ css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, TextAlign, TextStyle, TextureId, @@ -2155,7 +2155,7 @@ pub fn render_track_context_menu( if !sub_rect.is_empty() { keep.push(sub_rect); } - if ctx.input.clicked_outside_any(&keep) { + if ctx.input.consume_clicked_outside_any(&keep) { close_menu = true; } }); @@ -2485,7 +2485,7 @@ pub fn render_entity_context_menu( if !sub_rect.is_empty() { keep.push(sub_rect); } - if ctx.input.clicked_outside_any(&keep) { + if ctx.input.consume_clicked_outside_any(&keep) { close_menu = true; } }); @@ -2691,7 +2691,7 @@ pub fn render_vibe_settings_modal( 36.0, false, ); - if done_resp.clicked || ctx.input.clicked_outside(modal_r) { + if done_resp.clicked || ctx.input.consume_clicked_outside(modal_r) { actions.push(AppAction::SetVibeModalOpen(false)); } }); @@ -2917,7 +2917,7 @@ pub fn render_playlist_modal( submit = true; } - if ctx.input.clicked_outside(modal_r) { + if ctx.input.consume_clicked_outside(modal_r) { close_modal = true; } }); @@ -3070,7 +3070,7 @@ pub fn render_delete_playlist_confirm_modal( confirm = true; } - if ctx.input.clicked_outside(modal_r) { + if ctx.input.consume_clicked_outside(modal_r) { close_modal = true; } }); @@ -3214,7 +3214,7 @@ pub fn render_login_modal( actions.push(AppAction::SubmitOAuthToken(app.token_input.clone())); } - if ctx.input.clicked_outside(modal_r) { + if ctx.input.consume_clicked_outside(modal_r) { actions.push(AppAction::SetLoginModalOpen(false)); } }); @@ -3640,7 +3640,7 @@ pub fn render_track_detail_modal( let total_h = (y - (body_viewport.top() - scroll_y)).max(0.0); ctx.end_scroll_v(scroll_id, pal, total_h, true); - if ctx.input.clicked_outside(panel_r) { + if ctx.input.consume_clicked_outside(panel_r) { actions.push(AppAction::CloseTrackDetailModal); } }); @@ -3655,74 +3655,122 @@ pub fn render_eq_popover( pal: &YmPalette, app: &AppState, shell: &mut ShellUiState, + anim_t: f32, + eq_expand_t: f32, actions: &mut Vec, ) { let i18n = app.i18n(); let ru = i18n.is_ru(); let screen = ctx.screen_rect(); - let anim_t = if app.fixed_vibe_time.is_some() { - 1.0 - } else { - let raw = ctx.animate_bool(WidgetId::new("ym_quality_popover_anim"), true, 0.16); - let u = 1.0 - raw; - 1.0 - u * u * u - }; - let eq_expand_t = if app.fixed_vibe_time.is_some() { - if app.config.eq_enabled { 1.0 } else { 0.0 } - } else { - ctx.animate_bool(WidgetId::new("ym_quality_eq_expand"), app.config.eq_enabled, 0.18) - }; + let open = app.eq_popover_open; + let alpha = anim_t.clamp(0.0, 1.0); + let expand_t = eq_expand_t.clamp(0.0, 1.0); let pop_w = (screen.width() - 32.0).clamp(320.0, 430.0); - let base_h = 286.0; - let eq_extra_h = 256.0 * eq_expand_t; + let qualities = [ + ( + AudioQuality::Lossless, + if ru { "Превосходное" } else { "Superb" }, + if ru { + "Музыка в lossless и других высококачественных форматах для быстрого интернета и хорошей акустики" + } else { + "Music in lossless and other high-quality formats for fast internet connections and superior acoustic systems" + }, + ), + ( + AudioQuality::High, + if ru { "Оптимальное" } else { "Balanced" }, + if ru { + "Сбалансированный звук для большинства устройств" + } else { + "Balanced sound for most devices" + }, + ), + ( + AudioQuality::Standard, + if ru { "Экономичное" } else { "Efficient" }, + if ru { + "Стабильное звучание при медленном интернете" + } else { + "Stable sound with a slow internet connection" + }, + ), + ]; + + let txt_w = (pop_w - 72.0).max(120.0); + let mut row_heights = [0.0f32; 3]; + let mut total_rows_h = 0.0f32; + for (idx, (_, _, sub)) in qualities.iter().enumerate() { + let sub_h = ctx + .measure_text(sub, TextStyle::regular(12.0, pal.text_secondary), Some(txt_w)) + .y + .max(16.0); + let rh = 10.0 + 19.0 + 3.0 + sub_h + 10.0; + row_heights[idx] = rh; + total_rows_h += rh + 4.0; + } + + // Header (16+32+10) + Quality rows + Divider (6+1+14) + EQ header (28) + Bottom pad (18) + let base_h = 58.0 + total_rows_h + 21.0 + 28.0 + 18.0; + let eq_extra_h = 242.0 * expand_t; let pop_h = (base_h + eq_extra_h).min((screen.height() - PLAYER_BAR_HEIGHT - 56.0).max(280.0)); - let slide_dy = (1.0 - anim_t) * 14.0; + let slide_dy = (1.0 - alpha) * 12.0; let pop_r = Rect::from_xywh( (screen.right() - pop_w - 20.0).max(16.0), - (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 22.0 + slide_dy).max(40.0), + (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 20.0 + slide_dy).max(40.0), pop_w, pop_h, ); let mut enabled = app.config.eq_enabled; + let mut preamp = app.config.eq_preamp; let mut bands = app.config.eq_bands_db; let mut changed = false; - let mut dropdown_rect: Option = None; ctx.with_layer(ZLayer::Popover, |ctx| { - ctx.register_blocker(pop_r); - ctx.dl() - .push_shadow(pop_r, 16.0, 24.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); + if open { + ctx.register_blocker(pop_r); + } + ctx.dl().push_shadow( + pop_r, + 16.0, + 24.0, + 0.0, + Vec2::new(0.0, 6.0), + pal.shadow_menu.with_alpha_f32(alpha), + ); ctx.dl().push_rect_bordered( pop_r, 16.0, - pal.bg_popover, + pal.bg_popover.with_alpha_f32(alpha), 1.0, - pal.border_subtle, + pal.border_subtle.with_alpha_f32(alpha), ); + ctx.push_clip(pop_r, 16.0); + // Header: `"Настройки звука"` + circular Close `×` (`QualitySettings_headerWithCloseButton`) let hdr_r = Rect::from_xywh(pop_r.left() + 20.0, pop_r.top() + 16.0, pop_w - 40.0, 32.0); ctx.draw_text_ellipsis( i18n.sound_settings(), - TextStyle::headline(18.0, pal.text_bright), + TextStyle::headline(18.0, pal.text_bright.with_alpha_f32(alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); - if icon_button( - ctx, - WidgetId::new("qs_close_btn"), - Rect::from_xywh(hdr_r.right() - 28.0, hdr_r.top() + 2.0, 28.0, 28.0), - Icon::Close, - 13.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, - false, - i18n.close(), - ) - .clicked + if open + && icon_button( + ctx, + WidgetId::new("qs_close_btn"), + Rect::from_xywh(hdr_r.right() - 28.0, hdr_r.top() + 2.0, 28.0, 28.0), + Icon::Close, + 13.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + i18n.close(), + ) + .clicked { shell.eq_presets_dropdown_open = false; actions.push(AppAction::SetEqPopoverOpen(false)); @@ -3730,56 +3778,33 @@ pub fn render_eq_popover( // 3 Official Quality Options (`QualitySettings_item`) let mut y = hdr_r.bottom() + 10.0; - let qualities = [ - ( - AudioQuality::Lossless, - if ru { "Максимальное" } else { "Maximum" }, - if ru { - "Звук без потерь в формате FLAC (если доступно)" - } else { - "Lossless FLAC audio when available" - }, - ), - ( - AudioQuality::High, - if ru { "Оптимальное" } else { "Optimal" }, - if ru { - "Высокое качество звука (320 кбит/с)" - } else { - "High audio quality (320 kbps)" - }, - ), - ( - AudioQuality::Standard, - if ru { "Экономичное" } else { "Efficient" }, - if ru { - "Стабильное звучание при медленном интернете" - } else { - "Stable playback on slower connections" - }, - ), - ]; - - for (q, title, sub) in qualities { - let row_r = Rect::from_xywh(pop_r.left() + 10.0, y, pop_w - 20.0, 54.0); - let resp = ctx.interact(WidgetId::from_pair("qs_qual", q as u8), row_r); - let active = app.config.audio_quality == q; + for (idx, (q, title, sub)) in qualities.iter().enumerate() { + let rh = row_heights[idx]; + let row_r = Rect::from_xywh(pop_r.left() + 10.0, y, pop_w - 20.0, rh); + let resp = if open { + ctx.interact(WidgetId::from_pair("qs_qual", *q as u8), row_r) + } else { + Default::default() + }; + let active = app.config.audio_quality == *q; if resp.hovered { - ctx.dl().push_rect(row_r, 10.0, pal.surface_hover); + ctx.dl() + .push_rect(row_r, 10.0, pal.surface_hover.with_alpha_f32(alpha)); ctx.set_cursor(CursorKind::Pointer); } - let txt_x = row_r.left() + 12.0; - let txt_w = (row_r.width() - 46.0).max(80.0); + let row_txt_x = row_r.left() + 14.0; + let row_txt_w = (row_r.width() - 48.0).max(80.0); ctx.draw_text_ellipsis( title, - TextStyle::bold(14.5, pal.text_bright), - Rect::from_xywh(txt_x, row_r.top() + 8.0, txt_w, 19.0), + TextStyle::bold(14.5, pal.text_bright.with_alpha_f32(alpha)), + Rect::from_xywh(row_txt_x, row_r.top() + 9.0, row_txt_w, 19.0), TextAlign::Left, ); - ctx.draw_text_ellipsis( + ctx.draw_text_wrapped( sub, - TextStyle::regular(12.0, pal.text_secondary), - Rect::from_xywh(txt_x, row_r.top() + 28.0, txt_w, 17.0), + TextStyle::regular(12.0, pal.text_secondary.with_alpha_f32(alpha)), + Rect::from_xywh(row_txt_x, row_r.top() + 31.0, row_txt_w, rh - 36.0), + None, TextAlign::Left, ); if active { @@ -3789,13 +3814,13 @@ pub fn render_eq_popover( Pos2::new(row_r.right() - 18.0, row_r.center_y()), Vec2::splat(16.0), ), - pal.text_bright, + pal.text_bright.with_alpha_f32(alpha), ); } if resp.clicked && !active { - actions.push(AppAction::SetAudioQuality(q)); + actions.push(AppAction::SetAudioQuality(*q)); } - y += 56.0; + y += rh + 4.0; } // Hairline divider before Equalizer section @@ -3803,40 +3828,74 @@ pub fn render_eq_popover( ctx.dl().push_rect( Rect::from_xywh(pop_r.left() + 20.0, y, pop_w - 40.0, 1.0), 0.0, - pal.border_subtle, + pal.border_subtle.with_alpha_f32(alpha), ); y += 14.0; - // Inline Official Equalizer (`Equalizer_header` + expandable `EqualizerPresets` & 10 bands) + // Inline Official Equalizer (`Equalizer_header` + animated expandable Preamp + 10 bands + Presets) let eq_area = Rect::from_min_max( Pos2::new(pop_r.left() + 20.0, y), Pos2::new(pop_r.right() - 20.0, pop_r.bottom() - 16.0), ); - dropdown_rect = render_equalizer_body( + let dd_anchor = render_equalizer_body( ctx, pal, eq_area, if ru { "Эквалайзер" } else { "Equalizer" }, ru, &mut enabled, + &mut preamp, &mut bands, &mut changed, &mut shell.eq_presets_dropdown_open, - eq_expand_t > 0.15, + alpha, + expand_t, + false, + open, "qs_eq", ); - let clicked_in_dd = dropdown_rect - .and_then(|dr| ctx.input.pointer_pos.map(|p| dr.contains(p))) - .unwrap_or(false); - if ctx.input.clicked_outside(pop_r) && !clicked_in_dd { - shell.eq_presets_dropdown_open = false; - actions.push(AppAction::SetEqPopoverOpen(false)); + ctx.pop_clip(); + + // Render floating presets dropdown OUTSIDE popover clip so `placement: "top"` is never cut off! + let mut dd_rect: Option = None; + if open && shell.eq_presets_dropdown_open { + if let Some((sel_r, sel_clicked)) = dd_anchor { + dd_rect = render_eq_presets_dropdown( + ctx, + pal, + sel_r, + pop_r, + ru, + &mut enabled, + &mut preamp, + &mut bands, + &mut changed, + &mut shell.eq_presets_dropdown_open, + sel_clicked, + "qs_eq", + ); + } + } + + if open { + let mut keep = vec![pop_r]; + if let Some(dr) = dd_rect { + keep.push(dr); + } + if ctx.input.consume_clicked_outside_any(&keep) { + shell.eq_presets_dropdown_open = false; + actions.push(AppAction::SetEqPopoverOpen(false)); + } } }); if changed { - actions.push(AppAction::UpdateEq { enabled, bands }); + actions.push(AppAction::UpdateEq { + enabled, + preamp, + bands, + }); } } @@ -3846,105 +3905,216 @@ pub fn render_equalizer_modal( pal: &YmPalette, app: &AppState, shell: &mut ShellUiState, + anim_t: f32, actions: &mut Vec, ) { let i18n = app.i18n(); let ru = i18n.is_ru(); - let anim_t = if app.fixed_vibe_time.is_some() { - 1.0 - } else { - let raw = ctx.animate_bool(WidgetId::new("ym_eq_modal_anim"), true, 0.18); - let u = 1.0 - raw; - 1.0 - u * u * u - }; + let open = app.equalizer_modal_open; + let alpha = anim_t.clamp(0.0, 1.0); let screen = ctx.screen_rect(); let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); let modal_h = 376.0; - let slide_dy = (1.0 - anim_t) * 14.0; + let slide_dy = (1.0 - alpha) * 14.0; let modal_r = Rect::from_center_size( Pos2::new(screen.center_x(), screen.center_y() + slide_dy), Vec2::new(modal_w, modal_h), ); let mut enabled = app.config.eq_enabled; + let mut preamp = app.config.eq_preamp; let mut bands = app.config.eq_bands_db; let mut changed = false; ctx.with_layer(ZLayer::Modal, |ctx| { - ctx.register_blocker(screen); + if open { + ctx.register_blocker(screen); + } ctx.dl().push_rect( screen, 0.0, - Color::rgba(0, 0, 0, (150.0 * anim_t).round() as u8), + Color::rgba(0, 0, 0, (150.0 * alpha).round() as u8), + ); + ctx.dl().push_shadow( + modal_r, + 16.0, + 32.0, + 0.0, + Vec2::new(0.0, 8.0), + pal.shadow_modal.with_alpha_f32(alpha), + ); + ctx.dl().push_rect_bordered( + modal_r, + 16.0, + pal.bg_popover.with_alpha_f32(alpha), + 1.0, + pal.border_subtle.with_alpha_f32(alpha), ); - ctx.dl() - .push_shadow(modal_r, 16.0, 32.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); - ctx.dl() - .push_rect_bordered(modal_r, 16.0, pal.bg_popover, 1.0, pal.border_subtle); let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); ctx.draw_text_ellipsis( if ru { "Эквалайзер" } else { "Equalizer" }, - TextStyle::headline(20.0, pal.text_bright), + TextStyle::headline(20.0, pal.text_bright.with_alpha_f32(alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); - if icon_button( - ctx, - WidgetId::new("eq_modal_close"), - Rect::from_xywh(hdr_r.right() - 30.0, hdr_r.top() + 1.0, 30.0, 30.0), - Icon::Close, - 15.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, - false, - i18n.close(), - ) - .clicked + if open + && icon_button( + ctx, + WidgetId::new("eq_modal_close"), + Rect::from_xywh(hdr_r.right() - 30.0, hdr_r.top() + 1.0, 30.0, 30.0), + Icon::Close, + 15.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + i18n.close(), + ) + .clicked { shell.eq_presets_dropdown_open = false; actions.push(AppAction::SetEqualizerModalOpen(false)); } let eq_area = Rect::from_min_max( - Pos2::new(modal_r.left() + 20.0, hdr_r.bottom() + 18.0), + Pos2::new(modal_r.left() + 20.0, hdr_r.bottom() + 24.0), Pos2::new(modal_r.right() - 20.0, modal_r.bottom() - 20.0), ); - let dd_rect = render_equalizer_body( + let is_disabled = !enabled; + let dd_anchor = render_equalizer_body( ctx, pal, eq_area, - if ru { - "Включить эквалайзер" - } else { - "Enable equalizer" - }, + if ru { "Включить" } else { "Turn on" }, ru, &mut enabled, + &mut preamp, &mut bands, &mut changed, &mut shell.eq_presets_dropdown_open, - true, + alpha, + 1.0, + is_disabled, + open, "em_eq", ); - let clicked_in_dd = dd_rect - .and_then(|dr| ctx.input.pointer_pos.map(|p| dr.contains(p))) - .unwrap_or(false); - if ctx.input.clicked_outside(modal_r) && !clicked_in_dd { - shell.eq_presets_dropdown_open = false; - actions.push(AppAction::SetEqualizerModalOpen(false)); + let mut dd_rect: Option = None; + if open && shell.eq_presets_dropdown_open { + if let Some((sel_r, sel_clicked)) = dd_anchor { + dd_rect = render_eq_presets_dropdown( + ctx, + pal, + sel_r, + modal_r, + ru, + &mut enabled, + &mut preamp, + &mut bands, + &mut changed, + &mut shell.eq_presets_dropdown_open, + sel_clicked, + "em_eq", + ); + } + } + + if open { + let mut keep = vec![modal_r]; + if let Some(dr) = dd_rect { + keep.push(dr); + } + if ctx.input.consume_clicked_outside_any(&keep) { + shell.eq_presets_dropdown_open = false; + actions.push(AppAction::SetEqualizerModalOpen(false)); + } } }); if changed { - actions.push(AppAction::UpdateEq { enabled, bands }); + actions.push(AppAction::UpdateEq { + enabled, + preamp, + bands, + }); } } -/// Shared official Yandex Music 5.129.0 Equalizer UI (`8711fa44496b8e09.css:136-299`): -/// Toggle header + Preset selector dropdown (18 presets) + `+12 / 0 / -12 dB` scale + 10 bands (`60`..`16k`). +/// Official `EqualizerSlider` (`8711fa44496b8e09.css:340-416`): +/// - Thin `2px` muted vertical track (NO yellow fill from bottom) +/// - Centered `8×1px` `0 dB` serif tick +/// - Always-visible `14px` hollow dark-filled circular thumb with `1.5px` yellow border (`border_control` when disabled) +fn eq_vertical_slider( + ctx: &mut UiContext, + pal: &YmPalette, + id: WidgetId, + rect: Rect, + norm_val: f32, + disabled: bool, + interactive: bool, + alpha: f32, +) -> SliderResponse { + let resp = if !disabled && interactive { + ctx.interact(id, rect) + } else { + Default::default() + }; + let active = !disabled && (resp.hovered || resp.pressed || resp.dragged); + let cx = rect.center_x(); + let top = rect.top() + 7.0; + let bot = rect.bottom() - 7.0; + let track_h = (bot - top).max(20.0); + + // Thin 2px muted vertical track + let track_col = pal.border_control.with_alpha_f32(alpha); + ctx.dl() + .push_rect(Rect::from_xywh(cx - 1.0, top, 2.0, track_h), 1.0, track_col); + + // Centered 8×1px horizontal serif tick at midpoint (`EqualizerSlider_serif`) + ctx.dl().push_rect( + Rect::from_xywh((cx - 4.0).round(), (top + track_h * 0.5).round(), 8.0, 1.0), + 0.0, + track_col, + ); + + // Hollow circular thumb (`14px` diameter, `1.5px` yellow/muted ring) + let frac = norm_val.clamp(0.0, 1.0); + let thumb_y = bot - frac * track_h; + let thumb_r = if active { 7.5 } else { 7.0 }; + let border_col = if disabled { + pal.border_control.with_alpha_f32(alpha) + } else { + pal.yellow.with_alpha_f32(alpha) + }; + ctx.dl().push_rect_bordered( + Rect::from_center_size(Pos2::new(cx, thumb_y), Vec2::splat(thumb_r * 2.0)), + thumb_r, + pal.bg_popover.with_alpha_f32(alpha), + 1.5, + border_col, + ); + + if active { + ctx.set_cursor(CursorKind::Pointer); + } + + let mut new_val = None; + if !disabled && interactive && (resp.pressed || resp.dragged || resp.clicked) { + if let Some(p) = ctx.input.pointer_pos { + new_val = Some((1.0 - (p.y - top) / track_h).clamp(0.0, 1.0)); + } + } + + SliderResponse { + value: new_val, + hovered: resp.hovered, + dragging: resp.pressed || resp.dragged, + } +} + +/// Shared official Yandex Music 5.129.0 Equalizer UI (module `31051`, `8711fa44496b8e09.css:136-422`): +/// Header + Toggle -> Expandable (Preamp + `+12dB/0dB/-12dB` labels + 10 frequency bands) -> Full-width Pill Preset Selector. #[allow(clippy::too_many_arguments)] fn render_equalizer_body( ctx: &mut UiContext, @@ -3953,37 +4123,44 @@ fn render_equalizer_body( toggle_title: &str, ru: bool, enabled: &mut bool, + preamp: &mut f32, bands: &mut [f32; 10], changed: &mut bool, dropdown_open: &mut bool, - show_sliders: bool, + anim_alpha: f32, + expand_t: f32, + is_disabled: bool, + interactive: bool, salt: &str, -) -> Option { - // 1. Header row: Title + official Pill Toggle (`40×22`) +) -> Option<(Rect, bool)> { + // 1. Header row: Title + official Pill Toggle (`44×24`, smoothly animated) let hdr_r = Rect::from_xywh(area.left(), area.top(), area.width(), 28.0); ctx.draw_text_ellipsis( toggle_title, - TextStyle::bold(15.0, pal.text_bright), + TextStyle::medium(16.0, pal.text_bright.with_alpha_f32(anim_alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 56.0, hdr_r.height()), TextAlign::Left, ); - let sw_r = Rect::from_xywh(hdr_r.right() - 42.0, hdr_r.center_y() - 11.0, 42.0, 22.0); - let sw_resp = ctx.interact(WidgetId::new(salt).with("toggle"), sw_r); - ctx.dl().push_rect( - sw_r, - 11.0, - if *enabled { - pal.yellow - } else { - pal.surface_hover - }, - ); - let knob_x = if *enabled { sw_r.right() - 11.0 } else { sw_r.left() + 11.0 }; - ctx.dl().push_circle( - Pos2::new(knob_x, sw_r.center_y()), - 8.5, - if *enabled { Color::rgb(0x19, 0x19, 0x19) } else { pal.text_bright }, - ); + let sw_w = 44.0; + let sw_h = 24.0; + let sw_r = Rect::from_xywh(hdr_r.right() - sw_w, hdr_r.center_y() - sw_h * 0.5, sw_w, sw_h); + let sw_id = WidgetId::new(salt).with("toggle"); + let sw_resp = if interactive { + ctx.interact(sw_id, sw_r) + } else { + Default::default() + }; + let tog_t = ctx.animate_bool(sw_id.with("anim"), *enabled, 0.16); + let track_col = pal.border_control.lerp(pal.yellow, tog_t).with_alpha_f32(anim_alpha); + ctx.dl().push_rect(sw_r, sw_h * 0.5, track_col); + let knob_x = sw_r.left() + 12.0 + tog_t * (sw_w - 24.0); + let knob_col = if tog_t > 0.5 { + pal.on_yellow + } else { + pal.text_bright + }; + ctx.dl() + .push_circle(Pos2::new(knob_x, sw_r.center_y()), 9.0, knob_col.with_alpha_f32(anim_alpha)); if sw_resp.hovered { ctx.set_cursor(CursorKind::Pointer); } @@ -3995,145 +4172,96 @@ fn render_equalizer_body( } } - if !show_sliders { + if expand_t <= 0.01 { return None; } - let mut y = hdr_r.bottom() + 14.0; - let is_custom_or_modified = bands.iter().any(|&b| b.abs() >= 0.15); - - // 2. Preset selector button (`EqualizerPresets_root`) + optional Reset button - let reset_w = if is_custom_or_modified { 86.0 } else { 0.0 }; - let sel_w = (area.width() - if is_custom_or_modified { reset_w + 8.0 } else { 0.0 }).max(140.0); - let sel_r = Rect::from_xywh(area.left(), y, sel_w, 38.0); - let sel_resp = ctx.interact(WidgetId::new(salt).with("preset_sel"), sel_r); - ctx.dl().push_rect_bordered( - sel_r, - 12.0, - if sel_resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }, - 1.0, - if *dropdown_open { - pal.border_control - } else { - pal.border_subtle - }, - ); - let preset_lbl = active_eq_preset_name(bands, ru); - let label_col = if *enabled { - pal.text_bright - } else { - pal.text_disabled - }; - ctx.draw_text_ellipsis( - preset_lbl, - TextStyle::medium(13.5, label_col), - Rect::from_xywh(sel_r.left() + 14.0, sel_r.top(), sel_r.width() - 42.0, sel_r.height()), - TextAlign::Left, - ); - ctx.draw_icon( - Icon::ArrowDown, - Rect::from_center_size(Pos2::new(sel_r.right() - 18.0, sel_r.center_y()), Vec2::splat(16.0)), - if *enabled { - pal.text_secondary - } else { - pal.text_disabled - }, - ); - if sel_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if sel_resp.clicked { - *dropdown_open = !*dropdown_open; - } - - if is_custom_or_modified { - let rst_r = Rect::from_xywh(sel_r.right() + 8.0, y, reset_w, 38.0); - let rst_resp = ctx.interact(WidgetId::new(salt).with("preset_rst"), rst_r); - ctx.dl().push_rect( - rst_r, - 12.0, - if rst_resp.hovered { - pal.surface_hover - } else { - pal.surface_secondary - }, - ); - ctx.draw_text_ellipsis( - if ru { "Сбросить" } else { "Reset" }, - TextStyle::medium(12.5, pal.text_primary), - rst_r, - TextAlign::Center, - ); - if rst_resp.hovered { - ctx.set_cursor(CursorKind::Pointer); - } - if rst_resp.clicked { - *bands = [0.0; 10]; - *changed = true; - *dropdown_open = false; - } - } - - y += 50.0; - - // 3. Left dB Scale (`+12 dB`, `0 dB`, `-12 dB`) + 10 Vertical Band Sliders (`9rem` = `144px`) - let scale_w = 42.0; - let sliders_h = 136.0; - let lbl_col = if *enabled { - pal.text_secondary - } else { - pal.text_disabled - }; - ctx.draw_text_ellipsis( - "+12 dB", - TextStyle::regular(11.0, lbl_col), - Rect::from_xywh(area.left(), y, scale_w, 16.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - "0 dB", - TextStyle::regular(11.0, lbl_col), - Rect::from_xywh(area.left(), y + sliders_h * 0.5 - 8.0, scale_w, 16.0), - TextAlign::Left, - ); - ctx.draw_text_ellipsis( - "-12 dB", - TextStyle::regular(11.0, lbl_col), - Rect::from_xywh(area.left(), y + sliders_h - 16.0, scale_w, 16.0), - TextAlign::Left, - ); - - let grid_x = area.left() + scale_w + 4.0; - let grid_w = (area.width() - scale_w - 4.0).max(160.0); - // Subtle 0 dB center reference line - ctx.dl().push_rect( - Rect::from_xywh(grid_x, (y + sliders_h * 0.5).round(), grid_w, 1.0), + let content_alpha = (anim_alpha * expand_t).clamp(0.0, 1.0); + let clip_h = (242.0 * expand_t).max(0.0); + ctx.push_clip( + Rect::from_xywh(area.left() - 4.0, hdr_r.bottom(), area.width() + 8.0, clip_h), 0.0, - pal.border_subtle, ); - let col_w = grid_w / 10.0; - let fill_col = if *enabled { - pal.yellow - } else { + let y = hdr_r.bottom() + 16.0; + let sliders_h = 144.0; // `9rem` + let lbl_col = if is_disabled { pal.text_disabled - }; + } else { + pal.text_secondary + } + .with_alpha_f32(content_alpha); + + // 2. Left Preamp column (`Equalizer_preamp`) + amp labels (`12dB / 0dB / -12dB`) + let preamp_w = 42.0; + let preamp_r = Rect::from_xywh(area.left(), y, preamp_w, sliders_h); + let preamp_norm = ((*preamp - 0.5) / 1.0).clamp(0.0, 1.0); + let presp = eq_vertical_slider( + ctx, + pal, + WidgetId::new(salt).with("preamp"), + preamp_r, + preamp_norm, + is_disabled, + interactive && expand_t > 0.85, + content_alpha, + ); + if presp.hovered || presp.dragging { + ctx.show_tooltip(preamp_r, format!("{:.2}×", *preamp)); + } + if let Some(v) = presp.value { + let next = ((0.5 + v * 1.0) * 20.0).round() / 20.0; + let clamped = next.clamp(0.5, 1.5); + if (clamped - *preamp).abs() >= 0.025 { + *preamp = clamped; + *changed = true; + } + } + ctx.draw_text_ellipsis( + if ru { "уровень" } else { "level" }, + TextStyle::regular(11.5, lbl_col), + Rect::from_xywh(area.left() - 4.0, y + sliders_h + 8.0, preamp_w + 8.0, 16.0), + TextAlign::Center, + ); + + let scale_x = area.left() + preamp_w + 2.0; + let scale_w = 34.0; + ctx.draw_text_ellipsis( + "12dB", + TextStyle::regular(11.0, lbl_col), + Rect::from_xywh(scale_x, y, scale_w, 16.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + "0dB", + TextStyle::regular(11.0, lbl_col), + Rect::from_xywh(scale_x, y + sliders_h * 0.5 - 8.0, scale_w, 16.0), + TextAlign::Left, + ); + ctx.draw_text_ellipsis( + "-12dB", + TextStyle::regular(11.0, lbl_col), + Rect::from_xywh(scale_x, y + sliders_h - 16.0, scale_w, 16.0), + TextAlign::Left, + ); + + // 3. 10 Frequency Sliders (`60`..`16k`) + let grid_x = scale_x + scale_w + 4.0; + let grid_w = (area.right() - grid_x).max(160.0); + let col_w = grid_w / 10.0; for i in 0..10 { let bx = grid_x + i as f32 * col_w; - let sr = Rect::from_xywh(bx + 2.0, y, (col_w - 4.0).max(18.0), sliders_h); + let sr = Rect::from_xywh(bx + 1.0, y, (col_w - 2.0).max(18.0), sliders_h); let norm = ((bands[i] + 12.0) / 24.0).clamp(0.0, 1.0); - let sresp = ym_vertical_slider( + let sresp = eq_vertical_slider( ctx, pal, WidgetId::new(salt).with("band").with(i), sr, norm, - false, - fill_col, + is_disabled, + interactive && expand_t > 0.85, + content_alpha, ); if sresp.hovered || sresp.dragging { ctx.show_tooltip(sr, format!("{:+.1} dB", bands[i])); @@ -4143,75 +4271,148 @@ fn render_equalizer_body( let clamped = db.clamp(-12.0, 12.0); if (clamped - bands[i]).abs() >= 0.25 { bands[i] = clamped; - *enabled = true; *changed = true; } } ctx.draw_text_ellipsis( EQ_LABELS[i], - TextStyle::medium(11.0, lbl_col), - Rect::from_xywh(bx, y + sliders_h + 6.0, col_w, 16.0), + TextStyle::regular(11.5, lbl_col), + Rect::from_xywh(bx, y + sliders_h + 8.0, col_w, 16.0), TextAlign::Center, ); } - // 4. Floating Presets Dropdown (`EqualizerPresets_container`) rendered ON TOP of sliders! - if *dropdown_open { - let dd_h = 240.0f32.min((ctx.screen_rect().bottom() - sel_r.bottom() - 20.0).max(140.0)); - let dd_r = Rect::from_xywh(sel_r.left(), sel_r.bottom() + 6.0, sel_r.width(), dd_h); - ctx.register_blocker(dd_r); - ctx.dl() - .push_shadow(dd_r, 12.0, 20.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); - ctx.dl() - .push_rect_bordered(dd_r, 12.0, pal.bg_popover, 1.0, pal.border_control); - - let dd_scroll_id = WidgetId::new(salt).with("dd_scroll"); - let dd_inner = dd_r.shrink2(Vec2::new(6.0, 6.0)); - let scroll_y = ctx.begin_scroll_v(dd_scroll_id, dd_inner, 0.0); - let mut dy = dd_inner.top() - scroll_y; - let row_h = 36.0; - let cur_name = active_eq_preset_name(bands, ru); - - for (pi, preset) in EQ_PRESETS.iter().enumerate() { - let pname = preset.name(ru); - let rr = Rect::from_xywh(dd_inner.left(), dy, dd_inner.width() - 8.0, row_h); - let rresp = ctx.interact(WidgetId::new(salt).with("dd_item").with(pi), rr); - let is_cur = pname == cur_name; - if rresp.hovered { - ctx.dl().push_rect(rr, 8.0, pal.surface_hover); - ctx.set_cursor(CursorKind::Pointer); - } - ctx.draw_text_ellipsis( - pname, - TextStyle::medium(13.5, if is_cur { pal.text_bright } else { pal.text_primary }), - Rect::from_xywh(rr.left() + 10.0, rr.top(), rr.width() - 36.0, rr.height()), - TextAlign::Left, - ); - if is_cur { - ctx.draw_icon( - Icon::CheckXxs, - Rect::from_center_size(Pos2::new(rr.right() - 14.0, rr.center_y()), Vec2::splat(15.0)), - pal.yellow, - ); - } - if rresp.clicked { - *bands = preset.gains; - *enabled = true; - *changed = true; - *dropdown_open = false; - } - dy += row_h; + // 4. Full-width Pill Preset Selector BELOW sliders (`EqualizerPresets_button`, `radius = h/2`) + let sel_y = y + sliders_h + 8.0 + 16.0 + 16.0; + let sel_h = 42.0; + let sel_r = Rect::from_xywh(area.left(), sel_y, area.width(), sel_h); + let sel_resp = if !is_disabled && interactive && expand_t > 0.85 { + ctx.interact(WidgetId::new(salt).with("preset_sel"), sel_r) + } else { + Default::default() + }; + let sel_bg = if sel_resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + } + .with_alpha_f32(content_alpha); + ctx.dl().push_rect(sel_r, sel_h * 0.5, sel_bg); + let preset_lbl = active_eq_preset_name(bands, ru); + let label_col = if is_disabled { + pal.text_disabled + } else { + pal.text_bright + } + .with_alpha_f32(content_alpha); + ctx.draw_text_ellipsis( + preset_lbl, + TextStyle::medium(13.5, label_col), + Rect::from_xywh(sel_r.left() + 18.0, sel_r.top(), sel_r.width() - 48.0, sel_r.height()), + TextAlign::Left, + ); + ctx.draw_icon( + Icon::ArrowDown, + Rect::from_center_size(Pos2::new(sel_r.right() - 20.0, sel_r.center_y()), Vec2::splat(16.0)), + if is_disabled { + pal.text_disabled + } else { + pal.text_bright } - let total_dd_h = dy - (dd_inner.top() - scroll_y); - ctx.end_scroll_v(dd_scroll_id, pal, total_dd_h, true); - - if ctx.input.clicked_outside(dd_r) && !sel_resp.clicked { - *dropdown_open = false; - } - return Some(dd_r); + .with_alpha_f32(content_alpha), + ); + if sel_resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if sel_resp.clicked { + *dropdown_open = !*dropdown_open; } - None + ctx.pop_clip(); + + if *dropdown_open { + Some((sel_r, sel_resp.clicked)) + } else { + None + } +} + +/// Floating upward Equalizer Presets dropdown (`EqualizerPresets_container`, `placement: "top"`). +#[allow(clippy::too_many_arguments)] +fn render_eq_presets_dropdown( + ctx: &mut UiContext, + pal: &YmPalette, + sel_r: Rect, + parent_r: Rect, + ru: bool, + enabled: &mut bool, + preamp: &mut f32, + bands: &mut [f32; 10], + changed: &mut bool, + dropdown_open: &mut bool, + sel_clicked: bool, + salt: &str, +) -> Option { + let screen = ctx.screen_rect(); + let max_above = (sel_r.top() - screen.top() - 24.0).max(140.0); + let dd_h = 260.0f32.min(max_above); + let dd_r = Rect::from_xywh(sel_r.left(), (sel_r.top() - dd_h - 6.0).max(screen.top() + 12.0), sel_r.width(), dd_h); + ctx.register_blocker(dd_r); + ctx.dl() + .push_shadow(dd_r, 14.0, 20.0, 0.0, Vec2::new(0.0, 6.0), pal.shadow_menu); + ctx.dl() + .push_rect_bordered(dd_r, 14.0, pal.bg_popover, 1.0, pal.border_control); + + let dd_scroll_id = WidgetId::new(salt).with("dd_scroll"); + let dd_inner = dd_r.shrink2(Vec2::new(6.0, 6.0)); + let scroll_y = ctx.begin_scroll_v(dd_scroll_id, dd_inner, 0.0); + let mut dy = dd_inner.top() - scroll_y; + let row_h = 36.0; + let cur_name = active_eq_preset_name(bands, ru); + + for (pi, preset) in EQ_PRESETS.iter().enumerate() { + let pname = preset.name(ru); + let rr = Rect::from_xywh(dd_inner.left(), dy, dd_inner.width() - 8.0, row_h); + let rresp = ctx.interact(WidgetId::new(salt).with("dd_item").with(pi), rr); + let is_cur = pname == cur_name; + if rresp.hovered { + ctx.dl().push_rect(rr, 8.0, pal.surface_hover); + ctx.set_cursor(CursorKind::Pointer); + } + ctx.draw_text_ellipsis( + pname, + TextStyle::medium(13.5, if is_cur { pal.text_bright } else { pal.text_primary }), + Rect::from_xywh(rr.left() + 12.0, rr.top(), rr.width() - 36.0, rr.height()), + TextAlign::Left, + ); + if is_cur { + ctx.draw_icon( + Icon::CheckXxs, + Rect::from_center_size(Pos2::new(rr.right() - 14.0, rr.center_y()), Vec2::splat(15.0)), + pal.yellow, + ); + } + if rresp.clicked { + *bands = preset.gains; + if pi == 0 { + *preamp = 1.0; + } + *enabled = true; + *changed = true; + *dropdown_open = false; + } + dy += row_h; + } + let total_dd_h = dy - (dd_inner.top() - scroll_y); + ctx.end_scroll_v(dd_scroll_id, pal, total_dd_h, true); + + if ctx.input.clicked_outside(dd_r) && !sel_clicked { + *dropdown_open = false; + if ctx.input.pointer_pos.map_or(false, |p| parent_r.contains(p)) { + ctx.input.consume_pointer_press(); + } + } + Some(dd_r) } /// 1-to-1 Official `ShortcutsModal` (`29c95960ed6ac633.css:137-238`, `settings/page.js:1076-1175`). @@ -4219,42 +4420,51 @@ pub fn render_shortcuts_modal( ctx: &mut UiContext, pal: &YmPalette, app: &AppState, + anim_t: f32, actions: &mut Vec, ) { let i18n = app.i18n(); let ru = i18n.is_ru(); - let anim_t = if app.fixed_vibe_time.is_some() { - 1.0 - } else { - let raw = ctx.animate_bool(WidgetId::new("ym_shortcuts_modal_anim"), true, 0.18); - let u = 1.0 - raw; - 1.0 - u * u * u - }; + let open = app.shortcuts_modal_open; + let alpha = anim_t.clamp(0.0, 1.0); let screen = ctx.screen_rect(); let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); let modal_h = (screen.height() - 84.0).clamp(320.0, 560.0); - let slide_dy = (1.0 - anim_t) * 14.0; + let slide_dy = (1.0 - alpha) * 14.0; let modal_r = Rect::from_center_size( Pos2::new(screen.center_x(), screen.center_y() + slide_dy), Vec2::new(modal_w, modal_h), ); ctx.with_layer(ZLayer::Modal, |ctx| { - ctx.register_blocker(screen); + if open { + ctx.register_blocker(screen); + } ctx.dl().push_rect( screen, 0.0, - Color::rgba(0, 0, 0, (150.0 * anim_t).round() as u8), + Color::rgba(0, 0, 0, (150.0 * alpha).round() as u8), + ); + ctx.dl().push_shadow( + modal_r, + 16.0, + 32.0, + 0.0, + Vec2::new(0.0, 8.0), + pal.shadow_modal.with_alpha_f32(alpha), + ); + ctx.dl().push_rect_bordered( + modal_r, + 16.0, + pal.bg_popover.with_alpha_f32(alpha), + 1.0, + pal.border_subtle.with_alpha_f32(alpha), ); - ctx.dl() - .push_shadow(modal_r, 16.0, 32.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); - ctx.dl() - .push_rect_bordered(modal_r, 16.0, pal.bg_popover, 1.0, pal.border_subtle); let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); ctx.draw_text_ellipsis( - if ru { "Горячие клавиши" } else { "Keyboard shortcuts" }, - TextStyle::headline(20.0, pal.text_bright), + if ru { "Горячие клавиши" } else { "Hot keys" }, + TextStyle::headline(20.0, pal.text_bright.with_alpha_f32(alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); @@ -4352,7 +4562,7 @@ pub fn render_shortcuts_modal( let total_h = y - (scroll_r.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_h, true); - if ctx.input.clicked_outside(modal_r) { + if open && ctx.input.consume_clicked_outside(modal_r) { actions.push(AppAction::SetShortcutsModalOpen(false)); } }); @@ -4553,60 +4763,70 @@ pub fn render_release_notes_modal( ctx: &mut UiContext, pal: &YmPalette, app: &AppState, + anim_t: f32, actions: &mut Vec, ) { let i18n = app.i18n(); let ru = i18n.is_ru(); - let anim_t = if app.fixed_vibe_time.is_some() { - 1.0 - } else { - let raw = ctx.animate_bool(WidgetId::new("ym_release_notes_modal_anim"), true, 0.18); - let u = 1.0 - raw; - 1.0 - u * u * u - }; + let open = app.release_notes_modal_open; + let alpha = anim_t.clamp(0.0, 1.0); let screen = ctx.screen_rect(); let modal_w = (screen.width() - 48.0).clamp(320.0, 460.0); let modal_h = (screen.height() - 84.0).clamp(320.0, 500.0); - let slide_dy = (1.0 - anim_t) * 14.0; + let slide_dy = (1.0 - alpha) * 14.0; let modal_r = Rect::from_center_size( Pos2::new(screen.center_x(), screen.center_y() + slide_dy), Vec2::new(modal_w, modal_h), ); ctx.with_layer(ZLayer::Modal, |ctx| { - ctx.register_blocker(screen); + if open { + ctx.register_blocker(screen); + } ctx.dl().push_rect( screen, 0.0, - Color::rgba(0, 0, 0, (150.0 * anim_t).round() as u8), + Color::rgba(0, 0, 0, (150.0 * alpha).round() as u8), + ); + ctx.dl().push_shadow( + modal_r, + 16.0, + 32.0, + 0.0, + Vec2::new(0.0, 8.0), + pal.shadow_modal.with_alpha_f32(alpha), + ); + ctx.dl().push_rect_bordered( + modal_r, + 16.0, + pal.bg_popover.with_alpha_f32(alpha), + 1.0, + pal.border_subtle.with_alpha_f32(alpha), ); - ctx.dl() - .push_shadow(modal_r, 16.0, 32.0, 0.0, Vec2::new(0.0, 8.0), pal.shadow_modal); - ctx.dl() - .push_rect_bordered(modal_r, 16.0, pal.bg_popover, 1.0, pal.border_subtle); // Header (`padding: 16px`, title + circular close ×) let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 14.0, modal_w - 40.0, 34.0); ctx.draw_text_ellipsis( i18n.whats_new(), - TextStyle::headline(20.0, pal.text_bright), + TextStyle::headline(20.0, pal.text_bright.with_alpha_f32(alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); let close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top() + 1.0, 32.0, 32.0); - if icon_button( - ctx, - WidgetId::new("rn_modal_close"), - close_r, - Icon::Close, - 16.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, - false, - "", - ) - .clicked + if open + && icon_button( + ctx, + WidgetId::new("rn_modal_close"), + close_r, + Icon::Close, + 16.0, + pal.text_secondary, + pal.text_bright, + pal.surface_hover, + false, + "", + ) + .clicked { actions.push(AppAction::CloseReleaseNotesModal); } @@ -4828,7 +5048,7 @@ pub fn render_release_notes_modal( let total_h = y - (scroll_r.top() - scroll_y); ctx.end_scroll_v(scroll_id, pal, total_h, true); - if ctx.input.clicked_outside(modal_r) { + if open && ctx.input.consume_clicked_outside(modal_r) { actions.push(AppAction::CloseReleaseNotesModal); } }); diff --git a/src/views/settings.rs b/src/views/settings.rs index 97b18aa..66b4b09 100644 --- a/src/views/settings.rs +++ b/src/views/settings.rs @@ -1,6 +1,5 @@ use crate::app::i18n::APP_VERSION; use crate::app::state::{AppAction, AppState}; -use crate::audio::dsp::active_eq_preset_name; use crate::config::{AudioQuality, Language, ThemeMode}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; @@ -34,7 +33,7 @@ pub fn render_settings( // `views/mod.rs` already insets `inner_r` by (25, 12, 25, 0) let x = rect.left(); - let col_w = (rect.width() - 12.0).clamp(320.0, 520.0); + let col_w = (rect.width() - 12.0).clamp(320.0, 482.0); let mut y = rect.top() + 8.0 - scroll_y; // Page Heading @@ -176,31 +175,53 @@ pub fn render_settings( y += 18.0; // ------------------------------------------------------------------------- - // 2. Official Settings List (`Settings_root`, 24px vertical spacing) + // 2. Official Settings List (`Settings_root`, 32px vertical spacing) // ------------------------------------------------------------------------- - // 2a. Sound quality (`QualitySettingsModal` trigger) + // 2a. Clear memory (`offline.clear-memory`) + if settings_button_item( + ctx, + pal, + WidgetId::new("set_clear_cache"), + x, + &mut y, + col_w, + if ru { "Очистить память" } else { "Clear cache" }, + Some(if ru { + "Удалим только скачанное и кэш. Это не повлияет на ваши рекомендации и лайки" + } else { + "We'll only delete downloaded content and cache. This won't affect your recommendations or likes" + }), + None, + ) { + actions.push(AppAction::ClearCoverCache); + } + + // 2b. Equalizer (`EqualizerModal` trigger — clean row, no status subtitle) + if settings_button_item( + ctx, + pal, + WidgetId::new("set_eq_btn"), + x, + &mut y, + col_w, + if ru { "Эквалайзер" } else { "Equalizer" }, + None, + None, + ) { + actions.push(AppAction::SetEqualizerModalOpen(true)); + } + + // 2c. Sound settings (`QualitySettingsModal` trigger) let qual_sub = match app.config.audio_quality { AudioQuality::Lossless => { - if ru { - "Максимальное · FLAC без потерь" - } else { - "Maximum · Lossless FLAC" - } + if ru { "Превосходное" } else { "Superb" } } AudioQuality::High => { - if ru { - "Оптимальное · 320 кбит/с" - } else { - "Optimal · 320 kbps" - } + if ru { "Оптимальное" } else { "Balanced" } } AudioQuality::Standard => { - if ru { - "Экономичное" - } else { - "Efficient" - } + if ru { "Экономичное" } else { "Efficient" } } }; if settings_button_item( @@ -217,34 +238,7 @@ pub fn render_settings( actions.push(AppAction::SetEqPopoverOpen(true)); } - // 2b. Equalizer (`EqualizerModal` trigger) - let eq_sub = if app.config.eq_enabled { - let preset_name = active_eq_preset_name(&app.config.eq_bands_db, ru); - if ru { - format!("Включён · {}", preset_name) - } else { - format!("Enabled · {}", preset_name) - } - } else if ru { - "Выключен".to_string() - } else { - "Disabled".to_string() - }; - if settings_button_item( - ctx, - pal, - WidgetId::new("set_eq_btn"), - x, - &mut y, - col_w, - if ru { "Эквалайзер" } else { "Equalizer" }, - Some(&eq_sub), - None, - ) { - actions.push(AppAction::SetEqualizerModalOpen(true)); - } - - // 2c. Crossfade between tracks (toggle + optional duration override) + // 2d. Crossfade between tracks (toggle + optional duration override) let cf_sub = if app.config.crossfade_enabled { if app.config.crossfade_secs < 0.1 { if ru { @@ -392,30 +386,6 @@ pub fn render_settings( actions.push(AppAction::SetCloseToTray(next)); } - // 2h. Clear cover cache - let cache_sub = if ru { - format!("В кэше: {} обложек", covers.len()) - } else { - format!("Cached items: {}", covers.len()) - }; - if settings_button_item( - ctx, - pal, - WidgetId::new("set_clear_cache"), - x, - &mut y, - col_w, - if ru { - "Очистить кэш обложек" - } else { - "Clear cover cache" - }, - Some(&cache_sub), - None, - ) { - actions.push(AppAction::ClearCoverCache); - } - // 2i. Keyboard shortcuts (`ShortcutsModal` trigger) if settings_button_item( ctx, @@ -424,17 +394,38 @@ pub fn render_settings( x, &mut y, col_w, - if ru { - "Горячие клавиши" - } else { - "Keyboard shortcuts" - }, + if ru { "Горячие клавиши" } else { "Hot keys" }, None, None, ) { actions.push(AppAction::SetShortcutsModalOpen(true)); } + // 2j. About (`ReleaseNotesModal` trigger) + let about_sub = if let Some(ref upd) = app.available_update { + format!("v{} · {}", APP_VERSION, t.update_available_banner(&upd.version)) + } else { + format!("v{}", APP_VERSION) + }; + let about_badge_col = if app.available_update.is_some() { + Some(pal.yellow) + } else { + None + }; + if settings_button_item( + ctx, + pal, + WidgetId::new("set_about_btn"), + x, + &mut y, + col_w, + if ru { "О приложении" } else { "About the app" }, + Some(&about_sub), + about_badge_col, + ) { + actions.push(AppAction::OpenReleaseNotesModal); + } + // 2j. Appearance & Language (compact official pill selectors) ctx.draw_text_ellipsis( t.appearance(), @@ -496,34 +487,9 @@ pub fn render_settings( .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); y += 18.0; - // ------------------------------------------------------------------------- - // 3. About & Updates (`ReleaseNotesModal` + Update CTA) - // ------------------------------------------------------------------------- - let about_sub = if let Some(ref upd) = app.available_update { - format!("v{} · {}", APP_VERSION, t.update_available_banner(&upd.version)) - } else if ru { - format!("Версия {} · {}", APP_VERSION, t.up_to_date_badge()) - } else { - format!("Version {} · {}", APP_VERSION, t.up_to_date_badge()) - }; - let about_badge_col = if app.available_update.is_some() { - Some(pal.yellow) - } else { - None - }; - if settings_button_item( - ctx, - pal, - WidgetId::new("set_about_btn"), - x, - &mut y, - col_w, - if ru { "О приложении" } else { "About" }, - Some(&about_sub), - about_badge_col, - ) { - actions.push(AppAction::OpenReleaseNotesModal); - } + ctx.dl() + .push_rect(Rect::from_xywh(x, y, col_w, 1.0), 0.0, pal.border_subtle); + y += 18.0; if let Some(ref upd) = app.available_update { let banner_r = Rect::from_xywh(x, y - 6.0, col_w, 54.0); @@ -638,8 +604,8 @@ pub fn render_settings( } /// Official `SettingsListButtonItem` (`29c95960ed6ac633.css:74-119`): -/// Borderless row with bold 16px title, optional 13px subtitle, and right-aligned `arrowRight` chevron -/// that glides +4px right on hover. +/// Borderless row with NO hover background fill — 16px title, optional wrapped 14px description, +/// and right-aligned `arrowRight` chevron that glides +6px right on hover. #[allow(clippy::too_many_arguments)] fn settings_button_item( ctx: &mut UiContext, @@ -652,44 +618,47 @@ fn settings_button_item( description: Option<&str>, dot_color: Option, ) -> bool { - let row_h = if description.is_some() { 44.0 } else { 28.0 }; - let hit_r = Rect::from_xywh(x - 8.0, *y - 4.0, w + 16.0, row_h + 8.0); + let text_w = (w - 36.0).max(100.0); + let desc_h = description.map_or(0.0, |d| { + ctx.measure_text(d, TextStyle::regular(14.0, pal.text_secondary), Some(text_w)) + .y + .max(18.0) + + 4.0 + }); + let row_h = (22.0 + desc_h).max(26.0); + let hit_r = Rect::from_xywh(x, *y - 2.0, w, row_h + 4.0); let resp = ctx.interact(id, hit_r); - let hover_t = ctx.animate_bool(id.with("hov"), resp.hovered, 0.14); + let hover_t = ctx.animate_bool(id.with("hov"), resp.hovered, 0.16); if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } - if hover_t > 0.01 { - ctx.dl() - .push_rect(hit_r, 10.0, pal.surface_hover.with_alpha_f32(hover_t * 0.5)); - } - let text_w = (w - 32.0).max(80.0); ctx.draw_text_ellipsis( title, - TextStyle::bold(16.0, pal.text_bright), + TextStyle::medium(16.0, pal.text_bright), Rect::from_xywh(x, *y, text_w, 22.0), TextAlign::Left, ); if let Some(desc) = description { - ctx.draw_text_ellipsis( + ctx.draw_text_wrapped( desc, - TextStyle::medium(13.0, pal.text_secondary), - Rect::from_xywh(x, *y + 23.0, text_w, 18.0), + TextStyle::regular(14.0, pal.text_secondary), + Rect::from_xywh(x, *y + 24.0, text_w, desc_h), + None, TextAlign::Left, ); } if let Some(dc) = dot_color { ctx.dl() - .push_circle(Pos2::new(x + w - 34.0, *y + row_h * 0.5), 4.0, dc); + .push_circle(Pos2::new(x + w - 34.0, *y + 11.0), 4.0, dc); } - let chev_x = x + w - 12.0 + hover_t * 4.0; + let chev_x = x + w - 12.0 + hover_t * 6.0; ctx.draw_icon( Icon::MenuArrowXxs, - Rect::from_center_size(Pos2::new(chev_x, *y + row_h * 0.5), Vec2::splat(16.0)), + Rect::from_center_size(Pos2::new(chev_x, *y + 11.0), Vec2::splat(16.0)), if resp.hovered { pal.text_bright } else { @@ -697,12 +666,12 @@ fn settings_button_item( }, ); - *y += row_h + 20.0; + *y += row_h + 28.0; resp.clicked } /// Official `SettingsListToggleItem` (`29c95960ed6ac633.css:120-136`): -/// Borderless row with bold 16px title, optional wrapped 13px subtitle, and right-aligned pill toggle. +/// Borderless row with 16px title, optional wrapped 14px description, and right-aligned pill toggle. #[allow(clippy::too_many_arguments)] fn settings_toggle_item( ctx: &mut UiContext, @@ -717,37 +686,37 @@ fn settings_toggle_item( ) -> Option { let text_w = (w - 60.0).max(100.0); let desc_h = description.map_or(0.0, |d| { - ctx.measure_text(d, TextStyle::medium(13.0, pal.text_secondary), Some(text_w)) + ctx.measure_text(d, TextStyle::regular(14.0, pal.text_secondary), Some(text_w)) .y .max(18.0) + 4.0 }); - let row_h = (22.0 + desc_h).max(28.0); - let hit_r = Rect::from_xywh(x - 8.0, *y - 4.0, w + 16.0, row_h + 8.0); + let row_h = (22.0 + desc_h).max(26.0); + let hit_r = Rect::from_xywh(x, *y - 2.0, w, row_h + 4.0); let resp = ctx.interact(id, hit_r); - let anim = ctx.animate_bool(id.with("tog"), checked, 0.18); + let anim = ctx.animate_bool(id.with("tog"), checked, 0.16); ctx.draw_text_ellipsis( title, - TextStyle::bold(16.0, pal.text_bright), + TextStyle::medium(16.0, pal.text_bright), Rect::from_xywh(x, *y, text_w, 22.0), TextAlign::Left, ); if let Some(desc) = description { ctx.draw_text_wrapped( desc, - TextStyle::medium(13.0, pal.text_secondary), + TextStyle::regular(14.0, pal.text_secondary), Rect::from_xywh(x, *y + 24.0, text_w, desc_h), None, TextAlign::Left, ); } - let sw_w = 42.0; + let sw_w = 44.0; let sw_h = 24.0; let sw_r = Rect::from_xywh( x + w - sw_w, - *y + 11.0 - sw_h * 0.5, + *y + (row_h - sw_h) * 0.5, sw_w, sw_h, ); @@ -761,12 +730,12 @@ fn settings_toggle_item( pal.text_bright }; ctx.dl() - .push_circle(Pos2::new(knob_x, sw_r.center_y()), 8.5, knob_col); + .push_circle(Pos2::new(knob_x, sw_r.center_y()), 9.0, knob_col); if resp.hovered { ctx.set_cursor(CursorKind::Pointer); } - *y += row_h + 20.0; + *y += row_h + 28.0; if resp.clicked { Some(!checked) } else { diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index ea89e0c..aee1250 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -2568,11 +2568,13 @@ fn test_ext_19_official_settings_sound_quality_equalizer_and_shortcuts_modals() 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); From 5c6a8557b386d5426c54d139960fdc227c051c49 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 19:55:53 +0300 Subject: [PATCH 13/17] chore(release): v0.1.7 --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3b2d5f4..c6680dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6550,7 +6550,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.6" +version = "0.1.7" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 4d113ca..4ab709c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.6" +version = "0.1.7" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" diff --git a/README.md b/README.md index f915417..206a239 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.6-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.6-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.7-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.7-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.6-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.7-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.6-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.7-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности From 8bdb32623ff9113ae857ee2dcb2079558057ce32 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 23:32:38 +0300 Subject: [PATCH 14/17] feat: official sound settings right-slide, player view skins, and UI polish --- assets/icons/thumb_car.svg | 54 +++++ assets/icons/thumb_duck.svg | 44 +++++ src/app/state.rs | 14 +- src/config.rs | 45 +++++ src/engine/input.rs | 4 +- src/engine/mod.rs | 4 +- src/icons.rs | 8 + src/views/detail.rs | 33 +++- src/views/mod.rs | 14 +- src/views/my_vibe.rs | 25 +-- src/views/overlays.rs | 205 ++++++++++--------- src/views/player_bar.rs | 131 ++++++------ src/views/player_thumbs.rs | 385 ++++++++++++++++++++++++++++++++++++ src/views/settings.rs | 70 ++++++- src/views/sidebar.rs | 10 +- tests/parity_extended.rs | 7 + 16 files changed, 850 insertions(+), 203 deletions(-) create mode 100644 assets/icons/thumb_car.svg create mode 100644 assets/icons/thumb_duck.svg create mode 100644 src/views/player_thumbs.rs diff --git a/assets/icons/thumb_car.svg b/assets/icons/thumb_car.svg new file mode 100644 index 0000000..7037c0a --- /dev/null +++ b/assets/icons/thumb_car.svg @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/icons/thumb_duck.svg b/assets/icons/thumb_duck.svg new file mode 100644 index 0000000..18a11c0 --- /dev/null +++ b/assets/icons/thumb_duck.svg @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/app/state.rs b/src/app/state.rs index 6e69f38..cb1c51b 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -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, ThemeMode}; +use crate::config::{AppConfig, AudioQuality, Language, PinnedItem, PlayerThumbStyle, ThemeMode}; use crate::telemetry::PerfTelemetry; use crate::vulkan::vibe_renderer::VibePushConstants; @@ -378,6 +378,7 @@ pub enum AppAction { SetAiContentReduction(bool), SetChildMode(bool), SetCloseToTray(bool), + SetPlayerThumb(PlayerThumbStyle), UpdateEq { enabled: bool, preamp: f32, @@ -1088,6 +1089,13 @@ 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) @@ -3130,6 +3138,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, diff --git a/src/config.rs b/src/config.rs index 02bda70..c3c293a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,6 +10,48 @@ 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). @@ -165,6 +207,8 @@ 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, @@ -220,6 +264,7 @@ impl Default for AppConfig { ai_content_reduction: false, child_mode: false, close_to_tray: true, + player_thumb: PlayerThumbStyle::Standard, max_cover_cache: 256, show_perf_hud: false, search_history: Vec::new(), diff --git a/src/engine/input.rs b/src/engine/input.rs index 6018b59..ffa0819 100644 --- a/src/engine/input.rs +++ b/src/engine/input.rs @@ -277,7 +277,7 @@ impl InputState { self.pointer_pos = Some(next); if self.left_down { if let Some(origin) = self.drag_origin { - if origin.distance(next) >= 3.0 { + if origin.distance(next) >= 5.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.1) + ((time - prev_time) as f32).clamp(0.001, 0.033) } else { 1.0 / 60.0 }; diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 3a071ba..56dacf3 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -154,7 +154,9 @@ 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 immediate_repaint { + let repaint_after = if self.repaint_requested || !texture_uploads.is_empty() { + Some(std::time::Duration::from_millis(1)) + } else if self.animator.needs_repaint() { Some(std::time::Duration::from_millis(16)) } else { self.repaint_after diff --git a/src/icons.rs b/src/icons.rs index 091f4da..1a49a0c 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -131,6 +131,8 @@ pub enum Icon { YandexIdLogoRuLight, YandexIdLogoEnDark, YandexIdLogoEnLight, + ThumbDuck, + ThumbCar, } impl Icon { @@ -259,6 +261,8 @@ 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"), } } @@ -271,6 +275,8 @@ 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), } @@ -406,6 +412,8 @@ impl Icon { Icon::YandexIdLogoRuLight, Icon::YandexIdLogoEnDark, Icon::YandexIdLogoEnLight, + Icon::ThumbDuck, + Icon::ThumbCar, ]; } diff --git a/src/views/detail.rs b/src/views/detail.rs index 623f241..0fc8742 100644 --- a/src/views/detail.rs +++ b/src/views/detail.rs @@ -5,9 +5,9 @@ use crate::engine::input::WidgetId; use crate::engine::scroll::visible_row_range; use crate::engine::text::{TextAlign, TextStyle}; use crate::engine::theme::{YmPalette, TRACK_ROW_HEIGHT}; -use crate::engine::types::{CornerRadii, CursorKind, Pos2, Rect, Vec2}; +use crate::engine::types::{Color, CornerRadii, CursorKind, Pos2, Rect, Vec2}; use crate::engine::widgets::{ - draw_cover_art, media_card, secondary_pill_button, separated_artists, text_input_widget, + draw_cover_art, media_card, separated_artists, text_input_widget, track_row, yellow_pill_button, TextInputOptions, TrackRowAction, TrackRowOptions, }; use crate::engine::UiContext; @@ -769,16 +769,29 @@ pub fn render_detail( None => chip.id == "all", Some(sel) => sel == &chip.id, }; - let (resp, r) = secondary_pill_button( - ctx, - pal, - WidgetId::from_pair("fav_chip", &chip.id), - Pos2::new(cx, y), - None, + 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( &chip.name, - 40.0, - is_selected, + 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, ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } if resp.clicked { let next_id = if chip.id == "all" { None diff --git a/src/views/mod.rs b/src/views/mod.rs index 9c67299..ddd5a66 100644 --- a/src/views/mod.rs +++ b/src/views/mod.rs @@ -4,6 +4,7 @@ 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; @@ -549,17 +550,17 @@ impl YandexMusicShell { ease_out(self.ui.animate_bool( WidgetId::new("ym_quality_popover_anim"), self.app.eq_popover_open, - 0.18, + 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 { - ease_out(self.ui.animate_bool( + 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( @@ -671,9 +672,16 @@ impl YandexMusicShell { } // Dispatch all actions emitted during this frame + let had_actions = !actions.is_empty(); for act in actions { self.app.dispatch(act); } + // Any dispatched UI action may open/close a popover, modal, or start an animation + // that wasn't evaluated yet this frame — schedule an immediate follow-up frame so + // 0 FPS idle mode never stalls opening a menu until the next mouse move. + if had_actions { + self.ui.request_repaint(); + } // Flush any clipboard write requested by Share > Copy link / HTML code if let Some(clip_text) = self.app.take_pending_clipboard_text() { diff --git a/src/views/my_vibe.rs b/src/views/my_vibe.rs index 889d5fd..a9dc301 100644 --- a/src/views/my_vibe.rs +++ b/src/views/my_vibe.rs @@ -764,29 +764,14 @@ pub fn render_my_vibe( } } - // 6c. Like Button (darker contrast backing when liked over bright playing orange/red gradient!) + // 6c. Like Button (official 5.129.0 renders a clean white filled heart when liked!) 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 { - if play_fade_t > 0.1 { - Color::rgb(0xFF, 0x3B, 0x30) - } else { - pal.accent_coral - } - } else { - col_side_lo - }, + if is_liked { col_side_hi } else { col_side_lo }, ) { if let Some(ref tr) = current_track { actions.push(AppAction::ToggleLike(tr.clone())); @@ -1123,9 +1108,9 @@ pub fn render_my_vibe( } else { (APP_VERSION.to_string(), pal.text_secondary) }; - 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) + 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) .ceil(); let ver_r = Rect::from_xywh( (rect.right() - ver_w - 16.0).floor(), diff --git a/src/views/overlays.rs b/src/views/overlays.rs index c1fd5d1..ec841f7 100644 --- a/src/views/overlays.rs +++ b/src/views/overlays.rs @@ -849,11 +849,7 @@ pub fn render_fullscreen_player( "fs_ov_like", if is_liked { Icon::Liked } else { Icon::Like }, 30.0, - if is_liked { - pal.accent_coral - } else { - Color::WHITE - }, + Color::WHITE, i18n.like(), ) { actions.push(AppAction::ToggleLike(tr.clone())); @@ -3413,8 +3409,8 @@ pub fn render_track_detail_modal( like_r, if is_liked { Icon::Liked } else { Icon::Like }, 22.0, - if is_liked { pal.accent_coral } else { pal.text_primary }, - if is_liked { pal.accent_coral_hover } else { pal.text_bright }, + if is_liked { pal.text_bright } else { pal.text_primary }, + pal.text_bright, pal.surface_hover, false, i18n.like(), @@ -3710,14 +3706,15 @@ pub fn render_eq_popover( total_rows_h += rh + 4.0; } - // Header (16+32+10) + Quality rows + Divider (6+1+14) + EQ header (28) + Bottom pad (18) - let base_h = 58.0 + total_rows_h + 21.0 + 28.0 + 18.0; - let eq_extra_h = 242.0 * expand_t; + // Header (20+32+18) + Quality rows + Gap (20) + EQ header (28) + Bottom pad (22) + let base_h = 70.0 + total_rows_h + 20.0 + 28.0 + 22.0; + let eq_extra_h = 246.0 * expand_t; let pop_h = (base_h + eq_extra_h).min((screen.height() - PLAYER_BAR_HEIGHT - 56.0).max(280.0)); - let slide_dy = (1.0 - alpha) * 12.0; + // Official `Modal` (`placement="right"`, `1372-8bc732062b5d53ca.js`): glides smoothly in from right edge! + let slide_dx = (1.0 - alpha) * 32.0; let pop_r = Rect::from_xywh( - (screen.right() - pop_w - 20.0).max(16.0), - (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 20.0 + slide_dy).max(40.0), + (screen.right() - pop_w - 16.0).max(16.0) + slide_dx, + (screen.bottom() - PLAYER_BAR_HEIGHT - pop_h - 18.0).max(40.0), pop_w, pop_h, ); @@ -3737,36 +3734,39 @@ pub fn render_eq_popover( 24.0, 0.0, Vec2::new(0.0, 6.0), - pal.shadow_menu.with_alpha_f32(alpha), + pal.shadow_menu.scale_alpha(alpha), ); ctx.dl().push_rect_bordered( pop_r, 16.0, - pal.bg_popover.with_alpha_f32(alpha), + pal.bg_popover.scale_alpha(alpha), 1.0, - pal.border_subtle.with_alpha_f32(alpha), + pal.border_subtle.scale_alpha(alpha), ); ctx.push_clip(pop_r, 16.0); - // Header: `"Настройки звука"` + circular Close `×` (`QualitySettings_headerWithCloseButton`) - let hdr_r = Rect::from_xywh(pop_r.left() + 20.0, pop_r.top() + 16.0, pop_w - 40.0, 32.0); + // Header: `"Настройки звука"` + filled circular Close `×` (`radius="round" color="secondary"`) + let hdr_r = Rect::from_xywh(pop_r.left() + 24.0, pop_r.top() + 20.0, pop_w - 48.0, 32.0); ctx.draw_text_ellipsis( i18n.sound_settings(), - TextStyle::headline(18.0, pal.text_bright.with_alpha_f32(alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), + TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 40.0, hdr_r.height()), TextAlign::Left, ); + let close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top(), 32.0, 32.0); + ctx.dl() + .push_circle(close_r.center(), 16.0, pal.surface_hover.scale_alpha(alpha)); if open && icon_button( ctx, WidgetId::new("qs_close_btn"), - Rect::from_xywh(hdr_r.right() - 28.0, hdr_r.top() + 2.0, 28.0, 28.0), + close_r, Icon::Close, - 13.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, + 14.0, + pal.text_bright.scale_alpha(alpha), + pal.text_bright.scale_alpha(alpha), + pal.surface_hover.scale_alpha(alpha), false, i18n.close(), ) @@ -3777,7 +3777,7 @@ pub fn render_eq_popover( } // 3 Official Quality Options (`QualitySettings_item`) - let mut y = hdr_r.bottom() + 10.0; + let mut y = hdr_r.bottom() + 18.0; for (idx, (q, title, sub)) in qualities.iter().enumerate() { let rh = row_heights[idx]; let row_r = Rect::from_xywh(pop_r.left() + 10.0, y, pop_w - 20.0, rh); @@ -3789,20 +3789,20 @@ pub fn render_eq_popover( let active = app.config.audio_quality == *q; if resp.hovered { ctx.dl() - .push_rect(row_r, 10.0, pal.surface_hover.with_alpha_f32(alpha)); + .push_rect(row_r, 10.0, pal.surface_hover.scale_alpha(alpha)); ctx.set_cursor(CursorKind::Pointer); } let row_txt_x = row_r.left() + 14.0; let row_txt_w = (row_r.width() - 48.0).max(80.0); ctx.draw_text_ellipsis( title, - TextStyle::bold(14.5, pal.text_bright.with_alpha_f32(alpha)), + TextStyle::bold(14.5, pal.text_bright.scale_alpha(alpha)), Rect::from_xywh(row_txt_x, row_r.top() + 9.0, row_txt_w, 19.0), TextAlign::Left, ); ctx.draw_text_wrapped( sub, - TextStyle::regular(12.0, pal.text_secondary.with_alpha_f32(alpha)), + TextStyle::regular(12.0, pal.text_secondary.scale_alpha(alpha)), Rect::from_xywh(row_txt_x, row_r.top() + 31.0, row_txt_w, rh - 36.0), None, TextAlign::Left, @@ -3814,7 +3814,7 @@ pub fn render_eq_popover( Pos2::new(row_r.right() - 18.0, row_r.center_y()), Vec2::splat(16.0), ), - pal.text_bright.with_alpha_f32(alpha), + pal.text_bright.scale_alpha(alpha), ); } if resp.clicked && !active { @@ -3823,19 +3823,13 @@ pub fn render_eq_popover( y += rh + 4.0; } - // Hairline divider before Equalizer section - y += 6.0; - ctx.dl().push_rect( - Rect::from_xywh(pop_r.left() + 20.0, y, pop_w - 40.0, 1.0), - 0.0, - pal.border_subtle.with_alpha_f32(alpha), - ); - y += 14.0; + // Clean official vertical spacing before Equalizer section (no extra divider line) + y += 20.0; // Inline Official Equalizer (`Equalizer_header` + animated expandable Preamp + 10 bands + Presets) let eq_area = Rect::from_min_max( - Pos2::new(pop_r.left() + 20.0, y), - Pos2::new(pop_r.right() - 20.0, pop_r.bottom() - 16.0), + Pos2::new(pop_r.left() + 24.0, y), + Pos2::new(pop_r.right() - 24.0, pop_r.bottom() - 20.0), ); let dd_anchor = render_equalizer_body( ctx, @@ -3914,10 +3908,9 @@ pub fn render_equalizer_modal( let alpha = anim_t.clamp(0.0, 1.0); let screen = ctx.screen_rect(); let modal_w = (screen.width() - 48.0).clamp(320.0, 430.0); - let modal_h = 376.0; - let slide_dy = (1.0 - alpha) * 14.0; + let modal_h = 370.0; let modal_r = Rect::from_center_size( - Pos2::new(screen.center_x(), screen.center_y() + slide_dy), + Pos2::new(screen.center_x(), screen.center_y()), Vec2::new(modal_w, modal_h), ); @@ -3941,33 +3934,36 @@ pub fn render_equalizer_modal( 32.0, 0.0, Vec2::new(0.0, 8.0), - pal.shadow_modal.with_alpha_f32(alpha), + pal.shadow_modal.scale_alpha(alpha), ); ctx.dl().push_rect_bordered( modal_r, 16.0, - pal.bg_popover.with_alpha_f32(alpha), + pal.bg_popover.scale_alpha(alpha), 1.0, - pal.border_subtle.with_alpha_f32(alpha), + pal.border_subtle.scale_alpha(alpha), ); - let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); + let hdr_r = Rect::from_xywh(modal_r.left() + 24.0, modal_r.top() + 20.0, modal_w - 48.0, 32.0); ctx.draw_text_ellipsis( if ru { "Эквалайзер" } else { "Equalizer" }, - TextStyle::headline(20.0, pal.text_bright.with_alpha_f32(alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), + TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 40.0, hdr_r.height()), TextAlign::Left, ); + let eq_close_r = Rect::from_xywh(hdr_r.right() - 32.0, hdr_r.top(), 32.0, 32.0); + ctx.dl() + .push_circle(eq_close_r.center(), 16.0, pal.surface_hover.scale_alpha(alpha)); if open && icon_button( ctx, WidgetId::new("eq_modal_close"), - Rect::from_xywh(hdr_r.right() - 30.0, hdr_r.top() + 1.0, 30.0, 30.0), + eq_close_r, Icon::Close, - 15.0, - pal.text_secondary, - pal.text_bright, - pal.surface_hover, + 14.0, + pal.text_bright.scale_alpha(alpha), + pal.text_bright.scale_alpha(alpha), + pal.surface_hover.scale_alpha(alpha), false, i18n.close(), ) @@ -4041,10 +4037,10 @@ pub fn render_equalizer_modal( } } -/// Official `EqualizerSlider` (`8711fa44496b8e09.css:340-416`): -/// - Thin `2px` muted vertical track (NO yellow fill from bottom) +/// Official `EqualizerSlider` (`8711fa44496b8e09.css:340-416` + `.d6VuG0HnwpGO47uPjPeb` + `.P8_ABi1YnAOS8p8EY87f`): +/// - Thin `1px` (`0.0625rem`) muted vertical track (NO yellow fill from bottom) /// - Centered `8×1px` `0 dB` serif tick -/// - Always-visible `14px` hollow dark-filled circular thumb with `1.5px` yellow border (`border_control` when disabled) +/// - Always-visible `13px` (`0.8125rem`) hollow dark-filled circular thumb with `1.5px` yellow border (`border_control` when disabled) fn eq_vertical_slider( ctx: &mut UiContext, pal: &YmPalette, @@ -4066,10 +4062,10 @@ fn eq_vertical_slider( let bot = rect.bottom() - 7.0; let track_h = (bot - top).max(20.0); - // Thin 2px muted vertical track - let track_col = pal.border_control.with_alpha_f32(alpha); + // Thin 1.5px muted vertical track (`trackSize_xxs`) + let track_col = pal.border_control.scale_alpha(alpha); ctx.dl() - .push_rect(Rect::from_xywh(cx - 1.0, top, 2.0, track_h), 1.0, track_col); + .push_rect(Rect::from_xywh(cx - 0.75, top, 1.5, track_h), 0.75, track_col); // Centered 8×1px horizontal serif tick at midpoint (`EqualizerSlider_serif`) ctx.dl().push_rect( @@ -4078,19 +4074,25 @@ fn eq_vertical_slider( track_col, ); - // Hollow circular thumb (`14px` diameter, `1.5px` yellow/muted ring) + // Official circular thumb (`14px` diameter, medium-gray interior + crisp `1.5px` yellow ring) let frac = norm_val.clamp(0.0, 1.0); let thumb_y = bot - frac * track_h; let thumb_r = if active { 7.5 } else { 7.0 }; - let border_col = if disabled { - pal.border_control.with_alpha_f32(alpha) + let thumb_fill = if pal.is_dark { + Color::rgb(0x42, 0x42, 0x42) } else { - pal.yellow.with_alpha_f32(alpha) + Color::rgb(0xE0, 0xE0, 0xE0) + } + .scale_alpha(alpha); + let border_col = if disabled { + pal.border_control.scale_alpha(alpha) + } else { + pal.yellow.scale_alpha(alpha) }; ctx.dl().push_rect_bordered( Rect::from_center_size(Pos2::new(cx, thumb_y), Vec2::splat(thumb_r * 2.0)), thumb_r, - pal.bg_popover.with_alpha_f32(alpha), + thumb_fill, 1.5, border_col, ); @@ -4114,7 +4116,7 @@ fn eq_vertical_slider( } /// Shared official Yandex Music 5.129.0 Equalizer UI (module `31051`, `8711fa44496b8e09.css:136-422`): -/// Header + Toggle -> Expandable (Preamp + `+12dB/0dB/-12dB` labels + 10 frequency bands) -> Full-width Pill Preset Selector. +/// Header + Toggle -> Expandable (Preamp + `12dB/0dB/-12dB` labels + 10 frequency bands) -> Full-width Pill Preset Selector. #[allow(clippy::too_many_arguments)] fn render_equalizer_body( ctx: &mut UiContext, @@ -4133,16 +4135,16 @@ fn render_equalizer_body( interactive: bool, salt: &str, ) -> Option<(Rect, bool)> { - // 1. Header row: Title + official Pill Toggle (`44×24`, smoothly animated) - let hdr_r = Rect::from_xywh(area.left(), area.top(), area.width(), 28.0); + // 1. Header row: Title + official Toggle (`32×20px`, `16px` knob, `rqUESGQ8jp3tbDawOzuG`) + let hdr_r = Rect::from_xywh(area.left(), area.top(), area.width(), 24.0); ctx.draw_text_ellipsis( toggle_title, - TextStyle::medium(16.0, pal.text_bright.with_alpha_f32(anim_alpha)), - Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 56.0, hdr_r.height()), + TextStyle::medium(16.0, pal.text_bright.scale_alpha(anim_alpha)), + Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 44.0, hdr_r.height()), TextAlign::Left, ); - let sw_w = 44.0; - let sw_h = 24.0; + let sw_w = 32.0; + let sw_h = 20.0; let sw_r = Rect::from_xywh(hdr_r.right() - sw_w, hdr_r.center_y() - sw_h * 0.5, sw_w, sw_h); let sw_id = WidgetId::new(salt).with("toggle"); let sw_resp = if interactive { @@ -4151,16 +4153,18 @@ fn render_equalizer_body( Default::default() }; let tog_t = ctx.animate_bool(sw_id.with("anim"), *enabled, 0.16); - let track_col = pal.border_control.lerp(pal.yellow, tog_t).with_alpha_f32(anim_alpha); + let track_col = pal.surface_hover.lerp(pal.yellow, tog_t).scale_alpha(anim_alpha); ctx.dl().push_rect(sw_r, sw_h * 0.5, track_col); - let knob_x = sw_r.left() + 12.0 + tog_t * (sw_w - 24.0); + let knob_x = sw_r.left() + 10.0 + tog_t * 12.0; let knob_col = if tog_t > 0.5 { pal.on_yellow - } else { + } else if sw_resp.hovered { pal.text_bright + } else { + pal.text_secondary }; ctx.dl() - .push_circle(Pos2::new(knob_x, sw_r.center_y()), 9.0, knob_col.with_alpha_f32(anim_alpha)); + .push_circle(Pos2::new(knob_x, sw_r.center_y()), 8.0, knob_col.scale_alpha(anim_alpha)); if sw_resp.hovered { ctx.set_cursor(CursorKind::Pointer); } @@ -4177,7 +4181,7 @@ fn render_equalizer_body( } let content_alpha = (anim_alpha * expand_t).clamp(0.0, 1.0); - let clip_h = (242.0 * expand_t).max(0.0); + let clip_h = (246.0 * expand_t).max(0.0); ctx.push_clip( Rect::from_xywh(area.left() - 4.0, hdr_r.bottom(), area.width() + 8.0, clip_h), 0.0, @@ -4190,7 +4194,7 @@ fn render_equalizer_body( } else { pal.text_secondary } - .with_alpha_f32(content_alpha); + .scale_alpha(content_alpha); // 2. Left Preamp column (`Equalizer_preamp`) + amp labels (`12dB / 0dB / -12dB`) let preamp_w = 42.0; @@ -4282,9 +4286,9 @@ fn render_equalizer_body( ); } - // 4. Full-width Pill Preset Selector BELOW sliders (`EqualizerPresets_button`, `radius = h/2`) - let sel_y = y + sliders_h + 8.0 + 16.0 + 16.0; - let sel_h = 42.0; + // 4. Full-width Outlined Pill Preset Selector BELOW sliders (`EqualizerPresets_button`, `radius = h/2`) + let sel_y = y + sliders_h + 8.0 + 16.0 + 18.0; + let sel_h = 44.0; let sel_r = Rect::from_xywh(area.left(), sel_y, area.width(), sel_h); let sel_resp = if !is_disabled && interactive && expand_t > 0.85 { ctx.interact(WidgetId::new(salt).with("preset_sel"), sel_r) @@ -4292,23 +4296,28 @@ fn render_equalizer_body( Default::default() }; let sel_bg = if sel_resp.hovered { - pal.surface_hover + pal.surface_hover.scale_alpha(content_alpha) } else { - pal.surface_secondary - } - .with_alpha_f32(content_alpha); - ctx.dl().push_rect(sel_r, sel_h * 0.5, sel_bg); + Color::TRANSPARENT + }; + let sel_border = if is_disabled { + pal.border_subtle.scale_alpha(content_alpha) + } else { + pal.border_control.scale_alpha(content_alpha) + }; + ctx.dl() + .push_rect_bordered(sel_r, sel_h * 0.5, sel_bg, 1.0, sel_border); let preset_lbl = active_eq_preset_name(bands, ru); let label_col = if is_disabled { pal.text_disabled } else { pal.text_bright } - .with_alpha_f32(content_alpha); + .scale_alpha(content_alpha); ctx.draw_text_ellipsis( preset_lbl, - TextStyle::medium(13.5, label_col), - Rect::from_xywh(sel_r.left() + 18.0, sel_r.top(), sel_r.width() - 48.0, sel_r.height()), + TextStyle::bold(13.5, label_col), + Rect::from_xywh(sel_r.left() + 18.0, sel_r.top(), sel_r.width() - 46.0, sel_r.height()), TextAlign::Left, ); ctx.draw_icon( @@ -4319,7 +4328,7 @@ fn render_equalizer_body( } else { pal.text_bright } - .with_alpha_f32(content_alpha), + .scale_alpha(content_alpha), ); if sel_resp.hovered { ctx.set_cursor(CursorKind::Pointer); @@ -4451,20 +4460,20 @@ pub fn render_shortcuts_modal( 32.0, 0.0, Vec2::new(0.0, 8.0), - pal.shadow_modal.with_alpha_f32(alpha), + pal.shadow_modal.scale_alpha(alpha), ); ctx.dl().push_rect_bordered( modal_r, 16.0, - pal.bg_popover.with_alpha_f32(alpha), + pal.bg_popover.scale_alpha(alpha), 1.0, - pal.border_subtle.with_alpha_f32(alpha), + pal.border_subtle.scale_alpha(alpha), ); let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 18.0, modal_w - 40.0, 32.0); ctx.draw_text_ellipsis( if ru { "Горячие клавиши" } else { "Hot keys" }, - TextStyle::headline(20.0, pal.text_bright.with_alpha_f32(alpha)), + TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); @@ -4794,21 +4803,21 @@ pub fn render_release_notes_modal( 32.0, 0.0, Vec2::new(0.0, 8.0), - pal.shadow_modal.with_alpha_f32(alpha), + pal.shadow_modal.scale_alpha(alpha), ); ctx.dl().push_rect_bordered( modal_r, 16.0, - pal.bg_popover.with_alpha_f32(alpha), + pal.bg_popover.scale_alpha(alpha), 1.0, - pal.border_subtle.with_alpha_f32(alpha), + pal.border_subtle.scale_alpha(alpha), ); // Header (`padding: 16px`, title + circular close ×) let hdr_r = Rect::from_xywh(modal_r.left() + 20.0, modal_r.top() + 14.0, modal_w - 40.0, 34.0); ctx.draw_text_ellipsis( i18n.whats_new(), - TextStyle::headline(20.0, pal.text_bright.with_alpha_f32(alpha)), + TextStyle::headline(20.0, pal.text_bright.scale_alpha(alpha)), Rect::from_xywh(hdr_r.left(), hdr_r.top(), hdr_r.width() - 36.0, hdr_r.height()), TextAlign::Left, ); diff --git a/src/views/player_bar.rs b/src/views/player_bar.rs index 33f65ed..c83afc7 100644 --- a/src/views/player_bar.rs +++ b/src/views/player_bar.rs @@ -1,5 +1,6 @@ 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::{ @@ -8,6 +9,7 @@ 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 @@ -86,11 +88,13 @@ pub fn render_player_bar( ctx.dl().push_rect(rect, 12.0, base_bg); - // 2. Top-edge 4px yellow progress bar + 12px thumb + hover timecode pills - let bar_hover_zone = rect.expand2(Vec2::new(0.0, 6.0)); + // 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 })); let bar_hovered = ctx.is_hovered(bar_hover_zone); let scrub_zone = Rect::from_min_max( - Pos2::new(rect.left() + 8.0, rect.top() - 6.0), + Pos2::new(rect.left() + 8.0, rect.top() - if is_custom_thumb { 22.0 } else { 6.0 }), Pos2::new(rect.right() - 8.0, rect.top() + 12.0), ); let scrub_resp = ctx.interact(WidgetId::new("pb_top_scrub"), scrub_zone); @@ -136,65 +140,84 @@ 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); - if hover_t > 0.01 { + if is_custom_thumb || hover_t > 0.01 { let display_frac = display_progress; ctx.with_layer(ZLayer::Popover, |ctx| { let bar_y = rect.top() + 2.0; - 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)); + 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 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); + } - // 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); + 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 }; - 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 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 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, - ); + 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, + ); - // 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, - ); + // 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, + ); + } } } }); @@ -501,9 +524,7 @@ 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 { - pal.accent_coral - } else if like_resp.hovered { + if is_liked || like_resp.hovered { fg_bright } else { fg_muted diff --git a/src/views/player_thumbs.rs b/src/views/player_thumbs.rs new file mode 100644 index 0000000..ac8aa37 --- /dev/null +++ b/src/views/player_thumbs.rs @@ -0,0 +1,385 @@ +use crate::config::PlayerThumbStyle; +use crate::engine::theme::YmPalette; +use crate::engine::types::{Color, Pos2, Rect, Vec2}; +use crate::engine::{css_rgba, UiContext}; +use crate::icons::Icon; + +/// Draws the progress trail + live animated companion on the top edge of `PlayerBar`. +/// Called only when `style != PlayerThumbStyle::Standard`. +#[allow(clippy::too_many_arguments)] +pub fn render_player_bar_companion( + ctx: &mut UiContext, + pal: &YmPalette, + style: PlayerThumbStyle, + bar_left: f32, + bar_right: f32, + bar_y: f32, + progress: f32, + playing: bool, + time: f32, +) { + let frac = progress.clamp(0.0, 1.0); + let track_w = (bar_right - bar_left).max(1.0); + let fill_x = bar_left + track_w * frac; + let anim_t = if playing { time } else { 0.0 }; + + // Subtle base track along top edge + let track_r = Rect::from_xywh(bar_left, bar_y - 1.5, track_w, 3.0); + ctx.dl().push_rect(track_r, 1.5, css_rgba(255, 255, 255, 34)); + + // Themed progress trail behind the companion + let fill_w = (fill_x - bar_left).max(0.0); + if fill_w > 1.0 { + match style { + PlayerThumbStyle::Standard => {} + PlayerThumbStyle::Duck => { + ctx.dl() + .push_rect(Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), 1.5, pal.yellow); + } + PlayerThumbStyle::Car => { + ctx.dl().push_rect( + Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), + 1.5, + Color::rgb(0xE8, 0x22, 0x38), + ); + // Tiny drifting exhaust puffs while driving + if playing && fill_w > 48.0 { + for k in 0..3 { + let phase = ((anim_t * 2.4 + k as f32 * 0.33) % 1.0).clamp(0.0, 1.0); + let px = fill_x - 30.0 - phase * 24.0; + let py = bar_y - 5.0 - phase * 6.0; + let a = ((1.0 - phase) * 90.0).round() as u8; + if px > bar_left { + ctx.dl() + .push_circle(Pos2::new(px, py), 2.0 + phase * 2.5, css_rgba(220, 224, 232, a)); + } + } + } + } + PlayerThumbStyle::Claudik => { + ctx.dl().push_rect( + Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), + 1.5, + Color::rgb(0xD9, 0x77, 0x57), + ); + } + PlayerThumbStyle::Antigravity => { + ctx.dl().push_gradient_rect( + Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), + 1.5, + Color::rgb(0x9B, 0x84, 0xEC), + Color::rgb(0x52, 0xB6, 0xFF), + Vec2::new(1.0, 0.0), + ); + // Twinkling cosmic star dust trailing behind Antigravity + let count = ((fill_w / 22.0) as usize).min(6); + for k in 0..count { + let phase = ((anim_t * 1.6 + k as f32 * 0.27) % 1.0).clamp(0.0, 1.0); + let sx = fill_x - 16.0 - k as f32 * 18.0 - phase * 10.0; + let sy = bar_y - 6.0 - ((k as f32 * 1.9 + anim_t * 3.0).sin() * 4.5).abs(); + let twinkle = 0.35 + 0.65 * ((anim_t * 5.0 + k as f32 * 1.7).sin() * 0.5 + 0.5); + if sx > bar_left + 4.0 { + let col = if k % 2 == 0 { + Color::rgb(0x9B, 0x84, 0xEC).scale_alpha(twinkle * 0.85) + } else { + Color::rgb(0x6C, 0xD4, 0xFF).scale_alpha(twinkle * 0.85) + }; + ctx.dl().push_rect(Rect::from_xywh(sx.round(), sy.round(), 2.0, 2.0), 0.0, col); + } + } + } + PlayerThumbStyle::Ferris => { + ctx.dl().push_rect( + Rect::from_xywh(bar_left, bar_y - 1.5, fill_w, 3.0), + 1.5, + Color::rgb(0xF7, 0x4C, 0x00), + ); + } + PlayerThumbStyle::Nyan => { + // Classic 6-stripe waving pixel rainbow trail! + let stripes = [ + Color::rgb(0xFF, 0x26, 0x26), + Color::rgb(0xFF, 0x99, 0x00), + Color::rgb(0xFF, 0xEE, 0x00), + Color::rgb(0x33, 0xDD, 0x33), + Color::rgb(0x1E, 0x9E, 0xFF), + Color::rgb(0x7A, 0x44, 0xFF), + ]; + let seg_w = 10.0f32; + let max_trail = (fill_w - 6.0).max(0.0); + let num_segs = (max_trail / seg_w).ceil() as usize; + let wave_step = (anim_t * 8.0).floor() as i32; + for s in 0..num_segs { + let sx = bar_left + s as f32 * seg_w; + let sw = (fill_x - 6.0 - sx).min(seg_w); + if sw <= 0.5 { + break; + } + let dy = if ((s as i32 + wave_step) & 1) == 0 { -1.0 } else { 1.0 }; + for (ci, &col) in stripes.iter().enumerate() { + let sy = bar_y - 11.0 + ci as f32 * 2.0 + dy; + ctx.dl() + .push_rect(Rect::from_xywh(sx, sy, sw + 0.5, 2.0), 0.0, col); + } + } + } + } + } + + // Draw the companion anchored cleanly at `(fill_x, bar_y)` + match style { + PlayerThumbStyle::Standard => {} + PlayerThumbStyle::Duck => { + let bob = if playing { (anim_t * 9.0).sin().abs() * -2.0 } else { 0.0 }; + let sz = 32.0; + let r = Rect::from_xywh(fill_x - sz * 0.5, bar_y - sz + 3.0 + bob, sz, sz); + ctx.draw_icon(Icon::ThumbDuck, r, Color::WHITE); + } + PlayerThumbStyle::Car => { + let vib = if playing { (anim_t * 28.0).sin() * 0.6 } else { 0.0 }; + let w = 68.0; + let h = 21.0; + let r = Rect::from_xywh(fill_x - w * 0.52, bar_y - h + 2.0 + vib, w, h); + // Warm headlight beam ahead of the car when playing + if playing && r.right() < bar_right { + let beam_w = (bar_right - r.right()).min(26.0); + ctx.dl().push_gradient_rect( + Rect::from_xywh(r.right() - 2.0, bar_y - 10.0 + vib, beam_w, 8.0), + 2.0, + css_rgba(255, 240, 160, 95), + css_rgba(255, 240, 160, 0), + Vec2::new(1.0, 0.0), + ); + } + ctx.draw_icon(Icon::ThumbCar, r, Color::WHITE); + } + PlayerThumbStyle::Claudik => { + let step = if playing { ((anim_t * 7.0).floor() as u32) & 1 } else { 0 }; + let bob = if playing && step == 1 { -1.5 } else { 0.0 }; + draw_claudik_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.5, step == 1); + } + PlayerThumbStyle::Antigravity => { + let hover = if playing { (anim_t * 4.5).sin() * 2.2 - 3.5 } else { -2.5 }; + draw_antigravity_sprite(ctx, Pos2::new(fill_x, bar_y + hover), 2.5, anim_t, true); + } + PlayerThumbStyle::Ferris => { + let step = if playing { ((anim_t * 8.0).floor() as u32) & 1 } else { 0 }; + let bob = if playing && step == 1 { -1.0 } else { 0.0 }; + draw_ferris_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.2, step == 1); + } + PlayerThumbStyle::Nyan => { + let step = if playing { ((anim_t * 9.0).floor() as u32) & 1 } else { 0 }; + let bob = if playing && step == 1 { -1.5 } else { 0.0 }; + draw_nyan_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.0, step == 1); + } + } +} + +/// Draws the centered preview inside Settings -> «Вид плеера» card (`preview_r`). +pub fn render_thumb_preview( + ctx: &mut UiContext, + pal: &YmPalette, + style: PlayerThumbStyle, + preview_r: Rect, + time: f32, +) { + let cx = preview_r.center_x(); + let cy = preview_r.center_y(); + match style { + PlayerThumbStyle::Standard => { + let bar_w = 60.0; + ctx.dl().push_rect( + Rect::from_center_size(Pos2::new(cx, cy), Vec2::new(bar_w, 5.0)), + 2.5, + pal.border_control, + ); + ctx.dl().push_rect( + Rect::from_xywh(cx - bar_w * 0.5, cy - 2.5, bar_w * 0.52, 5.0), + 2.5, + pal.yellow, + ); + ctx.dl().push_circle(Pos2::new(cx, cy), 10.0, pal.yellow); + } + PlayerThumbStyle::Duck => { + ctx.draw_icon( + Icon::ThumbDuck, + Rect::from_center_size(Pos2::new(cx, cy + 2.0), Vec2::splat(48.0)), + Color::WHITE, + ); + } + PlayerThumbStyle::Car => { + ctx.draw_icon( + Icon::ThumbCar, + Rect::from_center_size(Pos2::new(cx, cy + 4.0), Vec2::new(82.0, 26.0)), + Color::WHITE, + ); + } + PlayerThumbStyle::Claudik => { + draw_claudik_sprite(ctx, Pos2::new(cx, cy + 16.0), 3.6, false); + } + PlayerThumbStyle::Antigravity => { + draw_antigravity_sprite(ctx, Pos2::new(cx - 2.0, cy + 16.0), 3.5, time, true); + } + PlayerThumbStyle::Ferris => { + draw_ferris_sprite(ctx, Pos2::new(cx, cy + 15.0), 3.2, false); + } + PlayerThumbStyle::Nyan => { + // Mini rainbow preview behind Nyan Cat + let stripes = [ + Color::rgb(0xFF, 0x26, 0x26), + Color::rgb(0xFF, 0x99, 0x00), + Color::rgb(0xFF, 0xEE, 0x00), + Color::rgb(0x33, 0xDD, 0x33), + Color::rgb(0x1E, 0x9E, 0xFF), + Color::rgb(0x7A, 0x44, 0xFF), + ]; + for (ci, &col) in stripes.iter().enumerate() { + ctx.dl().push_rect( + Rect::from_xywh(cx - 40.0, cy - 8.0 + ci as f32 * 2.5, 24.0, 2.5), + 0.0, + col, + ); + } + draw_nyan_sprite(ctx, Pos2::new(cx + 8.0, cy + 12.0), 2.7, false); + } + } +} + +/// Crisp pixel helper anchored at bottom-center `origin`, unit size `p` logical px. +#[inline] +fn px_rect(ctx: &mut UiContext, origin: Pos2, p: f32, gx: f32, gy: f32, gw: f32, gh: f32, col: Color) { + ctx.dl().push_rect( + Rect::from_xywh( + (origin.x + gx * p).round(), + (origin.y - gy * p).round(), + (gw * p).round().max(1.0), + (gh * p).round().max(1.0), + ), + 0.0, + col, + ); +} + +/// Pixel-art Claudik (Claude Code terracotta buddy `#D97757`, matching user's reference!). +fn draw_claudik_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, alt_step: bool) { + let body = Color::rgb(0xD9, 0x77, 0x57); + let eye = Color::rgb(0x1B, 0x1D, 0x24); + // Main blocky head/body (10×6 pixels) + px_rect(ctx, origin, p, -5.0, 8.0, 10.0, 6.0, body); + // Little side pixel arms + let arm_y = if alt_step { 4.5 } else { 4.0 }; + px_rect(ctx, origin, p, -6.5, arm_y, 1.5, 1.5, body); + px_rect(ctx, origin, p, 5.0, arm_y, 1.5, 1.5, body); + // Vertical dark eyes + px_rect(ctx, origin, p, -3.0, 6.5, 1.0, 2.0, eye); + px_rect(ctx, origin, p, 2.0, 6.5, 1.0, 2.0, eye); + // 4 cute little legs with walk alternation + let (l1, l2) = if alt_step { (1.4, 2.0) } else { (2.0, 1.4) }; + px_rect(ctx, origin, p, -4.0, 2.0, 1.0, l1, body); + px_rect(ctx, origin, p, -2.0, 2.0, 1.0, l2, body); + px_rect(ctx, origin, p, 1.0, 2.0, 1.0, l1, body); + px_rect(ctx, origin, p, 3.0, 2.0, 1.0, l2, body); +} + +/// Pixel-art Antigravity cosmic violet cat-bot (`#9B84EC`) + tiny succulent pot & floating aura! +fn draw_antigravity_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, time: f32, with_plant: bool) { + let body = Color::rgb(0x9B, 0x84, 0xEC); + let hi = Color::rgb(0xC2, 0xB3, 0xFF); + let eye = Color::rgb(0x17, 0x18, 0x22); + // Soft cyan-violet anti-gravity glow underneath + let pulse = 0.55 + 0.35 * (time * 4.5).sin(); + ctx.dl().push_rect( + Rect::from_xywh((origin.x - 4.0 * p).round(), (origin.y + 0.5 * p).round(), (8.0 * p).round(), (1.0 * p).round().max(2.0)), + 2.0, + Color::rgb(0x52, 0xB6, 0xFF).scale_alpha(pulse * 0.65), + ); + // Pointed cat ears + px_rect(ctx, origin, p, -5.0, 9.5, 1.5, 2.0, body); + px_rect(ctx, origin, p, -3.5, 8.5, 1.0, 1.0, body); + px_rect(ctx, origin, p, 3.5, 9.5, 1.5, 2.0, body); + px_rect(ctx, origin, p, 2.5, 8.5, 1.0, 1.0, body); + // Main body + px_rect(ctx, origin, p, -5.0, 7.5, 10.0, 5.5, body); + // Subtle top sheen + px_rect(ctx, origin, p, -2.5, 7.5, 5.0, 0.8, hi); + // Dark pixel eyes with tiny sparkle + px_rect(ctx, origin, p, -3.0, 6.0, 1.2, 2.0, eye); + px_rect(ctx, origin, p, 1.8, 6.0, 1.2, 2.0, eye); + // 4 floating legs + px_rect(ctx, origin, p, -4.0, 2.0, 1.0, 1.8, body); + px_rect(ctx, origin, p, -2.0, 2.0, 1.0, 1.8, body); + px_rect(ctx, origin, p, 1.0, 2.0, 1.0, 1.8, body); + px_rect(ctx, origin, p, 3.0, 2.0, 1.0, 1.8, body); + // Cute tiny potted cactus/succulent friend on the right (matching Screenshot 3!) + if with_plant { + px_rect(ctx, origin, p, 5.2, 1.8, 3.2, 1.2, Color::rgb(0x8D, 0x55, 0x2B)); + px_rect(ctx, origin, p, 5.7, 0.8, 2.2, 0.8, Color::rgb(0x6E, 0x40, 0x1E)); + px_rect(ctx, origin, p, 6.2, 4.4, 1.2, 2.6, Color::rgb(0x6D, 0xE8, 0x7A)); + px_rect(ctx, origin, p, 7.6, 3.2, 0.9, 1.4, Color::rgb(0x52, 0xC9, 0x60)); + } +} + +/// Pixel-art Ferris the Rust Crab (`#F74C00`) scuttling along the progress bar! +fn draw_ferris_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, alt_step: bool) { + let shell = Color::rgb(0xF7, 0x4C, 0x00); + let dark = Color::rgb(0xC2, 0x35, 0x00); + let white = Color::WHITE; + let pupil = Color::rgb(0x16, 0x16, 0x1A); + // Raised crab claws + let claw_dy = if alt_step { 0.7 } else { 0.0 }; + px_rect(ctx, origin, p, -7.2, 7.5 + claw_dy, 2.2, 2.4, shell); + px_rect(ctx, origin, p, 5.0, 7.5 + claw_dy, 2.2, 2.4, shell); + px_rect(ctx, origin, p, -6.5, 5.2, 1.8, 1.4, dark); + px_rect(ctx, origin, p, 4.7, 5.2, 1.8, 1.4, dark); + // Spiky rounded crab carapace + px_rect(ctx, origin, p, -5.0, 7.2, 10.0, 5.0, shell); + px_rect(ctx, origin, p, -3.5, 8.2, 7.0, 1.2, shell); + // Googly eyes + px_rect(ctx, origin, p, -3.0, 6.0, 2.0, 2.0, white); + px_rect(ctx, origin, p, 1.0, 6.0, 2.0, 2.0, white); + px_rect(ctx, origin, p, -2.0, 5.5, 1.0, 1.2, pupil); + px_rect(ctx, origin, p, 2.0, 5.5, 1.0, 1.2, pupil); + // Cute smile + px_rect(ctx, origin, p, -1.0, 3.4, 2.0, 0.8, dark); + // Scuttling legs + let off = if alt_step { 0.5 } else { 0.0 }; + px_rect(ctx, origin, p, -4.5 + off, 2.2, 1.2, 2.0, dark); + px_rect(ctx, origin, p, -2.0 - off, 2.2, 1.2, 2.0, dark); + px_rect(ctx, origin, p, 0.8 + off, 2.2, 1.2, 2.0, dark); + px_rect(ctx, origin, p, 3.3 - off, 2.2, 1.2, 2.0, dark); +} + +/// Pixel-art Nyan Cat zooming along the rainbow progress bar! +fn draw_nyan_sprite(ctx: &mut UiContext, origin: Pos2, p: f32, alt_step: bool) { + let crust = Color::rgb(0xF6, 0xCC, 0x8F); + let icing = Color::rgb(0xFF, 0x99, 0xD6); + let sprinkle = Color::rgb(0xFF, 0x33, 0x88); + let cat = Color::rgb(0x9A, 0x9E, 0xA8); + let dark = Color::rgb(0x1C, 0x1E, 0x24); + let blush = Color::rgb(0xFF, 0x85, 0xA1); + // Tail wagging on left + let ty = if alt_step { 6.2 } else { 4.8 }; + px_rect(ctx, origin, p, -8.0, ty, 2.5, 1.4, cat); + // Pop-tart body + px_rect(ctx, origin, p, -5.8, 8.6, 8.8, 6.8, crust); + px_rect(ctx, origin, p, -4.8, 7.6, 6.8, 4.8, icing); + // Sprinkles + px_rect(ctx, origin, p, -3.8, 6.6, 1.0, 1.0, sprinkle); + px_rect(ctx, origin, p, -1.5, 5.4, 1.0, 1.0, sprinkle); + px_rect(ctx, origin, p, 0.2, 6.8, 1.0, 1.0, sprinkle); + // Cat head on right + px_rect(ctx, origin, p, 1.2, 7.8, 5.4, 4.8, cat); + px_rect(ctx, origin, p, 1.5, 9.2, 1.5, 1.5, cat); + px_rect(ctx, origin, p, 4.8, 9.2, 1.5, 1.5, cat); + // Eyes & blush + px_rect(ctx, origin, p, 2.4, 6.4, 1.0, 1.2, dark); + px_rect(ctx, origin, p, 4.8, 6.4, 1.0, 1.2, dark); + px_rect(ctx, origin, p, 1.8, 5.0, 1.0, 0.9, blush); + px_rect(ctx, origin, p, 5.4, 5.0, 1.0, 0.9, blush); + // Tiny running paws + let paw_dx = if alt_step { 0.8 } else { 0.0 }; + px_rect(ctx, origin, p, -4.8 + paw_dx, 2.0, 1.5, 1.8, cat); + px_rect(ctx, origin, p, -1.8 + paw_dx, 2.0, 1.5, 1.8, cat); + px_rect(ctx, origin, p, 1.6 + paw_dx, 2.0, 1.5, 1.8, cat); + px_rect(ctx, origin, p, 4.0 + paw_dx, 2.0, 1.5, 1.8, cat); +} diff --git a/src/views/settings.rs b/src/views/settings.rs index 66b4b09..27851ed 100644 --- a/src/views/settings.rs +++ b/src/views/settings.rs @@ -1,6 +1,6 @@ use crate::app::i18n::APP_VERSION; use crate::app::state::{AppAction, AppState}; -use crate::config::{AudioQuality, Language, ThemeMode}; +use crate::config::{AudioQuality, Language, PlayerThumbStyle, ThemeMode}; use crate::covers::CoverCache; use crate::engine::input::WidgetId; use crate::engine::text::{TextAlign, TextStyle}; @@ -13,6 +13,7 @@ use crate::engine::widgets::{ use crate::engine::UiContext; use crate::icons::Icon; use crate::views::overlays::ShellUiState; +use crate::views::player_thumbs::render_thumb_preview; /// 1-to-1 Official Yandex Music Desktop 5.129.0 `SettingsPage` (`Settings_root__FVVrn`, `379bcce309ec9c74.css`): /// Clean borderless list of `SettingsListButtonItem` (title + description + `arrowRight` chevron) @@ -175,7 +176,58 @@ pub fn render_settings( y += 18.0; // ------------------------------------------------------------------------- - // 2. Official Settings List (`Settings_root`, 32px vertical spacing) + // 2. Official «Вид плеера» (`branded-player.player-type`) + Fun Companions + // ------------------------------------------------------------------------- + ctx.draw_text_ellipsis( + if ru { "Вид плеера" } else { "Player view" }, + TextStyle::bold(18.0, pal.text_bright), + Rect::from_xywh(x, y, col_w, 24.0), + TextAlign::Left, + ); + y += 34.0; + + let gap = 12.0; + let cols = 4usize; + let card_sz = ((col_w - gap * (cols as f32 - 1.0)) / cols as f32).floor().clamp(88.0, 114.0); + let anim_time = ctx.input.time as f32; + for (idx, &style) in PlayerThumbStyle::ALL.iter().enumerate() { + let col = idx % cols; + let row = idx / cols; + let cx = x + col as f32 * (card_sz + gap); + let cy = y + row as f32 * (card_sz + gap); + let card_r = Rect::from_xywh(cx, cy, card_sz, card_sz); + let resp = ctx.interact(WidgetId::from_pair("set_thumb_card", idx), card_r); + let selected = app.config.player_thumb == style; + let bg = if resp.hovered { + pal.surface_hover + } else { + pal.surface_secondary + }; + if selected { + ctx.dl().push_rect_bordered(card_r, 16.0, bg, 1.5, pal.yellow); + } else { + ctx.dl().push_rect(card_r, 16.0, bg); + } + let preview_r = Rect::from_xywh(card_r.left() + 8.0, card_r.top() + 10.0, card_sz - 16.0, card_sz - 38.0); + render_thumb_preview(ctx, pal, style, preview_r, anim_time); + ctx.draw_text_ellipsis( + style.label(ru), + TextStyle::medium(12.5, if selected { pal.text_bright } else { pal.text_secondary }), + Rect::from_xywh(card_r.left() + 6.0, card_r.bottom() - 26.0, card_sz - 12.0, 18.0), + TextAlign::Center, + ); + if resp.hovered { + ctx.set_cursor(CursorKind::Pointer); + } + if resp.clicked && !selected { + actions.push(AppAction::SetPlayerThumb(style)); + } + } + let thumb_rows = (PlayerThumbStyle::ALL.len() + cols - 1) / cols; + y += thumb_rows as f32 * (card_sz + gap) + 18.0; + + // ------------------------------------------------------------------------- + // 3. Official Settings List (`Settings_root`, 32px vertical spacing) // ------------------------------------------------------------------------- // 2a. Clear memory (`offline.clear-memory`) @@ -712,25 +764,27 @@ fn settings_toggle_item( ); } - let sw_w = 44.0; - let sw_h = 24.0; + let sw_w = 32.0; + let sw_h = 20.0; let sw_r = Rect::from_xywh( x + w - sw_w, *y + (row_h - sw_h) * 0.5, sw_w, sw_h, ); - let track_col = pal.border_control.lerp(pal.yellow, anim); + let track_col = pal.surface_hover.lerp(pal.yellow, anim); ctx.dl().push_rect(sw_r, sw_h * 0.5, track_col); - let knob_x = sw_r.left() + 12.0 + anim * (sw_w - 24.0); + let knob_x = sw_r.left() + 10.0 + anim * 12.0; let knob_col = if anim > 0.5 { pal.on_yellow - } else { + } else if resp.hovered { pal.text_bright + } else { + pal.text_secondary }; ctx.dl() - .push_circle(Pos2::new(knob_x, sw_r.center_y()), 9.0, knob_col); + .push_circle(Pos2::new(knob_x, sw_r.center_y()), 8.0, knob_col); if resp.hovered { ctx.set_cursor(CursorKind::Pointer); diff --git a/src/views/sidebar.rs b/src/views/sidebar.rs index 4eceeea..b8f38d9 100644 --- a/src/views/sidebar.rs +++ b/src/views/sidebar.rs @@ -381,7 +381,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 { 30.0 } else { 8.0 }; + let right_reserve = if show_more { 38.0 } else { 10.0 }; let max_tw = (item_r.right() - text_x - right_reserve).max(40.0); let title_col = if is_active { @@ -402,16 +402,16 @@ pub fn render_sidebar( TextAlign::Left, ); - // `•••` menu button on hover or when menu open (available on ALL pinned items, including Liked!) + // `•••` menu button on hover or when menu open (12px breathing room from right edge!) let more_r = Rect::from_center_size( - Pos2::new(item_r.right() - 14.0, item_r.center_y()), - Vec2::splat(24.0), + Pos2::new(item_r.right() - 20.0, item_r.center_y()), + Vec2::splat(26.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(20.0)), + Rect::from_center_size(more_r.center(), Vec2::splat(18.0)), if more_resp.hovered || menu_open_for_this { pal.text_primary } else { diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index aee1250..209b4eb 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -2584,5 +2584,12 @@ fn test_ext_19_official_settings_sound_quality_equalizer_and_shortcuts_modals() 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); + } } } From 6a20172ee4902015bc8cc12dcbec907de4b23704 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 23:32:38 +0300 Subject: [PATCH 15/17] chore(release): v0.1.8 --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c6680dc..243ebf0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6550,7 +6550,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.7" +version = "0.1.8" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 4ab709c..86980c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.7" +version = "0.1.8" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" diff --git a/README.md b/README.md index 206a239..afe93e1 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.7-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.7-1_amd64.deb` и установите: +- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.8-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). +- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.8-1_amd64.deb` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.7-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.8-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.7-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.8-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности From 8d25d641a468ee7904527159eaebb33cd1a00469 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 23:41:27 +0300 Subject: [PATCH 16/17] fix: hide bottom player bar companion when fullscreen player is open --- src/views/player_bar.rs | 3 ++- tests/parity_extended.rs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/views/player_bar.rs b/src/views/player_bar.rs index c83afc7..33f4a10 100644 --- a/src/views/player_bar.rs +++ b/src/views/player_bar.rs @@ -140,7 +140,8 @@ 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); - if is_custom_thumb || hover_t > 0.01 { + // 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) { let display_frac = display_progress; ctx.with_layer(ZLayer::Popover, |ctx| { diff --git a/tests/parity_extended.rs b/tests/parity_extended.rs index 209b4eb..b8ae92f 100644 --- a/tests/parity_extended.rs +++ b/tests/parity_extended.rs @@ -2591,5 +2591,17 @@ fn test_ext_19_official_settings_sound_quality_equalizer_and_shortcuts_modals() 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!" + ); } } From a6f33284a7edf5332a7f7674c10e1ba268f276a5 Mon Sep 17 00:00:00 2001 From: marwy Date: Fri, 27 Nov 2026 23:41:27 +0300 Subject: [PATCH 17/17] chore(release): v0.1.9 --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 243ebf0..80fc82e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6550,7 +6550,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yandex-music-rs" -version = "0.1.8" +version = "0.1.9" dependencies = [ "aes", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 86980c5..00e7a8d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "yandex-music-rs" -version = "0.1.8" +version = "0.1.9" edition = "2021" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" diff --git a/README.md b/README.md index afe93e1..d66c72c 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,12 @@ Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): -- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.8-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). -- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.8-1_amd64.deb` и установите: +- **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` и установите: ```bash - sudo apt install ./yandex-music-rs_0.1.8-1_amd64.deb + sudo apt install ./yandex-music-rs_0.1.9-1_amd64.deb ``` -- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.8-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). +- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.9-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). ## Стек и возможности