chore(release): v2.0.0

This commit is contained in:
marwy 2026-11-29 02:28:03 +03:00
parent a6f33284a7
commit 7fbf34ff2e
81 changed files with 16727 additions and 3280 deletions

1
.gitignore vendored
View file

@ -1,5 +1,6 @@
# Rust build artifacts # Rust build artifacts
/target/ /target/
packaging/windows/installer/target/
**/*.rs.bk **/*.rs.bk
*.pdb *.pdb

View file

@ -1,4 +1,59 @@
# Инструкция для AI-агентов (Git, коммиты и релизы на git.tatar) # Инструкция для AI-агентов (`yandex-music-rs`)
## 0. ЖЕЛЕЗНОЕ ПРАВИЛО: 1-в-1 с оригиналом Яндекс Музыки (НЕ выдумывать и НЕ врать!)
Этот проект — нативный Rust-клон **Yandex Music Desktop 5.129.0**. Любая фича, экран, модалка, кнопка, иконка, анимация, цвет или текст должны повторять оригинал **1-в-1**.
> **ЖЕЛЕЗНЫЕ ПРАВИЛА (нарушать ЗАПРЕЩЕНО):**
> 1. **НИКОГДА не делай «по памяти», «на глаз» или «как кажется красивее».** Перед написанием кода обязательно найди компонент в локальной распаковке оригинала `original_yandex_music/` и вытащи оттуда точные:
> - **тексты RU и EN** (из i18n-файлов, а не перевод из головы);
> - **структуру и порядок элементов** (из JS/JSX чанков);
> - **размеры, отступы, радиусы, цвета, `:hover` / `:disabled`, `@keyframes` и `transition`** (из CSS и `--ym-*` переменных);
> - **иконки / SVG / ассеты** (из оригинала, а не нарисованные с нуля, если они есть в бандле).
> 2. **ЧЕСТНЫЙ СТОП вместо фантазии и обмана:** если ты **не нашёл** реализацию в `original_yandex_music/`, **не понимаешь**, как оно работает в оригинале, или **не можешь** повторить 1-в-1 в нашем движке — **НЕ выдумывай свой вариант и НЕ выдавай его за оригинал**. Остановись и прямо скажи пользователю:
> - что именно не удалось найти или повторить;
> - где именно ты искал (пути/ключи);
> - что нужно от пользователя (скриншот, запись анимации или разрешение сделать упрощённо / по-своему).
> 3. **Отходить от оригинала можно ТОЛЬКО по прямому запросу пользователя** (например, кастомные скины прогресс-бара, специфика Linux-трея и т.п.).
> 4. **Подтверждай источником:** после реализации UI-фичи кратко указывай в ответе, из каких файлов/модулей/классов оригинала взяты стили, тексты и анимации (например, `8711fa44496b8e09.css`, модуль `31051`, `937.*.js`).
### Как быстро находить фичи в `original_yandex_music/` (проверенный алгоритм)
Папка `original_yandex_music/` лежит локально в корне репозитория (в `.gitignore`, **не коммитить!**).
1. **Начинай с видимого текста в i18n** — это самый быстрый вход к любому компоненту:
- RU: `original_yandex_music/beautified/js/937.a82b2fe17c4175bd.js`
- EN: `original_yandex_music/beautified/js/6983.7c6e04919dabf642.js`
- Найди русскую фразу → получи i18n-ключ (например, `"equalizer.preamp-level"`, `"player-actions.audio-quality-maximum"`, `"branded-player.duck"`).
- Прогрепай этот ключ по `original_yandex_music/raw/app/_next/static/chunks/**/*.js` → попадёшь прямо в нужный React-компонент.
2. **Важно: в `beautified/js/` лежат НЕ все чанки!**
- Если модуль `i(NNNNN)` не найден в `original_yandex_music/beautified/js/`, **всегда** ищи `NNNNN:` в `original_yandex_music/raw/app/_next/static/chunks/**/*.js` (через `python` или `rg`).
3. **Базовые компоненты UI-кита (`Button`, `Toggle`, `Slider`, `Modal`, `Tab`) используют обфусцированные CSS-классы**:
- Не останавливайся, если поиск по `.Toggle_` или `.Modal_root` ничего не дал.
- Открой импортированный модуль в `raw/.../chunks/*.js`, найди его карту классов вида `{root:"ifxS_8bgSnwBoCsyow0E", ...}`, и грепай именно этот хеш по `original_yandex_music/raw/app/_next/static/css/*.css`.
4. **Карта ключевых файлов оригинала**:
- **Все CSS-токены темы** (`--ym-spacer-size-*`, `--ym-radius-size-*`, `--ym-font-size-*`, цвета dark/light): `original_yandex_music/beautified/css/1d39aa9337a03444.css` (`1rem = 16px`).
- **Настройки звука + Эквалайзер**: `beautified/css/8711fa44496b8e09.css`, `beautified/js/3684-e589c857a6a465c0.js`, модуль `31051` в `raw/app/_next/static/chunks/7371-*.js`.
- **Настройки и Горячие клавиши**: `beautified/js/app/(product)/(app)/settings/page-*.js`, `beautified/css/29c95960ed6ac633.css`.
- **Модалки и их анимации** (`useTransitionStyles`, `placement="right"` = `translateX(5%) -> 0`): модуль `11372` в `raw/app/_next/static/chunks/1372-*.js`.
- **Базовые контролы**: `Toggle` — модуль `16161` (`chunks/6305-*.js`), `Slider` — модуль `54112` (`chunks/7371-*.js`), `Tab` — модули `87366` / `98225` (`chunks/4322-*.js`).
- **«Что нового?» (`ReleaseNotesModal`)**: `beautified/css/28bcd8bd8493d95a.css`.
- **Lottie и медиа-ассеты** (уточка, машинка и др.): `original_yandex_music/raw/app/_next/static/lottie/` и `.../media/`.
### Грабли нашего движка (`src/engine/`, `src/views/`), которые нельзя повторять
- **Полупрозрачные цвета (`scale_alpha`, НЕ `with_alpha_f32`!):** у `pal.border_subtle`, `pal.surface_secondary`, `pal.surface_hover`, `pal.text_secondary`, `pal.border_control`, `pal.shadow_*` уже есть альфа `< 255`. Для анимации затухания **всегда** вызывай `.scale_alpha(alpha)` — `.with_alpha_f32(alpha)` перезапишет альфу в `255` и превратит обводки/кнопки в сплошной белый `#FFFFFF`.
- **Поповеры и модалки (особенно на Linux):**
- Закрытие по клику снаружи делай только через `ctx.input.consume_clicked_outside(...)` / `consume_clicked_outside_any(...)`, чтобы mouse-up на кнопке-триггере не переоткрывал оверлей.
- `animate_bool` для оверлеев вызывай **каждый кадр** в `src/views/mod.rs` (иначе `or_insert(target)` на первом кадре сразу даст `1.0` без анимации). Пока `open == false` (анимация закрытия), **не** вызывай `register_blocker` и `consume_clicked_outside`.
- В `src/views/mod.rs` после `dispatch(actions)` стоит `self.ui.request_repaint()`, чтобы в простое (0 FPS) клик сразу запускал следующий кадр.
- **Слои `ZLayer` (`Base < Drawer < Popover < Modal < Titlebar`):** `FullscreenPlayer` рисуется на `ZLayer::Drawer`. Любые элементы нижнего `PlayerBar`, вынесенные на `ZLayer::Popover`, обязаны скрываться при `app.fullscreen_open`, иначе просвечивают поверх фуллскрина.
- **Linux-гигиена бинарника:** основной бинарник `yandex-music-rs` не должен линковаться с GTK / WebKit / libdbus / libappindicator (`ldd` ≈ 6 системных библиотек).
- **Проверка после правок:** прогоняй `cargo test --lib`, `cargo test --test parity_extended`, `cargo test --test visual_parity` (0 предупреждений).
---
# Git, коммиты и релизы на git.tatar
Этот репозиторий хостится на **Forgejo** (`https://git.tatar/marwy/yandex-music-rs`). Этот репозиторий хостится на **Forgejo** (`https://git.tatar/marwy/yandex-music-rs`).
Авторизация на `https://git.tatar` должна храниться в Windows Credential Manager как **бессрочный Personal Access Token (PAT)** с `credential.https://git.tatar.provider = generic` (НЕ через OAuth-окно GCM — OAuth-токен Forgejo протухает через ~1 час, после чего `git push` удаляет запись из Credential Manager). Авторизация на `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).
@ -7,12 +62,12 @@
> 1. **НИКОГДА не используй браузер** для создания релизов, загрузки ассетов или настройки репозитория на `git.tatar` — браузер не авторизован и упрётся в страницу логина. Все операции с `git.tatar` выполняются через **Forgejo REST API v1** с токеном из `git credential fill`. > 1. **НИКОГДА не используй браузер** для создания релизов, загрузки ассетов или настройки репозитория на `git.tatar` — браузер не авторизован и упрётся в страницу логина. Все операции с `git.tatar` выполняются через **Forgejo REST API v1** с токеном из `git credential fill`.
> 2. **НИКОГДА не печатай токен** в stdout, логи, файлы или ответы пользователю. > 2. **НИКОГДА не печатай токен** в stdout, логи, файлы или ответы пользователю.
> 3. **НИКОГДА не коммить** `target/`, `original_yandex_music/`, `Yandex_Music_*.exe`, локальные `.deb`/`.exe`/`.tar.gz` и личные OAuth-токены Яндекс Музыки. > 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). > 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.1).
> 5. **Релизы и теги строго иммутабельны — НИКОГДА не перезаписывай и не двигай уже выпущенную версию!** Запрещено делать `git tag -f` на существующий релиз, удалять/перезаливать ассеты под старым `vX.Y.Z` или пересобирать новую правку под уже отданным пользователю номером версии. Любое изменение после сборки/публикации `vX.Y.Z` **всегда** выходит как **новая версия** (`v0.1.2` → `v0.1.3`), чтобы у клиентов никогда не было разных бинарников под одним номером версии и автообновление работало корректно. > 5. **Релизы и теги строго иммутабельны — НИКОГДА не перезаписывай и не двигай уже выпущенную версию!** Запрещено делать `git tag -f` на существующий релиз, удалять/перезаливать ассеты под старым `vX.Y.Z` или пересобирать новую правку под уже отданным пользователю номером версии. Любое изменение после сборки/публикации `vX.Y.Z` **всегда** выходит как **новая версия** (`v0.1.2` → `v0.1.3`), чтобы у клиентов никогда не было разных бинарников под одним номером версии и автообновление работало корректно.
--- ---
## 0. Первичная настройка бессрочного токена (делается пользователем 1 раз) ## 0.1. Первичная настройка бессрочного токена (делается пользователем 1 раз)
Если токен отсутствует или протух (401), пользователь создаёт **Access Token** на `https://git.tatar/user/settings/applications` (права: `write:repository`, `read:user`) и сохраняет его один раз: Если токен отсутствует или протух (401), пользователь создаёт **Access Token** на `https://git.tatar/user/settings/applications` (права: `write:repository`, `read:user`) и сохраняет его один раз:

8
CLAUDE.md Normal file
View file

@ -0,0 +1,8 @@
# Инструкции для Claude Code (`yandex-music-rs`)
**Обязательно прочитай и строго соблюдай `AGENTS.md` в корне репозитория.**
Коротко — железное правило №0:
1. **1-в-1 с оригиналом Яндекс Музыки 5.129.0:** перед любой UI-правкой сначала ищи тексты, JSX, CSS, токены и анимации в локальной папке `original_yandex_music/` (i18n: `beautified/js/937.*.js` RU / `6983.*.js` EN; полный код и обфусцированные классы UI-кита: `raw/app/_next/static/chunks/**/*.js` и `raw/app/_next/static/css/*.css`; токены `--ym-*`: `beautified/css/1d39aa9337a03444.css`).
2. **Честный стоп вместо выдумки:** если не нашёл реализацию в `original_yandex_music/`, не понимаешь, как сделано в оригинале, или не можешь воспроизвести 1-в-1 — **НЕ выдумывай свой вариант и НЕ обманывай**. Остановись, честно скажи, что именно не нашёл/не понял, и попроси уточнение или скрин у пользователя.
3. Все детали карты оригинала, граблей движка (`scale_alpha`, `consume_clicked_outside`, `ZLayer`) и релизов на `git.tatar` — в `AGENTS.md`.

55
Cargo.lock generated
View file

@ -4386,6 +4386,15 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]] [[package]]
name = "serde_urlencoded" name = "serde_urlencoded"
version = "0.7.1" version = "0.7.1"
@ -4960,7 +4969,7 @@ dependencies = [
"cfg-expr", "cfg-expr",
"heck 0.5.0", "heck 0.5.0",
"pkg-config", "pkg-config",
"toml", "toml 0.8.2",
"version-compare", "version-compare",
] ]
@ -5216,11 +5225,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"
dependencies = [ dependencies = [
"serde", "serde",
"serde_spanned", "serde_spanned 0.6.9",
"toml_datetime 0.6.3", "toml_datetime 0.6.3",
"toml_edit 0.20.2", "toml_edit 0.20.2",
] ]
[[package]]
name = "toml"
version = "1.2.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073"
dependencies = [
"indexmap 2.14.2",
"serde_core",
"serde_spanned 1.1.3",
"toml_datetime 1.1.3+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow 1.0.5",
]
[[package]] [[package]]
name = "toml_datetime" name = "toml_datetime"
version = "0.6.3" version = "0.6.3"
@ -5258,7 +5282,7 @@ checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"
dependencies = [ dependencies = [
"indexmap 2.14.2", "indexmap 2.14.2",
"serde", "serde",
"serde_spanned", "serde_spanned 0.6.9",
"toml_datetime 0.6.3", "toml_datetime 0.6.3",
"winnow 0.5.40", "winnow 0.5.40",
] ]
@ -5277,13 +5301,19 @@ dependencies = [
[[package]] [[package]]
name = "toml_parser" name = "toml_parser"
version = "1.1.6+spec-1.1.0" version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [ dependencies = [
"winnow 1.0.5", "winnow 1.0.5",
] ]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]] [[package]]
name = "tower" name = "tower"
version = "0.5.3" version = "0.5.3"
@ -6413,6 +6443,16 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "winresource"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
dependencies = [
"toml 1.2.3+spec-1.1.0",
"version_check",
]
[[package]] [[package]]
name = "wit-bindgen" name = "wit-bindgen"
version = "0.57.1" version = "0.57.1"
@ -6550,7 +6590,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]] [[package]]
name = "yandex-music-rs" name = "yandex-music-rs"
version = "0.1.9" version = "2.0.0"
dependencies = [ dependencies = [
"aes", "aes",
"anyhow", "anyhow",
@ -6587,13 +6627,16 @@ dependencies = [
"serde_json", "serde_json",
"sha2", "sha2",
"souvlaki", "souvlaki",
"swash",
"symphonia", "symphonia",
"taffy", "taffy",
"tokio", "tokio",
"tray-icon", "tray-icon",
"urlencoding", "urlencoding",
"windows 0.61.3",
"windows-sys 0.59.0", "windows-sys 0.59.0",
"winit", "winit",
"winresource",
"wry", "wry",
] ]

View file

@ -1,6 +1,6 @@
[package] [package]
name = "yandex-music-rs" name = "yandex-music-rs"
version = "0.1.9" version = "2.0.0"
edition = "2021" edition = "2021"
description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text" description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust + ash Vulkan SDF + taffy + cosmic-text"
@ -23,6 +23,7 @@ winit = "0.30"
raw-window-handle = "0.6" raw-window-handle = "0.6"
taffy = "0.16" taffy = "0.16"
cosmic-text = "0.19" cosmic-text = "0.19"
swash = "0.2"
bytemuck = { version = "1", features = ["derive"] } bytemuck = { version = "1", features = ["derive"] }
arboard = "3" arboard = "3"
@ -73,12 +74,20 @@ wry = "0.51"
windows-sys = { version = "0.59", features = [ windows-sys = { version = "0.59", features = [
"Win32_Foundation", "Win32_Foundation",
"Win32_Graphics_Dwm", "Win32_Graphics_Dwm",
"Win32_Graphics_Gdi",
"Win32_System_LibraryLoader",
"Win32_System_Power", "Win32_System_Power",
"Win32_System_ProcessStatus", "Win32_System_ProcessStatus",
"Win32_System_Threading", "Win32_System_Threading",
"Win32_UI_HiDpi",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Shell", "Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging", "Win32_UI_WindowsAndMessaging",
] } ] }
windows = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Graphics_DirectWrite",
] }
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
ksni = { version = "0.3", features = ["blocking"] } ksni = { version = "0.3", features = ["blocking"] }
@ -88,6 +97,9 @@ gtk = { version = "0.18", optional = true }
[build-dependencies] [build-dependencies]
naga = { version = "24", features = ["wgsl-in", "spv-out"] } naga = { version = "24", features = ["wgsl-in", "spv-out"] }
[target.'cfg(windows)'.build-dependencies]
winresource = "0.1"
[profile.release] [profile.release]
opt-level = 3 opt-level = 3
lto = "thin" lto = "thin"
@ -115,5 +127,6 @@ assets = [
["packaging/icons/128x128.png", "usr/share/icons/hicolor/128x128/apps/yandex-music-rs.png", "644"], ["packaging/icons/128x128.png", "usr/share/icons/hicolor/128x128/apps/yandex-music-rs.png", "644"],
["packaging/icons/256x256.png", "usr/share/icons/hicolor/256x256/apps/yandex-music-rs.png", "644"], ["packaging/icons/256x256.png", "usr/share/icons/hicolor/256x256/apps/yandex-music-rs.png", "644"],
["packaging/yandex-music-rs.desktop", "usr/share/applications/", "644"], ["packaging/yandex-music-rs.desktop", "usr/share/applications/", "644"],
["packaging/ru.marwy.YandexMusicRs.metainfo.xml", "usr/share/metainfo/", "644"],
] ]

105
README.md
View file

@ -6,16 +6,88 @@
**marwy** + **Gemini 4 Neon** **marwy** + **Gemini 4 Neon**
## Скачать ## Скачать и установить
Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases): Готовые сборки доступны на странице [Releases](https://git.tatar/marwy/yandex-music-rs/releases).
- **Windows (x64)**: скачайте `yandex-music-rs-v0.1.9-windows-x86_64.exe` и запустите (переносной файл, установка не требуется). ### Windows (x64)
- **Linux (Debian / Ubuntu x64)**: скачайте `yandex-music-rs_0.1.9-1_amd64.deb` и установите:
```bash - **GUI-установщик (рекомендуется)**: скачайте `yandex-music-rs-v2.0.0-windows-x86_64-setup.exe`.
sudo apt install ./yandex-music-rs_0.1.9-1_amd64.deb - Ставится для текущего пользователя (`%LOCALAPPDATA%\Programs\YandexMusicRs`) без прав администратора.
- Создаёт ярлыки на Рабочем столе и в меню «Пуск», регистрируется в «Установленных приложениях» Windows (с деинсталлятором).
- При повторном запуске обновляет установленную версию; внутри самого плеера работает встроенное автообновление в 1 клик с `git.tatar`.
- Тихий режим: `--silent`, `--dir "<путь>"`, `--uninstall`.
- **Portable**: `yandex-music-rs-v2.0.0-windows-x86_64.exe` — запуск без установки.
- **Scoop**: манифест в `packaging/scoop/yandex-music-rs.json` (с `checkver` + `autoupdate`).
```powershell
scoop install https://git.tatar/marwy/yandex-music-rs/raw/branch/main/packaging/scoop/yandex-music-rs.json
``` ```
- **Linux (generic x64)**: архив `yandex-music-rs-v0.1.9-linux-x86_64.tar.gz` с готовыми бинарниками (`yandex-music-rs` + `yandex-music-auth`). - **Winget**: готовые манифесты в `packaging/winget/`.
### Linux — любой дистрибутив (one-liner, без `sudo`)
```bash
curl -fsSL https://git.tatar/marwy/yandex-music-rs/raw/branch/main/packaging/install.sh | sh
```
- Проверяет `SHA256SUMS.txt`, ставит бинарники в `~/.local/bin`, создаёт `.desktop`-ярлык и иконки.
- Обновление: запустить ту же команду (или нажать «Обновить» внутри плеера).
- Удаление: `sh install.sh --uninstall` (с удалением настроек и кэша: `--uninstall --purge`).
### NixOS (Flakes)
```bash
# Быстрый запуск
nix run git+https://git.tatar/marwy/yandex-music-rs
# Установка в профиль (обновление через `nix profile upgrade`)
nix profile install git+https://git.tatar/marwy/yandex-music-rs
```
Или через системный `flake.nix`:
```nix
{
inputs.yandex-music-rs.url = "git+https://git.tatar/marwy/yandex-music-rs";
# В модулях NixOS:
# imports = [ inputs.yandex-music-rs.nixosModules.default ];
# programs.yandex-music-rs.enable = true;
}
```
### Debian / Ubuntu (`.deb`)
```bash
sudo apt install ./yandex-music-rs_2.0.0-1_amd64.deb
```
### Arch Linux / CachyOS / Manjaro (AUR / `makepkg`)
- Пресобранный бинарник (`packaging/arch/yandex-music-rs-bin/PKGBUILD`):
```bash
cd packaging/arch/yandex-music-rs-bin && makepkg -si
```
- Сборка из исходников (`packaging/arch/yandex-music-rs/PKGBUILD`):
```bash
cd packaging/arch/yandex-music-rs && makepkg -si
```
### Fedora / openSUSE / RHEL (`.rpm`)
```bash
./packaging/build-rpm.sh
sudo dnf install ./target/rpm/yandex-music-rs-*.rpm
```
### AppImage & Flatpak
- **AppImage**: `./packaging/build-appimage.sh` → `target/appimage/yandex-music-rs-v2.0.0-linux-x86_64.AppImage` (поддерживает встроенное самообновление).
- **Flatpak**: `./packaging/build-flatpak.sh` → `target/flatpak/yandex-music-rs-v2.0.0.flatpak` (манифест `packaging/flatpak/ru.marwy.YandexMusicRs.yml` + AppStream `packaging/ru.marwy.YandexMusicRs.metainfo.xml`).
### Void Linux / Gentoo / Alpine
- **Void Linux (`xbps-src`)**: `packaging/void/template`
- **Gentoo (`ebuild`)**: `packaging/gentoo/media-sound/yandex-music-rs/yandex-music-rs-2.0.0.ebuild`
- **Alpine (`APKBUILD`)**: `packaging/alpine/APKBUILD`
## Стек и возможности ## Стек и возможности
@ -23,23 +95,20 @@
- **Вёрстка и типографика**: движок раскладки `taffy`, рендеринг текста `cosmic-text` и векторные иконки через `resvg`. - **Вёрстка и типографика**: движок раскладки `taffy`, рендеринг текста `cosmic-text` и векторные иконки через `resvg`.
- **Аудиодвижок**: потоковое воспроизведение через `symphonia` (MP3, FLAC lossless, AAC/M4A, Ogg, WAV) и `cpal` с собственным DSP-конвейером. - **Аудиодвижок**: потоковое воспроизведение через `symphonia` (MP3, FLAC lossless, AAC/M4A, Ogg, WAV) и `cpal` с собственным DSP-конвейером.
- **API Яндекс Музыки**: асинхронный клиент на `tokio` + `reqwest` (`rustls-tls`) с подписью запросов и расшифровкой потоков `encraw`. - **API Яндекс Музыки**: асинхронный клиент на `tokio` + `reqwest` (`rustls-tls`) с подписью запросов и расшифровкой потоков `encraw`.
- **Интеграция с системой**: иконка в трее (`tray-icon`), системные медиа-клавиши (`souvlaki`), встроенная WebView-авторизация (`wry`), тёмная/светлая/системная темы и локализация RU/EN. - **Интеграция с системой**: иконка в трее (`tray-icon` / `ksni`), системные медиа-клавиши (`souvlaki`), встроенная WebView-авторизация (`wry`), тёмная/светлая/системная темы и локализация RU/EN.
## Сборка ## Сборка
### Требования
- Rust (Edition 2021)
- Для Linux: библиотеки Vulkan/OpenGL (`libvulkan1`, `libgl1`, `libegl1`), а также dev-пакеты GTK/WebKit для `wry`/`gtk`
### Запуск
```bash ```bash
# Локальный запуск
cargo run --release cargo run --release
```
### Сборка `.deb`-пакета # Windows GUI-установщик (setup.exe)
.\packaging\build-windows-installer.ps1
```bash # Linux пакеты
./packaging/build-deb.sh ./packaging/build-deb.sh
./packaging/build-rpm.sh
./packaging/build-appimage.sh
./packaging/build-flatpak.sh
``` ```

View file

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 28 28" fill="none">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.42032 25.4019C9.14037 21.0934 5.66809 17.6882 1.42578 17.6882V16.5741C5.8511 16.5741 9.43853 12.8687 9.43853 8.29785H10.5171C10.5171 12.8687 14.1045 16.5741 18.5299 16.5741V17.6882C14.2876 17.6882 10.8153 21.0934 10.5353 25.4019H9.42032Z" fill="#FFFFFF"/>
<path d="M19.8267 3.83H21.4167L23.9567 11H22.7067L22.0467 9.12H19.0267L18.3667 11H17.2967L19.8267 3.83ZM21.6767 8.08L20.5367 4.85L19.3967 8.08H21.6767ZM27.0991 3.83V11H25.8891V3.83H27.0991Z" fill="#FFFFFF"/>
</svg>

After

Width:  |  Height:  |  Size: 623 B

View file

@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="none">
<path d="M4 14L3 7.5H4.25C7.75 11.5 9.35 5.5 9.35 5.5H10H10.65C10.65 5.5 12.25 11.5 15.75 7.5H17L16 14H10H4Z" fill="#FFFFFF" />
</svg>

After

Width:  |  Height:  |  Size: 208 B

View file

@ -1,11 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
<defs> <path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" d="M22 11.99c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10 10 4.478 10 10m-2 0a8 8 0 1 1-5.524-7.609l-1.83 5.61H7.329l-.652 2h5.319l-1.631 5h2.202l1.63-5zm-.252-2h-4.899l1.532-4.695a8 8 0 0 1 3.367 4.696"/>
<linearGradient id="g" x1="0" y1="0" x2="24" y2="24" gradientUnits="userSpaceOnUse">
<stop stop-color="#FF5C4D"/>
<stop offset="0.35" stop-color="#EB469F"/>
<stop offset="0.75" stop-color="#8341EF"/>
<stop offset="1" stop-color="#3F68F9"/>
</linearGradient>
</defs>
<path fill-rule="evenodd" clip-rule="evenodd" fill="url(#g)" d="M22 11.99c0 5.523-4.477 10-10 10s-10-4.477-10-10 4.477-10 10-10 10 4.478 10 10m-2 0a8 8 0 1 1-5.524-7.609l-1.83 5.61H7.329l-.652 2h5.319l-1.631 5h2.202l1.63-5zm-.252-2h-4.899l1.532-4.695a8 8 0 0 1 3.367 4.696"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 690 B

After

Width:  |  Height:  |  Size: 381 B

Before After
Before After

BIN
assets/media/bookshelf.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

BIN
assets/welcome_desktop.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

View file

@ -34,4 +34,20 @@ fn main() {
compile_wgsl_to_spv("shaders/ui_sdf.wgsl", "ui_sdf.spv"); compile_wgsl_to_spv("shaders/ui_sdf.wgsl", "ui_sdf.spv");
compile_wgsl_to_spv("shaders/blur.wgsl", "blur.spv"); compile_wgsl_to_spv("shaders/blur.wgsl", "blur.spv");
compile_wgsl_to_spv("shaders/vibe.wgsl", "vibe.spv"); compile_wgsl_to_spv("shaders/vibe.wgsl", "vibe.spv");
#[cfg(target_os = "windows")]
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let ico = "packaging/icons/yandex-music-rs.ico";
println!("cargo:rerun-if-changed={}", ico);
if Path::new(ico).exists() {
let mut res = winresource::WindowsResource::new();
res.set_icon(ico);
res.set("ProductName", "Яндекс Музыка (yandex-music-rs)");
res.set("FileDescription", "Yandex Music Desktop Client");
res.set("CompanyName", "marwy");
if let Err(e) = res.compile() {
println!("cargo:warning=winresource failed: {}", e);
}
}
}
} }

194
flake.nix Normal file
View file

@ -0,0 +1,194 @@
{
description = "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
};
outputs = { self, nixpkgs }:
let
supportedSystems = [ "x86_64-linux" "aarch64-linux" ];
forAllSystems = nixpkgs.lib.genAttrs supportedSystems;
cargoToml = builtins.fromTOML (builtins.readFile ./Cargo.toml);
mkPackage = pkgs:
let
runtimeLibs = with pkgs; [
alsa-lib
libxkbcommon
wayland
xorg.libX11
xorg.libXcursor
xorg.libXi
xorg.libXrandr
vulkan-loader
libGL
libEGL
];
# Isolated OAuth WebView helper binary (requires GTK + WebKitGTK)
authHelper = pkgs.rustPlatform.buildRustPackage {
pname = "yandex-music-auth";
version = cargoToml.package.version;
src = self;
cargoLock = {
lockFile = ./Cargo.lock;
};
cargoBuildFlags = [
"--features"
"linux-webview"
"--bin"
"yandex-music-auth"
];
doCheck = false;
nativeBuildInputs = with pkgs; [
pkg-config
wrapGAppsHook3
];
buildInputs = with pkgs; [
alsa-lib
glib
gtk3
libsoup_3
openssl
webkitgtk_4_1
];
};
in
pkgs.rustPlatform.buildRustPackage {
pname = "yandex-music-rs";
version = cargoToml.package.version;
src = self;
cargoLock = {
lockFile = ./Cargo.lock;
};
cargoBuildFlags = [
"--bin"
"yandex-music-rs"
];
doCheck = false;
nativeBuildInputs = with pkgs; [
pkg-config
makeWrapper
];
buildInputs = runtimeLibs;
postInstall = ''
# Install isolated OAuth helper alongside main binary
cp -a ${authHelper}/bin/yandex-music-auth "$out/bin/yandex-music-auth"
# Ensure Vulkan, OpenGL, Wayland, X11, and ALSA shared libs are discoverable via dlopen
wrapProgram "$out/bin/yandex-music-rs" \
--prefix LD_LIBRARY_PATH : "${pkgs.lib.makeLibraryPath runtimeLibs}" \
--prefix PATH : "$out/bin"
# Desktop shortcut entry
install -Dm644 packaging/yandex-music-rs.desktop \
"$out/share/applications/yandex-music-rs.desktop"
substituteInPlace "$out/share/applications/yandex-music-rs.desktop" \
--replace-fail "Exec=/usr/bin/yandex-music-rs" "Exec=$out/bin/yandex-music-rs"
# Application icons (hicolor theme + pixmaps)
install -Dm644 assets/icons/app_icon.png \
"$out/share/pixmaps/yandex-music-rs.png"
install -Dm644 assets/icons/app_48.png \
"$out/share/icons/hicolor/48x48/apps/yandex-music-rs.png"
install -Dm644 packaging/icons/64x64.png \
"$out/share/icons/hicolor/64x64/apps/yandex-music-rs.png"
install -Dm644 packaging/icons/128x128.png \
"$out/share/icons/hicolor/128x128/apps/yandex-music-rs.png"
install -Dm644 packaging/icons/256x256.png \
"$out/share/icons/hicolor/256x256/apps/yandex-music-rs.png"
'';
meta = with pkgs.lib; {
description = cargoToml.package.description;
homepage = "https://git.tatar/marwy/yandex-music-rs";
platforms = supportedSystems;
mainProgram = "yandex-music-rs";
};
};
in
{
packages = forAllSystems (system:
let
pkgs = nixpkgs.legacyPackages.${system};
in
{
default = mkPackage pkgs;
yandex-music-rs = mkPackage pkgs;
});
apps = forAllSystems (system: {
default = {
type = "app";
program = "${self.packages.${system}.default}/bin/yandex-music-rs";
};
});
overlays.default = final: _prev: {
yandex-music-rs = mkPackage final;
};
nixosModules.default = { config, lib, pkgs, ... }:
let
cfg = config.programs.yandex-music-rs;
in
{
options.programs.yandex-music-rs = {
enable = lib.mkEnableOption "Yandex Music native Rust desktop client";
package = lib.mkOption {
type = lib.types.package;
default = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
description = "The yandex-music-rs package to install.";
};
};
config = lib.mkIf cfg.enable {
environment.systemPackages = [ cfg.package ];
};
};
devShells = forAllSystems (system:
let
pkgs = nixpkgs.legacyPackages.${system};
runtimeLibs = with pkgs; [
alsa-lib
libxkbcommon
wayland
xorg.libX11
xorg.libXcursor
xorg.libXi
xorg.libXrandr
vulkan-loader
libGL
libEGL
];
in
{
default = pkgs.mkShell {
nativeBuildInputs = with pkgs; [
cargo
rustc
pkg-config
];
buildInputs = runtimeLibs ++ (with pkgs; [
glib
gtk3
libsoup_3
openssl
webkitgtk_4_1
]);
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath runtimeLibs;
};
});
};
}

34
packaging/alpine/APKBUILD Normal file
View file

@ -0,0 +1,34 @@
# Maintainer: marwy <hhhhyetr456@gmail.com>
pkgname=yandex-music-rs
pkgver=2.0.0
pkgrel=0
pkgdesc="Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust"
url="https://git.tatar/marwy/yandex-music-rs"
arch="x86_64 aarch64"
license="custom"
depends="alsa-lib hicolor-icon-theme"
makedepends="cargo pkgconf alsa-lib-dev gtk+3.0-dev webkit2gtk-4.1-dev libsoup3-dev openssl-dev"
options="net !check"
source="$pkgname-v$pkgver.tar.gz::https://git.tatar/marwy/yandex-music-rs/archive/v$pkgver.tar.gz"
builddir="$srcdir/$pkgname"
build() {
cargo build --release --locked --bin yandex-music-rs
cargo build --release --locked --features linux-webview --bin yandex-music-auth
}
package() {
install -Dm755 target/release/yandex-music-rs "$pkgdir"/usr/bin/yandex-music-rs
install -Dm755 target/release/yandex-music-auth "$pkgdir"/usr/bin/yandex-music-auth
install -Dm644 packaging/yandex-music-rs.desktop \
"$pkgdir"/usr/share/applications/yandex-music-rs.desktop
install -Dm644 packaging/ru.marwy.YandexMusicRs.metainfo.xml \
"$pkgdir"/usr/share/metainfo/ru.marwy.YandexMusicRs.metainfo.xml
install -Dm644 assets/icons/app_icon.png "$pkgdir"/usr/share/pixmaps/yandex-music-rs.png
install -Dm644 assets/icons/app_48.png "$pkgdir"/usr/share/icons/hicolor/48x48/apps/yandex-music-rs.png
install -Dm644 packaging/icons/64x64.png "$pkgdir"/usr/share/icons/hicolor/64x64/apps/yandex-music-rs.png
install -Dm644 packaging/icons/128x128.png "$pkgdir"/usr/share/icons/hicolor/128x128/apps/yandex-music-rs.png
install -Dm644 packaging/icons/256x256.png "$pkgdir"/usr/share/icons/hicolor/256x256/apps/yandex-music-rs.png
}

View file

@ -0,0 +1,32 @@
pkgbase = yandex-music-rs-bin
pkgdesc = Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust (prebuilt binary)
pkgver = 2.0.0
pkgrel = 1
url = https://git.tatar/marwy/yandex-music-rs
arch = x86_64
license = custom
depends = alsa-lib
depends = hicolor-icon-theme
optdepends = vulkan-icd-loader: Vulkan SDF hardware rendering
optdepends = libglvnd: OpenGL 3.3 Core fallback renderer
optdepends = webkit2gtk-4.1: embedded OAuth WebView helper (yandex-music-auth)
provides = yandex-music-rs
conflicts = yandex-music-rs
conflicts = yandex-music-rs-git
options = !strip
source = yandex-music-rs-v2.0.0-linux-x86_64.tar.gz::https://git.tatar/marwy/yandex-music-rs/releases/download/v2.0.0/yandex-music-rs-v2.0.0-linux-x86_64.tar.gz
source = yandex-music-rs.desktop::https://git.tatar/marwy/yandex-music-rs/raw/tag/v2.0.0/packaging/yandex-music-rs.desktop
source = ru.marwy.YandexMusicRs.metainfo.xml::https://git.tatar/marwy/yandex-music-rs/raw/tag/v2.0.0/packaging/ru.marwy.YandexMusicRs.metainfo.xml
source = app_48.png::https://git.tatar/marwy/yandex-music-rs/raw/tag/v2.0.0/assets/icons/app_48.png
source = icon_64.png::https://git.tatar/marwy/yandex-music-rs/raw/tag/v2.0.0/packaging/icons/64x64.png
source = icon_128.png::https://git.tatar/marwy/yandex-music-rs/raw/tag/v2.0.0/packaging/icons/128x128.png
source = icon_256.png::https://git.tatar/marwy/yandex-music-rs/raw/tag/v2.0.0/packaging/icons/256x256.png
sha256sums = SKIP
sha256sums = SKIP
sha256sums = SKIP
sha256sums = SKIP
sha256sums = SKIP
sha256sums = SKIP
sha256sums = SKIP
pkgname = yandex-music-rs-bin

View file

@ -0,0 +1,51 @@
# Maintainer: marwy <hhhhyetr456@gmail.com>
pkgname=yandex-music-rs-bin
pkgver=2.0.0
pkgrel=1
pkgdesc="Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust (prebuilt binary)"
arch=('x86_64')
url="https://git.tatar/marwy/yandex-music-rs"
license=('custom')
depends=('alsa-lib' 'hicolor-icon-theme')
optdepends=(
'vulkan-icd-loader: Vulkan SDF hardware rendering'
'libglvnd: OpenGL 3.3 Core fallback renderer'
'webkit2gtk-4.1: embedded OAuth WebView helper (yandex-music-auth)'
)
provides=('yandex-music-rs')
conflicts=('yandex-music-rs' 'yandex-music-rs-git')
options=('!strip')
source=(
"yandex-music-rs-v${pkgver}-linux-x86_64.tar.gz::${url}/releases/download/v${pkgver}/yandex-music-rs-v${pkgver}-linux-x86_64.tar.gz"
"yandex-music-rs.desktop::${url}/raw/tag/v${pkgver}/packaging/yandex-music-rs.desktop"
"ru.marwy.YandexMusicRs.metainfo.xml::${url}/raw/tag/v${pkgver}/packaging/ru.marwy.YandexMusicRs.metainfo.xml"
"app_48.png::${url}/raw/tag/v${pkgver}/assets/icons/app_48.png"
"icon_64.png::${url}/raw/tag/v${pkgver}/packaging/icons/64x64.png"
"icon_128.png::${url}/raw/tag/v${pkgver}/packaging/icons/128x128.png"
"icon_256.png::${url}/raw/tag/v${pkgver}/packaging/icons/256x256.png"
)
sha256sums=(
'SKIP'
'SKIP'
'SKIP'
'SKIP'
'SKIP'
'SKIP'
'SKIP'
)
package() {
install -Dm755 "${srcdir}/yandex-music-rs" "${pkgdir}/usr/bin/yandex-music-rs"
if [[ -f "${srcdir}/yandex-music-auth" ]]; then
install -Dm755 "${srcdir}/yandex-music-auth" "${pkgdir}/usr/bin/yandex-music-auth"
fi
install -Dm644 "${srcdir}/yandex-music-rs.desktop" "${pkgdir}/usr/share/applications/yandex-music-rs.desktop"
install -Dm644 "${srcdir}/ru.marwy.YandexMusicRs.metainfo.xml" "${pkgdir}/usr/share/metainfo/ru.marwy.YandexMusicRs.metainfo.xml"
install -Dm644 "${srcdir}/app_48.png" "${pkgdir}/usr/share/icons/hicolor/48x48/apps/yandex-music-rs.png"
install -Dm644 "${srcdir}/icon_64.png" "${pkgdir}/usr/share/icons/hicolor/64x64/apps/yandex-music-rs.png"
install -Dm644 "${srcdir}/icon_128.png" "${pkgdir}/usr/share/icons/hicolor/128x128/apps/yandex-music-rs.png"
install -Dm644 "${srcdir}/icon_256.png" "${pkgdir}/usr/share/icons/hicolor/256x256/apps/yandex-music-rs.png"
install -Dm644 "${srcdir}/icon_256.png" "${pkgdir}/usr/share/pixmaps/yandex-music-rs.png"
}

View file

@ -0,0 +1,50 @@
# Maintainer: marwy <hhhhyetr456@gmail.com>
pkgname=yandex-music-rs
pkgver=2.0.0
pkgrel=1
pkgdesc="Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust"
arch=('x86_64' 'aarch64')
url="https://git.tatar/marwy/yandex-music-rs"
license=('custom')
depends=('alsa-lib' 'hicolor-icon-theme')
makedepends=('cargo' 'pkgconf' 'gtk3' 'webkit2gtk-4.1')
optdepends=(
'vulkan-icd-loader: Vulkan SDF hardware rendering'
'libglvnd: OpenGL 3.3 Core fallback renderer'
'webkit2gtk-4.1: embedded OAuth WebView helper (yandex-music-auth)'
)
provides=('yandex-music-rs')
conflicts=('yandex-music-rs-bin' 'yandex-music-rs-git')
source=("${pkgname}-v${pkgver}.tar.gz::${url}/archive/v${pkgver}.tar.gz")
sha256sums=('SKIP')
prepare() {
cd "${srcdir}/${pkgname}"
export RUSTUP_TOOLCHAIN=stable
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}
build() {
cd "${srcdir}/${pkgname}"
export RUSTUP_TOOLCHAIN=stable
export CARGO_TARGET_DIR=target
# Main player binary (zero GTK/WebKit DT_NEEDED)
cargo build --frozen --release --bin yandex-music-rs
# Isolated OAuth WebView helper
cargo build --frozen --release --features linux-webview --bin yandex-music-auth
}
package() {
cd "${srcdir}/${pkgname}"
install -Dm755 "target/release/yandex-music-rs" "${pkgdir}/usr/bin/yandex-music-rs"
install -Dm755 "target/release/yandex-music-auth" "${pkgdir}/usr/bin/yandex-music-auth"
install -Dm644 "packaging/yandex-music-rs.desktop" "${pkgdir}/usr/share/applications/yandex-music-rs.desktop"
install -Dm644 "packaging/ru.marwy.YandexMusicRs.metainfo.xml" "${pkgdir}/usr/share/metainfo/ru.marwy.YandexMusicRs.metainfo.xml"
install -Dm644 "assets/icons/app_icon.png" "${pkgdir}/usr/share/pixmaps/yandex-music-rs.png"
install -Dm644 "assets/icons/app_48.png" "${pkgdir}/usr/share/icons/hicolor/48x48/apps/yandex-music-rs.png"
install -Dm644 "packaging/icons/64x64.png" "${pkgdir}/usr/share/icons/hicolor/64x64/apps/yandex-music-rs.png"
install -Dm644 "packaging/icons/128x128.png" "${pkgdir}/usr/share/icons/hicolor/128x128/apps/yandex-music-rs.png"
install -Dm644 "packaging/icons/256x256.png" "${pkgdir}/usr/share/icons/hicolor/256x256/apps/yandex-music-rs.png"
}

61
packaging/build-appimage.sh Executable file
View file

@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
export PATH="$HOME/.cargo/bin:$PATH"
if [[ "$PROJECT_DIR" == /mnt/* ]]; then
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/yandex-music-rs-target}"
else
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$PROJECT_DIR/target}"
fi
VERSION="$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$PROJECT_DIR/Cargo.toml" | head -n 1)"
ARCH="$(uname -m)"
cd "$PROJECT_DIR"
cargo build --release --bin yandex-music-rs
cargo build --release --features linux-webview --bin yandex-music-auth
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
APPDIR="$WORK/AppDir"
install -Dm755 "$CARGO_TARGET_DIR/release/yandex-music-rs" "$APPDIR/usr/bin/yandex-music-rs"
install -Dm755 "$CARGO_TARGET_DIR/release/yandex-music-auth" "$APPDIR/usr/bin/yandex-music-auth"
install -Dm644 "$PROJECT_DIR/packaging/yandex-music-rs.desktop" "$APPDIR/yandex-music-rs.desktop"
sed -i 's|^Exec=/usr/bin/yandex-music-rs|Exec=yandex-music-rs|' "$APPDIR/yandex-music-rs.desktop"
install -Dm644 "$APPDIR/yandex-music-rs.desktop" "$APPDIR/usr/share/applications/yandex-music-rs.desktop"
install -Dm644 "$PROJECT_DIR/packaging/ru.marwy.YandexMusicRs.metainfo.xml" \
"$APPDIR/usr/share/metainfo/ru.marwy.YandexMusicRs.metainfo.xml"
install -Dm644 "$PROJECT_DIR/packaging/icons/256x256.png" "$APPDIR/yandex-music-rs.png"
ln -sf "yandex-music-rs.png" "$APPDIR/.DirIcon"
install -Dm644 "$PROJECT_DIR/assets/icons/app_48.png" "$APPDIR/usr/share/icons/hicolor/48x48/apps/yandex-music-rs.png"
install -Dm644 "$PROJECT_DIR/packaging/icons/64x64.png" "$APPDIR/usr/share/icons/hicolor/64x64/apps/yandex-music-rs.png"
install -Dm644 "$PROJECT_DIR/packaging/icons/128x128.png" "$APPDIR/usr/share/icons/hicolor/128x128/apps/yandex-music-rs.png"
install -Dm644 "$PROJECT_DIR/packaging/icons/256x256.png" "$APPDIR/usr/share/icons/hicolor/256x256/apps/yandex-music-rs.png"
cat > "$APPDIR/AppRun" <<'EOF'
#!/usr/bin/env sh
HERE="$(dirname "$(readlink -f "$0")")"
export PATH="$HERE/usr/bin:$PATH"
exec "$HERE/usr/bin/yandex-music-rs" "$@"
EOF
chmod 755 "$APPDIR/AppRun"
APPIMAGETOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
if [[ -z "$APPIMAGETOOL" ]]; then
APPIMAGETOOL="$WORK/appimagetool"
echo "Downloading appimagetool..."
curl -fsSL "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${ARCH}.AppImage" -o "$APPIMAGETOOL"
chmod +x "$APPIMAGETOOL"
fi
OUT_DIR="$PROJECT_DIR/target/appimage"
mkdir -p "$OUT_DIR"
OUT_FILE="$OUT_DIR/yandex-music-rs-v${VERSION}-linux-${ARCH}.AppImage"
ARCH="$ARCH" "$APPIMAGETOOL" --appimage-extract-and-run "$APPDIR" "$OUT_FILE"
ls -lh "$OUT_FILE"

23
packaging/build-flatpak.sh Executable file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
VERSION="$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$PROJECT_DIR/Cargo.toml" | head -n 1)"
command -v flatpak-builder >/dev/null 2>&1 || {
echo "flatpak-builder not found. Install flatpak-builder and org.gnome.Sdk//47 + rust-stable extension." >&2
exit 1
}
BUILD_DIR="$PROJECT_DIR/target/flatpak-build"
REPO_DIR="$PROJECT_DIR/target/flatpak-repo"
OUT_DIR="$PROJECT_DIR/target/flatpak"
mkdir -p "$OUT_DIR"
flatpak-builder --force-clean --repo="$REPO_DIR" "$BUILD_DIR" \
"$PROJECT_DIR/packaging/flatpak/ru.marwy.YandexMusicRs.yml"
OUT_FILE="$OUT_DIR/yandex-music-rs-v${VERSION}.flatpak"
flatpak build-bundle "$REPO_DIR" "$OUT_FILE" ru.marwy.YandexMusicRs
ls -lh "$OUT_FILE"

39
packaging/build-rpm.sh Executable file
View file

@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
export PATH="$HOME/.cargo/bin:$PATH"
command -v rpmbuild >/dev/null 2>&1 || {
echo "rpmbuild not found. Install rpm-build (Fedora/RHEL) or rpm (Debian/Ubuntu)." >&2
exit 1
}
if [[ "$PROJECT_DIR" == /mnt/* ]]; then
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$HOME/.cache/yandex-music-rs-target}"
else
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$PROJECT_DIR/target}"
fi
VERSION="$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$PROJECT_DIR/Cargo.toml" | head -n 1)"
cd "$PROJECT_DIR"
cargo build --release --bin yandex-music-rs
cargo build --release --features linux-webview --bin yandex-music-auth
RPM_TOP="$(mktemp -d)"
trap 'rm -rf "$RPM_TOP"' EXIT
mkdir -p "$RPM_TOP"/{BUILD,RPMS,SOURCES,SPECS,SRPMS}
rpmbuild -bb \
--define "_topdir $RPM_TOP" \
--define "_ym_version $VERSION" \
--define "_ym_srcdir $PROJECT_DIR" \
--define "_ym_bindir $CARGO_TARGET_DIR/release" \
"$PROJECT_DIR/packaging/rpm/yandex-music-rs.spec"
OUT_DIR="$PROJECT_DIR/target/rpm"
mkdir -p "$OUT_DIR"
cp -f "$RPM_TOP"/RPMS/*/*.rpm "$OUT_DIR/"
ls -lh "$OUT_DIR/"*.rpm

View file

@ -0,0 +1,66 @@
$ErrorActionPreference = "Stop"
$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$CargoToml = Get-Content (Join-Path $RepoRoot "Cargo.toml") -Raw
if ($CargoToml -match '(?m)^version\s*=\s*"([^"]+)"') {
$Version = $Matches[1]
} else {
throw "Could not parse version from Cargo.toml"
}
$AppExe = Join-Path $RepoRoot "target\release\yandex-music-rs.exe"
$CargoArgs = @("build", "--release", "--bin", "yandex-music-rs")
$RunningLocked = Get-Process -Name "yandex-music-rs" -ErrorAction SilentlyContinue |
Where-Object { $_.Path -eq $AppExe }
if ($RunningLocked) {
$StageTarget = Join-Path $RepoRoot "target\installer-stage"
Write-Host " (target\release\yandex-music-rs.exe is running; staging into target\installer-stage)" -ForegroundColor DarkGray
$CargoArgs += @("--target-dir", $StageTarget)
$AppExe = Join-Path $StageTarget "release\yandex-music-rs.exe"
}
Write-Host "==> Building yandex-music-rs v$Version (release)..." -ForegroundColor Yellow
Push-Location $RepoRoot
try {
& cargo @CargoArgs
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} finally {
Pop-Location
}
if (-not (Test-Path $AppExe)) {
throw "Expected app binary not found: $AppExe"
}
Write-Host "==> Building Windows GUI installer (yandex-music-rs-setup.exe)..." -ForegroundColor Yellow
$InstallerDir = Join-Path $RepoRoot "packaging\windows\installer"
$env:YM_PAYLOAD_EXE = $AppExe
Push-Location $InstallerDir
try {
& cargo build --release
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} finally {
Pop-Location
}
$SetupExe = Join-Path $InstallerDir "target\release\yandex-music-rs-setup.exe"
if (-not (Test-Path $SetupExe)) {
throw "Expected installer binary not found: $SetupExe"
}
$DistDir = Join-Path $RepoRoot "target\release-dist-v$Version"
New-Item -ItemType Directory -Force -Path $DistDir | Out-Null
$OutPortable = Join-Path $DistDir "yandex-music-rs-v$Version-windows-x86_64.exe"
$OutSetup = Join-Path $DistDir "yandex-music-rs-v$Version-windows-x86_64-setup.exe"
Copy-Item -Force $AppExe $OutPortable
Copy-Item -Force $SetupExe $OutSetup
$pSize = [math]::Round((Get-Item $OutPortable).Length / 1MB, 2)
$sSize = [math]::Round((Get-Item $OutSetup).Length / 1MB, 2)
Write-Host ""
Write-Host "Done!" -ForegroundColor Green
Write-Host " Portable : $OutPortable ($pSize MB)"
Write-Host " Installer: $OutSetup ($sSize MB)"

View file

@ -0,0 +1,43 @@
app-id: ru.marwy.YandexMusicRs
runtime: org.gnome.Platform
runtime-version: '47'
sdk: org.gnome.Sdk
sdk-extensions:
- org.freedesktop.Sdk.Extension.rust-stable
command: yandex-music-rs
rename-desktop-file: yandex-music-rs.desktop
rename-icon: yandex-music-rs
finish-args:
- --share=network
- --share=ipc
- --socket=wayland
- --socket=fallback-x11
- --socket=pulseaudio
- --device=dri
- --talk-name=org.kde.StatusNotifierWatcher
- --own-name=org.mpris.MediaPlayer2.yandex-music-rs
build-options:
append-path: /usr/lib/sdk/rust-stable/bin
env:
CARGO_HOME: /run/build/yandex-music-rs/cargo
modules:
- name: yandex-music-rs
buildsystem: simple
build-commands:
- cargo build --release --bin yandex-music-rs
- cargo build --release --features linux-webview --bin yandex-music-auth
- install -Dm755 target/release/yandex-music-rs /app/bin/yandex-music-rs
- install -Dm755 target/release/yandex-music-auth /app/bin/yandex-music-auth
- sed 's|^Exec=/usr/bin/yandex-music-rs|Exec=yandex-music-rs|' packaging/yandex-music-rs.desktop > /tmp/yandex-music-rs.desktop
- install -Dm644 /tmp/yandex-music-rs.desktop /app/share/applications/yandex-music-rs.desktop
- install -Dm644 packaging/ru.marwy.YandexMusicRs.metainfo.xml /app/share/metainfo/ru.marwy.YandexMusicRs.metainfo.xml
- install -Dm644 assets/icons/app_48.png /app/share/icons/hicolor/48x48/apps/yandex-music-rs.png
- install -Dm644 packaging/icons/64x64.png /app/share/icons/hicolor/64x64/apps/yandex-music-rs.png
- install -Dm644 packaging/icons/128x128.png /app/share/icons/hicolor/128x128/apps/yandex-music-rs.png
- install -Dm644 packaging/icons/256x256.png /app/share/icons/hicolor/256x256/apps/yandex-music-rs.png
sources:
- type: dir
path: ../..

View file

@ -0,0 +1,60 @@
# Copyright 2026 marwy
# Distributed under the terms of the GNU General Public License v2
EAPI=8
inherit cargo desktop xdg
DESCRIPTION="Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust"
HOMEPAGE="https://git.tatar/marwy/yandex-music-rs"
SRC_URI="https://git.tatar/marwy/yandex-music-rs/archive/v${PV}.tar.gz -> ${P}.tar.gz"
S="${WORKDIR}/${PN}"
LICENSE="all-rights-reserved"
SLOT="0"
KEYWORDS="~amd64 ~arm64"
IUSE="+webview"
RESTRICT="network-sandbox"
DEPEND="
media-libs/alsa-lib
webview? (
x11-libs/gtk+:3
net-libs/webkit-gtk:4.1
net-libs/libsoup:3.0
)
"
RDEPEND="
${DEPEND}
media-libs/vulkan-loader
media-libs/libglvnd
x11-themes/hicolor-icon-theme
"
BDEPEND="
virtual/pkgconfig
>=virtual/rust-1.80
"
src_compile() {
cargo build --release --bin yandex-music-rs || die
if use webview; then
cargo build --release --features linux-webview --bin yandex-music-auth || die
fi
}
src_install() {
dobin target/release/yandex-music-rs
if use webview; then
dobin target/release/yandex-music-auth
fi
domenu packaging/yandex-music-rs.desktop
insinto /usr/share/metainfo
doins packaging/ru.marwy.YandexMusicRs.metainfo.xml
newicon -s 48 assets/icons/app_48.png yandex-music-rs.png
newicon -s 64 packaging/icons/64x64.png yandex-music-rs.png
newicon -s 128 packaging/icons/128x128.png yandex-music-rs.png
newicon -s 256 packaging/icons/256x256.png yandex-music-rs.png
newicon assets/icons/app_icon.png yandex-music-rs.png
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

208
packaging/install.sh Executable file
View file

@ -0,0 +1,208 @@
#!/usr/bin/env sh
# Universal Linux installer / updater / uninstaller for yandex-music-rs
# Usage:
# curl -fsSL https://git.tatar/marwy/yandex-music-rs/raw/branch/main/packaging/install.sh | sh
# sh install.sh --update
# sh install.sh --uninstall [--purge]
# sh install.sh --version v0.1.9
set -eu
REPO_API="https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases"
REPO_WEB="https://git.tatar/marwy/yandex-music-rs"
APP_NAME="yandex-music-rs"
AUTH_NAME="yandex-music-auth"
PREFIX="${XDG_DATA_HOME:-$HOME/.local/share}"
BIN_DIR="${YM_BIN_DIR:-$HOME/.local/bin}"
APPS_DIR="$PREFIX/applications"
ICONS_DIR="$PREFIX/icons/hicolor"
PIXMAPS_DIR="$PREFIX/pixmaps"
ACTION="install"
PURGE=0
REQ_VERSION=""
# Colors (only when stdout is a TTY)
if [ -t 1 ]; then
C_YEL='\033[1;33m'
C_GRN='\033[1;32m'
C_RED='\033[1;31m'
C_DIM='\033[2m'
C_RST='\033[0m'
else
C_YEL=''; C_GRN=''; C_RED=''; C_DIM=''; C_RST=''
fi
info() { printf "${C_YEL}==>${C_RST} %s\n" "$1"; }
ok() { printf "${C_GRN} ✓ ${C_RST} %s\n" "$1"; }
err() { printf "${C_RED} ✗ ${C_RST} %s\n" "$1" >&2; exit 1; }
while [ "$#" -gt 0 ]; do
case "$1" in
--install|--update|-u) ACTION="install" ;;
--uninstall|--remove) ACTION="uninstall" ;;
--purge) PURGE=1 ;;
--version|-v)
shift
[ "$#" -gt 0 ] || err "--version requires an argument (e.g. v0.1.9)"
REQ_VERSION="$1"
;;
--help|-h)
cat <<EOF
yandex-music-rs universal Linux installer
Usage:
install.sh [OPTIONS]
Options:
--install, --update Install or update yandex-music-rs in ~/.local/bin (default)
--version <vX.Y.Z> Install a specific release tag
--uninstall Remove binaries, desktop entry, and icons
--purge With --uninstall: also remove config and offline cache
-h, --help Show this help
EOF
exit 0
;;
*) err "Unknown option: $1 (try --help)" ;;
esac
shift
done
refresh_desktop_caches() {
if command -v update-desktop-database >/dev/null 2>&1; then
update-desktop-database -q "$APPS_DIR" 2>/dev/null || true
fi
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
gtk-update-icon-cache -q -t -f "$ICONS_DIR" 2>/dev/null || true
fi
}
do_uninstall() {
info "Uninstalling $APP_NAME..."
rm -f "$BIN_DIR/$APP_NAME" "$BIN_DIR/$AUTH_NAME"
rm -f "$APPS_DIR/$APP_NAME.desktop"
rm -f "$PIXMAPS_DIR/$APP_NAME.png"
for sz in 48x48 64x64 128x128 256x256; do
rm -f "$ICONS_DIR/$sz/apps/$APP_NAME.png"
done
if [ "$PURGE" -eq 1 ]; then
rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/YandexMusicRust"
rm -rf "${XDG_CACHE_HOME:-$HOME/.cache}/YandexMusicRust"
ok "Removed user config and offline cache"
fi
refresh_desktop_caches
ok "$APP_NAME has been uninstalled."
exit 0
}
[ "$ACTION" = "uninstall" ] && do_uninstall
# Architecture check
ARCH="$(uname -m)"
case "$ARCH" in
x86_64|amd64) ARCH_TAG="x86_64" ;;
*) err "Prebuilt Linux tarballs are currently x86_64 only (detected: $ARCH). On NixOS/Arch/Gentoo/Void you can build from source." ;;
esac
# HTTP client detection
if command -v curl >/dev/null 2>&1; then
fetch() { curl -fsSL "$1"; }
download() { curl -fL --progress-bar "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
fetch() { wget -qO- "$1"; }
download() { wget -q --show-progress "$1" -O "$2"; }
else
err "Neither curl nor wget is installed."
fi
command -v tar >/dev/null 2>&1 || err "tar is required."
# Resolve release tag
if [ -n "$REQ_VERSION" ]; then
TAG="$REQ_VERSION"
case "$TAG" in v*) ;; *) TAG="v$TAG" ;; esac
else
info "Checking latest release on git.tatar..."
JSON="$(fetch "$REPO_API?limit=1")" || err "Failed to query $REPO_API"
TAG="$(printf '%s' "$JSON" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)"
[ -n "$TAG" ] || err "Could not determine latest release tag."
fi
TAR_NAME="yandex-music-rs-${TAG}-linux-${ARCH_TAG}.tar.gz"
BASE_DL="$REPO_WEB/releases/download/$TAG"
TAR_URL="$BASE_DL/$TAR_NAME"
SHA_URL="$BASE_DL/SHA256SUMS.txt"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT INT TERM
info "Downloading $APP_NAME $TAG ($ARCH_TAG)..."
download "$TAR_URL" "$TMP_DIR/$TAR_NAME" || err "Failed to download $TAR_URL"
# Verify SHA-256 if SHA256SUMS.txt and sha256sum are available
if fetch "$SHA_URL" > "$TMP_DIR/SHA256SUMS.txt" 2>/dev/null; then
EXPECTED="$(awk -v f="$TAR_NAME" '{sub(/^\*/, "", $2); if ($2 == f) {print tolower($1); exit}}' "$TMP_DIR/SHA256SUMS.txt")"
if [ -n "$EXPECTED" ] && command -v sha256sum >/dev/null 2>&1; then
ACTUAL="$(sha256sum "$TMP_DIR/$TAR_NAME" | awk '{print tolower($1)}')"
[ "$ACTUAL" = "$EXPECTED" ] || err "SHA-256 mismatch! Expected $EXPECTED, got $ACTUAL"
ok "SHA-256 verified"
fi
fi
info "Installing binaries to $BIN_DIR..."
mkdir -p "$BIN_DIR" "$APPS_DIR" "$PIXMAPS_DIR"
tar -xzf "$TMP_DIR/$TAR_NAME" -C "$TMP_DIR"
[ -f "$TMP_DIR/$APP_NAME" ] || err "Archive did not contain $APP_NAME"
install -m 755 "$TMP_DIR/$APP_NAME" "$BIN_DIR/$APP_NAME"
if [ -f "$TMP_DIR/$AUTH_NAME" ]; then
install -m 755 "$TMP_DIR/$AUTH_NAME" "$BIN_DIR/$AUTH_NAME"
fi
ok "Installed $BIN_DIR/$APP_NAME"
# Download icons from the matching tag so desktop shortcut looks crisp
info "Installing desktop shortcut and icons..."
RAW_BASE="$REPO_WEB/raw/tag/$TAG"
for pair in "48x48:assets/icons/app_48.png" "64x64:packaging/icons/64x64.png" "128x128:packaging/icons/128x128.png" "256x256:packaging/icons/256x256.png"; do
sz="${pair%%:*}"
rel="${pair#*:}"
mkdir -p "$ICONS_DIR/$sz/apps"
fetch "$RAW_BASE/$rel" > "$ICONS_DIR/$sz/apps/$APP_NAME.png" 2>/dev/null || true
done
if [ -s "$ICONS_DIR/256x256/apps/$APP_NAME.png" ]; then
cp "$ICONS_DIR/256x256/apps/$APP_NAME.png" "$PIXMAPS_DIR/$APP_NAME.png"
fi
cat > "$APPS_DIR/$APP_NAME.desktop" <<EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=Yandex Music
Name[ru]=Яндекс Музыка
GenericName=Music Player
GenericName[ru]=Музыкальный плеер
Comment=Native high-performance Yandex Music desktop client
Comment[ru]=Нативный клиент Яндекс Музыки на Rust
Exec=$BIN_DIR/$APP_NAME %u
Icon=$APP_NAME
Terminal=false
Categories=AudioVideo;Audio;Player;
Keywords=music;yandex;audio;player;музыка;яндекс;
MimeType=x-scheme-handler/yandexmusic;
StartupNotify=true
StartupWMClass=yandex-music-rs
EOF
chmod 644 "$APPS_DIR/$APP_NAME.desktop"
refresh_desktop_caches
ok "Desktop shortcut created ($APPS_DIR/$APP_NAME.desktop)"
case ":$PATH:" in
*":$BIN_DIR:"*) ;;
*)
printf "\n${C_DIM}Note: %s is not in your PATH. Add this to ~/.bashrc or ~/.zshrc:${C_RST}\n" "$BIN_DIR"
printf " export PATH=\"%s:\$PATH\"\n" "$BIN_DIR"
;;
esac
printf "\n${C_GRN}Done!${C_RST} Launch from your app menu or run: ${C_YEL}%s${C_RST}\n" "$APP_NAME"

View file

@ -0,0 +1,71 @@
Name: yandex-music-rs
Version: %{?_ym_version}%{!?_ym_version:2.0.0}
Release: 1%{?dist}
Summary: Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust
License: Proprietary
URL: https://git.tatar/marwy/yandex-music-rs
Requires: alsa-lib
Recommends: vulkan-loader
Recommends: mesa-vulkan-drivers
Recommends: mesa-libGL
Recommends: mesa-libEGL
Recommends: webkit2gtk4.1
# Prebuilt binaries are supplied via _ym_bindir when invoked by packaging/build-rpm.sh
%global debug_package %{nil}
%description
Native high-performance, ultra-low-RAM Yandex Music desktop client built in Rust
with pure ash Vulkan SDF rendering (OpenGL 3.3 Core fallback), taffy layout,
cosmic-text typography, and symphonia + cpal lossless audio engine.
%install
rm -rf %{buildroot}
install -Dm755 "%{_ym_bindir}/yandex-music-rs" "%{buildroot}%{_bindir}/yandex-music-rs"
if [ -f "%{_ym_bindir}/yandex-music-auth" ]; then
install -Dm755 "%{_ym_bindir}/yandex-music-auth" "%{buildroot}%{_bindir}/yandex-music-auth"
fi
install -Dm644 "%{_ym_srcdir}/packaging/yandex-music-rs.desktop" \
"%{buildroot}%{_datadir}/applications/yandex-music-rs.desktop"
install -Dm644 "%{_ym_srcdir}/packaging/ru.marwy.YandexMusicRs.metainfo.xml" \
"%{buildroot}%{_datadir}/metainfo/ru.marwy.YandexMusicRs.metainfo.xml"
install -Dm644 "%{_ym_srcdir}/assets/icons/app_icon.png" \
"%{buildroot}%{_datadir}/pixmaps/yandex-music-rs.png"
install -Dm644 "%{_ym_srcdir}/assets/icons/app_48.png" \
"%{buildroot}%{_datadir}/icons/hicolor/48x48/apps/yandex-music-rs.png"
install -Dm644 "%{_ym_srcdir}/packaging/icons/64x64.png" \
"%{buildroot}%{_datadir}/icons/hicolor/64x64/apps/yandex-music-rs.png"
install -Dm644 "%{_ym_srcdir}/packaging/icons/128x128.png" \
"%{buildroot}%{_datadir}/icons/hicolor/128x128/apps/yandex-music-rs.png"
install -Dm644 "%{_ym_srcdir}/packaging/icons/256x256.png" \
"%{buildroot}%{_datadir}/icons/hicolor/256x256/apps/yandex-music-rs.png"
%post
if [ -x /usr/bin/update-desktop-database ]; then
/usr/bin/update-desktop-database -q %{_datadir}/applications || :
fi
if [ -x /usr/bin/gtk-update-icon-cache ]; then
/usr/bin/gtk-update-icon-cache -q -t -f %{_datadir}/icons/hicolor || :
fi
%postun
if [ -x /usr/bin/update-desktop-database ]; then
/usr/bin/update-desktop-database -q %{_datadir}/applications || :
fi
if [ -x /usr/bin/gtk-update-icon-cache ]; then
/usr/bin/gtk-update-icon-cache -q -t -f %{_datadir}/icons/hicolor || :
fi
%files
%{_bindir}/yandex-music-rs
%{_bindir}/yandex-music-auth
%{_datadir}/applications/yandex-music-rs.desktop
%{_datadir}/metainfo/ru.marwy.YandexMusicRs.metainfo.xml
%{_datadir}/pixmaps/yandex-music-rs.png
%{_datadir}/icons/hicolor/48x48/apps/yandex-music-rs.png
%{_datadir}/icons/hicolor/64x64/apps/yandex-music-rs.png
%{_datadir}/icons/hicolor/128x128/apps/yandex-music-rs.png
%{_datadir}/icons/hicolor/256x256/apps/yandex-music-rs.png

View file

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<component type="desktop-application">
<id>ru.marwy.YandexMusicRs</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>LicenseRef-proprietary</project_license>
<name>Yandex Music</name>
<name xml:lang="ru">Яндекс Музыка</name>
<summary>Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust</summary>
<summary xml:lang="ru">Нативный быстрый десктопный клиент Яндекс Музыки на Rust с минимальным потреблением ОЗУ</summary>
<description>
<p>
yandex-music-rs is a native Rust desktop client for Yandex Music built with a pure
Vulkan SDF UI renderer (with OpenGL 3.3 Core fallback), taffy layout, cosmic-text
typography, and a native symphonia + cpal lossless audio engine.
</p>
<p xml:lang="ru">
yandex-music-rs — нативный клиент Яндекс Музыки на Rust с Vulkan SDF рендерером
(и фолбэком на OpenGL 3.3 Core), поддержкой FLAC Lossless, «Моей волны»,
синхронизированных текстов песен, 10-полосного эквалайзера и системного трея.
</p>
</description>
<launchable type="desktop-id">yandex-music-rs.desktop</launchable>
<url type="homepage">https://git.tatar/marwy/yandex-music-rs</url>
<url type="bugtracker">https://git.tatar/marwy/yandex-music-rs/issues</url>
<developer id="ru.marwy">
<name>marwy</name>
</developer>
<categories>
<category>AudioVideo</category>
<category>Audio</category>
<category>Player</category>
</categories>
<provides>
<binary>yandex-music-rs</binary>
</provides>
<content_rating type="oars-1.1" />
<releases>
<release version="2.0.0" date="2026-11-29">
<url type="details">https://git.tatar/marwy/yandex-music-rs/releases/tag/v2.0.0</url>
</release>
</releases>
</component>

View file

@ -0,0 +1,34 @@
{
"version": "2.0.0",
"description": "Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust",
"homepage": "https://git.tatar/marwy/yandex-music-rs",
"license": "Proprietary",
"architecture": {
"64bit": {
"url": "https://git.tatar/marwy/yandex-music-rs/releases/download/v2.0.0/yandex-music-rs-v2.0.0-windows-x86_64.exe#/yandex-music-rs.exe"
}
},
"bin": "yandex-music-rs.exe",
"shortcuts": [
[
"yandex-music-rs.exe",
"Яндекс Музыка"
]
],
"checkver": {
"url": "https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases?limit=1",
"jsonpath": "$[0].tag_name",
"regex": "v([\\d.]+)"
},
"autoupdate": {
"architecture": {
"64bit": {
"url": "https://git.tatar/marwy/yandex-music-rs/releases/download/v$version/yandex-music-rs-v$version-windows-x86_64.exe#/yandex-music-rs.exe",
"hash": {
"url": "https://git.tatar/marwy/yandex-music-rs/releases/download/v$version/SHA256SUMS.txt",
"regex": "$sha256\\s+yandex-music-rs-v$version-windows-x86_64\\.exe"
}
}
}
}
}

33
packaging/void/template Normal file
View file

@ -0,0 +1,33 @@
# Template file for 'yandex-music-rs' (Void Linux xbps-src)
pkgname=yandex-music-rs
version=2.0.0
revision=1
hostmakedepends="cargo pkg-config"
makedepends="alsa-lib-devel gtk+3-devel webkit2gtk41-devel libsoup3-devel openssl-devel"
depends="alsa-lib hicolor-icon-theme"
short_desc="Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust"
maintainer="marwy <hhhhyetr456@gmail.com>"
license="custom:Proprietary"
homepage="https://git.tatar/marwy/yandex-music-rs"
distfiles="https://git.tatar/marwy/yandex-music-rs/archive/v${version}.tar.gz"
# Update checksum via `xgensum -i template`
checksum=SKIP
do_build() {
cargo build --release --locked --bin yandex-music-rs
cargo build --release --locked --features linux-webview --bin yandex-music-auth
}
do_install() {
vbin target/release/yandex-music-rs
vbin target/release/yandex-music-auth
vinstall packaging/yandex-music-rs.desktop 644 usr/share/applications
vinstall packaging/ru.marwy.YandexMusicRs.metainfo.xml 644 usr/share/metainfo
vinstall assets/icons/app_icon.png 644 usr/share/pixmaps yandex-music-rs.png
vinstall assets/icons/app_48.png 644 usr/share/icons/hicolor/48x48/apps yandex-music-rs.png
vinstall packaging/icons/64x64.png 644 usr/share/icons/hicolor/64x64/apps yandex-music-rs.png
vinstall packaging/icons/128x128.png 644 usr/share/icons/hicolor/128x128/apps yandex-music-rs.png
vinstall packaging/icons/256x256.png 644 usr/share/icons/hicolor/256x256/apps yandex-music-rs.png
}

431
packaging/windows/installer/Cargo.lock generated Normal file
View file

@ -0,0 +1,431 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "byteorder-lite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [
"cfg-if",
]
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]]
name = "image"
version = "0.25.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
dependencies = [
"bytemuck",
"byteorder-lite",
"moxcms",
"num-traits",
"png",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "moxcms"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
dependencies = [
"num-traits",
"pxfm",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "png"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pxfm"
version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_spanned"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
dependencies = [
"serde_core",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "toml"
version = "1.2.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"
dependencies = [
"serde_core",
]
[[package]]
name = "toml_parser"
version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.2.0+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "windows"
version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-link",
"windows-numerics",
]
[[package]]
name = "windows-collections"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core",
]
[[package]]
name = "windows-core"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
name = "windows-future"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
name = "windows-implement"
version = "0.60.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-numerics"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core",
"windows-link",
]
[[package]]
name = "windows-result"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"
dependencies = [
"windows-link",
]
[[package]]
name = "windows-threading"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"
dependencies = [
"windows-link",
]
[[package]]
name = "winnow"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
[[package]]
name = "winresource"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
dependencies = [
"toml",
"version_check",
]
[[package]]
name = "yandex-music-rs-setup"
version = "0.1.9"
dependencies = [
"flate2",
"image",
"windows",
"windows-numerics",
"winresource",
]
[[package]]
name = "zlib-rs"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"

View file

@ -0,0 +1,50 @@
[package]
name = "yandex-music-rs-setup"
version = "2.0.0"
edition = "2021"
description = "Pure native Win32 + Direct2D Yandex Music desktop client installer"
[[bin]]
name = "yandex-music-rs-setup"
path = "src/main.rs"
[dependencies]
flate2 = "1"
image = { version = "0.25", default-features = false, features = ["png"] }
[target.'cfg(windows)'.dependencies]
windows-numerics = "0.2"
windows = { version = "0.61", features = [
"Win32_Foundation",
"Win32_Graphics_Direct2D",
"Win32_Graphics_Direct2D_Common",
"Win32_Graphics_DirectWrite",
"Win32_Graphics_Dwm",
"Win32_Graphics_Dxgi_Common",
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_LibraryLoader",
"Win32_System_Registry",
"Win32_System_Variant",
"Win32_UI_HiDpi",
"Win32_UI_Input_KeyboardAndMouse",
"Win32_UI_Shell",
"Win32_UI_Shell_Common",
"Win32_UI_Shell_PropertiesSystem",
"Win32_UI_WindowsAndMessaging",
] }
[build-dependencies]
flate2 = "1"
[target.'cfg(windows)'.build-dependencies]
winresource = "0.1"
[profile.release]
opt-level = "z"
lto = "thin"
codegen-units = 1
strip = true
panic = "abort"

View file

@ -0,0 +1,100 @@
use flate2::write::GzEncoder;
use flate2::Compression;
use std::env;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
fn read_root_version(root_cargo_toml: &Path) -> String {
if let Ok(text) = fs::read_to_string(root_cargo_toml) {
for line in text.lines() {
let trimmed = line.trim();
if let Some(rest) = trimmed.strip_prefix("version") {
if let Some(val) = rest.trim().strip_prefix('=') {
let v = val.trim().trim_matches('"').trim_matches('\'');
if !v.is_empty() {
return v.to_string();
}
}
}
}
}
env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "0.1.9".to_string())
}
fn main() {
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
let repo_root = manifest_dir
.parent()
.and_then(|p| p.parent())
.and_then(|p| p.parent())
.expect("installer must live under packaging/windows/installer");
let root_cargo = repo_root.join("Cargo.toml");
println!("cargo:rerun-if-changed={}", root_cargo.display());
println!("cargo:rerun-if-env-changed=YM_PAYLOAD_EXE");
println!("cargo:rerun-if-env-changed=YM_ALLOW_EMPTY_PAYLOAD");
let app_version = read_root_version(&root_cargo);
println!("cargo:rustc-env=YM_APP_VERSION={}", app_version);
let payload_src = env::var("YM_PAYLOAD_EXE")
.map(PathBuf::from)
.unwrap_or_else(|_| repo_root.join("target").join("release").join("yandex-music-rs.exe"));
println!("cargo:rerun-if-changed={}", payload_src.display());
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let payload_gz = out_dir.join("payload.gz");
let raw_bytes = if payload_src.exists() {
fs::read(&payload_src).unwrap_or_else(|e| {
panic!(
"Failed to read app binary {}: {}",
payload_src.display(),
e
)
})
} else if env::var("YM_ALLOW_EMPTY_PAYLOAD").as_deref() == Ok("1") {
println!(
"cargo:warning=Using empty placeholder payload because {} does not exist",
payload_src.display()
);
Vec::new()
} else {
panic!(
"App binary not found at {}. Run `cargo build --release` in repo root first (or set YM_PAYLOAD_EXE).",
payload_src.display()
);
};
let uncompressed_kb = ((raw_bytes.len() as u64) + 1023) / 1024;
println!("cargo:rustc-env=YM_PAYLOAD_KB={}", uncompressed_kb.max(1));
let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
encoder
.write_all(&raw_bytes)
.expect("Failed to compress payload");
let compressed = encoder.finish().expect("Failed to finish gzip stream");
fs::write(&payload_gz, compressed).expect("Failed to write payload.gz");
#[cfg(target_os = "windows")]
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let ico = repo_root
.join("packaging")
.join("icons")
.join("yandex-music-rs.ico");
println!("cargo:rerun-if-changed={}", ico.display());
if ico.exists() {
let mut res = winresource::WindowsResource::new();
res.set_icon(ico.to_string_lossy().as_ref());
res.set("ProductName", "Яндекс Музыка — Установщик");
res.set("FileDescription", "Yandex Music Desktop Client Installer");
res.set("CompanyName", "marwy");
res.set("ProductVersion", &app_version);
res.set("FileVersion", &app_version);
if let Err(e) = res.compile() {
println!("cargo:warning=winresource failed: {}", e);
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,622 @@
#![cfg(windows)]
use flate2::read::GzDecoder;
use std::fs;
use std::io::Read;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::Duration;
use windows::core::{Interface, GUID, HSTRING, PCWSTR, PWSTR};
use windows::Win32::Foundation::{HWND, PROPERTYKEY};
use windows::Win32::Graphics::Dwm::{
DwmSetWindowAttribute, DWMWA_USE_IMMERSIVE_DARK_MODE, DWMWA_WINDOW_CORNER_PREFERENCE,
DWMWCP_ROUND,
};
use windows::Win32::System::Com::StructuredStorage::PROPVARIANT;
use windows::Win32::System::Com::{
CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, IPersistFile,
CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED,
};
use windows::Win32::System::Registry::{
RegCloseKey, RegCreateKeyExW, RegDeleteTreeW, RegDeleteValueW, RegOpenKeyExW,
RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_DWORD,
REG_OPTION_NON_VOLATILE, REG_SZ,
};
use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore;
use windows::Win32::UI::Shell::{
FOLDERID_Desktop, FOLDERID_Programs, FileOpenDialog, IFileOpenDialog, IShellLinkW,
SHGetKnownFolderPath, ShellLink, FOS_FORCEFILESYSTEM, FOS_PICKFOLDERS, KF_FLAG_DEFAULT,
SIGDN_FILESYSPATH,
};
pub const APP_VERSION: &str = env!("YM_APP_VERSION");
const PAYLOAD_GZ: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/payload.gz"));
const UNINSTALL_REG_SUBKEY: &str =
r"Software\Microsoft\Windows\CurrentVersion\Uninstall\YandexMusicRs";
const RUN_REG_SUBKEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE_NAME: &str = "YandexMusicRs";
const APP_EXE_NAME: &str = "yandex-music-rs.exe";
const UNINSTALL_EXE_NAME: &str = "uninstall.exe";
const SHORTCUT_NAME: &str = "Яндекс Музыка.lnk";
const APP_USER_MODEL_ID: &str = "ru.marwy.yandex-music-rs";
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// PKEY_AppUserModel_ID = {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 5
const PKEY_APP_USER_MODEL_ID: PROPERTYKEY = PROPERTYKEY {
fmtid: GUID::from_u128(0x9F4C2855_9F79_4B39_A8D0_E1D42DE1D5F3),
pid: 5,
};
#[derive(Debug, Clone)]
pub struct ExistingInstall {
pub installed: bool,
pub installed_version: Option<String>,
pub install_dir: String,
pub target_version: String,
pub has_desktop_shortcut: bool,
pub has_start_menu_shortcut: bool,
pub has_autostart: bool,
pub mode: String, // "install" | "update" | "reinstall" | "uninstall"
}
#[derive(Debug, Clone)]
pub struct InstallOptions {
pub install_dir: String,
pub desktop_shortcut: bool,
pub start_menu_shortcut: bool,
pub autostart: bool,
pub launch_after: bool,
}
#[derive(Debug, Clone)]
pub struct UninstallOptions {
pub remove_user_data: bool,
}
struct ComGuard;
impl ComGuard {
fn init() -> Self {
unsafe {
let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
}
Self
}
}
impl Drop for ComGuard {
fn drop(&mut self) {
unsafe {
CoUninitialize();
}
}
}
fn wide_null(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
pub fn apply_window_chrome(hwnd: isize) {
let hwnd = HWND(hwnd as *mut _);
unsafe {
let dark: i32 = 1;
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_USE_IMMERSIVE_DARK_MODE,
&dark as *const _ as *const _,
std::mem::size_of::<i32>() as u32,
);
let corner = DWMWCP_ROUND;
let _ = DwmSetWindowAttribute(
hwnd,
DWMWA_WINDOW_CORNER_PREFERENCE,
&corner as *const _ as *const _,
std::mem::size_of_val(&corner) as u32,
);
}
}
pub fn default_install_dir() -> PathBuf {
if let Ok(local) = std::env::var("LOCALAPPDATA") {
PathBuf::from(local).join("Programs").join("YandexMusicRs")
} else if let Ok(profile) = std::env::var("USERPROFILE") {
PathBuf::from(profile)
.join("AppData")
.join("Local")
.join("Programs")
.join("YandexMusicRs")
} else {
PathBuf::from(r"C:\YandexMusicRs")
}
}
fn known_folder_path(folder_id: &GUID) -> Option<PathBuf> {
unsafe {
let ptr: PWSTR = SHGetKnownFolderPath(folder_id, KF_FLAG_DEFAULT, None).ok()?;
let s = ptr.to_string().ok();
CoTaskMemFree(Some(ptr.0 as *const _));
s.map(PathBuf::from)
}
}
fn desktop_shortcut_path() -> Option<PathBuf> {
known_folder_path(&FOLDERID_Desktop).map(|d| d.join(SHORTCUT_NAME))
}
fn start_menu_shortcut_path() -> Option<PathBuf> {
known_folder_path(&FOLDERID_Programs).map(|p| p.join(SHORTCUT_NAME))
}
fn reg_read_string(subkey: &str, value_name: &str) -> Option<String> {
let subkey_w = wide_null(subkey);
let value_w = wide_null(value_name);
unsafe {
let mut hkey = HKEY::default();
if RegOpenKeyExW(
HKEY_CURRENT_USER,
PCWSTR(subkey_w.as_ptr()),
Some(0),
KEY_READ,
&mut hkey,
)
.is_err()
{
return None;
}
let mut size: u32 = 0;
let query_len = RegQueryValueExW(
hkey,
PCWSTR(value_w.as_ptr()),
None,
None,
None,
Some(&mut size),
);
if query_len.is_err() || size < 2 {
let _ = RegCloseKey(hkey);
return None;
}
let mut buf: Vec<u16> = vec![0u16; (size as usize + 1) / 2];
let query_val = RegQueryValueExW(
hkey,
PCWSTR(value_w.as_ptr()),
None,
None,
Some(buf.as_mut_ptr() as *mut u8),
Some(&mut size),
);
let _ = RegCloseKey(hkey);
if query_val.is_err() {
return None;
}
let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
Some(String::from_utf16_lossy(&buf[..end]))
}
}
fn reg_write_sz(hkey: HKEY, name: &str, value: &str) -> Result<(), String> {
let name_w = wide_null(name);
let val_w = wide_null(value);
let bytes =
unsafe { std::slice::from_raw_parts(val_w.as_ptr() as *const u8, val_w.len() * 2) };
unsafe {
RegSetValueExW(hkey, PCWSTR(name_w.as_ptr()), Some(0), REG_SZ, Some(bytes))
.ok()
.map_err(|e| format!("RegSetValueExW({name}): {e}"))
}
}
fn reg_write_dword(hkey: HKEY, name: &str, value: u32) -> Result<(), String> {
let name_w = wide_null(name);
let bytes = value.to_le_bytes();
unsafe {
RegSetValueExW(
hkey,
PCWSTR(name_w.as_ptr()),
Some(0),
REG_DWORD,
Some(&bytes),
)
.ok()
.map_err(|e| format!("RegSetValueExW({name}): {e}"))
}
}
pub fn detect_existing_install(uninstall_flag: bool) -> ExistingInstall {
let default_dir = default_install_dir();
let reg_dir = reg_read_string(UNINSTALL_REG_SUBKEY, "InstallLocation");
let reg_ver = reg_read_string(UNINSTALL_REG_SUBKEY, "DisplayVersion");
let candidate_dir = reg_dir
.as_deref()
.map(PathBuf::from)
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| default_dir.clone());
let exe_exists = candidate_dir.join(APP_EXE_NAME).exists();
let installed = exe_exists || reg_ver.is_some();
let has_desktop = desktop_shortcut_path().map_or(false, |p| p.exists());
let has_start = start_menu_shortcut_path().map_or(false, |p| p.exists());
let has_autostart = reg_read_string(RUN_REG_SUBKEY, RUN_VALUE_NAME).is_some();
let mode = if uninstall_flag {
"uninstall".to_string()
} else if !installed {
"install".to_string()
} else if reg_ver.as_deref() == Some(APP_VERSION) {
"reinstall".to_string()
} else {
"update".to_string()
};
ExistingInstall {
installed,
installed_version: reg_ver,
install_dir: candidate_dir.to_string_lossy().to_string(),
target_version: APP_VERSION.to_string(),
has_desktop_shortcut: if installed { has_desktop } else { true },
has_start_menu_shortcut: if installed { has_start } else { true },
has_autostart,
mode,
}
}
pub fn pick_folder_dialog(initial: Option<&str>) -> Option<String> {
let _com = ComGuard::init();
unsafe {
let dialog: IFileOpenDialog =
CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER).ok()?;
let mut opts = dialog.GetOptions().ok()?;
opts |= FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM;
dialog.SetOptions(opts).ok()?;
let _ = dialog.SetTitle(&HSTRING::from("Выберите папку установки"));
let _ = initial; // keep dialog clean even if folder does not exist yet
if dialog.Show(None).is_err() {
return None;
}
let item = dialog.GetResult().ok()?;
let path_pwstr = item.GetDisplayName(SIGDN_FILESYSPATH).ok()?;
let result = path_pwstr.to_string().ok();
CoTaskMemFree(Some(path_pwstr.0 as *const _));
result
}
}
fn close_running_app() {
let _ = Command::new("taskkill")
.args(["/IM", APP_EXE_NAME])
.creation_flags(CREATE_NO_WINDOW)
.output();
// Give graceful close up to 1.5s, then force-close if still alive
for _ in 0..6 {
thread::sleep(Duration::from_millis(250));
let out = Command::new("tasklist")
.args(["/FI", &format!("IMAGENAME eq {}", APP_EXE_NAME), "/NH"])
.creation_flags(CREATE_NO_WINDOW)
.output();
if let Ok(o) = out {
let stdout = String::from_utf8_lossy(&o.stdout);
if !stdout
.to_ascii_lowercase()
.contains(&APP_EXE_NAME.to_ascii_lowercase())
{
return;
}
}
}
let _ = Command::new("taskkill")
.args(["/F", "/IM", APP_EXE_NAME])
.creation_flags(CREATE_NO_WINDOW)
.output();
thread::sleep(Duration::from_millis(350));
}
fn create_shortcut(
lnk_path: &Path,
target_exe: &Path,
working_dir: &Path,
description: &str,
) -> Result<(), String> {
let _com = ComGuard::init();
if let Some(parent) = lnk_path.parent() {
let _ = fs::create_dir_all(parent);
}
unsafe {
let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)
.map_err(|e| format!("CoCreateInstance(ShellLink): {e}"))?;
let target_w = wide_null(&target_exe.to_string_lossy());
let work_w = wide_null(&working_dir.to_string_lossy());
let desc_w = wide_null(description);
link.SetPath(PCWSTR(target_w.as_ptr()))
.map_err(|e| format!("SetPath: {e}"))?;
link.SetWorkingDirectory(PCWSTR(work_w.as_ptr()))
.map_err(|e| format!("SetWorkingDirectory: {e}"))?;
link.SetIconLocation(PCWSTR(target_w.as_ptr()), 0)
.map_err(|e| format!("SetIconLocation: {e}"))?;
link.SetDescription(PCWSTR(desc_w.as_ptr()))
.map_err(|e| format!("SetDescription: {e}"))?;
if let Ok(store) = link.cast::<IPropertyStore>() {
let val = PROPVARIANT::from(APP_USER_MODEL_ID);
let _ = store.SetValue(&PKEY_APP_USER_MODEL_ID, &val);
let _ = store.Commit();
}
let persist: IPersistFile = link
.cast()
.map_err(|e| format!("cast IPersistFile: {e}"))?;
let lnk_w = wide_null(&lnk_path.to_string_lossy());
persist
.Save(PCWSTR(lnk_w.as_ptr()), true)
.map_err(|e| format!("IPersistFile::Save: {e}"))?;
}
Ok(())
}
fn set_autostart(exe_path: Option<&Path>) -> Result<(), String> {
let subkey_w = wide_null(RUN_REG_SUBKEY);
let val_name_w = wide_null(RUN_VALUE_NAME);
unsafe {
let mut hkey = HKEY::default();
RegCreateKeyExW(
HKEY_CURRENT_USER,
PCWSTR(subkey_w.as_ptr()),
Some(0),
PCWSTR::null(),
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
None,
&mut hkey,
None,
)
.ok()
.map_err(|e| format!("RegCreateKeyExW(Run): {e}"))?;
let res = match exe_path {
Some(path) => reg_write_sz(hkey, RUN_VALUE_NAME, &format!("\"{}\"", path.display())),
None => {
let _ = RegDeleteValueW(hkey, PCWSTR(val_name_w.as_ptr()));
Ok(())
}
};
let _ = RegCloseKey(hkey);
res
}
}
fn write_uninstall_registry(
install_dir: &Path,
exe_path: &Path,
uninstall_exe: &Path,
size_kb: u32,
) -> Result<(), String> {
let subkey_w = wide_null(UNINSTALL_REG_SUBKEY);
unsafe {
let mut hkey = HKEY::default();
RegCreateKeyExW(
HKEY_CURRENT_USER,
PCWSTR(subkey_w.as_ptr()),
Some(0),
PCWSTR::null(),
REG_OPTION_NON_VOLATILE,
KEY_WRITE,
None,
&mut hkey,
None,
)
.ok()
.map_err(|e| format!("RegCreateKeyExW(Uninstall): {e}"))?;
let res = (|| {
reg_write_sz(hkey, "DisplayName", "Яндекс Музыка (yandex-music-rs)")?;
reg_write_sz(hkey, "DisplayVersion", APP_VERSION)?;
reg_write_sz(hkey, "Publisher", "marwy")?;
reg_write_sz(hkey, "DisplayIcon", &format!("{},0", exe_path.display()))?;
reg_write_sz(hkey, "InstallLocation", &install_dir.to_string_lossy())?;
reg_write_sz(
hkey,
"UninstallString",
&format!("\"{}\" --uninstall", uninstall_exe.display()),
)?;
reg_write_sz(
hkey,
"URLInfoAbout",
"https://git.tatar/marwy/yandex-music-rs",
)?;
reg_write_dword(hkey, "EstimatedSize", size_kb)?;
reg_write_dword(hkey, "NoModify", 1)?;
reg_write_dword(hkey, "NoRepair", 1)?;
Ok(())
})();
let _ = RegCloseKey(hkey);
res
}
}
fn delete_uninstall_registry() {
let subkey_w = wide_null(UNINSTALL_REG_SUBKEY);
unsafe {
let _ = RegDeleteTreeW(HKEY_CURRENT_USER, PCWSTR(subkey_w.as_ptr()));
}
}
pub fn install_or_update<F>(opts: &InstallOptions, mut on_progress: F) -> Result<PathBuf, String>
where
F: FnMut(u8, &str),
{
let install_dir = PathBuf::from(opts.install_dir.trim());
if install_dir.as_os_str().is_empty() {
return Err("Не указана папка установки".into());
}
on_progress(10, "step_closing");
close_running_app();
on_progress(25, "step_preparing");
fs::create_dir_all(&install_dir)
.map_err(|e| format!("Не удалось создать папку {}: {}", install_dir.display(), e))?;
on_progress(45, "step_extracting");
let mut decoder = GzDecoder::new(PAYLOAD_GZ);
let mut exe_bytes = Vec::new();
decoder
.read_to_end(&mut exe_bytes)
.map_err(|e| format!("Ошибка распаковки приложения: {}", e))?;
if exe_bytes.is_empty() {
return Err("В установщик не встроен бинарник yandex-music-rs.exe".into());
}
let target_exe = install_dir.join(APP_EXE_NAME);
let temp_exe = install_dir.join("yandex-music-rs.exe.tmp");
fs::write(&temp_exe, &exe_bytes)
.map_err(|e| format!("Не удалось записать файл {}: {}", temp_exe.display(), e))?;
if let Err(e) = fs::rename(&temp_exe, &target_exe) {
// Retry once after brief wait if antivirus/handle was holding target
thread::sleep(Duration::from_millis(400));
if let Err(_) = fs::remove_file(&target_exe) {}
fs::rename(&temp_exe, &target_exe).map_err(|e2| {
let _ = fs::remove_file(&temp_exe);
format!("Не удалось заменить {}: {} ({})", target_exe.display(), e2, e)
})?;
}
on_progress(68, "step_uninstaller");
let uninstall_exe = install_dir.join(UNINSTALL_EXE_NAME);
if let Ok(self_exe) = std::env::current_exe() {
let same_file = self_exe
.canonicalize()
.ok()
.zip(uninstall_exe.canonicalize().ok())
.map_or(false, |(a, b)| a == b);
if !same_file {
let _ = fs::copy(&self_exe, &uninstall_exe);
}
}
on_progress(82, "step_shortcuts");
if let Some(desk_lnk) = desktop_shortcut_path() {
if opts.desktop_shortcut {
create_shortcut(
&desk_lnk,
&target_exe,
&install_dir,
"Яндекс Музыка (yandex-music-rs)",
)?;
} else if desk_lnk.exists() {
let _ = fs::remove_file(desk_lnk);
}
}
if let Some(start_lnk) = start_menu_shortcut_path() {
if opts.start_menu_shortcut {
create_shortcut(
&start_lnk,
&target_exe,
&install_dir,
"Яндекс Музыка (yandex-music-rs)",
)?;
} else if start_lnk.exists() {
let _ = fs::remove_file(start_lnk);
}
}
on_progress(92, "step_registry");
let size_kb = (((exe_bytes.len() as u64) + 1023) / 1024).max(1) as u32;
write_uninstall_registry(&install_dir, &target_exe, &uninstall_exe, size_kb)?;
set_autostart(if opts.autostart {
Some(&target_exe)
} else {
None
})?;
on_progress(100, "step_done");
Ok(target_exe)
}
pub fn uninstall_app<F>(
install_dir_str: &str,
opts: &UninstallOptions,
mut on_progress: F,
) -> Result<bool, String>
where
F: FnMut(u8, &str),
{
let install_dir = PathBuf::from(install_dir_str.trim());
on_progress(15, "step_closing");
close_running_app();
on_progress(40, "step_removing_files");
let app_exe = install_dir.join(APP_EXE_NAME);
if app_exe.exists() {
let _ = fs::remove_file(&app_exe);
}
on_progress(60, "step_removing_shortcuts");
if let Some(desk_lnk) = desktop_shortcut_path() {
let _ = fs::remove_file(desk_lnk);
}
if let Some(start_lnk) = start_menu_shortcut_path() {
let _ = fs::remove_file(start_lnk);
}
on_progress(75, "step_removing_registry");
let _ = set_autostart(None);
delete_uninstall_registry();
if opts.remove_user_data {
on_progress(88, "step_removing_data");
if let Ok(appdata) = std::env::var("APPDATA") {
let _ = fs::remove_dir_all(PathBuf::from(appdata).join("YandexMusicRust"));
}
if let Ok(local) = std::env::var("LOCALAPPDATA") {
let _ = fs::remove_dir_all(PathBuf::from(local).join("YandexMusicRust"));
}
}
// Check whether we are currently running as `<install_dir>\uninstall.exe`
let uninstall_exe = install_dir.join(UNINSTALL_EXE_NAME);
let running_from_install_dir = std::env::current_exe()
.ok()
.and_then(|p| p.canonicalize().ok())
.zip(uninstall_exe.canonicalize().ok())
.map_or(false, |(a, b)| a == b);
if !running_from_install_dir {
let _ = fs::remove_file(&uninstall_exe);
let _ = fs::remove_dir(&install_dir);
}
on_progress(100, "step_uninstalled");
Ok(running_from_install_dir)
}
pub fn schedule_self_cleanup(install_dir_str: &str) {
let install_dir = PathBuf::from(install_dir_str.trim());
let uninstall_exe = install_dir.join(UNINSTALL_EXE_NAME);
let cmd = format!(
"ping 127.0.0.1 -n 3 >NUL & del /F /Q \"{}\" >NUL 2>&1 & rmdir \"{}\" >NUL 2>&1",
uninstall_exe.display(),
install_dir.display()
);
let _ = Command::new("cmd.exe")
.args(["/C", &cmd])
.creation_flags(CREATE_NO_WINDOW)
.spawn();
}
pub fn launch_app(exe_path: &Path) -> Result<(), String> {
let mut cmd = Command::new(exe_path);
if let Some(dir) = exe_path.parent() {
cmd.current_dir(dir);
}
cmd.spawn()
.map(|_| ())
.map_err(|e| format!("Не удалось запустить приложение: {}", e))
}

View file

@ -0,0 +1,23 @@
# yaml-language-server: $schema=https://aka.ms/winget-manifest.installer.1.9.0.schema.json
PackageIdentifier: marwy.YandexMusicRs
PackageVersion: 2.0.0
InstallerType: exe
Scope: user
InstallModes:
- interactive
- silent
InstallerSwitches:
Silent: --silent
SilentWithProgress: --silent
InstallLocation: --dir "<INSTALLPATH>"
UpgradeBehavior: install
AppsAndFeaturesEntries:
- DisplayName: Яндекс Музыка (yandex-music-rs)
Publisher: marwy
DisplayVersion: 2.0.0
Installers:
- Architecture: x64
InstallerUrl: https://git.tatar/marwy/yandex-music-rs/releases/download/v2.0.0/yandex-music-rs-v2.0.0-windows-x86_64-setup.exe
InstallerSha256: REPLACE_WITH_RELEASE_SHA256
ManifestType: installer
ManifestVersion: 1.9.0

View file

@ -0,0 +1,18 @@
# yaml-language-server: $schema=https://aka.ms/winget-manifest.locale.1.9.0.schema.json
PackageIdentifier: marwy.YandexMusicRs
PackageVersion: 2.0.0
PackageLocale: en-US
Publisher: marwy
PublisherUrl: https://git.tatar/marwy
PackageName: Yandex Music (yandex-music-rs)
PackageUrl: https://git.tatar/marwy/yandex-music-rs
License: Proprietary
ShortDescription: Native high-performance, ultra-low-RAM Yandex Music desktop client in Rust
Tags:
- music
- yandex
- yandex-music
- player
- rust
ManifestType: locale
ManifestVersion: 1.9.0

View file

@ -0,0 +1,19 @@
# yaml-language-server: $schema=https://aka.ms/winget-manifest.defaultLocale.1.9.0.schema.json
PackageIdentifier: marwy.YandexMusicRs
PackageVersion: 2.0.0
PackageLocale: ru-RU
Publisher: marwy
PublisherUrl: https://git.tatar/marwy
PackageName: Яндекс Музыка (yandex-music-rs)
PackageUrl: https://git.tatar/marwy/yandex-music-rs
License: Proprietary
ShortDescription: Нативный высокопроизводительный клиент Яндекс Музыки на Rust
Description: Нативный десктопный клиент Яндекс Музыки на Rust с Vulkan SDF рендерером (фолбэк на OpenGL 3.3), поддержкой FLAC Lossless, «Моей волны», синхронизированных текстов и системного трея.
Tags:
- music
- yandex
- yandex-music
- player
- rust
ManifestType: defaultLocale
ManifestVersion: 1.9.0

View file

@ -0,0 +1,6 @@
# yaml-language-server: $schema=https://aka.ms/winget-manifest.version.1.9.0.schema.json
PackageIdentifier: marwy.YandexMusicRs
PackageVersion: 2.0.0
DefaultLocale: ru-RU
ManifestType: version
ManifestVersion: 1.9.0

View file

@ -26,6 +26,7 @@ const uint MODE_SHADOW = 5u;
const uint MODE_LINE = 6u; const uint MODE_LINE = 6u;
const uint FLAG_RING_ONLY = 1u; const uint FLAG_RING_ONLY = 1u;
const uint FLAG_LUMINOSITY_BLEND = 2u;
vec4 unpack_rgba(uint rgba) { vec4 unpack_rgba(uint rgba) {
float r = float(rgba & 255u) * (1.0 / 255.0); float r = float(rgba & 255u) * (1.0 / 255.0);
@ -110,7 +111,7 @@ void main() {
discard; discard;
} }
float fg_luma = dot(c_start.rgb, vec3(0.299, 0.587, 0.114)); float fg_luma = dot(c_start.rgb, vec3(0.299, 0.587, 0.114));
float glyph_gamma = mix(0.92, 0.66, fg_luma); float glyph_gamma = mix(1.05, 0.56, smoothstep(0.15, 0.75, fg_luma));
float cov = pow(clamp(cov_raw, 0.0, 1.0), glyph_gamma); float cov = pow(clamp(cov_raw, 0.0, 1.0), glyph_gamma);
float a = cov * c_start.a * clip_cov; float a = cov * c_start.a * clip_cov;
if (a <= 0.0001) { if (a <= 0.0001) {
@ -203,8 +204,31 @@ void main() {
float max_ratio = max(texels_per_px.x, texels_per_px.y); float max_ratio = max(texels_per_px.x, texels_per_px.y);
float lod = max(log2(max(max_ratio, 1.0)) - 0.25, 0.0); float lod = max(log2(max(max_ratio, 1.0)) - 0.25, 0.0);
vec4 tex = textureLod(u_tex, uv, lod); vec4 tex = textureLod(u_tex, uv, lod);
float scale = c_start.a * outer_cov; if ((v_meta.z & FLAG_LUMINOSITY_BLEND) != 0u) {
fill_pm = vec4(tex.rgb * c_start.rgb * scale, tex.a * scale); // Exact W3C Compositing & Blending Level 1 `mix-blend-mode: luminosity` + `opacity` over `c_start`
vec3 cs = tex.rgb / max(tex.a, 1e-5);
vec3 cb = c_start.rgb;
float lum_s = dot(cs, vec3(0.3, 0.59, 0.11));
float lum_b = dot(cb, vec3(0.3, 0.59, 0.11));
vec3 c = cb + vec3(lum_s - lum_b);
float l = dot(c, vec3(0.3, 0.59, 0.11));
float n = min(c.r, min(c.g, c.b));
float x = max(c.r, max(c.g, c.b));
if (n < 0.0) {
c = vec3(l) + ((c - vec3(l)) * l) / max(l - n, 1e-5);
}
if (x > 1.0) {
c = vec3(l) + ((c - vec3(l)) * (1.0 - l)) / max(x - l, 1e-5);
}
float mix_a = clamp(v_metrics.z, 0.0, 1.0) * tex.a;
float bright = (v_metrics.w > 0.0) ? v_metrics.w : 1.0;
vec3 out_rgb = clamp(mix(cb, c, mix_a) * bright, vec3(0.0), vec3(1.0));
float fa = c_start.a * outer_cov;
fill_pm = vec4(out_rgb * fa, fa);
} else {
float scale = c_start.a * outer_cov;
fill_pm = vec4(tex.rgb * c_start.rgb * scale, tex.a * scale);
}
} else if (mode == MODE_BACKDROP_BLUR) { } else if (mode == MODE_BACKDROP_BLUR) {
vec2 sz = max(u_screen_size, vec2(1.0)); vec2 sz = max(u_screen_size, vec2(1.0));
vec2 screen_uv = clamp(vec2(v_frag_pos.x / sz.x, 1.0 - v_frag_pos.y / sz.y), vec2(0.0), vec2(1.0)); vec2 screen_uv = clamp(vec2(v_frag_pos.x / sz.x, 1.0 - v_frag_pos.y / sz.y), vec2(0.0), vec2(1.0));

View file

@ -42,6 +42,7 @@ const MODE_SHADOW: u32 = 5u;
const MODE_LINE: u32 = 6u; const MODE_LINE: u32 = 6u;
const FLAG_RING_ONLY: u32 = 1u; const FLAG_RING_ONLY: u32 = 1u;
const FLAG_LUMINOSITY_BLEND: u32 = 2u;
struct VertOut { struct VertOut {
@builtin(position) pos: vec4<f32>, @builtin(position) pos: vec4<f32>,
@ -202,9 +203,9 @@ fn fs_main(in: VertOut) -> @location(0) vec4<f32> {
let c_start = unpack_rgba(inst.colors.x); let c_start = unpack_rgba(inst.colors.x);
let border_w = inst.metrics.x; let border_w = inst.metrics.x;
// MODE_GLYPH: R8 coverage mask from cosmic-text/swash glyph atlas // MODE_GLYPH: R8 coverage mask from DirectWrite (Windows) / swash (Linux/macOS) glyph atlas
// Applies perceptual Windows DirectWrite/Chromium stem darkening on UNORM swapchain: // Applies exact sRGB-linear blending on UNORM swapchain (1/2.2 ~= 0.45 for light-on-dark,
// light glyphs on dark backgrounds get gamma=0.66; dark glyphs on light backgrounds stay crisp at gamma=0.92. // 1.05 for dark-on-light), matching Chromium / DirectWrite gamma-correct text compositing 1-to-1.
if (mode == MODE_GLYPH) { if (mode == MODE_GLYPH) {
let local = clamp((in.frag_pos - inst.rect.xy) / max(inst.rect.zw, vec2<f32>(1e-5)), vec2<f32>(0.0), vec2<f32>(1.0)); let local = clamp((in.frag_pos - inst.rect.xy) / max(inst.rect.zw, vec2<f32>(1e-5)), vec2<f32>(0.0), vec2<f32>(1.0));
let uv = mix(inst.uv_or_params.xy, inst.uv_or_params.zw, local); let uv = mix(inst.uv_or_params.xy, inst.uv_or_params.zw, local);
@ -213,7 +214,9 @@ fn fs_main(in: VertOut) -> @location(0) vec4<f32> {
discard; discard;
} }
let fg_luma = dot(c_start.rgb, vec3<f32>(0.299, 0.587, 0.114)); let fg_luma = dot(c_start.rgb, vec3<f32>(0.299, 0.587, 0.114));
let glyph_gamma = mix(0.92, 0.66, fg_luma); // Chromium/Skia on Windows uses ~1.8 gamma (1/1.8 ~= 0.56) for light-on-dark text,
// matching DirectWrite stroke density on both white and gray secondary labels.
let glyph_gamma = mix(1.05, 0.56, smoothstep(0.15, 0.75, fg_luma));
let cov = pow(clamp(cov_raw, 0.0, 1.0), glyph_gamma); let cov = pow(clamp(cov_raw, 0.0, 1.0), glyph_gamma);
let a = cov * c_start.a * clip_cov; let a = cov * c_start.a * clip_cov;
if (a <= 0.0001) { if (a <= 0.0001) {
@ -305,8 +308,31 @@ fn fs_main(in: VertOut) -> @location(0) vec4<f32> {
} }
// Sample premultiplied linear-sRGB RGBA texture with hardware trilinear mipmapping // Sample premultiplied linear-sRGB RGBA texture with hardware trilinear mipmapping
let tex = textureSampleLevel(u_tex, u_smp, uv, lod); let tex = textureSampleLevel(u_tex, u_smp, uv, lod);
let scale = c_start.a * outer_cov; if ((inst.flags_meta.z & FLAG_LUMINOSITY_BLEND) != 0u) {
fill_pm = vec4<f32>(tex.rgb * c_start.rgb * scale, tex.a * scale); // Exact W3C Compositing & Blending Level 1 `mix-blend-mode: luminosity` + `opacity` over `c_start`
let cs = tex.rgb / max(tex.a, 1e-5);
let cb = c_start.rgb;
let lum_s = dot(cs, vec3<f32>(0.3, 0.59, 0.11));
let lum_b = dot(cb, vec3<f32>(0.3, 0.59, 0.11));
var c = cb + vec3<f32>(lum_s - lum_b);
let l = dot(c, vec3<f32>(0.3, 0.59, 0.11));
let n = min(c.r, min(c.g, c.b));
let x = max(c.r, max(c.g, c.b));
if (n < 0.0) {
c = vec3<f32>(l) + ((c - vec3<f32>(l)) * l) / max(l - n, 1e-5);
}
if (x > 1.0) {
c = vec3<f32>(l) + ((c - vec3<f32>(l)) * (1.0 - l)) / max(x - l, 1e-5);
}
let mix_a = clamp(inst.metrics.z, 0.0, 1.0) * tex.a;
let bright = select(1.0, inst.metrics.w, inst.metrics.w > 0.0);
let out_rgb = clamp(mix(cb, c, mix_a) * bright, vec3<f32>(0.0), vec3<f32>(1.0));
let fa = c_start.a * outer_cov;
fill_pm = vec4<f32>(out_rgb * fa, fa);
} else {
let scale = c_start.a * outer_cov;
fill_pm = vec4<f32>(tex.rgb * c_start.rgb * scale, tex.a * scale);
}
} else if (mode == MODE_BACKDROP_BLUR) { } else if (mode == MODE_BACKDROP_BLUR) {
let screen_uv = clamp(in.frag_pos / max(pc.screen_size, vec2<f32>(1.0)), vec2<f32>(0.0), vec2<f32>(1.0)); let screen_uv = clamp(in.frag_pos / max(pc.screen_size, vec2<f32>(1.0)), vec2<f32>(0.0), vec2<f32>(1.0));
let bg_sample = textureSampleLevel(u_tex, u_smp, screen_uv, 0.0); let bg_sample = textureSampleLevel(u_tex, u_smp, screen_uv, 0.0);

View file

@ -100,6 +100,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Хип-хоп".into()), genre: Some("Хип-хоп".into()),
is_explicit: true, is_explicit: true,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "rel_2".into(), id: "rel_2".into(),
@ -112,6 +113,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Поп".into()), genre: Some("Поп".into()),
is_explicit: false, is_explicit: false,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "rel_3".into(), id: "rel_3".into(),
@ -124,6 +126,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Рок".into()), genre: Some("Рок".into()),
is_explicit: true, is_explicit: true,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "rel_4".into(), id: "rel_4".into(),
@ -136,6 +139,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("R&B".into()), genre: Some("R&B".into()),
is_explicit: true, is_explicit: true,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "rel_5".into(), id: "rel_5".into(),
@ -148,6 +152,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Электроника".into()), genre: Some("Электроника".into()),
is_explicit: true, is_explicit: true,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "rel_6".into(), id: "rel_6".into(),
@ -160,6 +165,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Рэп".into()), genre: Some("Рэп".into()),
is_explicit: false, is_explicit: false,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}, },
]; ];
@ -248,6 +254,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Технологии".into()), genre: Some("Технологии".into()),
is_explicit: false, is_explicit: false,
content_type: Some("podcast".into()), content_type: Some("podcast".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "pod_2".into(), id: "pod_2".into(),
@ -260,6 +267,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Тру-крайм".into()), genre: Some("Тру-крайм".into()),
is_explicit: true, is_explicit: true,
content_type: Some("podcast".into()), content_type: Some("podcast".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "pod_3".into(), id: "pod_3".into(),
@ -272,6 +280,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Научпоп".into()), genre: Some("Научпоп".into()),
is_explicit: false, is_explicit: false,
content_type: Some("audiobook".into()), content_type: Some("audiobook".into()),
..Default::default()
}, },
AlbumSummary { AlbumSummary {
id: "pod_4".into(), id: "pod_4".into(),
@ -284,6 +293,7 @@ pub fn demo_landing() -> LandingData {
genre: Some("Фэнтези".into()), genre: Some("Фэнтези".into()),
is_explicit: false, is_explicit: false,
content_type: Some("audiobook".into()), content_type: Some("audiobook".into()),
..Default::default()
}, },
]; ];
@ -342,6 +352,8 @@ pub fn demo_landing() -> LandingData {
kids_playlists, kids_playlists,
rich_new_releases: Vec::new(), rich_new_releases: Vec::new(),
vibe_pick_tabs: Vec::new(), vibe_pick_tabs: Vec::new(),
ai_set_tabs: Vec::new(),
likes_and_history: None,
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,10 @@ pub struct UserAccount {
pub avatar_uri: Option<String>, pub avatar_uri: Option<String>,
#[serde(default)] #[serde(default)]
pub default_email: Option<String>, pub default_email: Option<String>,
#[serde(default)]
pub plus_balance: Option<u64>,
#[serde(default)]
pub collection_hue: Option<f32>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@ -20,7 +24,7 @@ pub struct ArtistSummary {
pub genres: Vec<String>, pub genres: Vec<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AlbumSummary { pub struct AlbumSummary {
pub id: String, pub id: String,
pub title: String, pub title: String,
@ -35,6 +39,15 @@ pub struct AlbumSummary {
/// Official API content type (`album.type` / `album.metaType`, e.g. "album", "single", "podcast", "audiobook") /// Official API content type (`album.type` / `album.metaType`, e.g. "album", "single", "podcast", "audiobook")
#[serde(default)] #[serde(default)]
pub content_type: Option<String>, pub content_type: Option<String>,
/// Official API likes counter (`likesCount` on `CHART_ALBUM_ITEM` / `NON_MUSIC_ALBUM_ITEM`).
#[serde(default)]
pub likes_count: Option<u64>,
/// Official API chart rank (`chart.position`) on `CHART_ALBUMS` / `PODCASTS_CHART_ALBUMS`.
#[serde(default)]
pub chart_position: Option<u32>,
/// Official API chart movement (`chart.progress`: `"same"` | `"up"` | `"down"` | `"new"` | `"crown"`).
#[serde(default)]
pub chart_progress: Option<String>,
} }
impl AlbumSummary { impl AlbumSummary {
@ -139,7 +152,8 @@ impl Track {
} }
pub fn format_ms(ms: u64) -> String { pub fn format_ms(ms: u64) -> String {
let total_secs = ms / 1000; // Original Yandex Music (`7053-6b0c477363016e30.js`): `Math.round((durationMs || 0) / 1000)`
let total_secs = ms.saturating_add(500) / 1000;
let mins = total_secs / 60; let mins = total_secs / 60;
let secs = total_secs % 60; let secs = total_secs % 60;
format!("{:02}:{:02}", mins, secs) format!("{:02}:{:02}", mins, secs)
@ -231,6 +245,27 @@ pub struct LandingData {
pub rich_new_releases: Vec<NewReleaseItem>, pub rich_new_releases: Vec<NewReleaseItem>,
#[serde(default)] #[serde(default)]
pub vibe_pick_tabs: Vec<VibePickTab>, pub vibe_pick_tabs: Vec<VibePickTab>,
#[serde(default)]
pub ai_set_tabs: Vec<VibePickTab>,
#[serde(default)]
pub likes_and_history: Option<LikesAndHistoryData>,
}
/// Official `LIKES_AND_HISTORY` block from `GET /landing/skeleton/web_main`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LikesAndHistoryData {
#[serde(default)]
pub likes_title: String,
#[serde(default)]
pub likes_count: u64,
#[serde(default)]
pub likes_track_covers: Vec<String>,
#[serde(default)]
pub history_title: String,
#[serde(default)]
pub history_artists: Vec<String>,
#[serde(default)]
pub history_track_covers: Vec<String>,
} }
/// Rich editorial new release item from `GET /landing/skeleton/web_main` (`NEW_RELEASES`). /// Rich editorial new release item from `GET /landing/skeleton/web_main` (`NEW_RELEASES`).
@ -242,6 +277,8 @@ pub struct NewReleaseItem {
#[serde(default)] #[serde(default)]
pub cover_color: Option<String>, pub cover_color: Option<String>,
#[serde(default)] #[serde(default)]
pub average_color: Option<String>,
#[serde(default)]
pub release_date: Option<String>, pub release_date: Option<String>,
} }
@ -254,6 +291,8 @@ pub struct VibePickItem {
#[serde(default)] #[serde(default)]
pub color_hex: Option<String>, pub color_hex: Option<String>,
#[serde(default)] #[serde(default)]
pub wave_text_hex: Option<String>,
#[serde(default)]
pub background_image_url: Option<String>, pub background_image_url: Option<String>,
#[serde(default)] #[serde(default)]
pub image_url: Option<String>, pub image_url: Option<String>,
@ -266,14 +305,63 @@ pub struct VibePickTab {
pub items: Vec<VibePickItem>, pub items: Vec<VibePickItem>,
} }
/// Editorial/non-music promotion card from `PROMOTIONS` / `EDITORIAL_PROMOTIONS` / `NON_MUSIC_PROMOTIONS`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NonMusicPromotion {
pub feature_id: String,
pub title: String,
pub subtitle: String,
pub weblink: String,
pub image_url: String,
}
/// Tab metadata (`Книги` / `Подкасты`) from `/landing/skeleton/non_music/tabs`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NonMusicTabMeta {
pub id: String,
pub title: String,
pub subtitle: String,
#[serde(default)]
pub cover_uri: Option<String>,
}
/// `CONTINUE_LISTEN` upper block on Books & Podcasts (`Моя полка` + `Новые выпуски`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NonMusicContinueListen {
pub bookshelf_title: String,
pub bookshelf_covers: Vec<String>,
pub bookshelf_book_count: u32,
pub bookshelf_podcast_count: u32,
pub new_episodes_title: String,
pub new_episodes_covers: Vec<String>,
pub new_episodes_track_count: u32,
}
/// Section block on the Books & Podcasts (`non_music`) landing page. /// Section block on the Books & Podcasts (`non_music`) landing page.
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NonMusicSection { pub struct NonMusicSection {
pub id: String, pub id: String,
pub title: String, pub title: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub view_all_link: Option<String>,
pub block_type: String, pub block_type: String,
#[serde(default)]
pub tab_id: String,
pub albums: Vec<AlbumSummary>, pub albums: Vec<AlbumSummary>,
pub playlists: Vec<PlaylistSummary>, pub playlists: Vec<PlaylistSummary>,
#[serde(default)]
pub promotions: Vec<NonMusicPromotion>,
}
/// Complete parsed payload of `/landing/skeleton/non_music`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NonMusicLandingData {
pub continue_listen: Option<NonMusicContinueListen>,
pub tabs: Vec<NonMusicTabMeta>,
pub sections: Vec<NonMusicSection>,
pub flat_albums: Vec<AlbumSummary>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -377,6 +465,60 @@ pub struct ConcertItem {
pub cover_color: Option<String>, pub cover_color: Option<String>,
#[serde(default)] #[serde(default)]
pub event_kind: Option<String>, pub event_kind: Option<String>,
#[serde(default)]
pub content_rating: Option<String>,
}
/// Slice window returned by `GET /concerts/tab-config` (`config.top` / `config.feed`)
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct ConcertsTabConfig {
pub top_offset: usize,
/// Negative means unlimited (official `ConcertsPageConfig` default `feedLimit: -1`).
pub top_limit: i32,
pub feed_offset: usize,
pub feed_limit: i32,
}
impl Default for ConcertsTabConfig {
fn default() -> Self {
// Official `ConcertsPageConfig` (`9298-*.js`) defaults
Self {
top_offset: 0,
top_limit: 3,
feed_offset: 3,
feed_limit: -1,
}
}
}
/// Single promo banner from `albumBanners` (`ALBUM_PROMO` / `ARTIST_RECOMMENDATIONS_PROMO`)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlbumPromoItem {
pub album_id: String,
pub title: String,
pub artist_names: String,
pub album_cover_uri: Option<String>,
pub artist_cover_uri: Option<String>,
#[serde(default)]
pub cover_top_position: bool,
#[serde(default)]
pub is_explicit: bool,
}
/// Landing block of promo cards rendered between `TopConcerts` and `FeedConcerts`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlbumPromoBlock {
pub id: String,
pub title: String,
pub items: Vec<AlbumPromoItem>,
}
/// Complete payload for `ConcertsPage` (`GET /concerts/tab-config` + `GET /concerts/feed` + `GET /landing/skeleton/concerts`)
#[derive(Debug, Clone, Default)]
pub struct ConcertsPagePayload {
pub config: ConcertsTabConfig,
pub concerts: Vec<ConcertItem>,
pub promo_blocks: Vec<AlbumPromoBlock>,
} }
fn default_wheel_item_type() -> String { fn default_wheel_item_type() -> String {
@ -565,6 +707,9 @@ pub struct ReleaseNoteEntry {
pub date: String, pub date: String,
pub body: String, pub body: String,
pub html_url: String, pub html_url: String,
pub asset_name: Option<String>,
pub asset_url: Option<String>,
pub sha256sums_url: Option<String>,
} }
/// Available application update metadata for `NotificationUpdate` & Settings card. /// Available application update metadata for `NotificationUpdate` & Settings card.
@ -574,4 +719,49 @@ pub struct UpdateInfo {
pub html_url: String, pub html_url: String,
pub date: String, pub date: String,
pub body: String, pub body: String,
pub asset_name: Option<String>,
pub asset_url: Option<String>,
pub sha256sums_url: Option<String>,
}
/// Live in-app self-update download / SHA-256 verification state.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum UpdateInstallState {
#[default]
Idle,
Downloading(u8),
Verifying,
Applying,
Failed(String),
}
/// Official `COLLECTION_TOP_ARTISTS` (`GET /personal/top/artists/month`) item.
#[derive(Debug, Clone)]
pub struct TopArtistItem {
pub artist: ArtistSummary,
pub listen_time_seconds: u64,
pub position: u32,
pub progress: Option<String>,
}
/// Official `COLLECTION_WAVE_ROOMS` (`GET /wave/rooms`, "Моя волна на двоих") item.
#[derive(Debug, Clone)]
pub struct VibeRoomSummary {
pub id: String,
pub name: String,
pub status: String,
pub owner_uid: Option<u64>,
pub owner_avatar_uri: Option<String>,
pub member_avatar_uris: Vec<String>,
pub seeds: Vec<String>,
}
/// Official `COLLECTION_CLIPS` (`GET /users/{uid}/likes/clips`) item.
#[derive(Debug, Clone)]
pub struct ClipSummary {
pub clip_id: String,
pub title: String,
pub thumbnail: Option<String>,
pub duration_secs: u64,
pub artists: Vec<ArtistSummary>,
} }

View file

@ -553,6 +553,26 @@ impl I18n {
self.pick("Очередь", "Queue") self.pick("Очередь", "Queue")
} }
pub const fn now_playing(self) -> &'static str {
self.pick("Сейчас играет", "Playing now")
}
pub const fn next_in_queue(self) -> &'static str {
self.pick("Далее в очереди", "Queuing")
}
pub const fn queue_repeat_context(self) -> &'static str {
self.pick("Включен повтор очереди", "Repeat queue on")
}
pub const fn queue_repeat_one(self) -> &'static str {
self.pick("Включен повтор трека", "Repeat track on")
}
pub const fn queue_shuffle_mode(self) -> &'static str {
self.pick("В случайном порядке", "Shuffle")
}
pub const fn sound_settings(self) -> &'static str { pub const fn sound_settings(self) -> &'static str {
self.pick("Настройки звука", "Sound settings") self.pick("Настройки звука", "Sound settings")
} }

View file

@ -7,5 +7,5 @@ pub mod state;
pub use i18n::{tr, I18n, APP_VERSION}; pub use i18n::{tr, I18n, APP_VERSION};
pub use state::{ pub use state::{
AppAction, AppState, CollectionTab, ForYouTab, PlaylistModalState, RepeatMode, RightDrawerTab, AppAction, AppState, CollectionTab, ForYouTab, PlaylistModalState, RepeatMode, RightDrawerTab,
Route, SearchBrowseTab, SearchFilter, WindowCommand, Route, SearchBrowseTab, SearchFilter, WindowCommand, WindowResizeDirection,
}; };

View file

@ -141,7 +141,7 @@ impl AppState {
return; return;
} }
let dur_ms = self.duration_ms(); let dur_ms = self.duration_ms();
if dur_ms < 8_000 { if dur_ms < 1_500 {
return; return;
} }
let pos_ms = self.position_ms(); let pos_ms = self.position_ms();
@ -157,7 +157,8 @@ impl AppState {
} else { } else {
dur_ms dur_ms
}; };
if pos_ms + 15_000 < transition_ms { // Preload next track 12s before transition (or immediately for short tracks <= 12s)
if pos_ms + 12_000 < transition_ms {
return; return;
} }
let Some(next_idx) = self.peek_next_queue_index() else { let Some(next_idx) = self.peek_next_queue_index() else {
@ -603,10 +604,8 @@ impl AppState {
/// Forbidden in My Vibe. Enable -> pins current track at index 0, shuffles rest. /// Forbidden in My Vibe. Enable -> pins current track at index 0, shuffles rest.
/// Disable -> restores original order and current track's original index! /// Disable -> restores original order and current track's original index!
pub fn toggle_shuffle(&mut self) { pub fn toggle_shuffle(&mut self) {
let t = self.i18n();
if self.is_vibe_active { if self.is_vibe_active {
self.shuffle = false; self.shuffle = false;
self.show_toast(t.toast_shuffle_vibe_managed());
return; return;
} }
self.invalidate_preload(); self.invalidate_preload();
@ -629,11 +628,6 @@ impl AppState {
} }
} }
} }
self.show_toast(if self.shuffle {
t.toast_shuffle_on()
} else {
t.toast_shuffle_off()
});
} }
/// Exact 5.129.0 Repeat Cycle (`Off -> All -> One -> Off`; in VibeContext toggles `Off <-> One` ONLY!) /// Exact 5.129.0 Repeat Cycle (`Off -> All -> One -> Off`; in VibeContext toggles `Off <-> One` ONLY!)
@ -647,12 +641,6 @@ impl AppState {
} else { } else {
self.repeat.next() self.repeat.next()
}; };
let t = self.i18n();
self.show_toast(match self.repeat {
RepeatMode::Off => t.toast_repeat_off(),
RepeatMode::All => t.toast_repeat_all(),
RepeatMode::One => t.toast_repeat_one(),
});
} }
fn ensure_current_lyrics_loaded(&mut self) { fn ensure_current_lyrics_loaded(&mut self) {
@ -963,18 +951,15 @@ impl AppState {
// ========================================================================= // =========================================================================
pub fn toggle_like(&mut self, track: Track) { pub fn toggle_like(&mut self, track: Track) {
let t = self.i18n();
let now_liked = !self.liked_ids.contains(&track.id); let now_liked = !self.liked_ids.contains(&track.id);
if now_liked { if now_liked {
self.liked_ids.insert(track.id.clone()); self.liked_ids.insert(track.id.clone());
self.disliked_ids.remove(&track.id); self.disliked_ids.remove(&track.id);
self.liked_tracks.retain(|tr| tr.id != track.id); self.liked_tracks.retain(|tr| tr.id != track.id);
self.liked_tracks.insert(0, track.clone()); self.liked_tracks.insert(0, track.clone());
self.show_toast(t.toast_track_liked(&track.title));
} else { } else {
self.liked_ids.remove(&track.id); self.liked_ids.remove(&track.id);
self.liked_tracks.retain(|tr| tr.id != track.id); self.liked_tracks.retain(|tr| tr.id != track.id);
self.show_toast(t.toast_track_unliked(&track.title));
} }
if self.is_vibe_active { if self.is_vibe_active {
@ -1000,14 +985,12 @@ impl AppState {
} }
pub fn toggle_dislike(&mut self, track: Track) { pub fn toggle_dislike(&mut self, track: Track) {
let t = self.i18n();
let now_dis = !self.disliked_ids.contains(&track.id); let now_dis = !self.disliked_ids.contains(&track.id);
let pos_sec = self.audio.state.position_ms.load(Ordering::Relaxed) as f64 / 1000.0; let pos_sec = self.audio.state.position_ms.load(Ordering::Relaxed) as f64 / 1000.0;
if now_dis { if now_dis {
self.disliked_ids.insert(track.id.clone()); self.disliked_ids.insert(track.id.clone());
self.liked_ids.remove(&track.id); self.liked_ids.remove(&track.id);
self.liked_tracks.retain(|tr| tr.id != track.id); self.liked_tracks.retain(|tr| tr.id != track.id);
self.show_toast(t.toast_track_disliked());
if self.is_vibe_active { if self.is_vibe_active {
self.send_rotor_feedback(RotorFeedbackKind::Dislike, Some(&track), Some(pos_sec)); self.send_rotor_feedback(RotorFeedbackKind::Dislike, Some(&track), Some(pos_sec));
if self.queue_index + 2 < self.queue.len() { if self.queue_index + 2 < self.queue.len() {
@ -1020,7 +1003,6 @@ impl AppState {
} }
} else { } else {
self.disliked_ids.remove(&track.id); self.disliked_ids.remove(&track.id);
self.show_toast(t.toast_track_undisliked());
if self.is_vibe_active { if self.is_vibe_active {
self.send_rotor_feedback(RotorFeedbackKind::Undislike, Some(&track), None); self.send_rotor_feedback(RotorFeedbackKind::Undislike, Some(&track), None);
} }
@ -1052,7 +1034,6 @@ impl AppState {
cover_uri: Option<String>, cover_uri: Option<String>,
owner_uid: Option<String>, owner_uid: Option<String>,
) -> bool { ) -> bool {
let t = self.i18n();
if self.is_pinned(kind, id) { if self.is_pinned(kind, id) {
let removed_pin = self let removed_pin = self
.config .config
@ -1064,7 +1045,6 @@ impl AppState {
.pinned_items .pinned_items
.retain(|p| !pin_matches(p, kind, id)); .retain(|p| !pin_matches(p, kind, id));
self.save_config(); self.save_config();
self.show_toast(t.toast_unpinned(kind, title));
if let Some(pin) = removed_pin { if let Some(pin) = removed_pin {
self.sync_pin_remote(pin, false); self.sync_pin_remote(pin, false);
} }
@ -1084,19 +1064,16 @@ impl AppState {
}; };
self.config.pinned_items.insert(0, pin.clone()); self.config.pinned_items.insert(0, pin.clone());
self.save_config(); self.save_config();
self.show_toast(t.toast_pinned(kind, title));
self.sync_pin_remote(pin, true); self.sync_pin_remote(pin, true);
true true
} }
} }
pub fn unpin_item(&mut self, pin: PinnedItem) { pub fn unpin_item(&mut self, pin: PinnedItem) {
let t = self.i18n();
self.config self.config
.pinned_items .pinned_items
.retain(|p| !pin_matches(p, &pin.kind, &pin.id)); .retain(|p| !pin_matches(p, &pin.kind, &pin.id));
self.save_config(); self.save_config();
self.show_toast(t.toast_unpinned(&pin.kind, &pin.title));
self.sync_pin_remote(pin, false); self.sync_pin_remote(pin, false);
} }

File diff suppressed because it is too large Load diff

View file

@ -1359,13 +1359,42 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
active = Some(next_dec); active = Some(next_dec);
} }
// Decode up to 1024 stereo frames from active + optional outgoing crossfade deck // Decode up to 1024 stereo frames from active + optional outgoing crossfade deck.
// True sample-accurate gapless handoff happens directly inside the frame loop
// so track N's last sample is immediately followed by track N+1's first sample (0ms gap).
let mut frames_mixed = 0usize; let mut frames_mixed = 0usize;
while frames_mixed < 1024 { while frames_mixed < 1024 {
let dec = active.as_mut().unwrap(); let next_sample = {
let Some((al, ar)) = next_stereo_frame(dec) else { let dec = active.as_mut().unwrap();
next_stereo_frame(dec)
};
let Some((al, ar)) = next_sample else {
let dec_eof = active
.as_ref()
.map_or(false, |d| d.eof && d.pending_idx >= d.pending.len());
if dec_eof && outgoing.is_none() {
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; break;
}; };
let dec = active.as_mut().unwrap();
let mut in_gain = deck_gain(dec, normalize); let mut in_gain = deck_gain(dec, normalize);
if let Some((in_start, in_stop)) = dec.fade_in_window { if let Some((in_start, in_stop)) = dec.fade_in_window {
let span = in_stop.saturating_sub(in_start).max(1) as f32; let span = in_stop.saturating_sub(in_start).max(1) as f32;
@ -1403,28 +1432,6 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
} }
if frames_mixed == 0 { 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; break;
} }
@ -1455,11 +1462,13 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
} }
} }
if active.as_ref().map_or(false, |dec| { if preloaded.is_none()
dec.eof && active.as_ref().map_or(false, |dec| {
&& dec.pending_idx >= dec.pending.len() dec.eof
&& applied_seek_seq == state.seek_seq.load(Ordering::Acquire) && dec.pending_idx >= dec.pending.len()
}) { && applied_seek_seq == state.seek_seq.load(Ordering::Acquire)
})
{
state.is_playing.store(false, Ordering::SeqCst); state.is_playing.store(false, Ordering::SeqCst);
state.track_finished.store(true, Ordering::SeqCst); state.track_finished.store(true, Ordering::SeqCst);
active = None; active = None;

View file

@ -36,9 +36,9 @@ impl PlayerThumbStyle {
pub const fn label(self, ru: bool) -> &'static str { pub const fn label(self, ru: bool) -> &'static str {
match (self, ru) { match (self, ru) {
(Self::Standard, true) => "Стандартный", (Self::Standard, true) => "Стандартный",
(Self::Standard, false) => "Default", (Self::Standard, false) => "Standard",
(Self::Duck, true) => "Уточка", (Self::Duck, true) => "Уточка",
(Self::Duck, false) => "Duck", (Self::Duck, false) => "Duckie",
(Self::Car, true) => "Машинка", (Self::Car, true) => "Машинка",
(Self::Car, false) => "Car", (Self::Car, false) => "Car",
(Self::Claudik, true) => "Клодик", (Self::Claudik, true) => "Клодик",
@ -202,6 +202,8 @@ pub struct AppConfig {
pub crossfade_enabled: bool, pub crossfade_enabled: bool,
pub crossfade_secs: f32, pub crossfade_secs: f32,
#[serde(default)] #[serde(default)]
pub offline_mode: bool,
#[serde(default)]
pub ai_content_reduction: bool, pub ai_content_reduction: bool,
#[serde(default)] #[serde(default)]
pub child_mode: bool, pub child_mode: bool,
@ -210,6 +212,8 @@ pub struct AppConfig {
#[serde(default)] #[serde(default)]
pub player_thumb: PlayerThumbStyle, pub player_thumb: PlayerThumbStyle,
pub max_cover_cache: usize, pub max_cover_cache: usize,
#[serde(default = "default_ui_zoom")]
pub ui_zoom: f32,
pub show_perf_hud: bool, pub show_perf_hud: bool,
pub search_history: Vec<String>, pub search_history: Vec<String>,
pub pinned_items: Vec<PinnedItem>, pub pinned_items: Vec<PinnedItem>,
@ -245,6 +249,10 @@ fn default_eq_preamp() -> f32 {
1.0 1.0
} }
fn default_ui_zoom() -> f32 {
1.0
}
impl Default for AppConfig { impl Default for AppConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
@ -261,11 +269,13 @@ impl Default for AppConfig {
normalize_loudness: true, normalize_loudness: true,
crossfade_enabled: true, crossfade_enabled: true,
crossfade_secs: 0.0, crossfade_secs: 0.0,
offline_mode: false,
ai_content_reduction: false, ai_content_reduction: false,
child_mode: false, child_mode: false,
close_to_tray: true, close_to_tray: true,
player_thumb: PlayerThumbStyle::Standard, player_thumb: PlayerThumbStyle::Standard,
max_cover_cache: 256, max_cover_cache: 256,
ui_zoom: 1.0,
show_perf_hud: false, show_perf_hud: false,
search_history: Vec::new(), search_history: Vec::new(),
pinned_items: vec![PinnedItem { pinned_items: vec![PinnedItem {
@ -309,6 +319,7 @@ impl AppConfig {
if let Ok(data) = std::fs::read_to_string(&path) { if let Ok(data) = std::fs::read_to_string(&path) {
if let Ok(mut cfg) = serde_json::from_str::<AppConfig>(&data) { if let Ok(mut cfg) = serde_json::from_str::<AppConfig>(&data) {
cfg.max_cover_cache = cfg.max_cover_cache.clamp(128, 1024); cfg.max_cover_cache = cfg.max_cover_cache.clamp(128, 1024);
cfg.ui_zoom = cfg.ui_zoom.clamp(0.5, 2.0);
return cfg; return cfg;
} }
} }

View file

@ -257,6 +257,107 @@ impl CoverCache {
} }
} }
/// Official `createAvatarUrl(uri, size, withAspectRatio=true)` (`m{size}x{size}`),
/// preserving non-square banner aspect ratios (e.g. 3:2 `NON_MUSIC_PROMOTIONS` cards).
pub fn format_url_aspect(uri: &str, size_px: u32) -> String {
let size_str = if size_px <= 400 {
"m400x400"
} else if size_px <= 600 {
"m600x600"
} else {
"m800x800"
};
let replaced = uri.replace("%%", size_str);
if replaced.starts_with("http://") || replaced.starts_with("https://") {
replaced
} else {
format!("https://{}", replaced.trim_start_matches('/'))
}
}
/// Fetch an image preserving its original aspect ratio via Yandex Avatars `m{N}x{N}` sizing.
/// Falls back to `orig` and square `400x400` if a specific avatars namespace rejects `m{N}x{N}`.
pub fn get_or_fetch_aspect(
&mut self,
uri: &str,
size_px: u32,
) -> Option<(TextureId, Color, f32, u32, u32)> {
if uri.is_empty() {
return None;
}
let frame_id = self.frame_id;
let url = Self::format_url_aspect(uri, size_px);
if let Some(entry) = self.cache.get_mut(&url) {
entry.last_used_frame = frame_id;
return Some((
entry.texture_id,
entry.dominant_color,
entry.hue,
entry.width,
entry.height,
));
}
if uri.starts_with("test.local/")
|| self.in_flight.contains(&url)
|| self.failed.contains(&url)
|| self.in_flight.len() >= 16
{
return None;
}
self.in_flight.insert(url.clone());
let http = self.http.clone();
let tx = self.tx_done.clone();
let key = url.clone();
let target_px = size_px.clamp(200, 800);
let mut candidates = vec![url];
if uri.contains("%%") {
let orig_raw = uri.replace("%%", "orig");
let orig_url = if orig_raw.starts_with("http://") || orig_raw.starts_with("https://") {
orig_raw
} else {
format!("https://{}", orig_raw.trim_start_matches('/'))
};
if !candidates.contains(&orig_url) {
candidates.push(orig_url);
}
let sq_url = Self::format_url(uri, 400);
if !candidates.contains(&sq_url) {
candidates.push(sq_url);
}
}
self.runtime.spawn(async move {
for candidate in &candidates {
let Ok(resp) = http.get(candidate).send().await else {
continue;
};
if !resp.status().is_success() {
continue;
}
let Ok(bytes) = resp.bytes().await else {
continue;
};
let res =
tokio::task::spawn_blocking(move || decode_and_analyze(&bytes, target_px))
.await;
if let Ok(Some((width, height, rgba_unpremul, dominant_color, hue))) = res {
let _ = tx.send(CoverFetchOutcome::Ok(DecodedCover {
key,
width,
height,
rgba_unpremul,
dominant_color,
hue,
}));
return;
}
}
let _ = tx.send(CoverFetchOutcome::Failed(key));
});
None
}
/// Returns `(TextureId, dominant_color, hue)` if loaded, or triggers background fetch. /// Returns `(TextureId, dominant_color, hue)` if loaded, or triggers background fetch.
/// Reuses an already-cached higher-resolution entry (`200x200` / `400x400`) when available /// 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! /// because our Vulkan SDF renderer samples full hardware mipmap chains cleanly at any size!

204
src/engine/dwrite.rs Normal file
View file

@ -0,0 +1,204 @@
//! Native Windows DirectWrite glyph rasterizer (`DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC`)
//! for 1-to-1 pixel-level parity with Chromium / Electron (official Yandex Music Desktop on Windows).
//!
//! Uses `IDWriteFactory5::CreateInMemoryFontFileLoader` so both embedded official Yandex TTFs and
//! system fallback fonts from `cosmic_text::fontdb` rasterize through the exact Windows DirectWrite
//! 3x subpixel 5-tap FIR filter pipeline. Returns `None` for unsupported/color glyphs so `swash`
//! handles them as a seamless fallback.
use std::collections::HashMap;
use std::mem::ManuallyDrop;
use cosmic_text::{fontdb, CacheKey, CacheKeyFlags, FontSystem};
use windows::core::Interface;
use windows::Win32::Graphics::DirectWrite::{
DWriteCreateFactory, IDWriteFactory, IDWriteFactory5, IDWriteFontFace,
IDWriteInMemoryFontFileLoader, DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_FACE_TYPE_CFF,
DWRITE_FONT_FACE_TYPE_TRUETYPE, DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION,
DWRITE_FONT_SIMULATIONS_NONE, DWRITE_FONT_SIMULATIONS_OBLIQUE, DWRITE_GLYPH_OFFSET,
DWRITE_GLYPH_RUN, DWRITE_MEASURING_MODE_NATURAL,
DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC, DWRITE_TEXTURE_CLEARTYPE_3x1,
};
pub struct RasterizedGlyph {
pub width: u32,
pub height: u32,
pub left: i32,
pub top: i32,
pub r8_pixels: Vec<u8>,
}
pub struct DirectWriteRasterizer {
factory: IDWriteFactory,
loader: IDWriteInMemoryFontFileLoader,
faces: HashMap<(fontdb::ID, bool), Option<IDWriteFontFace>>,
}
impl Drop for DirectWriteRasterizer {
fn drop(&mut self) {
self.faces.clear();
unsafe {
let _ = self.factory.UnregisterFontFileLoader(&self.loader);
}
}
}
impl DirectWriteRasterizer {
pub fn new() -> Option<Self> {
unsafe {
let factory5: IDWriteFactory5 =
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED).ok()?;
let loader = factory5.CreateInMemoryFontFileLoader().ok()?;
let factory: IDWriteFactory = factory5.cast().ok()?;
factory.RegisterFontFileLoader(&loader).ok()?;
Some(Self {
factory,
loader,
faces: HashMap::with_capacity(16),
})
}
}
fn get_or_create_face(
&mut self,
font_system: &FontSystem,
font_id: fontdb::ID,
fake_italic: bool,
) -> Option<IDWriteFontFace> {
let face_key = (font_id, fake_italic);
if let Some(cached) = self.faces.get(&face_key) {
return cached.clone();
}
let created = font_system.db().with_face_data(font_id, |bytes, face_index| {
if bytes.len() < 4 {
return None;
}
let face_type = match &bytes[0..4] {
b"OTTO" => DWRITE_FONT_FACE_TYPE_CFF,
b"ttcf" => DWRITE_FONT_FACE_TYPE_TRUETYPE_COLLECTION,
_ => DWRITE_FONT_FACE_TYPE_TRUETYPE,
};
let sims = if fake_italic {
DWRITE_FONT_SIMULATIONS_OBLIQUE
} else {
DWRITE_FONT_SIMULATIONS_NONE
};
unsafe {
// `ownerobject = None` tells DirectWrite to copy the font bytes internally.
let font_file = self
.loader
.CreateInMemoryFontFileReference(
&self.factory,
bytes.as_ptr() as *const _,
bytes.len() as u32,
None,
)
.ok()?;
self.factory
.CreateFontFace(face_type, &[Some(font_file)], face_index, sims)
.ok()
}
})?;
self.faces.insert(face_key, created.clone());
created
}
pub fn rasterize(
&mut self,
font_system: &FontSystem,
key: CacheKey,
) -> Option<RasterizedGlyph> {
let fake_italic = key.flags.contains(CacheKeyFlags::FAKE_ITALIC);
let face = self.get_or_create_face(font_system, key.font_id, fake_italic)?;
let font_size = f32::from_bits(key.font_size_bits);
if font_size <= 0.0 || !font_size.is_finite() {
return None;
}
let glyph_index = key.glyph_id;
let glyph_advance = 0.0f32;
let glyph_offset = DWRITE_GLYPH_OFFSET {
advanceOffset: 0.0,
ascenderOffset: 0.0,
};
let baseline_x = if key.flags.contains(CacheKeyFlags::PIXEL_FONT) {
key.x_bin.as_float().round()
} else {
key.x_bin.as_float()
};
let baseline_y = if key.flags.contains(CacheKeyFlags::PIXEL_FONT) {
key.y_bin.as_float().round()
} else {
key.y_bin.as_float()
};
let run = DWRITE_GLYPH_RUN {
fontFace: ManuallyDrop::new(Some(face)),
fontEmSize: font_size,
glyphCount: 1,
glyphIndices: &glyph_index,
glyphAdvances: &glyph_advance,
glyphOffsets: &glyph_offset,
isSideways: false.into(),
bidiLevel: 0,
};
let res = unsafe {
let analysis = self
.factory
.CreateGlyphRunAnalysis(
&run,
1.0,
None,
DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL_SYMMETRIC,
DWRITE_MEASURING_MODE_NATURAL,
baseline_x,
baseline_y,
)
.ok()?;
let bounds = analysis
.GetAlphaTextureBounds(DWRITE_TEXTURE_CLEARTYPE_3x1)
.ok()?;
let w = (bounds.right - bounds.left).max(0) as u32;
let h = (bounds.bottom - bounds.top).max(0) as u32;
if w == 0 || h == 0 {
return Some(RasterizedGlyph {
width: 0,
height: 0,
left: 0,
top: 0,
r8_pixels: Vec::new(),
});
}
let mut rgb = vec![0u8; (w * h * 3) as usize];
analysis
.CreateAlphaTexture(DWRITE_TEXTURE_CLEARTYPE_3x1, &bounds, &mut rgb)
.ok()?;
let r8_pixels: Vec<u8> = rgb
.chunks_exact(3)
.map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16 + 1) / 3) as u8)
.collect();
Some(RasterizedGlyph {
width: w,
height: h,
left: bounds.left,
top: -bounds.top,
r8_pixels,
})
};
// Release our cloned COM reference held inside `ManuallyDrop`.
let mut run = run;
unsafe {
ManuallyDrop::drop(&mut run.fontFace);
}
res
}
}

View file

@ -213,6 +213,7 @@ pub struct InputState {
pub active_id: Option<WidgetId>, pub active_id: Option<WidgetId>,
pub drag_origin: Option<Pos2>, pub drag_origin: Option<Pos2>,
pub is_dragging: bool, pub is_dragging: bool,
drag_started_this_frame: bool,
pub window_focused: bool, pub window_focused: bool,
pub scale_factor: f32, pub scale_factor: f32,
@ -252,6 +253,7 @@ impl InputState {
active_id: None, active_id: None,
drag_origin: None, drag_origin: None,
is_dragging: false, is_dragging: false,
drag_started_this_frame: false,
window_focused: true, window_focused: true,
scale_factor: 1.0, scale_factor: 1.0,
screen_size: Vec2::new(1280.0, 800.0), screen_size: Vec2::new(1280.0, 800.0),
@ -275,10 +277,11 @@ impl InputState {
self.pointer_delta = self.pointer_delta + (next - prev); self.pointer_delta = self.pointer_delta + (next - prev);
} }
self.pointer_pos = Some(next); self.pointer_pos = Some(next);
if self.left_down { if self.left_down && !self.is_dragging {
if let Some(origin) = self.drag_origin { if let Some(origin) = self.drag_origin {
if origin.distance(next) >= 5.0 { if origin.distance(next) >= 5.0 {
self.is_dragging = true; self.is_dragging = true;
self.drag_started_this_frame = true;
} }
} }
} }
@ -298,6 +301,7 @@ impl InputState {
let pos = self.pointer_pos.unwrap_or(Pos2::ZERO); let pos = self.pointer_pos.unwrap_or(Pos2::ZERO);
self.drag_origin = Some(pos); self.drag_origin = Some(pos);
self.is_dragging = false; self.is_dragging = false;
self.drag_started_this_frame = false;
if (self.time - self.last_click_time) <= 0.35 if (self.time - self.last_click_time) <= 0.35
&& pos.distance(self.last_click_pos) <= 6.0 && pos.distance(self.last_click_pos) <= 6.0
{ {
@ -356,7 +360,9 @@ impl InputState {
self.left_down = false; self.left_down = false;
self.right_down = false; self.right_down = false;
self.active_id = None; self.active_id = None;
self.drag_origin = None;
self.is_dragging = false; self.is_dragging = false;
self.drag_started_this_frame = false;
self.modifiers = Modifiers::default(); self.modifiers = Modifiers::default();
} }
true true
@ -417,6 +423,19 @@ impl InputState {
self.curr_blockers.clear(); self.curr_blockers.clear();
} }
/// Clear stuck mouse/drag state when handing pointer capture to the OS (e.g. `drag_window` / `drag_resize_window`),
/// since the OS modal move/resize loop consumes `WM_LBUTTONUP` without notifying `winit`.
pub fn reset_pointer_buttons(&mut self) {
self.left_down = false;
self.left_pressed = false;
self.left_released = false;
self.left_double_clicked = false;
self.active_id = None;
self.drag_origin = None;
self.is_dragging = false;
self.drag_started_this_frame = false;
}
/// Call at the end of every UI frame to clear single-frame edge flags. /// Call at the end of every UI frame to clear single-frame edge flags.
pub fn end_frame(&mut self) { pub fn end_frame(&mut self) {
if self.left_released { if self.left_released {
@ -424,6 +443,7 @@ impl InputState {
self.drag_origin = None; self.drag_origin = None;
self.is_dragging = false; self.is_dragging = false;
} }
self.drag_started_this_frame = false;
self.pointer_delta = Vec2::ZERO; self.pointer_delta = Vec2::ZERO;
self.left_pressed = false; self.left_pressed = false;
self.left_released = false; self.left_released = false;
@ -496,8 +516,8 @@ impl InputState {
if self.is_dragging { if self.is_dragging {
dragged = true; dragged = true;
drag_delta = self.pointer_delta; drag_delta = self.pointer_delta;
if self.drag_origin.is_some() && self.pointer_delta != Vec2::ZERO { if self.drag_started_this_frame {
drag_started = false; drag_started = true;
} }
} }
} }
@ -510,14 +530,6 @@ impl InputState {
} }
} }
// Detect first frame of drag start
if dragged && self.drag_origin.map_or(false, |o| {
let p = self.pointer_pos.unwrap_or(o);
o.distance(p) >= 3.0 && o.distance(p - self.pointer_delta) < 3.0
}) {
drag_started = true;
}
Interaction { Interaction {
rect, rect,
hovered, hovered,
@ -767,4 +779,65 @@ mod tests {
assert!(!rel_resp.clicked); assert!(!rel_resp.clicked);
input.end_frame(); input.end_frame();
} }
#[test]
fn test_drag_started_fires_once_on_slow_multi_frame_drag_and_reset_clears_state() {
let mut input = InputState::new();
let screen = Vec2::new(1280.0, 800.0);
let drag_id = WidgetId::new("ym_tb_drag");
let drag_r = Rect::from_xywh(0.0, 0.0, 1100.0, 32.0);
// Frame 1: Press down at (100, 16)
input.begin_frame(screen, 1.0, 1.0);
input.handle_winit_event(&WindowEvent::CursorMoved {
device_id: unsafe { std::mem::zeroed() },
position: PhysicalPosition::new(100.0, 16.0),
});
input.handle_winit_event(&WindowEvent::MouseInput {
device_id: unsafe { std::mem::zeroed() },
state: ElementState::Pressed,
button: MouseButton::Left,
});
let r1 = input.interact(drag_id, ZLayer::Titlebar, drag_r, None);
assert!(!r1.drag_started);
input.end_frame();
// Frame 2: Move 3.5px (inside old [3.0, 5.0) dead zone)
input.begin_frame(screen, 1.0, 1.02);
input.handle_winit_event(&WindowEvent::CursorMoved {
device_id: unsafe { std::mem::zeroed() },
position: PhysicalPosition::new(103.5, 16.0),
});
let r2 = input.interact(drag_id, ZLayer::Titlebar, drag_r, None);
assert!(!r2.drag_started);
input.end_frame();
// Frame 3: Move another 2.0px (total 5.5px >= 5.0) — MUST fire drag_started!
input.begin_frame(screen, 1.0, 1.04);
input.handle_winit_event(&WindowEvent::CursorMoved {
device_id: unsafe { std::mem::zeroed() },
position: PhysicalPosition::new(105.5, 16.0),
});
let r3 = input.interact(drag_id, ZLayer::Titlebar, drag_r, None);
assert!(r3.drag_started);
assert!(r3.dragged);
input.end_frame();
// Frame 4: Continue moving — drag_started MUST be false (one-shot)
input.begin_frame(screen, 1.0, 1.06);
input.handle_winit_event(&WindowEvent::CursorMoved {
device_id: unsafe { std::mem::zeroed() },
position: PhysicalPosition::new(112.0, 16.0),
});
let r4 = input.interact(drag_id, ZLayer::Titlebar, drag_r, None);
assert!(!r4.drag_started);
assert!(r4.dragged);
// Simulate OS modal drag_window() handoff (WM_LBUTTONUP swallowed by OS)
input.reset_pointer_buttons();
assert!(!input.left_down);
assert!(input.active_id.is_none());
assert!(!input.is_dragging);
input.end_frame();
}
} }

View file

@ -1,3 +1,5 @@
#[cfg(windows)]
pub mod dwrite;
pub mod input; pub mod input;
pub mod layout; pub mod layout;
pub mod scroll; pub mod scroll;
@ -55,6 +57,9 @@ pub struct UiContext {
pub scrolls: ScrollStore, pub scrolls: ScrollStore,
pub textures: TextureRegistry, pub textures: TextureRegistry,
pub icons: IconCache, pub icons: IconCache,
/// Root `rem` scale multiplier above 1920px (`3d8697b385d765d6.css:22-25`: `calc(0.75rem + 0.3vw)`).
/// `1.0` below 1920px; divide pure-`PX` constants (`103px` vibe title, `1200PX` wheel max-height) by this.
pub rem_scale: f32,
pub(crate) layers: [DisplayList; ZLayer::COUNT], pub(crate) layers: [DisplayList; ZLayer::COUNT],
pub(crate) current_layer: ZLayer, pub(crate) current_layer: ZLayer,
pub(crate) text_inputs: HashMap<WidgetId, TextInputState>, pub(crate) text_inputs: HashMap<WidgetId, TextInputState>,
@ -79,6 +84,7 @@ impl UiContext {
scrolls: ScrollStore::new(), scrolls: ScrollStore::new(),
textures: TextureRegistry::new(), textures: TextureRegistry::new(),
icons: IconCache::new(), icons: IconCache::new(),
rem_scale: 1.0,
layers: [ layers: [
DisplayList::new(), DisplayList::new(),
DisplayList::new(), DisplayList::new(),
@ -107,6 +113,7 @@ impl UiContext {
self.pending_tooltip = None; self.pending_tooltip = None;
self.input.begin_frame(screen_size, scale_factor, time); self.input.begin_frame(screen_size, scale_factor, time);
self.animator.begin_frame(); self.animator.begin_frame();
self.text.begin_frame();
self.text.set_scale_factor(scale_factor); self.text.set_scale_factor(scale_factor);
} }
@ -154,10 +161,10 @@ impl UiContext {
let texture_uploads = self.textures.drain_uploads(); let texture_uploads = self.textures.drain_uploads();
let immediate_repaint = let immediate_repaint =
self.repaint_requested || self.animator.needs_repaint() || !texture_uploads.is_empty(); self.repaint_requested || self.animator.needs_repaint() || !texture_uploads.is_empty();
let repaint_after = if self.repaint_requested || !texture_uploads.is_empty() { // Use Duration::ZERO for active scroll/animations so Windows WaitUntil(1ms) doesn't
Some(std::time::Duration::from_millis(1)) // quantize to 15.6ms and miss VSync (dropping 60/144Hz scroll to ~30 FPS).
} else if self.animator.needs_repaint() { let repaint_after = if immediate_repaint {
Some(std::time::Duration::from_millis(16)) Some(std::time::Duration::ZERO)
} else { } else {
self.repaint_after self.repaint_after
}; };
@ -327,6 +334,18 @@ impl UiContext {
self.layers[self.current_layer.index()].push_image(rect, tex_id, 0.0, tint); self.layers[self.current_layer.index()].push_image(rect, tex_id, 0.0, tint);
} }
/// Draw a horizontally mirrored SVG icon into `rect` (e.g. reversing Car companion).
pub fn draw_icon_flipped_x(&mut self, icon: Icon, rect: Rect, tint: Color) {
let tex_id = self.icons.get(&mut self.textures, icon);
self.layers[self.current_layer.index()].push_image_uv(
rect,
tex_id,
Rect::from_xywh(1.0, 0.0, -1.0, 1.0),
0.0,
tint,
);
}
#[inline] #[inline]
pub fn measure_text(&mut self, text: &str, style: TextStyle, max_width: Option<f32>) -> Vec2 { pub fn measure_text(&mut self, text: &str, style: TextStyle, max_width: Option<f32>) -> Vec2 {
self.text.measure(text, style, max_width) self.text.measure(text, style, max_width)

View file

@ -2,11 +2,15 @@ use std::collections::HashMap;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use cosmic_text::{ use cosmic_text::{
Action, Align, Attrs, Buffer, CacheKey, Color as CosmicColor, Cursor, Edit, Editor, Ellipsize, Action, Align, Attrs, Buffer, CacheKey, CacheKeyFlags, Color as CosmicColor, Cursor, Edit,
EllipsizeHeightLimit, Family, FontSystem, Metrics, Motion, Selection, Shaping, SwashCache, Editor, Ellipsize, EllipsizeHeightLimit, Family, FontSystem, Metrics, Motion, Selection,
SwashContent, Weight, Wrap, Shaping, Wrap,
}; };
use swash::scale::{image::Content as SwashContent, Render, ScaleContext, Source, StrikeWith};
use swash::zeno::{Angle, Format, Transform, Vector};
#[cfg(windows)]
use crate::engine::dwrite::DirectWriteRasterizer;
use crate::engine::input::{InputState, Key}; use crate::engine::input::{InputState, Key};
use crate::engine::textures::TextureRegistry; use crate::engine::textures::TextureRegistry;
use crate::engine::types::{ use crate::engine::types::{
@ -209,7 +213,8 @@ impl GlyphAtlas {
&mut self, &mut self,
key: CacheKey, key: CacheKey,
font_system: &mut FontSystem, font_system: &mut FontSystem,
swash: &mut SwashCache, scale_ctx: &mut ScaleContext,
#[cfg(windows)] dwrite: &mut Option<DirectWriteRasterizer>,
textures: &mut TextureRegistry, textures: &mut TextureRegistry,
) -> Option<AtlasEntry> { ) -> Option<AtlasEntry> {
self.ensure_initialized(textures); self.ensure_initialized(textures);
@ -217,33 +222,73 @@ impl GlyphAtlas {
return *cached; return *cached;
} }
let Some(img) = swash.get_image_uncached(font_system, key) else { let (gw, gh, left, top, r8_pixels) = {
self.entries.insert(key, None); #[cfg(windows)]
return None; let dw_opt = dwrite
.as_mut()
.and_then(|dw| dw.rasterize(font_system, key));
#[cfg(not(windows))]
let dw_opt: Option<()> = None;
#[cfg(windows)]
if let Some(g) = dw_opt {
(g.width, g.height, g.left, g.top, g.r8_pixels)
} else {
let Some(img) = rasterize_glyph_directwrite_parity(font_system, scale_ctx, key)
else {
self.entries.insert(key, None);
return None;
};
let r8: Vec<u8> = match img.content {
SwashContent::Mask => img.data,
SwashContent::Color => img.data.chunks_exact(4).map(|px| px[3]).collect(),
SwashContent::SubpixelMask => img
.data
.chunks_exact(4)
.map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16 + 1) / 3) as u8)
.collect(),
};
(
img.placement.width,
img.placement.height,
img.placement.left,
img.placement.top,
r8,
)
}
#[cfg(not(windows))]
{
let _ = dw_opt;
let Some(img) = rasterize_glyph_directwrite_parity(font_system, scale_ctx, key)
else {
self.entries.insert(key, None);
return None;
};
let r8: Vec<u8> = match img.content {
SwashContent::Mask => img.data,
SwashContent::Color => img.data.chunks_exact(4).map(|px| px[3]).collect(),
SwashContent::SubpixelMask => img
.data
.chunks_exact(4)
.map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16 + 1) / 3) as u8)
.collect(),
};
(
img.placement.width,
img.placement.height,
img.placement.left,
img.placement.top,
r8,
)
}
}; };
let gw = img.placement.width;
let gh = img.placement.height;
if gw == 0 || gh == 0 { if gw == 0 || gh == 0 {
self.entries.insert(key, None); self.entries.insert(key, None);
return None; return None;
} }
// Convert to single-channel R8 coverage mask
let r8_pixels: Vec<u8> = match img.content {
SwashContent::Mask => img.data,
SwashContent::Color => img
.data
.chunks_exact(4)
.map(|px| px[3])
.collect(),
SwashContent::SubpixelMask => img
.data
.chunks_exact(4)
.map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16) / 3) as u8)
.collect(),
};
// Allocate in shelf packer with 1px padding to avoid bilinear bleed // Allocate in shelf packer with 1px padding to avoid bilinear bleed
if self.cursor_x + gw + 1 >= self.width { if self.cursor_x + gw + 1 >= self.width {
self.cursor_x = 1; self.cursor_x = 1;
@ -272,8 +317,8 @@ impl GlyphAtlas {
), ),
width: gw, width: gw,
height: gh, height: gh,
left: img.placement.left, left,
top: img.placement.top, top,
}; };
self.entries.insert(key, Some(entry)); self.entries.insert(key, Some(entry));
Some(entry) Some(entry)
@ -293,16 +338,53 @@ struct ShapeCacheKey {
align: TextAlign, align: TextAlign,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct RichShapeCacheKey {
spans_hash: u64,
span_count: u16,
total_len: usize,
rect_w_bits: u32,
rect_h_bits: u32,
max_lines: u16,
align: TextAlign,
}
fn evict_stale_entries<K: Eq + Hash, V>(
map: &mut HashMap<K, (V, u64)>,
max_entries: usize,
current_gen: u64,
) {
if map.len() <= max_entries {
return;
}
let stale_cutoff = current_gen.saturating_sub(2);
map.retain(|_, (_, gen)| *gen > stale_cutoff);
if map.len() > max_entries / 2 {
let mut gens: Vec<u64> = map.values().map(|(_, g)| *g).collect();
let mid = gens.len() / 2;
let (_, median, _) = gens.select_nth_unstable(mid);
let cutoff = *median;
map.retain(|_, (_, gen)| *gen > cutoff);
if map.len() > max_entries {
map.clear();
}
}
}
/// Core text shaping, measurement, rich-text, and R8 GPU glyph atlas engine /// Core text shaping, measurement, rich-text, and R8 GPU glyph atlas engine
/// built on `cosmic-text 0.19` + `swash` with all 4 embedded official Yandex fonts. /// built on `cosmic-text 0.19` + `swash` with all 4 embedded official Yandex fonts.
pub struct TextEngine { pub struct TextEngine {
pub font_system: FontSystem, pub font_system: FontSystem,
swash_cache: SwashCache, scale_ctx: ScaleContext,
#[cfg(windows)]
dwrite: Option<DirectWriteRasterizer>,
atlas: GlyphAtlas, atlas: GlyphAtlas,
scale_factor: f32, scale_factor: f32,
ys_text_family: String, ys_text_family: String,
ys_headline_family: String, ys_headline_family: String,
shape_cache: HashMap<ShapeCacheKey, (Buffer, Vec2)>, frame_gen: u64,
shape_cache: HashMap<ShapeCacheKey, ((Buffer, Vec2), u64)>,
rich_shape_cache: HashMap<RichShapeCacheKey, ((Buffer, f32), u64)>,
} }
impl Default for TextEngine { impl Default for TextEngine {
@ -356,15 +438,24 @@ impl TextEngine {
Self { Self {
font_system, font_system,
swash_cache: SwashCache::new(), scale_ctx: ScaleContext::new(),
#[cfg(windows)]
dwrite: DirectWriteRasterizer::new(),
atlas: GlyphAtlas::new(), atlas: GlyphAtlas::new(),
scale_factor: 1.0, scale_factor: 1.0,
ys_text_family, ys_text_family,
ys_headline_family, ys_headline_family,
frame_gen: 1,
shape_cache: HashMap::with_capacity(256), shape_cache: HashMap::with_capacity(256),
rich_shape_cache: HashMap::with_capacity(128),
} }
} }
#[inline]
pub fn begin_frame(&mut self) {
self.frame_gen = self.frame_gen.wrapping_add(1);
}
#[inline] #[inline]
pub fn set_scale_factor(&mut self, scale: f32) { pub fn set_scale_factor(&mut self, scale: f32) {
self.scale_factor = scale.clamp(0.5, 4.0); self.scale_factor = scale.clamp(0.5, 4.0);
@ -377,10 +468,10 @@ impl TextEngine {
pub fn attrs_for(&self, style: TextStyle) -> Attrs<'_> { pub fn attrs_for(&self, style: TextStyle) -> Attrs<'_> {
let (family, weight) = match style.role { let (family, weight) = match style.role {
FontRole::Regular => (Family::Name(&self.ys_text_family), Weight::NORMAL), FontRole::Regular => (Family::Name(&self.ys_text_family), cosmic_text::Weight::NORMAL),
FontRole::Medium => (Family::Name(&self.ys_text_family), Weight::MEDIUM), FontRole::Medium => (Family::Name(&self.ys_text_family), cosmic_text::Weight::MEDIUM),
FontRole::Bold => (Family::Name(&self.ys_text_family), Weight::BOLD), FontRole::Bold => (Family::Name(&self.ys_text_family), cosmic_text::Weight::BOLD),
FontRole::Headline => (Family::Name(&self.ys_headline_family), Weight::BOLD), FontRole::Headline => (Family::Name(&self.ys_headline_family), cosmic_text::Weight::BOLD),
}; };
Attrs::new() Attrs::new()
.family(family) .family(family)
@ -437,7 +528,7 @@ impl TextEngine {
} }
let (key, size) = let (key, size) =
self.get_or_shape(text, style, Some(rect.w), Some(1), true, align); self.get_or_shape(text, style, Some(rect.w), Some(1), true, align);
let y = rect.center_y() - size.y * 0.5 + 1.0; let y = rect.center_y() - size.y * 0.5;
let x = rect.x; let x = rect.x;
self.emit_cached_buffer(dl, textures, key, Pos2::new(x, y), style.color, Some(1)); self.emit_cached_buffer(dl, textures, key, Pos2::new(x, y), style.color, Some(1));
size size
@ -492,7 +583,7 @@ impl TextEngine {
self.emit_cached_buffer(dl, textures, key, origin, style.color, None); self.emit_cached_buffer(dl, textures, key, origin, style.color, None);
return size; return size;
} }
let Some((buffer, _)) = self.shape_cache.get(&key) else { let Some(((buffer, _), _)) = self.shape_cache.get(&key) else {
return size; return size;
}; };
@ -513,7 +604,9 @@ impl TextEngine {
if let Some(entry) = self.atlas.get_or_insert( if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key, phys.cache_key,
&mut self.font_system, &mut self.font_system,
&mut self.swash_cache, &mut self.scale_ctx,
#[cfg(windows)]
&mut self.dwrite,
textures, textures,
) { ) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_dpi; let gx = (origin_px + (phys.x + entry.left) as f32) * inv_dpi;
@ -547,36 +640,72 @@ impl TextEngine {
return Vec::new(); return Vec::new();
} }
let base_style = spans[0].style; let base_style = spans[0].style;
let metrics = Metrics::new(base_style.size, base_style.line_height); let box_h = rect.h.max(base_style.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
buffer.set_wrap(if max_lines == Some(1) {
Wrap::None
} else {
Wrap::WordOrGlyph
});
if let Some(n) = max_lines {
buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(n)));
}
buffer.set_size(Some(rect.w), Some(rect.h.max(base_style.line_height)));
let default_attrs = self.attrs_for(base_style); let mut hasher = std::collections::hash_map::DefaultHasher::new();
let rich_items: Vec<(&str, Attrs<'_>)> = spans let mut total_len = 0usize;
.iter() for sp in spans {
.map(|sp| { sp.text.hash(&mut hasher);
let a = self.attrs_for(sp.style).metadata(sp.metadata); sp.style.role.hash(&mut hasher);
(sp.text, a) sp.style.size.to_bits().hash(&mut hasher);
}) sp.style.line_height.to_bits().hash(&mut hasher);
.collect(); sp.style.color.to_packed_u32().hash(&mut hasher);
buffer.set_rich_text( sp.metadata.hash(&mut hasher);
rich_items, total_len += sp.text.len();
&default_attrs, }
Shaping::Advanced, let key = RichShapeCacheKey {
Some(align.to_cosmic()), spans_hash: hasher.finish(),
); span_count: spans.len() as u16,
buffer.shape_until_scroll(&mut self.font_system, false); total_len,
rect_w_bits: rect.w.to_bits(),
rect_h_bits: box_h.to_bits(),
max_lines: max_lines.unwrap_or(0) as u16,
align,
};
let cur_gen = self.frame_gen;
let content_h = if let Some(((_, ch), gen)) = self.rich_shape_cache.get_mut(&key) {
*gen = cur_gen;
*ch
} else {
evict_stale_entries(&mut self.rich_shape_cache, 256, cur_gen);
let metrics = Metrics::new(base_style.size, base_style.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics);
buffer.set_wrap(if max_lines == Some(1) {
Wrap::None
} else {
Wrap::WordOrGlyph
});
if let Some(n) = max_lines {
buffer.set_ellipsize(Ellipsize::End(EllipsizeHeightLimit::Lines(n)));
}
buffer.set_size(Some(rect.w), Some(box_h));
let default_attrs = self.attrs_for(base_style);
let rich_items: Vec<(&str, Attrs<'_>)> = spans
.iter()
.map(|sp| {
let a = self.attrs_for(sp.style).metadata(sp.metadata);
(sp.text, a)
})
.collect();
buffer.set_rich_text(
rich_items,
&default_attrs,
Shaping::Advanced,
Some(align.to_cosmic()),
);
buffer.shape_until_scroll(&mut self.font_system, false);
let ch = measure_buffer_size(&buffer, max_lines).y;
self.rich_shape_cache.insert(key, ((buffer, ch), cur_gen));
ch
};
let Some(((buffer, _), _)) = self.rich_shape_cache.get(&key) else {
return Vec::new();
};
// Vertically center if single-line inside a taller box // Vertically center if single-line inside a taller box
let content_h = measure_buffer_size(&buffer, max_lines).y;
let origin_y = if max_lines == Some(1) && rect.h > content_h { let origin_y = if max_lines == Some(1) && rect.h > content_h {
rect.center_y() - content_h * 0.5 rect.center_y() - content_h * 0.5
} else { } else {
@ -589,6 +718,7 @@ impl TextEngine {
let inv_scale = 1.0 / scale; let inv_scale = 1.0 / scale;
let origin_px = (origin.x * scale).round(); let origin_px = (origin.x * scale).round();
let mut glyphs_to_draw = Vec::with_capacity(64);
for (run_idx, run) in buffer.layout_runs().enumerate() { for (run_idx, run) in buffer.layout_runs().enumerate() {
if let Some(limit) = max_lines { if let Some(limit) = max_lines {
if run_idx >= limit { if run_idx >= limit {
@ -616,18 +746,24 @@ impl TextEngine {
} }
let phys = glyph.physical((0.0, 0.0), scale); let phys = glyph.physical((0.0, 0.0), scale);
if let Some(entry) = self.atlas.get_or_insert( glyphs_to_draw.push((phys, baseline_py, col));
phys.cache_key, }
&mut self.font_system, }
&mut self.swash_cache,
textures, for (phys, baseline_py, col) in glyphs_to_draw {
) { if let Some(entry) = self.atlas.get_or_insert(
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale; phys.cache_key,
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_scale; &mut self.font_system,
let gw = entry.width as f32 * inv_scale; &mut self.scale_ctx,
let gh = entry.height as f32 * inv_scale; #[cfg(windows)]
dl.push_glyph(Rect::from_xywh(gx, gy, gw, gh), entry.uv, col); &mut self.dwrite,
} textures,
) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
let gy = (baseline_py + (phys.y - entry.top) as f32) * inv_scale;
let gw = entry.width as f32 * inv_scale;
let gh = entry.height as f32 * inv_scale;
dl.push_glyph(Rect::from_xywh(gx, gy, gw, gh), entry.uv, col);
} }
} }
@ -659,14 +795,14 @@ impl TextEngine {
align, align,
}; };
if let Some((_, size)) = self.shape_cache.get(&key) { let cur_gen = self.frame_gen;
if let Some(((_, size), gen)) = self.shape_cache.get_mut(&key) {
*gen = cur_gen;
return (key, *size); return (key, *size);
} }
// Bound cache memory so RAM stays tiny even during infinite browsing // Bound cache memory with generational eviction so visible strings stay warm during scroll
if self.shape_cache.len() > 640 { evict_stale_entries(&mut self.shape_cache, 1024, cur_gen);
self.shape_cache.clear();
}
let metrics = Metrics::new(style.size, style.line_height); let metrics = Metrics::new(style.size, style.line_height);
let mut buffer = Buffer::new(&mut self.font_system, metrics); let mut buffer = Buffer::new(&mut self.font_system, metrics);
@ -691,7 +827,7 @@ impl TextEngine {
buffer.shape_until_scroll(&mut self.font_system, false); buffer.shape_until_scroll(&mut self.font_system, false);
let size = measure_buffer_size(&buffer, max_lines); let size = measure_buffer_size(&buffer, max_lines);
self.shape_cache.insert(key, (buffer, size)); self.shape_cache.insert(key, ((buffer, size), cur_gen));
(key, size) (key, size)
} }
@ -704,7 +840,7 @@ impl TextEngine {
color: Color, color: Color,
max_lines: Option<usize>, max_lines: Option<usize>,
) { ) {
let Some((buffer, _)) = self.shape_cache.get(&key) else { let Some(((buffer, _), _)) = self.shape_cache.get(&key) else {
return; return;
}; };
// Collect physical glyphs first so we don't hold an immutable borrow of `self.shape_cache` // Collect physical glyphs first so we don't hold an immutable borrow of `self.shape_cache`
@ -729,7 +865,9 @@ impl TextEngine {
if let Some(entry) = self.atlas.get_or_insert( if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key, phys.cache_key,
&mut self.font_system, &mut self.font_system,
&mut self.swash_cache, &mut self.scale_ctx,
#[cfg(windows)]
&mut self.dwrite,
textures, textures,
) { ) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale; let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
@ -761,7 +899,7 @@ impl TextEngine {
return Vec2::ZERO; return Vec2::ZERO;
} }
let (key, size) = self.get_or_shape(text, style, None, Some(1), false, TextAlign::Left); let (key, size) = self.get_or_shape(text, style, None, Some(1), false, TextAlign::Left);
let Some((buffer, _)) = self.shape_cache.get(&key) else { let Some(((buffer, _), _)) = self.shape_cache.get(&key) else {
return size; return size;
}; };
@ -786,7 +924,9 @@ impl TextEngine {
if let Some(entry) = self.atlas.get_or_insert( if let Some(entry) = self.atlas.get_or_insert(
phys.cache_key, phys.cache_key,
&mut self.font_system, &mut self.font_system,
&mut self.swash_cache, &mut self.scale_ctx,
#[cfg(windows)]
&mut self.dwrite,
textures, textures,
) { ) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale; let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
@ -837,6 +977,61 @@ fn measure_buffer_size(buffer: &Buffer, max_lines: Option<usize>) -> Vec2 {
Vec2::new(max_w.ceil(), total_h.ceil()) Vec2::new(max_w.ceil(), total_h.ceil())
} }
/// Rasterize a single glyph via `swash` with `text-rendering: geometricprecision` (`hint(false)`),
/// 3x horizontal subpixel oversampling, and subtle small-size stem darkening matching Windows
/// DirectWrite / Chromium (`DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC`).
fn rasterize_glyph_directwrite_parity(
font_system: &mut FontSystem,
scale_ctx: &mut ScaleContext,
key: CacheKey,
) -> Option<swash::scale::image::Image> {
let font = font_system.get_font(key.font_id, key.font_weight)?;
let font_size = f32::from_bits(key.font_size_bits);
let swash_font = font.as_swash();
let mut scaler_builder = scale_ctx
.builder(swash_font)
.size(font_size)
.hint(false);
if let Some(variation) = swash_font
.variations()
.find_by_tag(swash::Tag::from_be_bytes(*b"wght"))
{
scaler_builder = scaler_builder.normalized_coords(
swash_font.variations().normalized_coords([(
swash::Tag::from_be_bytes(*b"wght"),
f32::from(key.font_weight.0).clamp(variation.min_value(), variation.max_value()),
)]),
);
}
let mut scaler = scaler_builder.build();
let offset = if key.flags.contains(CacheKeyFlags::PIXEL_FONT) {
Vector::new(key.x_bin.as_float().round(), key.y_bin.as_float().round())
} else {
Vector::new(key.x_bin.as_float(), key.y_bin.as_float())
};
// Subtle perceptual stem darkening on UI sizes (<= 24px), tapering smoothly to 0 on headlines.
let stem_darkening = ((28.0 - font_size) / 16.0).clamp(0.0, 1.0) * 0.10;
Render::new(&[
Source::ColorOutline(0),
Source::ColorBitmap(StrikeWith::BestFit),
Source::Outline,
])
.format(Format::Subpixel)
.offset(offset)
.embolden(stem_darkening)
.transform(if key.flags.contains(CacheKeyFlags::FAKE_ITALIC) {
Some(Transform::skew(Angle::from_degrees(14.0), Angle::from_degrees(0.0)))
} else {
None
})
.render(&mut scaler, key.glyph_id)
}
fn load_font_and_detect_family( fn load_font_and_detect_family(
db: &mut cosmic_text::fontdb::Database, db: &mut cosmic_text::fontdb::Database,
bytes: &'static [u8], bytes: &'static [u8],
@ -1214,7 +1409,9 @@ impl TextInputState {
if let Some(entry) = text_engine.atlas.get_or_insert( if let Some(entry) = text_engine.atlas.get_or_insert(
phys.cache_key, phys.cache_key,
&mut text_engine.font_system, &mut text_engine.font_system,
&mut text_engine.swash_cache, &mut text_engine.scale_ctx,
#[cfg(windows)]
&mut text_engine.dwrite,
textures, textures,
) { ) {
let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale; let gx = (origin_px + (phys.x + entry.left) as f32) * inv_scale;
@ -1255,3 +1452,107 @@ pub fn paste_from_clipboard() -> Option<String> {
let mut cb = arboard::Clipboard::new().ok()?; let mut cb = arboard::Clipboard::new().ok()?;
cb.get_text().ok() cb.get_text().ok()
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn glyph_rasterization_matches_directwrite_stroke_mass() {
let mut engine = TextEngine::new();
let style = TextStyle::medium(13.0, Color::rgb(0xE6, 0xE6, 0xE6));
let (key, size) = engine.get_or_shape("Мой 2025", style, None, Some(1), false, TextAlign::Left);
assert!(size.x >= 56.0 && size.x <= 62.0, "unexpected width: {}", size.x);
let buffer = &engine.shape_cache[&key].0 .0;
let run = buffer.layout_runs().next().expect("layout run");
let glyphs: Vec<_> = run.glyphs.iter().map(|g| g.physical((0.0, 0.0), 1.0)).collect();
// Simulate shader gamma for #E6E6E6 (fg_luma = 0.90196 >= 0.85 => smoothstep = 1.0)
let glyph_gamma = 0.62f32;
let mut total_sum = 0.0f64;
let mut nonzero = 0usize;
for phys in glyphs {
#[cfg(windows)]
let r8_opt = engine
.dwrite
.as_mut()
.and_then(|dw| dw.rasterize(&engine.font_system, phys.cache_key))
.map(|g| g.r8_pixels);
#[cfg(not(windows))]
let r8_opt: Option<Vec<u8>> = None;
let pixels = r8_opt.unwrap_or_else(|| {
rasterize_glyph_directwrite_parity(
&mut engine.font_system,
&mut engine.scale_ctx,
phys.cache_key,
)
.map(|img| {
img.data
.chunks_exact(4)
.map(|px| ((px[0] as u16 + px[1] as u16 + px[2] as u16 + 1) / 3) as u8)
.collect()
})
.unwrap_or_default()
});
for byte in pixels {
let r8 = byte as f32 / 255.0;
if r8 > 0.0001 {
let cov = r8.powf(glyph_gamma);
let v = cov * 230.0;
if v > 5.0 {
nonzero += 1;
total_sum += v as f64;
}
}
}
}
// Original Yandex Music (Chromium/DirectWrite) on "Мой 2025" at 13px #E6E6E6: sum ~= 66384, nz ~= 428
eprintln!(
"[glyph_parity] 'Мой 2025' 13px #E6E6E6: w={:.1} sum={:.0} nz={}",
size.x, total_sum, nonzero
);
assert!(
total_sum >= 50_000.0 && total_sum <= 72_000.0,
"stroke mass {:.0} out of DirectWrite parity range [60000..72000]",
total_sum
);
}
#[test]
fn rich_text_cache_hits_and_evicts_stale_entries() {
let mut engine = TextEngine::new();
let mut textures = TextureRegistry::new();
let spans = [
RichSpan::tagged("Artist One", TextStyle::medium(14.0, Color::WHITE), 1),
RichSpan::new(", ", TextStyle::medium(14.0, Color::WHITE)),
RichSpan::tagged("Artist Two", TextStyle::medium(14.0, Color::WHITE), 2),
];
let rect1 = Rect::from_xywh(10.0, 20.0, 240.0, 20.0);
let rect2 = Rect::from_xywh(10.0, 76.0, 240.0, 20.0);
let mut dl1 = DisplayList::new();
let r1 = engine.draw_rich_text(&mut dl1, &mut textures, &spans, rect1, Some(1), TextAlign::Left);
assert_eq!(engine.rich_shape_cache.len(), 1);
engine.begin_frame();
let mut dl2 = DisplayList::new();
let r2 = engine.draw_rich_text(&mut dl2, &mut textures, &spans, rect2, Some(1), TextAlign::Left);
assert_eq!(engine.rich_shape_cache.len(), 1, "scrolled rich text should hit cache");
assert_eq!(dl1.instances.len(), dl2.instances.len());
assert_eq!(r1.len(), 2);
assert_eq!(r2.len(), 2);
assert!((r2[0].1.y - r1[0].1.y - 56.0).abs() < 0.01);
let mut map: HashMap<usize, (u8, u64)> = HashMap::new();
for i in 0..300 {
map.insert(i, (0, if i >= 260 { 10 } else { 1 }));
}
evict_stale_entries(&mut map, 256, 10);
assert!(map.len() <= 256);
assert!(map.contains_key(&299), "recently used entry must be retained");
assert!(!map.contains_key(&0), "stale entry must be evicted");
}
}

View file

@ -702,6 +702,8 @@ pub enum CursorKind {
Grabbing, Grabbing,
ResizeHorizontal, ResizeHorizontal,
ResizeVertical, ResizeVertical,
ResizeNwSe,
ResizeNeSw,
NotAllowed, NotAllowed,
} }
@ -715,6 +717,8 @@ impl CursorKind {
CursorKind::Grabbing => winit::window::CursorIcon::Grabbing, CursorKind::Grabbing => winit::window::CursorIcon::Grabbing,
CursorKind::ResizeHorizontal => winit::window::CursorIcon::EwResize, CursorKind::ResizeHorizontal => winit::window::CursorIcon::EwResize,
CursorKind::ResizeVertical => winit::window::CursorIcon::NsResize, CursorKind::ResizeVertical => winit::window::CursorIcon::NsResize,
CursorKind::ResizeNwSe => winit::window::CursorIcon::NwseResize,
CursorKind::ResizeNeSw => winit::window::CursorIcon::NeswResize,
CursorKind::NotAllowed => winit::window::CursorIcon::NotAllowed, CursorKind::NotAllowed => winit::window::CursorIcon::NotAllowed,
} }
} }
@ -730,6 +734,7 @@ pub const MODE_SHADOW: u32 = 5;
pub const MODE_LINE: u32 = 6; pub const MODE_LINE: u32 = 6;
pub const FLAG_RING_ONLY: u32 = 1 << 0; pub const FLAG_RING_ONLY: u32 = 1 << 0;
pub const FLAG_LUMINOSITY_BLEND: u32 = 1 << 1;
/// GPU instance record uploaded directly to the `UiVulkanRenderer` SSBO (exact 112 bytes, std430-aligned). /// GPU instance record uploaded directly to the `UiVulkanRenderer` SSBO (exact 112 bytes, std430-aligned).
#[repr(C)] #[repr(C)]
@ -984,7 +989,8 @@ impl DisplayList {
self.instances.push(UiInstance { self.instances.push(UiInstance {
rect: rect.to_array(), rect: rect.to_array(),
radii: CornerRadii::same(radius).to_array(), radii: CornerRadii::same(radius).to_array(),
uv_or_params: [0.7071, 0.7071, 0.0, 0.0], // Exact `plus.0bddd56c.svg` / `plus.e731b15a.svg` horizontal linearGradient (`x1="0" x2="56"`).
uv_or_params: [1.0, 0.0, 0.0, 0.0],
clip_rect, clip_rect,
colors: [tint, tint, tint, 0], colors: [tint, tint, tint, 0],
metrics: [thickness, clip_radius, 0.0, 0.0], metrics: [thickness, clip_radius, 0.0, 0.0],
@ -1053,6 +1059,35 @@ impl DisplayList {
}); });
} }
/// SDF-clipped textured quad composited over `backdrop` using exact W3C `mix-blend-mode: luminosity`
/// with `opacity` (e.g. `0.5` for official `.VibeButton_image__GOwKJ`) and optional `brightness` (`1.15` on hover).
#[allow(clippy::too_many_arguments)]
pub fn push_image_uv_luminosity(
&mut self,
rect: Rect,
texture: TextureId,
uv: Rect,
radii: impl Into<CornerRadii>,
backdrop: Color,
opacity: f32,
brightness: f32,
) {
if rect.is_empty() || backdrop.a == 0 || texture == NONE_TEXTURE_ID {
return;
}
let (clip_rect, clip_radius) = self.clip_fields();
let c = backdrop.to_packed_u32();
self.instances.push(UiInstance {
rect: rect.to_array(),
radii: radii.into().to_array(),
uv_or_params: uv.to_uv_array(),
clip_rect,
colors: [c, c, 0, 0],
metrics: [0.0, clip_radius, opacity.clamp(0.0, 1.0), brightness.max(0.0)],
meta: [MODE_TEXTURED, texture.0, FLAG_LUMINOSITY_BLEND, 0],
});
}
pub fn push_image_bordered( pub fn push_image_bordered(
&mut self, &mut self,
rect: Rect, rect: Rect,

View file

@ -16,8 +16,8 @@ pub fn ym_menu_frame(ctx: &mut UiContext, pal: &YmPalette, rect: Rect) -> Rect {
let dl = ctx.dl(); let dl = ctx.dl();
// Analytical shadow: `box-shadow: 0 1px 20px 0 var(--ym-shadow-menu)` // Analytical shadow: `box-shadow: 0 1px 20px 0 var(--ym-shadow-menu)`
dl.push_shadow(rect, 16.0, 20.0, 0.0, Vec2::new(0.0, 2.0), pal.shadow_menu); dl.push_shadow(rect, 16.0, 20.0, 0.0, Vec2::new(0.0, 2.0), pal.shadow_menu);
// Real Dual Kawase backdrop-filter blur + translucent tint + subtle 1px border // Exact `.s7_MO4NdsYs7nPQALD8W`: `backdrop-filter: blur(.875rem); background: rgba(26,26,26,.70); border: none;`
dl.push_backdrop_blur(rect, 16.0, 2.0, pal.bg_menu, 1.0, pal.border_subtle); dl.push_backdrop_blur(rect, 16.0, 3.5, pal.bg_menu, 0.0, Color::TRANSPARENT);
rect.shrink(8.0) rect.shrink(8.0)
} }
@ -79,6 +79,9 @@ pub fn ym_menu_item_ex(
ctx.dl().push_rect(rect, 8.0, bg); ctx.dl().push_rect(rect, 8.0, bg);
} }
// Exact 5.129.0 `.EiyUV4aCJzpfNzuihfMM` (`5495aae20be2440c.css`):
// idle = `--ym-controls-color-primary-text-enabled` (`pal.text_secondary`: hsla(0,0%,100%,.5) / #666)
// hover = `--ym-controls-color-primary-text-enabled_variant` (`pal.text_primary`: #e6e6e6 / #1a1a1a)
let fg = if disabled { let fg = if disabled {
pal.text_disabled pal.text_disabled
} else if active { } else if active {
@ -88,9 +91,9 @@ pub fn ym_menu_item_ex(
pal.outline_selected pal.outline_selected
} }
} else if resp.hovered { } else if resp.hovered {
pal.text_bright
} else {
pal.text_primary pal.text_primary
} else {
pal.text_secondary
}; };
let icon_rect = Rect::from_center_size(Pos2::new(rect.left() + 18.0, rect.center_y()), Vec2::splat(20.0)); let icon_rect = Rect::from_center_size(Pos2::new(rect.left() + 18.0, rect.center_y()), Vec2::splat(20.0));
@ -203,6 +206,53 @@ pub fn yellow_pill_button(
(resp, rect) (resp, rect)
} }
/// Official Yandex Music circular user avatar with standard Yandex ID silhouette fallback
/// when no avatar photo is set or while loading.
pub fn draw_user_avatar(
ctx: &mut UiContext,
pal: &YmPalette,
covers: &mut CoverCache,
center: Pos2,
diam: f32,
avatar_uri: Option<&str>,
has_plus: bool,
) {
let r = diam * 0.5;
let rect = Rect::from_center_size(center, Vec2::splat(diam));
let mut drew_photo = false;
if let Some(uri) = avatar_uri {
// Request 256px so `islands-200` avatars keep full native 200x200 resolution without downscale blur.
if let Some((tex_id, _, _, tw, th)) = covers.get_or_fetch_with_size(uri, 256) {
let uv = cover_fit_uv(tw, th, rect, 0.5);
ctx.dl()
.push_image_uv(rect, tex_id, uv, CornerRadii::same(r), Color::WHITE);
drew_photo = true;
}
}
if !drew_photo {
if !has_plus {
ctx.dl()
.push_circle_stroke(center, r + 2.5, 1.5, pal.border_control);
}
let bg = if pal.is_dark {
Color::rgb(0x2B, 0x2B, 0x2B)
} else {
Color::rgb(0xE6, 0xE6, 0xE6)
};
let fg = if pal.is_dark {
Color::rgb(0x9E, 0x9E, 0x9E)
} else {
Color::rgb(0x66, 0x66, 0x66)
};
ctx.dl().push_circle(center, r, bg);
ctx.draw_icon(
Icon::ProfileAccountXxs,
Rect::from_center_size(center, Vec2::splat((diam * 0.58).round())),
fg,
);
}
}
/// Primary yellow pill button drawn inside an explicit `rect`. /// Primary yellow pill button drawn inside an explicit `rect`.
pub fn yellow_pill_button_in( pub fn yellow_pill_button_in(
ctx: &mut UiContext, ctx: &mut UiContext,
@ -348,8 +398,9 @@ pub fn draw_plus_badge(
label: &str, label: &str,
) -> (Interaction, Rect) { ) -> (Interaction, Rect) {
let clean = label.trim_start_matches('+').trim(); let clean = label.trim_start_matches('+').trim();
let text_sz = ctx.measure_text(clean, TextStyle::medium(14.0, Color::WHITE), None); let fg = Color::WHITE.with_alpha_f32(0.90); // --ym-controls-color-plus-on_default-enabled: hsla(0,0%,100%,.9)
let pill_w = (22.0 + text_sz.x + 10.0).max(58.0); let text_sz = ctx.measure_text(clean, TextStyle::medium(14.0, fg), None);
let pill_w = (22.0 + text_sz.x + 7.0).max(58.0);
let rect = Rect::from_min_size(pos, Vec2::new(pill_w, 20.0)); let rect = Rect::from_min_size(pos, Vec2::new(pill_w, 20.0));
let resp = ctx.interact(id, rect); let resp = ctx.interact(id, rect);
@ -358,7 +409,7 @@ pub fn draw_plus_badge(
.push_plus_gradient_rect(rect, rect.height() * 0.5, alpha); .push_plus_gradient_rect(rect, rect.height() * 0.5, alpha);
let emblem_r = Rect::from_center_size(Pos2::new(rect.left() + 11.0, rect.center_y()), Vec2::splat(14.0)); let emblem_r = Rect::from_center_size(Pos2::new(rect.left() + 11.0, rect.center_y()), Vec2::splat(14.0));
ctx.draw_icon(Icon::Plus, emblem_r, Color::WHITE); ctx.draw_icon(Icon::Plus, emblem_r, fg);
let tx_rect = Rect::from_xywh( let tx_rect = Rect::from_xywh(
rect.left() + 21.0, rect.left() + 21.0,
@ -366,7 +417,7 @@ pub fn draw_plus_badge(
(rect.width() - 25.0).max(12.0), (rect.width() - 25.0).max(12.0),
rect.height(), rect.height(),
); );
ctx.draw_text_ellipsis(clean, TextStyle::medium(14.0, Color::WHITE), tx_rect, TextAlign::Left); ctx.draw_text_ellipsis(clean, TextStyle::medium(14.0, fg), tx_rect, TextAlign::Left);
if resp.hovered { if resp.hovered {
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
@ -679,12 +730,24 @@ pub fn track_row(
x += 44.0; // 36px number slot + 8px gap x += 44.0; // 36px number slot + 8px gap
} }
// Right controls area: Dislike (40px) + Like (40px, 56px left of duration) + Duration/More swap slot // Right controls area (`CommonControlsBar_root__N8b0F`, gap 16px, item 40x40 => 56px center-to-center):
// Exact 1280x800 CDP measurements against `favorites.jpg`: duration cx = right - 32.5, heart cx = duration cx - 56.0 // [Dislike (hover/disliked)] + [Download (if downloaded/downloading)] + [Like (heart)] + [Duration/More swap]
// Exact 1280x800 CDP measurements: duration cx = right - 32.5, heart cx = duration cx - 56.0, download cx = heart cx - 56.0
let has_download_slot = opts.is_downloaded || opts.is_downloading;
let slot_more_cx = rect.right() - 32.5; let slot_more_cx = rect.right() - 32.5;
let slot_like_cx = slot_more_cx - 56.0; let slot_like_cx = slot_more_cx - 56.0;
let slot_dislike_cx = slot_like_cx - 40.0; let slot_download_cx = slot_like_cx - 56.0;
let right_reserved = if hovered || opts.is_disliked { 160.0 } else { 124.0 }; let slot_dislike_cx = if has_download_slot {
slot_download_cx - 44.0
} else {
slot_like_cx - 40.0
};
let right_reserved = match (has_download_slot, hovered || opts.is_disliked) {
(true, true) => 216.0,
(true, false) => 176.0,
(false, true) => 160.0,
(false, false) => 124.0,
};
let title_col_w = (rect.right() - right_reserved - x - 8.0).max(80.0); let title_col_w = (rect.right() - right_reserved - x - 8.0).max(80.0);
let title_color = if opts.is_disliked && !hovered { let title_color = if opts.is_disliked && !hovered {
@ -698,13 +761,8 @@ pub fn track_row(
pal.text_secondary pal.text_secondary
}; };
// Title + optional version + explicit badge + downloaded/downloading badge // Title + optional version + explicit badge
let badge_w = if track.is_explicit { 22.0 } else { 0.0 } 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 title_rect = Rect::from_xywh(x, rect.top() + 9.5, (title_col_w - badge_w).max(40.0), 20.0);
let version_text = track let version_text = track
.version .version
@ -716,44 +774,25 @@ pub fn track_row(
if let Some(ref vt) = version_text { if let Some(ref vt) = version_text {
title_spans.push(RichSpan::new(vt, TextStyle::medium(14.0, ver_color))); title_spans.push(RichSpan::new(vt, TextStyle::medium(14.0, ver_color)));
} }
let measured_title_w = ctx
.measure_text(
&match &version_text {
Some(vt) => format!("{}{}", track.title, vt),
None => track.title.clone(),
},
TextStyle::medium(14.0, title_color),
None,
)
.x
.min(title_rect.width());
ctx.draw_rich_text(&title_spans, title_rect, Some(1), TextAlign::Left); ctx.draw_rich_text(&title_spans, title_rect, Some(1), TextAlign::Left);
let mut badge_x = title_rect.left() + measured_title_w + 4.0;
if track.is_explicit { if track.is_explicit {
let measured_title_w = match &version_text {
Some(vt) => ctx.measure_text(
&format!("{}{}", track.title, vt),
TextStyle::medium(14.0, title_color),
None,
),
None => ctx.measure_text(&track.title, TextStyle::medium(14.0, title_color), None),
}
.x
.min(title_rect.width());
let badge_x = title_rect.left() + measured_title_w + 4.0;
ctx.draw_icon( ctx.draw_icon(
Icon::Explicit, Icon::Explicit,
Rect::from_center_size(Pos2::new(badge_x + 9.0, title_rect.center_y()), Vec2::splat(18.0)), Rect::from_center_size(Pos2::new(badge_x + 9.0, title_rect.center_y()), Vec2::splat(18.0)),
ver_color, ver_color,
); );
badge_x += 22.0;
}
if opts.is_downloading {
draw_downloading_progress(
ctx,
pal,
Pos2::new(badge_x + 8.0, title_rect.center_y()),
16.0,
opts.download_progress,
false,
false,
);
} else if opts.is_downloaded {
ctx.draw_icon(
Icon::Downloaded,
Rect::from_center_size(Pos2::new(badge_x + 8.0, title_rect.center_y()), Vec2::splat(16.0)),
pal.success,
);
} }
// Individually clickable multi-artists (`SeparatedArtists`)! // Individually clickable multi-artists (`SeparatedArtists`)!
@ -807,6 +846,27 @@ pub fn track_row(
} }
} }
// Official `CommonControlsBar_downloadIcon` (`TrackDownloadControl`):
// 20x20 (`size="xxs"`) vertically centered in row, 56px left of Like button.
// `downloaded_xxs.svg` already has `fill="#51CF66"` baked in from `sprite.svg`, so pass `Color::WHITE` (no double-tint).
if opts.is_downloading {
draw_downloading_progress(
ctx,
pal,
Pos2::new(slot_download_cx, cy),
16.0,
opts.download_progress,
false,
false,
);
} else if opts.is_downloaded {
ctx.draw_icon(
Icon::Downloaded,
Rect::from_center_size(Pos2::new(slot_download_cx, cy), Vec2::splat(20.0)),
Color::WHITE,
);
}
// Like button (40x40 slot) — official 5.129.0 renders muted gray hearts in track lists (`favorites.jpg`) // Like button (40x40 slot) — official 5.129.0 renders muted gray hearts in track lists (`favorites.jpg`)
let like_rect = Rect::from_center_size(Pos2::new(slot_like_cx, cy), Vec2::splat(36.0)); let like_rect = Rect::from_center_size(Pos2::new(slot_like_cx, cy), Vec2::splat(36.0));
if hovered || opts.is_liked { if hovered || opts.is_liked {
@ -923,30 +983,30 @@ pub fn separated_artists(
}; };
let in_line = ctx.input.is_hovered_in(ctx.current_layer(), rect, clip); let in_line = ctx.input.is_hovered_in(ctx.current_layer(), rect, clip);
// Pre-pass: estimate horizontal span positions for single-line hover tinting // Pre-pass: only measure individual artist spans when the pointer is actually over this line
let sep_w = ctx
.measure_text(", ", TextStyle::medium(font_size, normal_color), None)
.x;
let mut total_w = 0.0f32;
let mut widths = Vec::with_capacity(artists.len());
for (i, a) in artists.iter().enumerate() {
let w = ctx
.measure_text(&a.name, TextStyle::medium(font_size, normal_color), None)
.x;
widths.push(w);
total_w += w;
if i + 1 < artists.len() {
total_w += sep_w;
}
}
let start_x = match align {
TextAlign::Left => rect.x,
TextAlign::Center => rect.x + ((rect.w - total_w.min(rect.w)) * 0.5).max(0.0),
TextAlign::Right => (rect.right() - total_w.min(rect.w)).max(rect.x),
};
let mut hovered_idx: Option<usize> = None; let mut hovered_idx: Option<usize> = None;
if in_line { if in_line {
if let Some(p) = pointer { if let Some(p) = pointer {
let sep_w = ctx
.measure_text(", ", TextStyle::medium(font_size, normal_color), None)
.x;
let mut total_w = 0.0f32;
let mut widths = Vec::with_capacity(artists.len());
for (i, a) in artists.iter().enumerate() {
let w = ctx
.measure_text(&a.name, TextStyle::medium(font_size, normal_color), None)
.x;
widths.push(w);
total_w += w;
if i + 1 < artists.len() {
total_w += sep_w;
}
}
let start_x = match align {
TextAlign::Left => rect.x,
TextAlign::Center => rect.x + ((rect.w - total_w.min(rect.w)) * 0.5).max(0.0),
TextAlign::Right => (rect.right() - total_w.min(rect.w)).max(rect.x),
};
let mut cx = start_x; let mut cx = start_x;
for (i, &w) in widths.iter().enumerate() { for (i, &w) in widths.iter().enumerate() {
if p.x >= cx && p.x <= (cx + w).min(rect.right()) { if p.x >= cx && p.x <= (cx + w).min(rect.right()) {
@ -1449,63 +1509,71 @@ pub fn ym_slider(
} }
} }
/// Official 5.129.0 vertical volume / EQ slider (`5b3a6ee99e2bd1b8.css` `.VibePlayerBar_verticalSlider` /// Official 5.129.0 vertical volume slider (`5b3a6ee99e2bd1b8.css` `.ChangeVolume_slider`
/// & `.ChangeVolume_wrapperSlider`): /// & `.ChangeVolume_wrapperSlider`, `5495aae20be2440c.css`, `1d39aa9337a03444.css`):
/// - `8px` wide centered rounded pill track (`radius = 4px`), unfilled `rgba(255,255,255,0.20)` /// - `8px` wide × `192px` (`12rem`) centered rounded pill track (`radius = 4px`),
/// - Idle fill: `#E6E6E6` white-gray (NOT yellow!) with NO circular thumb ball /// unfilled `hsla(0,0%,100%,.16)` (dark/glass) or `rgba(0,0,0,.16)` (light)
/// - Direct hover/drag on slider: smoothly reveals `16px` (`radius = 8px`) circular thumb and transitions /// - Idle fill: `#E6E6E6` (dark/glass) / `#1A1A1A` (light) with NO circular thumb
/// fill to `hover_accent` (`Color::WHITE` on My Vibe, `pal.yellow` on Player Bar) /// - Hover/drag anywhere on `interact_rect` (`.ChangeVolume_wrapperSlider`): reveals `16px` (`1rem`, `r=8px`)
/// circular thumb in `hover_accent` and transitions fill to `hover_accent`
#[allow(clippy::too_many_arguments)]
pub fn ym_vertical_slider( pub fn ym_vertical_slider(
ctx: &mut UiContext, ctx: &mut UiContext,
pal: &YmPalette, pal: &YmPalette,
id: WidgetId, id: WidgetId,
rect: Rect, interact_rect: Rect,
track_rect: Rect,
value: f32, value: f32,
glass_no_border: bool, glass_no_border: bool,
hover_accent: Color, hover_accent: Color,
interactive: bool,
alpha: f32,
) -> SliderResponse { ) -> SliderResponse {
let resp = ctx.interact(id, rect); let (hovered, pressed, dragged, clicked) = if interactive {
let active = resp.hovered || resp.pressed || resp.dragged; let resp = ctx.interact(id, interact_rect);
(resp.hovered, resp.pressed, resp.dragged, resp.clicked)
} else {
(false, false, false, false)
};
let active = hovered || pressed || dragged;
let hov_t = ctx.animate_bool(id.with("hov"), active, 0.18); let hov_t = ctx.animate_bool(id.with("hov"), active, 0.18);
let track_w = 8.0; let track_w = 8.0;
let radius = 4.0; let radius = 4.0;
let cx = rect.center_x(); let cx = track_rect.center_x();
let track_rect = Rect::from_xywh(cx - track_w * 0.5, rect.top(), track_w, rect.height()); let bar_rect = Rect::from_xywh(cx - track_w * 0.5, track_rect.top(), track_w, track_rect.height());
let unfilled_col = if glass_no_border || pal.is_dark { let unfilled_col = if glass_no_border || pal.is_dark {
css_rgba(255, 255, 255, 51) // rgba(255,255,255,0.20) css_rgba(255, 255, 255, 41) // --ym-slider-color-primary-progress: hsla(0,0%,100%,.16)
} else { } else {
css_rgba(0, 0, 0, 41) css_rgba(0, 0, 0, 41) // rgba(0,0,0,.16)
}; }
ctx.dl().push_rect(track_rect, radius, unfilled_col); .scale_alpha(alpha);
ctx.dl().push_rect(bar_rect, radius, unfilled_col);
let frac = value.clamp(0.0, 1.0); let frac = value.clamp(0.0, 1.0);
let fill_h = track_rect.height() * frac; let fill_h = bar_rect.height() * frac;
let fill_y = track_rect.bottom() - fill_h; let fill_y = bar_rect.bottom() - fill_h;
let idle_fill = if glass_no_border || pal.is_dark { let idle_fill = if glass_no_border || pal.is_dark {
Color::rgb(0xE6, 0xE6, 0xE6) Color::rgb(0xE6, 0xE6, 0xE6) // --ym-controls-color-secondary-on_outline-enabled
} else { } else {
Color::rgb(0x66, 0x66, 0x66) Color::rgb(0x1A, 0x1A, 0x1A)
}; };
let fill_col = idle_fill.lerp(hover_accent, hov_t); let fill_col = idle_fill.lerp(hover_accent, hov_t).scale_alpha(alpha);
if fill_h > 0.5 { if fill_h > 0.5 {
ctx.dl().push_rect( ctx.dl().push_rect(
Rect::from_xywh(track_rect.x, fill_y, track_w, fill_h), Rect::from_xywh(bar_rect.x, fill_y, track_w, fill_h),
radius, radius,
fill_col, fill_col,
); );
} }
// Thumb is HIDDEN when idle; reveals crisp 16px (r=8px) circular thumb ONLY when directly hovered/dragged // Thumb is HIDDEN when idle; reveals crisp 16px (r=8px) circular thumb in `hover_accent`
// ONLY when `.ChangeVolume_wrapperSlider` is hovered or dragged.
if hov_t > 0.02 { if hov_t > 0.02 {
let thumb_r = 8.0 * hov_t; let thumb_r = 8.0 * hov_t;
let thumb_col = if glass_no_border || pal.is_dark { let thumb_col = hover_accent.scale_alpha(alpha);
Color::WHITE let thumb_y = fill_y.clamp(bar_rect.top() + thumb_r, bar_rect.bottom() - thumb_r);
} else {
pal.text_bright
};
let thumb_y = fill_y.clamp(track_rect.top(), track_rect.bottom());
ctx.dl() ctx.dl()
.push_circle(Pos2::new(cx, thumb_y), thumb_r, thumb_col); .push_circle(Pos2::new(cx, thumb_y), thumb_r, thumb_col);
} }
@ -1515,23 +1583,26 @@ pub fn ym_vertical_slider(
} }
let mut new_val = None; let mut new_val = None;
if resp.pressed || resp.dragged || resp.clicked { if interactive && (pressed || dragged || clicked) {
if let Some(p) = ctx.input.pointer_pos { if let Some(p) = ctx.input.pointer_pos {
new_val = new_val = Some(
Some((1.0 - (p.y - track_rect.top()) / track_rect.height().max(1.0)).clamp(0.0, 1.0)); (1.0 - (p.y - bar_rect.top()) / bar_rect.height().max(1.0)).clamp(0.0, 1.0),
);
} }
} }
SliderResponse { SliderResponse {
value: new_val, value: new_val,
hovered: resp.hovered, hovered,
dragging: resp.pressed || resp.dragged, dragging: pressed || dragged,
} }
} }
/// Complete official 5.129.0 `44×216px` (`radius = 22px`) vertical volume popover capsule + slider: /// Complete official 5.129.0 `44×216px` (`2.75rem × 13.5rem`, `radius = 22px`) vertical volume popover capsule:
/// - `glass_no_border == true` (My Vibe `.VibePlayerBar_verticalSlider`): `hsla(0,0%,100%,0.08)` Kawase glass, ZERO border, `#FFFFFF` hover accent /// - `glass_no_border == true` (`.VibePlayerBar_verticalSlider`): `hsla(0,0%,100%,0.08)` glass, ZERO border
/// - `glass_no_border == false` (Player Bar `.ChangeVolume_wrapperSlider`): `pal.bg_popover` Kawase glass + subtle `1px rgba(..., 0.08)` border, `pal.yellow` hover accent /// - `glass_no_border == false` (`.ChangeVolume_wrapperSlider`): solid `#1A1A1A` (`#F5F5F5` light) +
/// `1px solid #4D4D4D` (`rgba(0,0,0,0.3)` light), `pal.yellow` hover fill & 16px thumb
#[allow(clippy::too_many_arguments)]
pub fn ym_volume_capsule( pub fn ym_volume_capsule(
ctx: &mut UiContext, ctx: &mut UiContext,
pal: &YmPalette, pal: &YmPalette,
@ -1540,50 +1611,58 @@ pub fn ym_volume_capsule(
value: f32, value: f32,
glass_no_border: bool, glass_no_border: bool,
hover_accent: Color, hover_accent: Color,
interactive: bool,
alpha: f32,
) -> SliderResponse { ) -> SliderResponse {
ctx.register_blocker(capsule_rect); if interactive {
let radius = capsule_rect.width() * 0.5; ctx.register_blocker(capsule_rect);
}
let radius = (capsule_rect.width() * 0.5).min(24.0);
if glass_no_border { if glass_no_border {
ctx.dl().push_backdrop_blur( ctx.dl().push_backdrop_blur(
capsule_rect, capsule_rect,
radius, radius,
2.0, 2.0,
css_rgba(255, 255, 255, 20), // hsla(0,0%,100%,0.08) css_rgba(255, 255, 255, 20).scale_alpha(alpha), // hsla(0,0%,100%,0.08)
0.0, 0.0,
Color::TRANSPARENT, Color::TRANSPARENT,
); );
} else { } else {
let subtle_border = if pal.is_dark { let bg = if pal.is_dark {
css_rgba(255, 255, 255, 20) // rgba(255,255,255,0.08) Color::rgb(0x1A, 0x1A, 0x1A) // --ym-background-color-primary-enabled-popover
} else { } else {
css_rgba(0, 0, 0, 20) // rgba(0,0,0,0.08) Color::rgb(0xF5, 0xF5, 0xF5)
}; }
ctx.dl().push_shadow( .scale_alpha(alpha);
capsule_rect, let border = if pal.is_dark {
radius, Color::rgb(0x4D, 0x4D, 0x4D) // --ym-controls-color-secondary-outline-enabled_stroke
18.0, } else {
0.0, css_rgba(0, 0, 0, 77) // rgba(0,0,0,.3)
Vec2::new(0.0, 4.0), }
pal.shadow_menu, .scale_alpha(alpha);
); ctx.dl()
ctx.dl().push_backdrop_blur( .push_rect_bordered(capsule_rect, radius, bg, 1.0, border);
capsule_rect,
radius,
2.0,
pal.bg_popover.with_alpha(232),
1.0,
subtle_border,
);
} }
// Track spans full capsule width for direct capsule hover detection, with 18px top/bottom inset // Track is `12rem` (192px) tall inside `13.5rem` (216px) capsule -> 12px top/bottom inset.
let track_r = Rect::from_xywh( let track_r = Rect::from_xywh(
capsule_rect.left(), capsule_rect.center_x() - 4.0,
capsule_rect.top() + 18.0, capsule_rect.top() + 12.0,
capsule_rect.width(), 8.0,
(capsule_rect.height() - 36.0).max(24.0), (capsule_rect.height() - 24.0).max(24.0),
); );
ym_vertical_slider(ctx, pal, id, track_r, value, glass_no_border, hover_accent) ym_vertical_slider(
ctx,
pal,
id,
capsule_rect,
track_r,
value,
glass_no_border,
hover_accent,
interactive,
alpha,
)
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]

View file

@ -30,12 +30,20 @@ struct SceneAndBlurTargets {
half_h: u32, half_h: u32,
quarter_w: u32, quarter_w: u32,
quarter_h: u32, quarter_h: u32,
eighth_w: u32,
eighth_h: u32,
sixteenth_w: u32,
sixteenth_h: u32,
scene_tex: glow::Texture, scene_tex: glow::Texture,
scene_fbo: glow::Framebuffer, scene_fbo: glow::Framebuffer,
half_tex: glow::Texture, half_tex: glow::Texture,
half_fbo: glow::Framebuffer, half_fbo: glow::Framebuffer,
quarter_tex: glow::Texture, quarter_tex: glow::Texture,
quarter_fbo: glow::Framebuffer, quarter_fbo: glow::Framebuffer,
eighth_tex: glow::Texture,
eighth_fbo: glow::Framebuffer,
sixteenth_tex: glow::Texture,
sixteenth_fbo: glow::Framebuffer,
byte_size: u64, byte_size: u64,
} }
@ -47,6 +55,10 @@ impl SceneAndBlurTargets {
let half_h = (height / 2).max(1); let half_h = (height / 2).max(1);
let quarter_w = (width / 4).max(1); let quarter_w = (width / 4).max(1);
let quarter_h = (height / 4).max(1); let quarter_h = (height / 4).max(1);
let eighth_w = (width / 8).max(1);
let eighth_h = (height / 8).max(1);
let sixteenth_w = (width / 16).max(1);
let sixteenth_h = (height / 16).max(1);
let (scene_tex, scene_fbo) = create_rgba8_fbo(gl, width, height, "scene")?; let (scene_tex, scene_fbo) = create_rgba8_fbo(gl, width, height, "scene")?;
let (half_tex, half_fbo) = match create_rgba8_fbo(gl, half_w, half_h, "blur_half") { let (half_tex, half_fbo) = match create_rgba8_fbo(gl, half_w, half_h, "blur_half") {
@ -68,10 +80,40 @@ impl SceneAndBlurTargets {
return Err(e); return Err(e);
} }
}; };
let (eighth_tex, eighth_fbo) =
match create_rgba8_fbo(gl, eighth_w, eighth_h, "blur_eighth") {
Ok(pair) => pair,
Err(e) => {
gl.delete_framebuffer(quarter_fbo);
gl.delete_texture(quarter_tex);
gl.delete_framebuffer(half_fbo);
gl.delete_texture(half_tex);
gl.delete_framebuffer(scene_fbo);
gl.delete_texture(scene_tex);
return Err(e);
}
};
let (sixteenth_tex, sixteenth_fbo) =
match create_rgba8_fbo(gl, sixteenth_w, sixteenth_h, "blur_sixteenth") {
Ok(pair) => pair,
Err(e) => {
gl.delete_framebuffer(eighth_fbo);
gl.delete_texture(eighth_tex);
gl.delete_framebuffer(quarter_fbo);
gl.delete_texture(quarter_tex);
gl.delete_framebuffer(half_fbo);
gl.delete_texture(half_tex);
gl.delete_framebuffer(scene_fbo);
gl.delete_texture(scene_tex);
return Err(e);
}
};
let byte_size = ((width as u64) * (height as u64) let byte_size = ((width as u64) * (height as u64)
+ (half_w as u64) * (half_h as u64) + (half_w as u64) * (half_h as u64)
+ (quarter_w as u64) * (quarter_h as u64)) + (quarter_w as u64) * (quarter_h as u64)
+ (eighth_w as u64) * (eighth_h as u64)
+ (sixteenth_w as u64) * (sixteenth_h as u64))
* 4; * 4;
Ok(Self { Ok(Self {
@ -81,12 +123,20 @@ impl SceneAndBlurTargets {
half_h, half_h,
quarter_w, quarter_w,
quarter_h, quarter_h,
eighth_w,
eighth_h,
sixteenth_w,
sixteenth_h,
scene_tex, scene_tex,
scene_fbo, scene_fbo,
half_tex, half_tex,
half_fbo, half_fbo,
quarter_tex, quarter_tex,
quarter_fbo, quarter_fbo,
eighth_tex,
eighth_fbo,
sixteenth_tex,
sixteenth_fbo,
byte_size, byte_size,
}) })
} }
@ -98,6 +148,10 @@ impl SceneAndBlurTargets {
gl.delete_texture(self.half_tex); gl.delete_texture(self.half_tex);
gl.delete_framebuffer(self.quarter_fbo); gl.delete_framebuffer(self.quarter_fbo);
gl.delete_texture(self.quarter_tex); gl.delete_texture(self.quarter_tex);
gl.delete_framebuffer(self.eighth_fbo);
gl.delete_texture(self.eighth_tex);
gl.delete_framebuffer(self.sixteenth_fbo);
gl.delete_texture(self.sixteenth_tex);
} }
} }
@ -563,7 +617,14 @@ impl UiGlRenderer {
let Some(bt) = &self.scene_blur else { let Some(bt) = &self.scene_blur else {
return; return;
}; };
let offset = radius.clamp(0.5, 4.0); let r = radius.clamp(0.5, 4.0);
let (levels, offset) = if r > 3.0 {
(4u32, (0.95 + (r - 3.0) * 0.45).clamp(0.95, 1.5))
} else if r > 2.0 {
(3u32, (0.90 + (r - 2.0) * 0.45).clamp(0.90, 1.45))
} else {
(2u32, (0.75 + r * 0.55).clamp(0.75, 1.85))
};
gl.disable(glow::BLEND); gl.disable(glow::BLEND);
gl.use_program(Some(self.blur_program)); gl.use_program(Some(self.blur_program));
@ -571,44 +632,47 @@ impl UiGlRenderer {
gl.active_texture(glow::TEXTURE0); gl.active_texture(glow::TEXTURE0);
gl.bind_vertex_array(Some(self.fullscreen_vao)); gl.bind_vertex_array(Some(self.fullscreen_vao));
// Pass 1: Downsample Full -> Half let run_pass = |dst_fbo: glow::Framebuffer,
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(bt.half_fbo)); dst_w: u32,
gl.viewport(0, 0, bt.half_w as i32, bt.half_h as i32); dst_h: u32,
gl.bind_texture(glow::TEXTURE_2D, Some(bt.scene_tex)); src_tex: glow::Texture,
gl.uniform_2_f32( src_w: u32,
self.loc_blur_texel_size.as_ref(), src_h: u32,
1.0 / bt.width.max(1) as f32, mode: i32| {
1.0 / bt.height.max(1) as f32, gl.bind_framebuffer(glow::FRAMEBUFFER, Some(dst_fbo));
); gl.viewport(0, 0, dst_w as i32, dst_h as i32);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset); gl.bind_texture(glow::TEXTURE_2D, Some(src_tex));
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), 0); gl.uniform_2_f32(
gl.draw_arrays(glow::TRIANGLES, 0, 3); self.loc_blur_texel_size.as_ref(),
1.0 / src_w.max(1) as f32,
1.0 / src_h.max(1) as f32,
);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset);
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), mode);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
};
// Pass 2: Downsample Half -> Quarter // Downsample 1: Full -> Half
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(bt.quarter_fbo)); run_pass(bt.half_fbo, bt.half_w, bt.half_h, bt.scene_tex, bt.width, bt.height, 0);
gl.viewport(0, 0, bt.quarter_w as i32, bt.quarter_h as i32); // Downsample 2: Half -> Quarter
gl.bind_texture(glow::TEXTURE_2D, Some(bt.half_tex)); run_pass(bt.quarter_fbo, bt.quarter_w, bt.quarter_h, bt.half_tex, bt.half_w, bt.half_h, 0);
gl.uniform_2_f32(
self.loc_blur_texel_size.as_ref(),
1.0 / bt.half_w.max(1) as f32,
1.0 / bt.half_h.max(1) as f32,
);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset * 1.25);
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), 0);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
// Pass 3: Upsample Quarter -> Half (BLUR_TEXTURE_ID samples half_tex with linear filter) if levels >= 3 {
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(bt.half_fbo)); // Downsample 3: Quarter -> Eighth
gl.viewport(0, 0, bt.half_w as i32, bt.half_h as i32); run_pass(bt.eighth_fbo, bt.eighth_w, bt.eighth_h, bt.quarter_tex, bt.quarter_w, bt.quarter_h, 0);
gl.bind_texture(glow::TEXTURE_2D, Some(bt.quarter_tex)); }
gl.uniform_2_f32( if levels >= 4 {
self.loc_blur_texel_size.as_ref(), // Downsample 4: Eighth -> Sixteenth
1.0 / bt.quarter_w.max(1) as f32, run_pass(bt.sixteenth_fbo, bt.sixteenth_w, bt.sixteenth_h, bt.eighth_tex, bt.eighth_w, bt.eighth_h, 0);
1.0 / bt.quarter_h.max(1) as f32, // Upsample: Sixteenth -> Eighth
); run_pass(bt.eighth_fbo, bt.eighth_w, bt.eighth_h, bt.sixteenth_tex, bt.sixteenth_w, bt.sixteenth_h, 1);
gl.uniform_1_f32(self.loc_blur_offset.as_ref(), offset * 1.25); }
gl.uniform_1_i32(self.loc_blur_mode.as_ref(), 1); if levels >= 3 {
gl.draw_arrays(glow::TRIANGLES, 0, 3); // Upsample: Eighth -> Quarter
run_pass(bt.quarter_fbo, bt.quarter_w, bt.quarter_h, bt.eighth_tex, bt.eighth_w, bt.eighth_h, 1);
}
// Final Upsample: Quarter -> Half (BLUR_TEXTURE_ID samples half_tex with linear filter)
run_pass(bt.half_fbo, bt.half_w, bt.half_h, bt.quarter_tex, bt.quarter_w, bt.quarter_h, 1);
gl.bind_vertex_array(None); gl.bind_vertex_array(None);
gl.bind_texture(glow::TEXTURE_2D, None); gl.bind_texture(glow::TEXTURE_2D, None);

View file

@ -72,6 +72,7 @@ pub enum Icon {
ChartDown, ChartDown,
ChartNew, ChartNew,
ChartSame, ChartSame,
CrownXxs,
History, History,
Share, Share,
Note, Note,
@ -80,6 +81,7 @@ pub enum Icon {
YandexPlusRu, YandexPlusRu,
LinkRounded, LinkRounded,
AiSparkles, AiSparkles,
AiSparklesText,
// Exact 5.129.0 `_xxs` ContextMenu icons from `app/icons/sprite.svg` // Exact 5.129.0 `_xxs` ContextMenu icons from `app/icons/sprite.svg`
VibeXxs, VibeXxs,
MenuArrowXxs, MenuArrowXxs,
@ -205,6 +207,7 @@ impl Icon {
Icon::ChartDown => include_bytes!("../assets/icons/chartDown_xxs.svg"), Icon::ChartDown => include_bytes!("../assets/icons/chartDown_xxs.svg"),
Icon::ChartNew => include_bytes!("../assets/icons/chartNew_xxs.svg"), Icon::ChartNew => include_bytes!("../assets/icons/chartNew_xxs.svg"),
Icon::ChartSame => include_bytes!("../assets/icons/chartSame_xxs.svg"), Icon::ChartSame => include_bytes!("../assets/icons/chartSame_xxs.svg"),
Icon::CrownXxs => include_bytes!("../assets/icons/crown_xxs.svg"),
Icon::History => include_bytes!("../assets/icons/history_m.svg"), Icon::History => include_bytes!("../assets/icons/history_m.svg"),
Icon::Share => include_bytes!("../assets/icons/share_xxs.svg"), Icon::Share => include_bytes!("../assets/icons/share_xxs.svg"),
Icon::Note => include_bytes!("../assets/icons/note_l.svg"), Icon::Note => include_bytes!("../assets/icons/note_l.svg"),
@ -213,6 +216,7 @@ impl Icon {
Icon::YandexPlusRu => include_bytes!("../assets/icons/yandexPlusRu.svg"), Icon::YandexPlusRu => include_bytes!("../assets/icons/yandexPlusRu.svg"),
Icon::LinkRounded => include_bytes!("../assets/icons/link_rounded_xxs.svg"), Icon::LinkRounded => include_bytes!("../assets/icons/link_rounded_xxs.svg"),
Icon::AiSparkles => include_bytes!("../assets/icons/ai_sparkles_28.svg"), Icon::AiSparkles => include_bytes!("../assets/icons/ai_sparkles_28.svg"),
Icon::AiSparklesText => include_bytes!("../assets/icons/ai_sparkles_ai_28.svg"),
Icon::VibeXxs => include_bytes!("../assets/icons/vibe_xxs.svg"), Icon::VibeXxs => include_bytes!("../assets/icons/vibe_xxs.svg"),
Icon::MenuArrowXxs => include_bytes!("../assets/icons/menuArrow_xxs.svg"), Icon::MenuArrowXxs => include_bytes!("../assets/icons/menuArrow_xxs.svg"),
Icon::ShuffleXxs => include_bytes!("../assets/icons/shuffle_xxs.svg"), Icon::ShuffleXxs => include_bytes!("../assets/icons/shuffle_xxs.svg"),
@ -356,6 +360,7 @@ impl Icon {
Icon::ChartDown, Icon::ChartDown,
Icon::ChartNew, Icon::ChartNew,
Icon::ChartSame, Icon::ChartSame,
Icon::CrownXxs,
Icon::History, Icon::History,
Icon::Share, Icon::Share,
Icon::Note, Icon::Note,
@ -364,6 +369,7 @@ impl Icon {
Icon::YandexPlusRu, Icon::YandexPlusRu,
Icon::LinkRounded, Icon::LinkRounded,
Icon::AiSparkles, Icon::AiSparkles,
Icon::AiSparklesText,
Icon::VibeXxs, Icon::VibeXxs,
Icon::MenuArrowXxs, Icon::MenuArrowXxs,
Icon::ShuffleXxs, Icon::ShuffleXxs,
@ -424,6 +430,12 @@ pub struct IconCache {
heart_tex: Option<TextureId>, heart_tex: Option<TextureId>,
search_glow_tex: Option<TextureId>, search_glow_tex: Option<TextureId>,
meteor_glow_tex: Option<TextureId>, meteor_glow_tex: Option<TextureId>,
concert_date_bg_tex: Option<TextureId>,
concert_feed_mask_tex: Option<TextureId>,
concert_top_mask_tex: Option<TextureId>,
bookshelf_tex: Option<TextureId>,
new_episodes_tex: Option<TextureId>,
clear_memory_tex: Option<TextureId>,
} }
impl Default for IconCache { impl Default for IconCache {
@ -439,6 +451,12 @@ impl IconCache {
heart_tex: None, heart_tex: None,
search_glow_tex: None, search_glow_tex: None,
meteor_glow_tex: None, meteor_glow_tex: None,
concert_date_bg_tex: None,
concert_feed_mask_tex: None,
concert_top_mask_tex: None,
bookshelf_tex: None,
new_episodes_tex: None,
clear_memory_tex: None,
} }
} }
@ -483,6 +501,83 @@ impl IconCache {
id id
} }
/// Official glowing yellow concert date badge PNG from Yandex Music 5.128.0 CDN
/// (`ConcertImage_dateBackground__GAONC`, 433x454).
pub fn get_official_concert_date_bg(&mut self, registry: &mut TextureRegistry) -> TextureId {
if let Some(id) = self.concert_date_bg_tex {
return id;
}
let bytes = include_bytes!("../assets/media/concert_date_bg.png");
let (w, h, premul) = decode_png_rgba_css_premul(bytes);
let id = registry.create_rgba_premul(w, h, premul);
self.concert_date_bg_tex = Some(id);
id
}
/// Exact inverted ticket-cutout mask overlay from official `mask.a4bd3ae5.svg` (164x234,
/// `ConcertImage_root_withMask__1ayfK`). Rasterized white with `fill-rule="evenodd"` so
/// tinting by `pal.bg_content` punches the exact top + left ticket notches in any theme.
pub fn get_concert_feed_mask_overlay(&mut self, registry: &mut TextureRegistry) -> TextureId {
if let Some(id) = self.concert_feed_mask_tex {
return id;
}
const INVERTED_MASK_SVG: &[u8] = br##"<svg width="164" height="234" viewBox="0 0 164 234" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M0 0H164V234H0V0ZM164 228V6C164 2.68629 161.314 0 158 0H118.406C116.23 0 114.154 0.887049 112.461 2.25393C107.85 5.97583 97.2013 13 82.5 13C67.5506 13 56.2328 5.73674 51.47 2.06836C49.8305 0.805567 47.8438 0 45.7744 0H6C2.68629 0 0 2.68629 0 6V41C0 57.5685 13.4315 71 30 71H31V77H30C13.4315 77 0 90.4315 0 107V228C0 231.314 2.6863 234 6 234H158C161.314 234 164 231.314 164 228Z" fill="#FFFFFF"/></svg>"##;
let premul = rasterize_svg_premul(INVERTED_MASK_SVG, 328, 468);
let id = registry.create_rgba_premul(328, 468, premul);
self.concert_feed_mask_tex = Some(id);
id
}
/// Exact inverted ticket-cutout mask overlay from official `top-concerts-mask.b653027d.svg`
/// (366x379, `.TopConcerts_concertCard__h86wP`). Rasterized white with `fill-rule="evenodd"` so
/// tinting by `pal.bg_content` punches the exact wide top + deep left ticket notches in any theme.
pub fn get_concert_top_mask_overlay(&mut self, registry: &mut TextureRegistry) -> TextureId {
if let Some(id) = self.concert_top_mask_tex {
return id;
}
const INVERTED_TOP_MASK_SVG: &[u8] = br##"<svg width="366" height="379" viewBox="0 0 366 379" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M0 0H366V379H0V0ZM365.636 122.549C365.636 122.624 365.717 122.684 365.818 122.684C365.918 122.684 366 122.744 366 122.819V370.54C366 375.212 360.879 379 354.562 379H11.4376C5.12077 379 0 375.212 0 370.54V173.443C.000580861 145.564 14.6301 128.012 52.2434 127.764C52.2509 127.743 52.2434 122.686 52.2434 122.686C52.2434 122.686 52.2434 117.592 52.2434 117.605C14.7994 117.214.366903 99.7218.36636 71.9333V8.45982C.36636 3.78759 5.48713 0 11.8039 0H119.828C122.695 0 125.44.811806 127.633 2.17756C142.462 13.9042 155.653 22.0735 183.334 22.0735C211.015 22.0735 224.206 13.9042 239.035 2.17757C241.228.811808 243.973 0 246.84 0H354.198C360.515 0 365.636 3.78759 365.636 8.45982V122.549Z" fill="#FFFFFF"/></svg>"##;
let premul = rasterize_svg_premul(INVERTED_TOP_MASK_SVG, 732, 758);
let id = registry.create_rgba_premul(732, 758, premul);
self.concert_top_mask_tex = Some(id);
id
}
/// Official 83x82 "Моя полка" icon extracted from Yandex Music (`bookshelf.ee78862c.png`).
pub fn get_official_bookshelf(&mut self, registry: &mut TextureRegistry) -> TextureId {
if let Some(id) = self.bookshelf_tex {
return id;
}
let bytes = include_bytes!("../assets/media/bookshelf.png");
let (w, h, premul) = decode_png_rgba_css_premul(bytes);
let id = registry.create_rgba_premul(w, h, premul);
self.bookshelf_tex = Some(id);
id
}
/// Official 83x82 "Новые выпуски" icon extracted from Yandex Music (`newEpisodes.00911c05.png`).
pub fn get_official_new_episodes(&mut self, registry: &mut TextureRegistry) -> TextureId {
if let Some(id) = self.new_episodes_tex {
return id;
}
let bytes = include_bytes!("../assets/media/new_episodes.png");
let (w, h, premul) = decode_png_rgba_css_premul(bytes);
let id = registry.create_rgba_premul(w, h, premul);
self.new_episodes_tex = Some(id);
id
}
/// Official ClearMemoryModal illustration extracted from Yandex Music (`clearMemory.33a5df30.png`).
pub fn get_official_clear_memory(&mut self, registry: &mut TextureRegistry) -> TextureId {
if let Some(id) = self.clear_memory_tex {
return id;
}
let bytes = include_bytes!("../assets/media/clear_memory.png");
let (w, h, premul) = decode_png_rgba_css_premul(bytes);
let id = registry.create_rgba_premul(w, h, premul);
self.clear_memory_tex = Some(id);
id
}
pub fn get(&mut self, registry: &mut TextureRegistry, icon: Icon) -> TextureId { pub fn get(&mut self, registry: &mut TextureRegistry, icon: Icon) -> TextureId {
if let Some(&id) = self.textures.get(&icon) { if let Some(&id) = self.textures.get(&icon) {
return id; return id;
@ -599,3 +694,19 @@ fn generate_search_ai_orb_premul(width: u32, height: u32) -> (u32, u32, Vec<u8>)
let premul = premultiply_rgba_srgb(&raw); let premul = premultiply_rgba_srgb(&raw);
(width, height, premul) (width, height, premul)
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_official_concert_date_bg_png_decodes_with_glow() {
let bytes = include_bytes!("../assets/media/concert_date_bg.png");
let (w, h, premul) = decode_png_rgba_css_premul(bytes);
assert_eq!((w, h), (433, 454));
assert_eq!(premul.len(), (w * h * 4) as usize);
let has_opaque = premul.chunks_exact(4).any(|px| px[3] > 230 && px[0] > 200 && px[1] > 180);
let has_glow = premul.chunks_exact(4).any(|px| px[3] > 15 && px[3] < 180);
assert!(has_opaque && has_glow);
}
}

View file

@ -304,7 +304,9 @@ impl AppRunner {
let playing = shell.app.is_audio_playing(); let playing = shell.app.is_audio_playing();
if let Some(ref mut native) = self.native { if let Some(ref mut native) = self.native {
let pos_ms = shell.app.position_ms(); let pos_ms = shell.app.position_ms();
native.sync_playback(shell.app.current_track(), playing, pos_ms); let app = &shell.app;
let has_queue = !app.queue.is_empty();
native.sync_playback(app.current_track(), playing, pos_ms, has_queue, has_queue);
} }
#[cfg(windows)] #[cfg(windows)]
if playing != self.power_save_blocked { if playing != self.power_save_blocked {
@ -368,6 +370,9 @@ impl AppRunner {
need_redraw = true; need_redraw = true;
force_present = true; force_present = true;
} }
NativeEvent::OpenUrl(url) => {
yandex_music_rs::api::open_url_in_browser(url);
}
NativeEvent::QuitApp => { NativeEvent::QuitApp => {
should_exit = true; should_exit = true;
} }
@ -434,7 +439,8 @@ impl AppRunner {
self.last_render_at = Instant::now(); self.last_render_at = Instant::now();
let sf = (window.scale_factor() as f32).max(0.5); let (sf, rem_scale) = effective_ui_scale_and_rem(window, shell.app.config.ui_zoom);
shell.ui.rem_scale = rem_scale;
let logical = Vec2::new(size.width as f32 / sf, size.height as f32 / sf); let logical = Vec2::new(size.width as f32 / sf, size.height as f32 / sf);
let is_max = window.is_maximized(); let is_max = window.is_maximized();
let elapsed = shell.elapsed_secs(); let elapsed = shell.elapsed_secs();
@ -452,12 +458,16 @@ impl AppRunner {
window.set_cursor(frame.cursor.to_winit()); window.set_cursor(frame.cursor.to_winit());
} }
// Sync localized window title (`"Яндекс Музыка"` RU / `"Yandex Music"` EN) // Sync localized window title & tray menu (`"Яндекс Музыка"` RU / `"Yandex Music"` EN)
let title = shell.window_title(); let title = shell.window_title();
if title != self.last_window_title { if title != self.last_window_title {
self.last_window_title = title; self.last_window_title = title;
window.set_title(title); window.set_title(title);
} }
if let Some(ref mut native) = self.native {
native.set_language(shell.app.config.language.is_ru());
native.set_dark_mode(shell.is_dark());
}
// Sync Windows 11 DWM immersive dark mode dynamically to `palette.is_dark` // Sync Windows 11 DWM immersive dark mode dynamically to `palette.is_dark`
#[cfg(windows)] #[cfg(windows)]
@ -474,15 +484,32 @@ impl AppRunner {
match win_cmd { match win_cmd {
WindowCommand::None => {} WindowCommand::None => {}
WindowCommand::DragWindow => { WindowCommand::DragWindow => {
shell.ui.input.reset_pointer_buttons();
let _ = window.drag_window(); let _ = window.drag_window();
} }
WindowCommand::DragResize(dir) => {
use winit::window::ResizeDirection;
use yandex_music_rs::app::WindowResizeDirection;
let winit_dir = match dir {
WindowResizeDirection::North => ResizeDirection::North,
WindowResizeDirection::South => ResizeDirection::South,
WindowResizeDirection::East => ResizeDirection::East,
WindowResizeDirection::West => ResizeDirection::West,
WindowResizeDirection::NorthEast => ResizeDirection::NorthEast,
WindowResizeDirection::NorthWest => ResizeDirection::NorthWest,
WindowResizeDirection::SouthEast => ResizeDirection::SouthEast,
WindowResizeDirection::SouthWest => ResizeDirection::SouthWest,
};
shell.ui.input.reset_pointer_buttons();
let _ = window.drag_resize_window(winit_dir);
}
WindowCommand::Minimize => window.set_minimized(true), WindowCommand::Minimize => window.set_minimized(true),
WindowCommand::ToggleMaximize => window.set_maximized(!window.is_maximized()), WindowCommand::ToggleMaximize => window.set_maximized(!window.is_maximized()),
WindowCommand::Close => { WindowCommand::Close => {
if shell.app.config.close_to_tray { if shell.app.config.close_to_tray {
self.window_visible = false; self.window_visible = false;
window.set_visible(false); window.set_visible(false);
if let Some(ref native) = self.native { if let Some(ref mut native) = self.native {
native.set_window_visible_label(false); native.set_window_visible_label(false);
} }
} else { } else {
@ -556,6 +583,14 @@ impl AppRunner {
(None, Some(b)) => Some(b), (None, Some(b)) => Some(b),
(None, None) => None, (None, None) => None,
}; };
// If GPU present was skipped (identical frame), never spin at Duration::ZERO without VSync.
let next_delay = next_delay.map(|d| {
if skip_gpu_present && d.is_zero() {
Duration::from_millis(16)
} else {
d
}
});
self.next_repaint = if self.window_visible { self.next_repaint = if self.window_visible {
next_delay.map(|d| Instant::now() + d) next_delay.map(|d| Instant::now() + d)
} else { } else {
@ -650,7 +685,8 @@ impl ApplicationHandler for AppRunner {
self.last_dwm_dark = Some(init_dark); self.last_dwm_dark = Some(init_dark);
} }
let native = NativeDesktop::new(&window, shell.app.config.language.is_ru()); let mut native = NativeDesktop::new(&window, shell.app.config.language.is_ru());
native.set_dark_mode(shell.is_dark());
self.backend = Some(backend); self.backend = Some(backend);
self.window = Some(window.clone()); self.window = Some(window.clone());
@ -677,8 +713,18 @@ impl ApplicationHandler for AppRunner {
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) { fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
let is_cursor_moved = matches!(event, WindowEvent::CursorMoved { .. }); let is_cursor_moved = matches!(event, WindowEvent::CursorMoved { .. });
let mut wants_redraw = false; let mut wants_redraw = false;
let eff_sf = match (self.window.as_ref(), self.shell.as_ref()) {
(Some(w), Some(s)) => Some(effective_ui_scale(w, s.app.config.ui_zoom)),
_ => None,
};
if let Some(shell) = self.shell.as_mut() { if let Some(shell) = self.shell.as_mut() {
if let Some(sf) = eff_sf {
shell.ui.input.scale_factor = sf;
}
wants_redraw = shell.handle_winit_event(&event); wants_redraw = shell.handle_winit_event(&event);
if let Some(w) = self.window.as_ref() {
shell.ui.input.scale_factor = effective_ui_scale(w, shell.app.config.ui_zoom);
}
} }
if wants_redraw && self.is_window_renderable() { if wants_redraw && self.is_window_renderable() {
@ -709,7 +755,7 @@ impl ApplicationHandler for AppRunner {
if let Some(w) = self.window.as_ref() { if let Some(w) = self.window.as_ref() {
w.set_visible(false); w.set_visible(false);
} }
if let Some(ref native) = self.native { if let Some(ref mut native) = self.native {
native.set_window_visible_label(false); native.set_window_visible_label(false);
} }
} else { } else {
@ -806,6 +852,24 @@ impl ApplicationHandler for AppRunner {
/// Fast 64-bit FNV-1a visual fingerprint used to skip redundant Vulkan submits & DWM presents /// Fast 64-bit FNV-1a visual fingerprint used to skip redundant Vulkan submits & DWM presents
/// whenever a frame is visually identical to the last presented frame. /// whenever a frame is visually identical to the last presented frame.
/// Official Yandex Music 5.129.0 root `rem` scaling (`3d8697b385d765d6.css:17-27`):
/// `@media only screen and (min-width: 1920px) { html { --html-font-size: calc(0.75rem + 0.3vw); } }`
/// Scales the entire `rem`-based UI above 1920 logical px (1.11× at 1920px, 1.23× at 2560px).
fn effective_ui_scale_and_rem(window: &Window, ui_zoom: f32) -> (f32, f32) {
let base_sf = (window.scale_factor() as f32).max(0.5) * ui_zoom.clamp(0.5, 2.0);
let raw_logical_w = window.inner_size().width as f32 / base_sf;
let rem_scale = if raw_logical_w >= 1920.0 {
(12.0 + 0.003 * raw_logical_w) / 16.0
} else {
1.0
};
((base_sf * rem_scale).clamp(0.5, 4.0), rem_scale)
}
fn effective_ui_scale(window: &Window, ui_zoom: f32) -> f32 {
effective_ui_scale_and_rem(window, ui_zoom).0
}
fn compute_frame_hash( fn compute_frame_hash(
dl: &DisplayList, dl: &DisplayList,
clear_col: [f32; 4], clear_col: [f32; 4],

View file

@ -8,6 +8,7 @@ pub enum NativeEvent {
ShowWindow, ShowWindow,
ToggleWindow, ToggleWindow,
CheckUpdates, CheckUpdates,
OpenUrl(&'static str),
QuitApp, QuitApp,
Play, Play,
Pause, Pause,
@ -18,12 +19,79 @@ pub enum NativeEvent {
SeekMs(u64), SeekMs(u64),
} }
/// Exact external URLs from `original_yandex_music/beautified/js/index.js` (lines 89, 2525-2534).
pub const TERMS_OF_USE_URL: &str = "https://yandex.ru/legal/music_mobile_agreement/";
pub const RECOMMENDATIONS_URL: &str = "https://music.yandex.ru/legal/recommendations/ru/#music";
pub const SUPPORT_CHAT_URL: &str =
"https://yandex.ru/chat?context=%7B%22entrypoint%22%3A%22web_desktop%22%7D#/user/ee219503-b69b-9484-405b-6877a510e13c";
/// Exact tray menu strings from `original_yandex_music/beautified/js/index.js`:
/// `translationsRU` (lines 1753-1807), `translationsEN` (lines 1808-1862), `createContextMenu$1` (lines 2588-2753).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TrayLabels {
pub tooltip: &'static str,
pub roll_up: &'static str,
pub unwrap: &'static str,
pub check_updates: &'static str,
pub play: &'static str,
pub pause: &'static str,
pub prev: &'static str,
pub next: &'static str,
pub about: &'static str,
pub terms: &'static str,
pub recommendations: &'static str,
pub support: &'static str,
pub quit: &'static str,
}
impl TrayLabels {
pub const fn for_lang(is_ru: bool) -> Self {
if is_ru {
Self {
tooltip: "Яндекс Музыка",
roll_up: "Свернуть",
unwrap: "Развернуть",
check_updates: "Проверить обновления",
play: "Воспроизведение",
pause: "Пауза",
prev: "Предыдущая песня",
next: "Следующая песня",
about: "О приложении",
terms: "Пользовательское соглашение",
recommendations: "Правила рекомендаций",
support: "Чат с поддержкой",
quit: "Закрыть приложение",
}
} else {
Self {
tooltip: "Yandex Music",
roll_up: "Hide",
unwrap: "Expand",
check_updates: "Check updates",
play: "Playback",
pause: "Pause",
prev: "Previous song",
next: "Next song",
about: "About the app",
terms: "User agreement",
recommendations: "Recommendation rules",
support: "Support chat",
quit: "Close app",
}
}
}
}
#[cfg(windows)]
mod tray_menu_win;
// ============================================================================= // =============================================================================
// WINDOWS IMPLEMENTATION // WINDOWS IMPLEMENTATION
// ============================================================================= // =============================================================================
#[cfg(windows)] #[cfg(windows)]
mod imp { mod imp {
use super::NativeEvent; use super::tray_menu_win;
use super::{NativeEvent, TrayLabels};
use crate::api::models::Track; use crate::api::models::Track;
use crate::api::signing::extract_oauth_token; use crate::api::signing::extract_oauth_token;
use crate::api::YANDEX_OAUTH_URL; use crate::api::YANDEX_OAUTH_URL;
@ -37,7 +105,6 @@ mod imp {
use std::io::{BufRead, BufReader, Write}; use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::time::Duration; use std::time::Duration;
use tray_icon::menu::{Menu, MenuEvent, MenuId, MenuItem, PredefinedMenuItem, Submenu};
use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent}; use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use winit::application::ApplicationHandler; use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize; use winit::dpi::LogicalSize;
@ -48,98 +115,42 @@ mod imp {
const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:"; const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:";
pub struct NativeDesktop { pub struct NativeDesktop {
_tray: Option<TrayIcon>, tray: Option<TrayIcon>,
item_toggle_win: Option<MenuItem>,
item_play: Option<MenuItem>,
menu_toggle_win_id: Option<MenuId>,
menu_updates_id: Option<MenuId>,
menu_play_id: Option<MenuId>,
menu_prev_id: Option<MenuId>,
menu_next_id: Option<MenuId>,
menu_quit_id: Option<MenuId>,
is_ru: bool, is_ru: bool,
is_dark: bool,
window_visible: bool,
smtc: Option<MediaControls>, smtc: Option<MediaControls>,
rx_smtc: Receiver<NativeEvent>, tx_events: Sender<NativeEvent>,
rx_events: Receiver<NativeEvent>,
last_track_id: Option<String>, last_track_id: Option<String>,
last_playing: Option<bool>, last_playing: Option<bool>,
can_prev: bool,
can_next: bool,
}
impl Drop for NativeDesktop {
fn drop(&mut self) {
tray_menu_win::close_tray_menu();
}
} }
impl NativeDesktop { impl NativeDesktop {
pub fn new(window: &Window, is_ru: bool) -> Self { pub fn new(window: &Window, is_ru: bool) -> Self {
// 1. Build System Tray icon + exact 5.129.0 menu matching Yandex Music Desktop! let labels = TrayLabels::for_lang(is_ru);
let mut item_toggle_win_slot = None;
let mut item_play_slot = None;
let mut menu_toggle_win_id = None;
let mut menu_updates_id = None;
let mut menu_play_id = None;
let mut menu_prev_id = None;
let mut menu_next_id = None;
let mut menu_quit_id = None;
let tray = (|| -> Option<TrayIcon> { let tray = (|| -> Option<TrayIcon> {
let menu = Menu::new();
let item_toggle_win = MenuItem::new(if is_ru { "Скрыть" } else { "Hide" }, true, None);
let item_updates = MenuItem::new(
if is_ru { "Проверить обновления" } else { "Check updates" },
true,
None,
);
let item_play = MenuItem::new(if is_ru { "Играть" } else { "Play" }, true, None);
let item_prev = MenuItem::new(
if is_ru { "Предыдущий трек" } else { "Previous song" },
true,
None,
);
let item_next = MenuItem::new(
if is_ru { "Следующий трек" } else { "Next song" },
true,
None,
);
let about_sub = Submenu::new(if is_ru { "О приложении" } else { "About the app" }, true);
let about_ver = MenuItem::new(
if is_ru { "Яндекс Музыка 5.129.0" } else { "Yandex Music 5.129.0" },
false,
None,
);
let _ = about_sub.append(&about_ver);
let item_quit = MenuItem::new(
if is_ru { "Закрыть приложение" } else { "Close app" },
true,
None,
);
menu_toggle_win_id = Some(item_toggle_win.id().clone());
menu_updates_id = Some(item_updates.id().clone());
menu_play_id = Some(item_play.id().clone());
menu_prev_id = Some(item_prev.id().clone());
menu_next_id = Some(item_next.id().clone());
menu_quit_id = Some(item_quit.id().clone());
let _ = menu.append(&item_toggle_win);
let _ = menu.append(&item_updates);
let _ = menu.append(&PredefinedMenuItem::separator());
let _ = menu.append(&item_play);
let _ = menu.append(&item_prev);
let _ = menu.append(&item_next);
let _ = menu.append(&PredefinedMenuItem::separator());
let _ = menu.append(&about_sub);
let _ = menu.append(&PredefinedMenuItem::separator());
let _ = menu.append(&item_quit);
item_toggle_win_slot = Some(item_toggle_win);
item_play_slot = Some(item_play);
let icon = build_tray_icon()?; let icon = build_tray_icon()?;
// No `.with_menu(...)`: right-click opens our pixel-accurate Win32 Chromium-style
// popup menu (`tray_menu_win`) matching Yandex Music Desktop 5.129.0 1-to-1.
TrayIconBuilder::new() TrayIconBuilder::new()
.with_menu(Box::new(menu)) .with_tooltip(labels.tooltip)
.with_tooltip(if is_ru { "Яндекс Музыка" } else { "Yandex Music" })
.with_icon(icon) .with_icon(icon)
.build() .build()
.ok() .ok()
})(); })();
// 2. Build Windows SMTC (`souvlaki::MediaControls`) bound to our Win32 HWND // 2. Build Windows SMTC (`souvlaki::MediaControls`) bound to our Win32 HWND
let (tx_smtc, rx_smtc): (Sender<NativeEvent>, Receiver<NativeEvent>) = unbounded(); let (tx_events, rx_events): (Sender<NativeEvent>, Receiver<NativeEvent>) = unbounded();
let tx_smtc = tx_events.clone();
let smtc = (|| -> Option<MediaControls> { let smtc = (|| -> Option<MediaControls> {
let hwnd = match window.window_handle().ok()?.as_raw() { let hwnd = match window.window_handle().ok()?.as_raw() {
RawWindowHandle::Win32(h) => h.hwnd.get() as *mut std::ffi::c_void, RawWindowHandle::Win32(h) => h.hwnd.get() as *mut std::ffi::c_void,
@ -174,37 +185,43 @@ mod imp {
})(); })();
Self { Self {
_tray: tray, tray,
item_toggle_win: item_toggle_win_slot,
item_play: item_play_slot,
menu_toggle_win_id,
menu_updates_id,
menu_play_id,
menu_prev_id,
menu_next_id,
menu_quit_id,
is_ru, is_ru,
is_dark: true,
window_visible: true,
smtc, smtc,
rx_smtc, tx_events,
rx_events,
last_track_id: None, last_track_id: None,
last_playing: None, last_playing: None,
can_prev: false,
can_next: false,
} }
} }
pub fn set_window_visible_label(&self, visible: bool) { pub fn set_dark_mode(&mut self, is_dark: bool) {
if let Some(ref item) = self.item_toggle_win { self.is_dark = is_dark;
item.set_text(if visible { }
if self.is_ru { "Скрыть" } else { "Hide" }
} else { pub fn set_language(&mut self, is_ru: bool) {
if self.is_ru { "Показать" } else { "Show" } if self.is_ru == is_ru {
}); return;
} }
self.is_ru = is_ru;
let labels = TrayLabels::for_lang(is_ru);
if let Some(ref tray) = self.tray {
let _ = tray.set_tooltip(Some(labels.tooltip));
}
}
pub fn set_window_visible_label(&mut self, visible: bool) {
self.window_visible = visible;
} }
pub fn poll_events(&self) -> Vec<NativeEvent> { pub fn poll_events(&self) -> Vec<NativeEvent> {
let mut out = Vec::new(); let mut out = Vec::new();
while let Ok(ev) = self.rx_smtc.try_recv() { while let Ok(ev) = self.rx_events.try_recv() {
out.push(ev); out.push(ev);
} }
@ -214,33 +231,29 @@ mod imp {
button: MouseButton::Left, button: MouseButton::Left,
button_state: MouseButtonState::Up, button_state: MouseButtonState::Up,
.. ..
} => {
tray_menu_win::close_tray_menu();
out.push(NativeEvent::ToggleWindow);
} }
| TrayIconEvent::DoubleClick { TrayIconEvent::Click {
button: MouseButton::Left, button: MouseButton::Right,
button_state: MouseButtonState::Up,
.. ..
} => { } => {
out.push(NativeEvent::ShowWindow); tray_menu_win::show_tray_menu(
self.tx_events.clone(),
self.is_ru,
self.is_dark,
self.window_visible,
self.last_playing.unwrap_or(false),
self.can_prev,
self.can_next,
);
} }
_ => {} _ => {}
} }
} }
while let Ok(ev) = MenuEvent::receiver().try_recv() {
if self.menu_toggle_win_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::ToggleWindow);
} else if self.menu_updates_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::CheckUpdates);
} else if self.menu_play_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::TogglePlay);
} else if self.menu_next_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::Next);
} else if self.menu_prev_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::Prev);
} else if self.menu_quit_id.as_ref() == Some(&ev.id) {
out.push(NativeEvent::QuitApp);
}
}
out out
} }
@ -249,16 +262,11 @@ mod imp {
track: Option<&Track>, track: Option<&Track>,
is_playing: bool, is_playing: bool,
position_ms: u64, position_ms: u64,
can_prev: bool,
can_next: bool,
) { ) {
if self.last_playing != Some(is_playing) { self.can_prev = can_prev;
if let Some(ref item) = self.item_play { self.can_next = can_next;
item.set_text(if is_playing {
if self.is_ru { "Пауза" } else { "Pause" }
} else {
if self.is_ru { "Играть" } else { "Play" }
});
}
}
let Some(ref mut smtc) = self.smtc else { let Some(ref mut smtc) = self.smtc else {
self.last_playing = Some(is_playing); self.last_playing = Some(is_playing);
return; return;
@ -449,7 +457,9 @@ mod imp {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
mod imp { mod imp {
use super::NativeEvent; use super::{
NativeEvent, TrayLabels, RECOMMENDATIONS_URL, SUPPORT_CHAT_URL, TERMS_OF_USE_URL,
};
use crate::api::models::Track; use crate::api::models::Track;
use crossbeam_channel::{unbounded, Receiver, Sender}; use crossbeam_channel::{unbounded, Receiver, Sender};
use ksni::blocking::{Handle, TrayMethods}; use ksni::blocking::{Handle, TrayMethods};
@ -466,6 +476,8 @@ mod imp {
is_ru: bool, is_ru: bool,
window_visible: bool, window_visible: bool,
is_playing: bool, is_playing: bool,
can_prev: bool,
can_next: bool,
track_summary: String, track_summary: String,
} }
@ -479,11 +491,7 @@ mod imp {
} }
fn title(&self) -> String { fn title(&self) -> String {
if self.is_ru { TrayLabels::for_lang(self.is_ru).tooltip.into()
"Яндекс Музыка".into()
} else {
"Yandex Music".into()
}
} }
fn icon_name(&self) -> String { fn icon_name(&self) -> String {
@ -509,24 +517,16 @@ mod imp {
fn menu(&self) -> Vec<ksni::MenuItem<Self>> { fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
use ksni::menu::*; use ksni::menu::*;
let labels = TrayLabels::for_lang(self.is_ru);
let toggle_label = if self.window_visible { let toggle_label = if self.window_visible {
if self.is_ru { "Скрыть" } else { "Hide" } labels.roll_up
} else if self.is_ru {
"Показать"
} else { } else {
"Show" labels.unwrap
}; };
let play_label = if self.is_playing { let play_label = if self.is_playing {
if self.is_ru { "Пауза" } else { "Pause" } labels.pause
} else if self.is_ru {
"Играть"
} else { } else {
"Play" labels.play
};
let ver_label = if self.is_ru {
format!("Яндекс Музыка {}", env!("CARGO_PKG_VERSION"))
} else {
format!("Yandex Music {}", env!("CARGO_PKG_VERSION"))
}; };
vec![ vec![
@ -539,11 +539,7 @@ mod imp {
} }
.into(), .into(),
StandardItem { StandardItem {
label: if self.is_ru { label: labels.check_updates.into(),
"Проверить обновления".into()
} else {
"Check updates".into()
},
activate: Box::new(|this: &mut Self| { activate: Box::new(|this: &mut Self| {
let _ = this.tx.send(NativeEvent::CheckUpdates); let _ = this.tx.send(NativeEvent::CheckUpdates);
}), }),
@ -560,11 +556,8 @@ mod imp {
} }
.into(), .into(),
StandardItem { StandardItem {
label: if self.is_ru { label: labels.prev.into(),
"Предыдущий трек".into() enabled: self.can_prev,
} else {
"Previous song".into()
},
activate: Box::new(|this: &mut Self| { activate: Box::new(|this: &mut Self| {
let _ = this.tx.send(NativeEvent::Prev); let _ = this.tx.send(NativeEvent::Prev);
}), }),
@ -572,11 +565,8 @@ mod imp {
} }
.into(), .into(),
StandardItem { StandardItem {
label: if self.is_ru { label: labels.next.into(),
"Следующий трек".into() enabled: self.can_next,
} else {
"Next song".into()
},
activate: Box::new(|this: &mut Self| { activate: Box::new(|this: &mut Self| {
let _ = this.tx.send(NativeEvent::Next); let _ = this.tx.send(NativeEvent::Next);
}), }),
@ -585,27 +575,39 @@ mod imp {
.into(), .into(),
MenuItem::Separator, MenuItem::Separator,
SubMenu { SubMenu {
label: if self.is_ru { label: labels.about.into(),
"О приложении".into() submenu: vec![
} else { StandardItem {
"About the app".into() label: labels.terms.into(),
}, activate: Box::new(|this: &mut Self| {
submenu: vec![StandardItem { let _ = this.tx.send(NativeEvent::OpenUrl(TERMS_OF_USE_URL));
label: ver_label, }),
enabled: false, ..Default::default()
..Default::default() }
} .into(),
.into()], StandardItem {
label: labels.recommendations.into(),
activate: Box::new(|this: &mut Self| {
let _ = this.tx.send(NativeEvent::OpenUrl(RECOMMENDATIONS_URL));
}),
..Default::default()
}
.into(),
StandardItem {
label: labels.support.into(),
activate: Box::new(|this: &mut Self| {
let _ = this.tx.send(NativeEvent::OpenUrl(SUPPORT_CHAT_URL));
}),
..Default::default()
}
.into(),
],
..Default::default() ..Default::default()
} }
.into(), .into(),
MenuItem::Separator, MenuItem::Separator,
StandardItem { StandardItem {
label: if self.is_ru { label: labels.quit.into(),
"Закрыть приложение".into()
} else {
"Close app".into()
},
activate: Box::new(|this: &mut Self| { activate: Box::new(|this: &mut Self| {
let _ = this.tx.send(NativeEvent::QuitApp); let _ = this.tx.send(NativeEvent::QuitApp);
}), }),
@ -633,8 +635,11 @@ mod imp {
pub struct NativeDesktop { pub struct NativeDesktop {
handle: Option<Handle<LinuxTray>>, handle: Option<Handle<LinuxTray>>,
rx: Receiver<NativeEvent>, rx: Receiver<NativeEvent>,
is_ru: bool,
last_playing: Option<bool>, last_playing: Option<bool>,
last_track_id: Option<String>, last_track_id: Option<String>,
last_can_prev: Option<bool>,
last_can_next: Option<bool>,
} }
impl Drop for NativeDesktop { impl Drop for NativeDesktop {
@ -661,18 +666,37 @@ mod imp {
is_ru, is_ru,
window_visible: true, window_visible: true,
is_playing: false, is_playing: false,
can_prev: false,
can_next: false,
track_summary: String::new(), track_summary: String::new(),
}; };
let handle = tray.assume_sni_available(true).spawn().ok(); let handle = tray.assume_sni_available(true).spawn().ok();
Self { Self {
handle, handle,
rx, rx,
is_ru,
last_playing: None, last_playing: None,
last_track_id: None, last_track_id: None,
last_can_prev: Some(false),
last_can_next: Some(false),
} }
} }
pub fn set_window_visible_label(&self, visible: bool) { pub fn set_dark_mode(&mut self, _is_dark: bool) {}
pub fn set_language(&mut self, is_ru: bool) {
if self.is_ru == is_ru {
return;
}
self.is_ru = is_ru;
if let Some(ref handle) = self.handle {
handle.update(move |t| {
t.is_ru = is_ru;
});
}
}
pub fn set_window_visible_label(&mut self, visible: bool) {
if let Some(ref handle) = self.handle { if let Some(ref handle) = self.handle {
handle.update(move |t| { handle.update(move |t| {
t.window_visible = visible; t.window_visible = visible;
@ -688,13 +712,26 @@ mod imp {
out out
} }
pub fn sync_playback(&mut self, track: Option<&Track>, is_playing: bool, _pos_ms: u64) { pub fn sync_playback(
&mut self,
track: Option<&Track>,
is_playing: bool,
_pos_ms: u64,
can_prev: bool,
can_next: bool,
) {
let track_id = track.map(|t| t.id.as_str()); 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 { if self.last_playing == Some(is_playing)
&& self.last_track_id.as_deref() == track_id
&& self.last_can_prev == Some(can_prev)
&& self.last_can_next == Some(can_next)
{
return; return;
} }
self.last_playing = Some(is_playing); self.last_playing = Some(is_playing);
self.last_track_id = track_id.map(String::from); self.last_track_id = track_id.map(String::from);
self.last_can_prev = Some(can_prev);
self.last_can_next = Some(can_next);
let summary = track let summary = track
.map(|tr| { .map(|tr| {
let artists = tr.artists_string(); let artists = tr.artists_string();
@ -708,6 +745,8 @@ mod imp {
if let Some(ref handle) = self.handle { if let Some(ref handle) = self.handle {
handle.update(move |t| { handle.update(move |t| {
t.is_playing = is_playing; t.is_playing = is_playing;
t.can_prev = can_prev;
t.can_next = can_next;
t.track_summary = summary; t.track_summary = summary;
}); });
} }
@ -869,11 +908,21 @@ mod imp {
pub fn new(_window: &Window, _is_ru: bool) -> Self { pub fn new(_window: &Window, _is_ru: bool) -> Self {
Self Self
} }
pub fn set_window_visible_label(&self, _visible: bool) {} pub fn set_dark_mode(&mut self, _is_dark: bool) {}
pub fn set_language(&mut self, _is_ru: bool) {}
pub fn set_window_visible_label(&mut self, _visible: bool) {}
pub fn poll_events(&self) -> Vec<NativeEvent> { pub fn poll_events(&self) -> Vec<NativeEvent> {
Vec::new() Vec::new()
} }
pub fn sync_playback(&mut self, _track: Option<&Track>, _is_playing: bool, _pos_ms: u64) {} pub fn sync_playback(
&mut self,
_track: Option<&Track>,
_is_playing: bool,
_pos_ms: u64,
_can_prev: bool,
_can_next: bool,
) {
}
} }
pub fn load_window_icon() -> Option<winit::window::Icon> { pub fn load_window_icon() -> Option<winit::window::Icon> {
@ -886,3 +935,39 @@ mod imp {
} }
pub use imp::{load_window_icon, run_auth_webview_subprocess, spawn_auth_webview_subprocess, NativeDesktop}; pub use imp::{load_window_icon, run_auth_webview_subprocess, spawn_auth_webview_subprocess, NativeDesktop};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tray_labels_match_original_desktop_index_js() {
let ru = TrayLabels::for_lang(true);
assert_eq!(ru.roll_up, "Свернуть");
assert_eq!(ru.unwrap, "Развернуть");
assert_eq!(ru.check_updates, "Проверить обновления");
assert_eq!(ru.play, "Воспроизведение");
assert_eq!(ru.pause, "Пауза");
assert_eq!(ru.prev, "Предыдущая песня");
assert_eq!(ru.next, "Следующая песня");
assert_eq!(ru.about, "О приложении");
assert_eq!(ru.terms, "Пользовательское соглашение");
assert_eq!(ru.recommendations, "Правила рекомендаций");
assert_eq!(ru.support, "Чат с поддержкой");
assert_eq!(ru.quit, "Закрыть приложение");
let en = TrayLabels::for_lang(false);
assert_eq!(en.roll_up, "Hide");
assert_eq!(en.unwrap, "Expand");
assert_eq!(en.check_updates, "Check updates");
assert_eq!(en.play, "Playback");
assert_eq!(en.pause, "Pause");
assert_eq!(en.prev, "Previous song");
assert_eq!(en.next, "Next song");
assert_eq!(en.about, "About the app");
assert_eq!(en.terms, "User agreement");
assert_eq!(en.recommendations, "Recommendation rules");
assert_eq!(en.support, "Support chat");
assert_eq!(en.quit, "Close app");
}
}

1084
src/native/tray_menu_win.rs Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -54,6 +54,9 @@ pub fn render_detail(
}, },
} }
let app_ref: &AppState = &*app;
let mut next_filter: Option<String> = None;
let ( let (
entity_kind, entity_kind,
kind_label, kind_label,
@ -81,15 +84,15 @@ pub fn render_detail(
String, String,
Option<String>, Option<String>,
String, String,
Vec<Track>, &[Track],
) = match app.route.clone() { ) = match app_ref.route.clone() {
Route::LikedTracks => { Route::LikedTracks => {
let author_name = app let author_name = app_ref
.account .account
.as_ref() .as_ref()
.map(|a| a.display_name.clone()) .map(|a| a.display_name.clone())
.unwrap_or_else(|| t.app_name().to_string()); .unwrap_or_else(|| t.app_name().to_string());
let share = if let Some(ref acc) = app.account { let share = if let Some(ref acc) = app_ref.account {
format!("https://music.yandex.ru/users/{}/playlists/3", acc.login) format!("https://music.yandex.ru/users/{}/playlists/3", acc.login)
} else { } else {
"https://music.yandex.ru/collection".into() "https://music.yandex.ru/collection".into()
@ -107,7 +110,7 @@ pub fn render_detail(
"likes".into(), "likes".into(),
my_uid.clone(), my_uid.clone(),
share, share,
app.liked_tracks.clone(), app_ref.liked_tracks.as_slice(),
) )
} }
Route::Playlist { Route::Playlist {
@ -115,7 +118,7 @@ pub fn render_detail(
kind, kind,
title: fallback_title, title: fallback_title,
} => { } => {
let det = app let det = app_ref
.current_playlist_detail .current_playlist_detail
.as_ref() .as_ref()
.filter(|d| d.summary.owner_uid == owner_uid && d.summary.kind == kind); .filter(|d| d.summary.owner_uid == owner_uid && d.summary.kind == kind);
@ -132,14 +135,14 @@ pub fn render_detail(
d.summary.title.clone(), d.summary.title.clone(),
d.summary.owner_name.clone(), d.summary.owner_name.clone(),
d.summary.cover_uri.clone(), d.summary.cover_uri.clone(),
d.tracks.clone(), d.tracks.as_slice(),
) )
} else { } else {
( (
fallback_title, fallback_title,
t.app_name().to_string(), t.app_name().to_string(),
None, None,
Vec::new(), &[][..],
) )
}; };
let p_id = format!("{}:{}", owner_uid, kind); let p_id = format!("{}:{}", owner_uid, kind);
@ -169,7 +172,7 @@ pub fn render_detail(
id, id,
title: fallback_title, title: fallback_title,
} => { } => {
let det = app let det = app_ref
.current_album_detail .current_album_detail
.as_ref() .as_ref()
.filter(|d| d.summary.id == id); .filter(|d| d.summary.id == id);
@ -189,10 +192,10 @@ pub fn render_detail(
arts arts
}, },
d.summary.cover_uri.clone(), d.summary.cover_uri.clone(),
d.tracks.clone(), d.tracks.as_slice(),
) )
} else { } else {
(fallback_title, t.album().to_string(), None, Vec::new()) (fallback_title, t.album().to_string(), None, &[][..])
}; };
let share = format!("https://music.yandex.ru/album/{}", id); let share = format!("https://music.yandex.ru/album/{}", id);
( (
@ -215,7 +218,7 @@ pub fn render_detail(
id, id,
name: fallback_name, name: fallback_name,
} => { } => {
let det = app let det = app_ref
.current_artist_detail .current_artist_detail
.as_ref() .as_ref()
.filter(|d| d.summary.id == id); .filter(|d| d.summary.id == id);
@ -239,14 +242,14 @@ pub fn render_detail(
d.summary.name.clone(), d.summary.name.clone(),
sub, sub,
d.summary.cover_uri.clone(), d.summary.cover_uri.clone(),
d.popular_tracks.clone(), d.popular_tracks.as_slice(),
) )
} else { } else {
( (
fallback_name, fallback_name,
t.popular_tracks().to_string(), t.popular_tracks().to_string(),
None, None,
Vec::new(), &[][..],
) )
}; };
let share = format!("https://music.yandex.ru/artist/{}", id); let share = format!("https://music.yandex.ru/artist/{}", id);
@ -287,26 +290,75 @@ pub fn render_detail(
EntityKind::Artist { id } => format!("artist:{}", id), EntityKind::Artist { id } => format!("artist:{}", id),
}; };
// Displayed tracks: on My Favorites uses `app.filtered_liked_tracks()` (chip + search filter!) // Zero-copy track view: avoids cloning thousands of `Track` structs every frame during scroll!
let displayed_tracks: Vec<Track> = if is_liked_page { enum TrackView<'a> {
app.filtered_liked_tracks() Slice(&'a [Track]),
} else { Filtered(Vec<&'a Track>),
let q = app.detail_track_filter.trim().to_lowercase(); }
if q.is_empty() { impl<'a> TrackView<'a> {
raw_tracks.clone() #[inline]
fn len(&self) -> usize {
match self {
Self::Slice(s) => s.len(),
Self::Filtered(v) => v.len(),
}
}
#[inline]
fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
fn get(&self, idx: usize) -> &'a Track {
match self {
Self::Slice(s) => &s[idx],
Self::Filtered(v) => v[idx],
}
}
fn to_owned_vec(&self) -> Vec<Track> {
match self {
Self::Slice(s) => s.to_vec(),
Self::Filtered(v) => v.iter().map(|t| (*t).clone()).collect(),
}
}
}
let displayed_tracks: TrackView<'_> = {
let q = app_ref.detail_track_filter.trim().to_lowercase();
let active_chip = if is_liked_page {
match app_ref.selected_favorite_filter_id.as_deref() {
Some(sel_id) if sel_id != "all" => app_ref
.effective_favorite_filters()
.into_iter()
.find(|c| c.id == sel_id),
_ => None,
}
} else { } else {
raw_tracks None
};
if active_chip.is_none() && q.is_empty() {
TrackView::Slice(raw_tracks)
} else {
let filtered: Vec<&Track> = raw_tracks
.iter() .iter()
.filter(|tr| { .filter(|tr| {
tr.title.to_lowercase().contains(&q) if let Some(ref chip) = active_chip {
|| tr.artists_string().to_lowercase().contains(&q) if !chip.matches_track(tr) {
|| tr return false;
.album_title }
.as_deref() }
.map_or(false, |a| a.to_lowercase().contains(&q)) if !q.is_empty() {
return tr.title.to_lowercase().contains(&q)
|| tr.artists_string().to_lowercase().contains(&q)
|| tr
.album_title
.as_deref()
.map_or(false, |a| a.to_lowercase().contains(&q));
}
true
}) })
.cloned() .collect();
.collect() TrackView::Filtered(filtered)
} }
}; };
@ -527,7 +579,7 @@ pub fn render_detail(
); );
if play_resp.clicked && !displayed_tracks.is_empty() { if play_resp.clicked && !displayed_tracks.is_empty() {
actions.push(AppAction::ToggleContextPlay { actions.push(AppAction::ToggleContextPlay {
tracks: displayed_tracks.clone(), tracks: displayed_tracks.to_owned_vec(),
context_name: title.clone(), context_name: title.clone(),
context_key: context_key.clone(), context_key: context_key.clone(),
is_vibe: false, is_vibe: false,
@ -616,7 +668,7 @@ pub fn render_detail(
cover_uri: cover_uri.clone(), cover_uri: cover_uri.clone(),
owner_uid: pin_owner_uid.clone(), owner_uid: pin_owner_uid.clone(),
is_own_playlist, is_own_playlist,
tracks: displayed_tracks.clone(), tracks: displayed_tracks.to_owned_vec(),
anchor: Pos2::new(more_r.left(), more_r.bottom() + 6.0), anchor: Pos2::new(more_r.left(), more_r.bottom() + 6.0),
share_url: share_url.clone(), share_url: share_url.clone(),
}); });
@ -721,7 +773,7 @@ pub fn render_detail(
ctx.show_tooltip(dl_r, t.download()); ctx.show_tooltip(dl_r, t.download());
} }
if resp.clicked { if resp.clicked {
actions.push(AppAction::DownloadTracks(raw_tracks.clone())); actions.push(AppAction::DownloadTracks(raw_tracks.to_vec()));
} }
} }
} }
@ -750,7 +802,7 @@ pub fn render_detail(
}, },
); );
if ti.changed || ti.cleared { if ti.changed || ti.cleared {
app.detail_track_filter = filter_buf; next_filter = Some(filter_buf);
} }
y += 32.5 + 23.5; y += 32.5 + 23.5;
} }
@ -826,7 +878,7 @@ pub fn render_detail(
let is_album_page = matches!(entity_kind, EntityKind::Album { .. }); let is_album_page = matches!(entity_kind, EntityKind::Album { .. });
let range = visible_row_range(rect, y, TRACK_ROW_HEIGHT, displayed_tracks.len(), 2); let range = visible_row_range(rect, y, TRACK_ROW_HEIGHT, displayed_tracks.len(), 2);
for idx in range { for idx in range {
let tr = &displayed_tracks[idx]; let tr = displayed_tracks.get(idx);
let row_r = Rect::from_xywh(x, y + idx as f32 * TRACK_ROW_HEIGHT, avail_w, TRACK_ROW_HEIGHT); let row_r = Rect::from_xywh(x, y + idx as f32 * TRACK_ROW_HEIGHT, avail_w, TRACK_ROW_HEIGHT);
let is_curr = current_track_id.as_deref() == Some(tr.id.as_str()); let is_curr = current_track_id.as_deref() == Some(tr.id.as_str());
match track_row( match track_row(
@ -842,17 +894,17 @@ pub fn render_detail(
show_cover: !is_album_page, show_cover: !is_album_page,
is_current: is_curr, is_current: is_curr,
is_playing: is_curr && is_playing, is_playing: is_curr && is_playing,
is_liked: app.liked_ids.contains(&tr.id), is_liked: app_ref.liked_ids.contains(&tr.id),
is_disliked: app.disliked_ids.contains(&tr.id), is_disliked: app_ref.disliked_ids.contains(&tr.id),
is_downloaded: app.is_track_downloaded(&tr.id), is_downloaded: app_ref.is_track_downloaded(&tr.id),
is_downloading: app.is_track_downloading(&tr.id), is_downloading: app_ref.is_track_downloading(&tr.id),
download_progress: app.track_download_progress(&tr.id), download_progress: app_ref.track_download_progress(&tr.id),
menu_open: shell.is_track_menu_open(&tr.id), menu_open: shell.is_track_menu_open(&tr.id),
}, },
) { ) {
TrackRowAction::Play => { TrackRowAction::Play => {
actions.push(AppAction::PlayTracks { actions.push(AppAction::PlayTracks {
tracks: displayed_tracks.clone(), tracks: displayed_tracks.to_owned_vec(),
start_index: idx, start_index: idx,
context_name: title.clone(), context_name: title.clone(),
context_key: context_key.clone(), context_key: context_key.clone(),
@ -902,9 +954,9 @@ pub fn render_detail(
// 9. Artist Extra Sections: Localized Albums & Similar Artists Carousels! // 9. Artist Extra Sections: Localized Albums & Similar Artists Carousels!
if let EntityKind::Artist { id: ref route_art_id } = entity_kind { if let EntityKind::Artist { id: ref route_art_id } = entity_kind {
if let Some(art_detail) = app if let Some(art_detail) = app_ref
.current_artist_detail .current_artist_detail
.clone() .as_ref()
.filter(|d| &d.summary.id == route_art_id) .filter(|d| &d.summary.id == route_art_id)
{ {
if !art_detail.albums.is_empty() { if !art_detail.albums.is_empty() {
@ -1034,6 +1086,10 @@ pub fn render_detail(
y += 28.0; y += 28.0;
let total_h = y - (rect.top() - scroll_y); let total_h = y - (rect.top() - scroll_y);
ctx.end_scroll_v(scroll_id, pal, total_h, true); ctx.end_scroll_v(scroll_id, pal, total_h, true);
if let Some(f) = next_filter {
app.detail_track_filter = f;
}
} }
fn format_thousands(n: u64) -> String { fn format_thousands(n: u64) -> String {

File diff suppressed because it is too large Load diff

View file

@ -23,11 +23,13 @@ use crate::engine::{
use crate::vulkan::vibe_renderer::VibePushConstants; use crate::vulkan::vibe_renderer::VibePushConstants;
use overlays::{ use overlays::{
render_delete_playlist_confirm_modal, render_entity_context_menu, render_eq_popover, render_about_app_modal, render_clear_memory_modal, render_delete_playlist_confirm_modal,
render_equalizer_modal, render_fullscreen_player, render_login_modal, render_playlist_modal, render_entity_context_menu, render_eq_popover, render_equalizer_modal,
render_vibe_room_invite_modal,
render_fullscreen_player, render_login_screen, render_playlist_modal,
render_release_notes_modal, render_right_drawer, render_shortcuts_modal, render_release_notes_modal, render_right_drawer, render_shortcuts_modal,
render_toast_with_offset, render_track_context_menu, render_track_detail_modal, render_track_context_menu, render_track_detail_modal, render_update_notification,
render_update_notification, render_vibe_settings_modal, ShellUiState, SplashPlayer, render_vibe_settings_modal, ShellUiState, SplashPlayer,
}; };
use player_bar::render_player_bar; use player_bar::render_player_bar;
use sidebar::render_sidebar; use sidebar::render_sidebar;
@ -203,10 +205,12 @@ impl YandexMusicShell {
let screen = self.ui.screen_rect(); let screen = self.ui.screen_rect();
let is_my_vibe_page = matches!(self.app.route, Route::MyVibe); let is_my_vibe_page = matches!(self.app.route, Route::MyVibe);
// 1. Left Sidebar (full-height, smooth 224px <-> 72px collapse animation) // 1. Left Sidebar (full-height, smooth 224px <-> 72px collapse animation;
// auto-collapses below 1060px logical width just like official Yandex Music Desktop!)
let auto_collapsed = screen.width() < 1060.0;
let collapse_t = self.ui.animate_bool( let collapse_t = self.ui.animate_bool(
WidgetId::new("ym_sidebar_collapse_anim"), WidgetId::new("ym_sidebar_collapse_anim"),
self.app.config.sidebar_collapsed, self.app.config.sidebar_collapsed || auto_collapsed,
0.16, 0.16,
); );
let nav_w = (NAVBAR_FULL_WIDTH * (1.0 - collapse_t) let nav_w = (NAVBAR_FULL_WIDTH * (1.0 - collapse_t)
@ -588,8 +592,11 @@ impl YandexMusicShell {
&mut self.shell, &mut self.shell,
&mut actions, &mut actions,
); );
if self.app.login_modal_open { render_vibe_room_invite_modal(&mut self.ui, &pal, &mut self.app, &mut actions);
render_login_modal(&mut self.ui, &pal, &mut self.app, &mut actions); let needs_auth_gate =
!self.app.api.has_token() && self.app.persist_enabled && self.app.fixed_vibe_time.is_none();
if needs_auth_gate || self.app.login_modal_open {
render_login_screen(&mut self.ui, &pal, &self.app, &mut self.shell, &mut actions);
} }
if self.app.track_detail_modal.is_some() { if self.app.track_detail_modal.is_some() {
render_track_detail_modal(&mut self.ui, &pal, &mut self.covers, &self.app, &mut actions); render_track_detail_modal(&mut self.ui, &pal, &mut self.covers, &self.app, &mut actions);
@ -604,7 +611,14 @@ impl YandexMusicShell {
)) ))
}; };
if rn_mod_t > 0.01 { if rn_mod_t > 0.01 {
render_release_notes_modal(&mut self.ui, &pal, &self.app, rn_mod_t, &mut actions); render_release_notes_modal(
&mut self.ui,
&pal,
&self.app,
&mut self.shell,
rn_mod_t,
&mut actions,
);
} }
let eq_mod_t = if self.app.fixed_vibe_time.is_some() { let eq_mod_t = if self.app.fixed_vibe_time.is_some() {
if self.app.equalizer_modal_open { 1.0 } else { 0.0 } if self.app.equalizer_modal_open { 1.0 } else { 0.0 }
@ -637,6 +651,30 @@ impl YandexMusicShell {
if sc_mod_t > 0.01 { if sc_mod_t > 0.01 {
render_shortcuts_modal(&mut self.ui, &pal, &self.app, sc_mod_t, &mut actions); render_shortcuts_modal(&mut self.ui, &pal, &self.app, sc_mod_t, &mut actions);
} }
let cm_mod_t = if self.app.fixed_vibe_time.is_some() {
if self.app.clear_memory_modal_open { 1.0 } else { 0.0 }
} else {
ease_out(self.ui.animate_bool(
WidgetId::new("ym_clear_memory_modal_anim"),
self.app.clear_memory_modal_open,
0.18,
))
};
if cm_mod_t > 0.01 {
render_clear_memory_modal(&mut self.ui, &pal, &self.app, cm_mod_t, &mut actions);
}
let ab_mod_t = if self.app.fixed_vibe_time.is_some() {
if self.app.about_app_modal_open { 1.0 } else { 0.0 }
} else {
ease_out(self.ui.animate_bool(
WidgetId::new("ym_about_app_modal_anim"),
self.app.about_app_modal_open,
0.18,
))
};
if ab_mod_t > 0.01 {
render_about_app_modal(&mut self.ui, &pal, &self.app, ab_mod_t, &mut actions);
}
// 8. Transparent 32px Floating TitleBar (ZLayer::Titlebar) // 8. Transparent 32px Floating TitleBar (ZLayer::Titlebar)
let win_cmd = render_titlebar( let win_cmd = render_titlebar(
@ -647,7 +685,7 @@ impl YandexMusicShell {
self.app.fullscreen_open, self.app.fullscreen_open,
); );
// 9. Official `NotificationUpdate` + Floating Toast (when splash is done) // 9. Official `NotificationUpdate` (when splash is done; floating toast banners disabled 1-to-1 with original)
let show_upd_notif = self.splash.is_none() let show_upd_notif = self.splash.is_none()
&& !self.app.fullscreen_open && !self.app.fullscreen_open
&& !self.app.update_notification_dismissed && !self.app.update_notification_dismissed
@ -657,12 +695,6 @@ impl YandexMusicShell {
render_update_notification(&mut self.ui, &pal, &self.app, upd, &mut actions); 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) {
let extra_offset = if show_upd_notif { 64.0 } else { 0.0 };
render_toast_with_offset(&mut self.ui, &pal, &msg, extra_offset);
}
}
// 10. Theme-Aware Streaming Animated Splash Screen (`splash_dark.webp` / `splash_light.webp`) // 10. Theme-Aware Streaming Animated Splash Screen (`splash_dark.webp` / `splash_light.webp`)
if let Some(ref mut sp) = self.splash { if let Some(ref mut sp) = self.splash {
@ -717,6 +749,30 @@ impl YandexMusicShell {
actions.push(AppAction::DismissOverlays); actions.push(AppAction::DismissOverlays);
} }
// Global UI zoom (`Ctrl +` / `Ctrl -` / `Ctrl 0` & `Ctrl + Wheel`), matching Chromium/Electron
{
let mut next_zoom: Option<f32> = None;
let cur = self.app.config.ui_zoom;
for e in &self.ui.input.key_events {
if e.modifiers.command() && !e.modifiers.alt {
match e.key {
Key::Char('+') | Key::Char('=') => next_zoom = Some((cur + 0.10).clamp(0.5, 2.0)),
Key::Char('-') | Key::Char('_') => next_zoom = Some((cur - 0.10).clamp(0.5, 2.0)),
Key::Char('0') => next_zoom = Some(1.0),
_ => {}
}
}
}
if self.ui.input.modifiers.command() && self.ui.input.wheel_delta.y.abs() > 0.1 {
let step = if self.ui.input.wheel_delta.y > 0.0 { 0.10 } else { -0.10 };
next_zoom = Some((cur + step).clamp(0.5, 2.0));
self.ui.input.wheel_delta.y = 0.0;
}
if let Some(z) = next_zoom {
actions.push(AppAction::SetUiZoom(z));
}
}
if self.ui.input.has_text_focus() { if self.ui.input.has_text_focus() {
return; return;
} }

View file

@ -109,10 +109,35 @@ pub fn render_my_vibe(
// so skip drawing a redundant full-stage blended quad over the entire screen! // so skip drawing a redundant full-stage blended quad over the entire screen!
ctx.push_clip(rect, 0.0); ctx.push_clip(rect, 0.0);
let left_w = if rect.width() > 780.0 { 380.0 } else { 0.0 }; // Exact `.VibePage_root__dGvPX` (`5b3a6ee99e2bd1b8.css:3345-3428, 3756-3760`) inside
// `.DefaultLayout_root_applicationPreserveTitleBar__ygJtq` (`dc13ce0fb949bab3.css:283`: 32px)
// + `.Content_root_newVibe__5S1qr` (`d236a4c44d4081b0.css:291-295`: -12px top/bottom/right)
// + `.Content_main_newVibe__tfCx9` (`d236a4c44d4081b0.css:316-320`: +12px right):
// Net layout bounds: top offset = 20px, right inset = 12px on desktop (`>= 768px`).
// Desktop flex split: `VibePage_wheel` = `flex: 1 1 40%`, `VibePage_meta` = `flex: 1 1 60%`
// with `padding-inline-start: 24px (xxl)` and `padding-inline-end: 48px (xxxxxl)`.
let rem_scale = ctx.rem_scale.max(0.5);
let screen_w = rect.right();
let raw_screen_w = screen_w * rem_scale;
let page_top = rect.top() + if raw_screen_w >= 768.0 { 20.0 } else { 0.0 };
let page_right = rect.right() - if raw_screen_w >= 768.0 { 12.0 } else { 0.0 };
let page_w = (page_right - rect.left()).max(240.0);
let left_w = if raw_screen_w >= 768.0 {
page_w * 0.40
} else {
0.0
};
let meta_outer = Rect::from_min_max(
Pos2::new(rect.left() + left_w, page_top),
Pos2::new(page_right, rect.bottom()),
);
let meta_pad_l = 24.0;
let meta_pad_r = if raw_screen_w >= 768.0 { 48.0 } else { 24.0 };
let meta_inner_l = meta_outer.left() + meta_pad_l;
let meta_inner_r = (meta_outer.right() - meta_pad_r).max(meta_inner_l + 240.0);
let hero_rect = Rect::from_min_max( let hero_rect = Rect::from_min_max(
Pos2::new(rect.left() + left_w, rect.top()), Pos2::new(meta_inner_l, meta_outer.top()),
rect.max(), Pos2::new(meta_inner_r, meta_outer.bottom()),
); );
// 1. RIGHT HERO STAGE — Exact `.DefaultLayout_rootNewVibe__MSDOn` 16-stop exponential-decay 270deg gradient // 1. RIGHT HERO STAGE — Exact `.DefaultLayout_rootNewVibe__MSDOn` 16-stop exponential-decay 270deg gradient
@ -214,16 +239,13 @@ pub fn render_my_vibe(
} }
} }
// 2. VIBE WEBGL-EQUIVALENT VULKAN ORB — Exact `.VibePage_vibeAnimation { width: 250%; inset: 50% }` // 2. VIBE WEBGL-EQUIVALENT VULKAN ORB — Exact `.VibePage_meta__kWwRE` responsive flex layout
// Decouple orb vertical center (`318.0` at 800px height) from headline vertical center (`247.0` at 800px height)! // (`5b3a6ee99e2bd1b8.css:3398-3431, 3513-3608, 3667-3680, 3784-3834`):
let orb_cy = rect.top() + (rect.height() * 0.3975).clamp(240.0, 318.0); // - `justify-content: center` centers `(context + entityMeta + playerBlock)` vertically
let headline_cy = rect.top() + (rect.height() * 0.30875).clamp(175.0, 247.0); // - `@media (max-aspect-ratio: 3/2)` caps `--entity-meta-max-height` to `43.75rem (700px)` (else `1080px`)
let entity_meta_w = (rect.width() * 0.60 - 72.0).max(280.0); // - `@container vibe-page (max-height: 800px)` uses `24px/16px` vertical padding (`40px/64px` above 800px)
let orb_sz = entity_meta_w * 2.25; // - `@container vibe-page (max-height: 640px)` shrinks `--album-cover-size` to `64px` and bottom padding to `0`
let orb_rect = Rect::from_center_size(Pos2::new(cx, orb_cy), Vec2::splat(orb_sz)); // - `.VibePage_vibeAnimation__qQ6ci { width: 250%; inset: 50%; transform: translate(-50%,-50%) }`
ctx.dl().push_image(orb_rect, VIBE_TEXTURE_ID, 0.0, Color::WHITE);
// 3. HEADLINE: Idle "Моя волна"/"My Vibe" vs Playing yellow label + dynamic Artist Name
let default_vibe_title = t.my_vibe(); let default_vibe_title = t.my_vibe();
let vibe_label = if app.active_vibe_title.is_empty() let vibe_label = if app.active_vibe_title.is_empty()
|| app.active_vibe_title == "My Vibe" || app.active_vibe_title == "My Vibe"
@ -238,7 +260,6 @@ pub fn render_my_vibe(
let playing_alpha = play_fade_t.clamp(0.0, 1.0); let playing_alpha = play_fade_t.clamp(0.0, 1.0);
let idle_alpha = (1.0 - play_fade_t).clamp(0.0, 1.0); let idle_alpha = (1.0 - play_fade_t).clamp(0.0, 1.0);
// 3a. Top Source Context Header (`y = rect.top() + 54.0`, official `VIBE_PAGE_CONTEXT_BLOCK`)
let is_custom_vibe_station = app.is_vibe_active let is_custom_vibe_station = app.is_vibe_active
&& !app.active_vibe_title.is_empty() && !app.active_vibe_title.is_empty()
&& !app.active_vibe_title.eq_ignore_ascii_case("My Vibe") && !app.active_vibe_title.eq_ignore_ascii_case("My Vibe")
@ -247,7 +268,56 @@ pub fn render_my_vibe(
&& !app.context_name.is_empty() && !app.context_name.is_empty()
&& !app.context_name.eq_ignore_ascii_case("My Vibe") && !app.context_name.eq_ignore_ascii_case("My Vibe")
&& !app.context_name.eq_ignore_ascii_case("Моя волна"); && !app.context_name.eq_ignore_ascii_case("Моя волна");
let top_y = rect.top() + 54.0; // `.VibeResetButton_root__ju8pE` (`5b3a6ee99e2bd1b8.css:1510-1520`) always reserves
// `--reset-button-height: 3rem (48px)` and fades via opacity, so Play/Pause never shifts layout.
let h = (rect.bottom() - page_top).max(200.0);
let raw_h = h * rem_scale;
let screen_aspect = screen_w / rect.height().max(1.0);
let (pad_top, pad_bot, cover_sz) = if raw_h <= 640.0 {
(24.0_f32, 0.0_f32, 64.0_f32)
} else if raw_h <= 800.0 {
(24.0_f32, 16.0_f32, 96.0_f32)
} else {
(40.0_f32, 64.0_f32, 96.0_f32)
};
let play_btn_sz = if raw_h <= 480.0 { 56.0_f32 } else { 64.0_f32 };
let context_h = 48.0_f32;
let player_block_h = 268.0_f32; // `--player-block-height: 16.75rem`
let entity_meta_max_h = if screen_aspect <= 1.5 {
700.0_f32 // `@media (max-aspect-ratio: 3/2)` -> `43.75rem`
} else {
1080.0_f32 / rem_scale // default `1080PX` (pure px, does not scale with `rem`)
};
let avail_h = (h - pad_top - pad_bot).max(player_block_h + 120.0);
let entity_meta_h = (avail_h - context_h - player_block_h).clamp(120.0, entity_meta_max_h);
let total_content_h = context_h + entity_meta_h + player_block_h;
let content_top = page_top + pad_top + ((avail_h - total_content_h) * 0.5).max(0.0);
let top_y = if context_h > 0.0 {
content_top + context_h * 0.5
} else {
content_top + 24.0
};
let entity_meta_top = content_top + context_h;
let entity_meta_bottom = entity_meta_top + entity_meta_h;
let player_block_top = entity_meta_bottom;
let cov_cy = player_block_top - cover_sz * 0.5 - 16.0;
// `.VibePage_textContainer__odK0M` (`5b3a6ee99e2bd1b8.css:3349, 3597`):
// `padding-block-end: calc(var(--album-cover-size) + var(--ym-spacer-size-l))` = `cover_sz + 16px`
let headline_cy = entity_meta_top + (entity_meta_h - (cover_sz + 16.0)) * 0.5;
let orb_cy = entity_meta_top + entity_meta_h * 0.554;
// `.VibePage_vibeAnimation__qQ6ci` (`5b3a6ee99e2bd1b8.css:3559`): `width: 250%` of `VibePage_entityMeta`
// (keep the 2.25x cap only on compact `<= 800px` heights matching the 1280x800 visual fixture)
let orb_sz = if h <= 800.0 {
(hero_rect.width() * 2.25).min(entity_meta_h * 2.85).max(520.0)
} else {
(hero_rect.width() * 2.50).max(520.0)
};
let orb_rect = Rect::from_center_size(Pos2::new(cx, orb_cy), Vec2::splat(orb_sz));
ctx.dl().push_image(orb_rect, VIBE_TEXTURE_ID, 0.0, Color::WHITE);
// 3. HEADLINE: Idle "Моя волна"/"My Vibe" vs Playing yellow label + dynamic Artist Name
// 3a. Top Source Context Header (`VibePage_context__CoYut`)
let reset_tooltip = if ru { let reset_tooltip = if ru {
"Сбросить на Мою волну" "Сбросить на Мою волну"
} else { } else {
@ -277,8 +347,10 @@ pub fn render_my_vibe(
let close_center = Pos2::new(pill_r.right() - 12.0 - 11.0, pill_r.center_y()); let close_center = Pos2::new(pill_r.right() - 12.0 - 11.0, pill_r.center_y());
let reset_r = Rect::from_center_size(close_center, Vec2::splat(32.0)); let reset_r = Rect::from_center_size(close_center, Vec2::splat(32.0));
// Non-overlapping hit rects so the outer pill never steals clicks from the `×` reset button!
let pill_hit_r = Rect::from_min_max(pill_r.min(), Pos2::new(reset_r.left(), pill_r.bottom()));
let pill_resp = ctx.interact(WidgetId::new("vb_ctx_source_pill"), pill_hit_r);
let reset_resp = ctx.interact(WidgetId::new("vb_ctx_reset_btn"), reset_r); let reset_resp = ctx.interact(WidgetId::new("vb_ctx_reset_btn"), reset_r);
let pill_resp = ctx.interact(WidgetId::new("vb_ctx_source_pill"), pill_r);
let pill_bg = if pill_resp.pressed || reset_resp.pressed { let pill_bg = if pill_resp.pressed || reset_resp.pressed {
css_rgba(0, 0, 0, 153) // rgba(0,0,0,0.60) css_rgba(0, 0, 0, 153) // rgba(0,0,0,0.60)
@ -345,18 +417,18 @@ pub fn render_my_vibe(
let artist_str = tr.artists_string(); let artist_str = tr.artists_string();
let char_len = artist_str.chars().count(); let char_len = artist_str.chars().count();
let max_w = (hero_rect.width() - 64.0).max(260.0); let max_w = (hero_rect.width() - 64.0).max(260.0);
// Exact `useDynamicText` (`iM`: 44..104px) // Exact `useDynamicText` (`iM`: 44..104px pure px, divided by `rem_scale` on >=1920px)
let art_sz = (if char_len <= 8 { let art_sz = (if char_len <= 8 {
100.0_f32 100.0_f32 / rem_scale
} else if char_len <= 14 { } else if char_len <= 14 {
80.0_f32 80.0_f32 / rem_scale
} else if char_len <= 22 { } else if char_len <= 22 {
64.0_f32 64.0_f32 / rem_scale
} else { } else {
48.0_f32 48.0_f32 / rem_scale
}) })
.min(max_w / (char_len.max(4) as f32 * 0.52)) .min(max_w / (char_len.max(4) as f32 * 0.52))
.clamp(44.0, 104.0); .clamp(44.0 / rem_scale, 104.0 / rem_scale);
let headline_r = Rect::from_center_size( let headline_r = Rect::from_center_size(
Pos2::new(cx, headline_cy), Pos2::new(cx, headline_cy),
@ -389,18 +461,30 @@ pub fn render_my_vibe(
} }
} }
if idle_alpha > 0.005 { if idle_alpha > 0.005 {
let max_hl_w = hero_rect.width().max(240.0);
let headline_r = Rect::from_center_size( let headline_r = Rect::from_center_size(
Pos2::new(cx, headline_cy), Pos2::new(cx, headline_cy),
Vec2::new((hero_rect.width() - 40.0).max(260.0), 124.0), Vec2::new(max_hl_w, 124.0),
); );
let hl_size = if vibe_label.chars().count() > 14 { // Exact `useDynamicText` (`4362-2ce1c1620f867094.js:1639-1640, 4445`):
64.0 // `iR = { minFontSize: 48, maxFontSize: 104 }` -> `maxFontSize - 1 = 103px` (pure `px`,
// not `rem`, so divide by `rem_scale` on `>= 1920px` viewports).
let base_hl_size = if vibe_label.chars().count() > 14 {
64.0_f32 / rem_scale
} else { } else {
104.0 103.0_f32 / rem_scale
}; };
let idle_col = pal let idle_col = pal
.text_bright .text_bright
.with_alpha(((pal.text_bright.a as f32) * idle_alpha).round() as u8); .with_alpha(((pal.text_bright.a as f32) * idle_alpha).round() as u8);
let measured_w = ctx
.measure_text(vibe_label, TextStyle::headline(base_hl_size, idle_col), None)
.x;
let hl_size = if measured_w > max_hl_w && measured_w > 1.0 {
(base_hl_size * (max_hl_w / measured_w)).clamp(44.0, base_hl_size)
} else {
base_hl_size
};
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
vibe_label, vibe_label,
TextStyle::headline(hl_size, idle_col), TextStyle::headline(hl_size, idle_col),
@ -418,9 +502,9 @@ pub fn render_my_vibe(
} }
} }
// 4. FLOATING 96x96 TRACK COVER (exact CDP 1280x800 Y=452; click opens Album page or Fullscreen player) // 4. FLOATING TRACK COVER (`--album-cover-size`: 96px default, 64px when height <= 640px)
let cov_center = Pos2::new(cx, rect.top() + (rect.height() * 0.565).clamp(330.0, 452.0)); let cov_center = Pos2::new(cx, cov_cy);
let cov_rect = Rect::from_center_size(cov_center, Vec2::splat(96.0)); let cov_rect = Rect::from_center_size(cov_center, Vec2::splat(cover_sz));
if let Some(ref tr) = current_track { if let Some(ref tr) = current_track {
draw_cover_art( draw_cover_art(
ctx, ctx,
@ -455,9 +539,9 @@ pub fn render_my_vibe(
} }
} }
// 5. PROGRESS CAPSULE (`VibePlayerbarTimecodeContent`: 64px height, 32px radius, hover timecode pill) // 5. PROGRESS CAPSULE (`VibePlayerBar_root`: `width: min(48rem, 100%)` = 768px minus 4*48px buttons + 4*4px gaps = 208px)
let pill_y = cov_center.y + 96.0; let pill_y = player_block_top + 32.0;
let capsule_w = (hero_rect.width() * 0.52).clamp(260.0, 360.0); let capsule_w = (hero_rect.width().min(768.0) - 208.0).clamp(160.0, 560.0);
let capsule_r = Rect::from_center_size(Pos2::new(cx, pill_y), Vec2::new(capsule_w, 64.0)); let capsule_r = Rect::from_center_size(Pos2::new(cx, pill_y), Vec2::new(capsule_w, 64.0));
let cap_id = WidgetId::new("vibe_capsule_scrub"); let cap_id = WidgetId::new("vibe_capsule_scrub");
let cap_resp = ctx.interact(cap_id, capsule_r); let cap_resp = ctx.interact(cap_id, capsule_r);
@ -693,33 +777,44 @@ pub fn render_my_vibe(
actions.push(AppAction::ToggleMute); actions.push(AppAction::ToggleMute);
} }
// `.VibePlayerBar_changeVolume`: --default-slider-block-start: -13.75rem (-220px),
// --slider-hover-gap: 0.25rem (4px hover bridge). Opens only on button hover.
let vol_slider_box = Rect::from_xywh( let vol_slider_box = Rect::from_xywh(
vol_btn_center.x - 22.0, vol_btn_center.x - 22.0,
vol_btn_r.top() - 224.0, vol_btn_r.top() - 220.0,
44.0, 44.0,
216.0, 216.0,
); );
let vol_bridge = vol_btn_r.union(vol_slider_box); let vol_container_rect = Rect::from_xywh(
let vol_hovered = ctx vol_btn_center.x - 42.0,
vol_slider_box.top(),
84.0,
220.0,
);
let btn_hovered = ctx
.input .input
.pointer_pos .pointer_pos
.map_or(false, |p| vol_bridge.contains(p)); .map_or(false, |p| vol_btn_r.contains(p));
if vol_hovered { let container_hovered = ctx
shell.vibe_vol_open = true; .input
} else if !ctx.input.left_down { .pointer_pos
shell.vibe_vol_open = false; .map_or(false, |p| vol_container_rect.contains(p));
let vol_dragging = ctx.input.active_id == Some(WidgetId::new("vb_vol_vslider"));
let was_open = shell.vibe_vol_open;
let show_vol = btn_hovered || vol_dragging || (was_open && container_hovered);
shell.vibe_vol_open = show_vol;
let vol_alpha = ctx.animate_bool(WidgetId::new("vb_vol_pop_alpha"), show_vol, 0.22);
if show_vol && ctx.input.wheel_delta.y.abs() > 0.1 {
let delta = if ctx.input.wheel_delta.y > 0.0 {
0.01
} else {
-0.01
};
let next = ((volume + delta) * 100.0).round() / 100.0;
actions.push(AppAction::SetVolume(next.clamp(0.0, 1.0)));
} }
if shell.vibe_vol_open { if vol_alpha > 0.01 {
if vol_hovered && ctx.input.wheel_delta.y.abs() > 0.1 {
let delta = if ctx.input.wheel_delta.y > 0.0 {
0.01
} else {
-0.01
};
let next = ((volume + delta) * 100.0).round() / 100.0;
actions.push(AppAction::SetVolume(next.clamp(0.0, 1.0)));
}
let mut keep_open = true;
ctx.with_layer(ZLayer::Popover, |ctx| { ctx.with_layer(ZLayer::Popover, |ctx| {
let cur_v = if muted { 0.0 } else { volume }; let cur_v = if muted { 0.0 } else { volume };
let s_resp = ym_volume_capsule( let s_resp = ym_volume_capsule(
@ -730,17 +825,13 @@ pub fn render_my_vibe(
cur_v, cur_v,
true, true,
Color::WHITE, Color::WHITE,
show_vol,
vol_alpha,
); );
if let Some(v) = s_resp.value { if let Some(v) = s_resp.value {
actions.push(AppAction::SetVolume(v)); actions.push(AppAction::SetVolume(v));
} }
if !s_resp.dragging && !vol_hovered {
keep_open = false;
}
}); });
if !keep_open {
shell.vibe_vol_open = false;
}
} }
// 6b. Dislike Button // 6b. Dislike Button
@ -790,8 +881,8 @@ pub fn render_my_vibe(
}); });
} }
// 7. TRANSPORT ROW (Prev / 64px Play-Pause / Next) // 7. TRANSPORT ROW (Prev / Play-Pause `--play-button-size` / Next)
let tr_y = pill_y + 84.0; let tr_y = pill_y + 32.0 + 20.0 + play_btn_sz * 0.5;
let prev_r = Rect::from_center_size(Pos2::new(cx - 76.0, tr_y), Vec2::splat(40.0)); let prev_r = Rect::from_center_size(Pos2::new(cx - 76.0, tr_y), Vec2::splat(40.0));
let prev_resp = ctx.interact(WidgetId::new("vb_prev"), prev_r); let prev_resp = ctx.interact(WidgetId::new("vb_prev"), prev_r);
ctx.draw_icon( ctx.draw_icon(
@ -810,7 +901,7 @@ pub fn render_my_vibe(
actions.push(AppAction::Prev); actions.push(AppAction::Prev);
} }
let play_r = Rect::from_center_size(Pos2::new(cx, tr_y), Vec2::splat(64.0)); let play_r = Rect::from_center_size(Pos2::new(cx, tr_y), Vec2::splat(play_btn_sz));
let play_id = WidgetId::new("vb_play"); let play_id = WidgetId::new("vb_play");
let play_resp = ctx.interact(play_id, play_r); let play_resp = ctx.interact(play_id, play_r);
let play_hov = ctx.animate_bool(play_id.with("hov"), play_resp.hovered, 0.20); let play_hov = ctx.animate_bool(play_id.with("hov"), play_resp.hovered, 0.20);
@ -830,7 +921,7 @@ pub fn render_my_vibe(
(pal.yellow.lerp(pal.yellow_hover, play_hov), pal.on_yellow) (pal.yellow.lerp(pal.yellow_hover, play_hov), pal.on_yellow)
}; };
ctx.dl() ctx.dl()
.push_circle(play_r.center(), 32.0 + 1.2 * play_hov, play_bg); .push_circle(play_r.center(), play_btn_sz * 0.5 + 1.2 * play_hov, play_bg);
ctx.draw_icon( ctx.draw_icon(
if is_playing { if is_playing {
Icon::PauseLarge Icon::PauseLarge
@ -865,14 +956,17 @@ pub fn render_my_vibe(
actions.push(AppAction::Next); actions.push(AppAction::Next);
} }
// 8. OFFICIAL 5.129.0 `WordsCard` (AI Track Facts / Replies — `4874` mod `78572`, `5b3a6ee99e2bd1b8.css`) // 8. OFFICIAL 5.129.0 `WordsCard` (`4362` mod `69850` / `75042`, `5b3a6ee99e2bd1b8.css`)
// `.AiBadge_root__EfKG1 { width: 48px; height: 48px; }` // `.AiBadge_root__EfKG1 { width: 48px; height: 48px; }`
// `.AiBadge_glow__R6cQa { opacity: 0.65; transform: translate3d(-25%, -43%, 0); }` // `.AiBadge_glow__R6cQa { opacity: 0.65; transform: translate3d(-25%, -43%, 0); }` (`size: 200` -> 200x200)
let ai_y = (tr_y + 100.0).min(rect.bottom() - 68.0); // `.AiBadge_icon_sparkles__cS_kL { width: 28px; height: 28px; }` (`--ym-icon-size-s`)
// `.WordsCard_text__ZquMQ`: `type="text" size="l" weight="medium"` (`16px` / `line-height: 24px`, white)
// `.WordsCard_root__6r3u2` (`5b3a6ee99e2bd1b8.css:2555`): `min-height: 7.5rem (120px)` centered below `VibePlayerBar`
let ai_offset = if h <= 800.0 { 66.0 } else { 78.0 };
let ai_y = (tr_y + play_btn_sz * 0.5 + ai_offset).min(rect.bottom() - 48.0);
let meteor_tex = ctx.icons.get_official_meteor_glow(&mut ctx.textures); let meteor_tex = ctx.icons.get_official_meteor_glow(&mut ctx.textures);
// Exact 180px base size at t=0 (matches lossless CDP reference) with gentle 1.25s alternate breathing let glow_sz = 200.0_f32;
let pulse_t = 0.5 - 0.5 * ((ctx.input.time as f32) * (std::f32::consts::TAU / 2.5)).cos(); let load_pulse_t = 0.5 - 0.5 * ((ctx.input.time as f32) * (std::f32::consts::TAU / 2.5)).cos();
let glow_sz = 180.0_f32 * (1.0 + 0.04 * pulse_t);
let active_words_card: Option<WordsCard> = app.current_words_card().cloned(); let active_words_card: Option<WordsCard> = app.current_words_card().cloned();
let feedback_msg: Option<String> = app.current_words_feedback_message().map(str::to_string); let feedback_msg: Option<String> = app.current_words_feedback_message().map(str::to_string);
@ -891,14 +985,14 @@ pub fn render_my_vibe(
if let Some(ref msg) = feedback_msg { if let Some(ref msg) = feedback_msg {
// State A — Feedback toast active (< 3s): sparkle + centered feedback message (non-clickable) // State A — Feedback toast active (< 3s): sparkle + centered feedback message (non-clickable)
let msg_style = TextStyle::medium(14.0, pal.text_primary); let msg_style = TextStyle::medium(16.0, pal.text_bright).with_line_height(24.0);
let msg_w = ctx let msg_w = ctx
.measure_text(msg, msg_style, None) .measure_text(msg, msg_style, None)
.x .x
.min((hero_rect.width() - 120.0).max(160.0)); .min((hero_rect.width() - 120.0).max(160.0));
let block_w = 44.0 + msg_w; let block_w = 56.0 + msg_w;
let block_l = cx - block_w * 0.5; let block_l = cx - block_w * 0.5;
let sp_c = Pos2::new(block_l + 18.0, ai_y); let sp_c = Pos2::new(block_l + 24.0, ai_y);
let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0);
let meteor_r = Rect::from_xywh( let meteor_r = Rect::from_xywh(
badge_tl.x - glow_sz * 0.25, badge_tl.x - glow_sz * 0.25,
@ -910,84 +1004,91 @@ pub fn render_my_vibe(
.push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166));
ctx.draw_icon( ctx.draw_icon(
Icon::AiSparkles, Icon::AiSparkles,
Rect::from_center_size(sp_c, Vec2::splat(24.0)), Rect::from_center_size(sp_c, Vec2::splat(28.0)),
pal.text_bright, pal.text_bright,
); );
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
msg, msg,
msg_style, msg_style,
Rect::from_xywh(block_l + 40.0, ai_y - 16.0, msg_w + 8.0, 32.0), Rect::from_xywh(block_l + 56.0, ai_y - 16.0, msg_w + 8.0, 32.0),
TextAlign::Left, TextAlign::Left,
); );
ctx.request_repaint_after(std::time::Duration::from_millis(250)); ctx.request_repaint_after(std::time::Duration::from_millis(250));
} else if let Some(ref card) = active_words_card.as_ref().filter(|c| !c.is_disliked()) { } else if let Some(ref card) = active_words_card.as_ref().filter(|c| !c.is_disliked()) {
// State B — Real `WordsCard` loaded for current track & not disliked! // State B — Exact official 5.129.0 `.VibePage_words__39Mii` (`max-width: 25rem = 400px`, `width: calc(100% - 7rem)`)
let max_card_w = (hero_rect.width() - 64.0).clamp(320.0, 480.0); // + `.WordsCard_content__AUDsR` (centered directly under Play button `cx`)
let text_max_w = (max_card_w - 60.0).max(200.0); // + `.WordsCard_badge__Y5HRe` (`position: absolute; left: -8px; transform: translate(-100%, -50%)`).
let text_style_base = TextStyle::medium(14.0, pal.text_primary).with_line_height(19.0); let text_max_w = (hero_rect.width() - 112.0).clamp(200.0, 400.0);
let text_style_base = TextStyle::medium(16.0, pal.text_bright).with_line_height(24.0);
let measured_text = ctx.measure_text(&card.text, text_style_base, Some(text_max_w)); let measured_text = ctx.measure_text(&card.text, text_style_base, Some(text_max_w));
let text_h = measured_text.y.clamp(20.0, 58.0); let text_w = measured_text.x.clamp(120.0, text_max_w);
let text_h = measured_text.y.clamp(24.0, 74.0);
let has_action = card.action.is_some(); let has_action = card.action.is_some();
let action_h = if has_action { 22.0 } else { 0.0 }; let action_h = if has_action { 26.0 } else { 0.0 };
let card_h = (text_h + action_h + 10.0).clamp(48.0, 92.0); let card_h = (text_h + action_h + 10.0).clamp(48.0, 108.0);
let card_w = (measured_text.x + 64.0).clamp(240.0, max_card_w);
let card_cy = ai_y.min(rect.bottom() - card_h * 0.5 - 12.0); let card_cy = ai_y.min(rect.bottom() - card_h * 0.5 - 12.0);
let card_r = Rect::from_center_size(Pos2::new(cx, card_cy), Vec2::new(card_w, card_h)); let text_x = cx - text_w * 0.5;
let badge_left = text_x - 8.0 - 48.0;
let card_r = Rect::from_min_max(
Pos2::new(badge_left, card_cy - card_h * 0.5),
Pos2::new(text_x + text_w, card_cy + card_h * 0.5),
);
let card_resp = ctx.interact(WidgetId::new("vb_words_card"), card_r); let card_resp = ctx.interact(WidgetId::new("vb_words_card"), card_r);
let ai_hov = ctx.animate_bool(WidgetId::new("vb_words_hov"), card_resp.hovered, 0.18); let ai_hov = ctx.animate_bool(WidgetId::new("vb_words_hov"), card_resp.hovered, 0.18);
let ai_scale = 1.0 + 0.02 * ai_hov; let ai_scale = 1.0 + 0.02 * ai_hov;
let sp_c = Pos2::new(card_r.left() + 24.0, card_r.center_y()); // `.WordsCard_badge__Y5HRe` (`48x48`, positioned absolutely 8px left of `.WordsCard_content`)
let sp_c = Pos2::new(badge_left + 24.0, card_cy);
let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0);
let g_sz = glow_sz * ai_scale;
let meteor_r = Rect::from_xywh( let meteor_r = Rect::from_xywh(
badge_tl.x - glow_sz * 0.25, badge_tl.x - g_sz * 0.25,
badge_tl.y - glow_sz * 0.43, badge_tl.y - g_sz * 0.43,
glow_sz, g_sz,
glow_sz, g_sz,
); );
ctx.dl() ctx.dl()
.push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166));
// Official `a5` in `4362-*.js`: `isFact && !dimmed` -> `a1` (star + "AI", 28x28), else `a6` (2 stars, 28x28)
let badge_icon = if card.is_fact() {
Icon::AiSparklesText
} else {
Icon::AiSparkles
};
ctx.draw_icon( ctx.draw_icon(
Icon::AiSparkles, badge_icon,
Rect::from_center_size(sp_c, Vec2::splat(24.0 * ai_scale)), Rect::from_center_size(sp_c, Vec2::splat(28.0 * ai_scale)),
pal.text_bright, pal.text_bright,
); );
let text_x = card_r.left() + 50.0; let text_top = card_cy - (text_h + action_h) * 0.5;
let text_w = (card_r.right() - text_x - 8.0).max(120.0); let card_text_style = TextStyle::medium(16.0 * ai_scale, pal.text_bright)
let text_top = card_r.center_y() - (text_h + action_h) * 0.5; .with_line_height(24.0 * ai_scale);
let card_text_col = if card_resp.hovered {
pal.text_bright
} else {
pal.text_primary
};
let card_text_style = TextStyle::medium(14.0 * ai_scale, card_text_col)
.with_line_height(19.0 * ai_scale);
ctx.draw_text_wrapped( ctx.draw_text_wrapped(
&card.text, &card.text,
card_text_style, card_text_style,
Rect::from_xywh(text_x, text_top, text_w, text_h + 4.0), Rect::from_xywh(text_x, text_top, text_w + 4.0, text_h + 4.0),
Some(3), Some(3),
TextAlign::Left, TextAlign::Center,
); );
let mut action_clicked = false; let mut action_clicked = false;
if let Some(ref act) = card.action { if let Some(ref act) = card.action {
let act_r = Rect::from_xywh(text_x, text_top + text_h + 2.0, text_w, 20.0); let act_r = Rect::from_xywh(text_x, text_top + text_h + 2.0, text_w, 24.0);
let act_resp = ctx.interact(WidgetId::new("vb_words_action"), act_r); let act_resp = ctx.interact(WidgetId::new("vb_words_action"), act_r);
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
&act.title, &act.title,
TextStyle::medium( TextStyle::medium(
13.0, 15.0,
if act_resp.hovered { if act_resp.hovered {
pal.text_bright pal.text_bright
} else { } else {
pal.logo_text pal.text_secondary
}, },
), ),
act_r, act_r,
TextAlign::Left, TextAlign::Center,
); );
if act_resp.hovered { if act_resp.hovered {
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
@ -1019,7 +1120,7 @@ pub fn render_my_vibe(
words_popover_anchor = Some((card_r, (*card).clone())); words_popover_anchor = Some((card_r, (*card).clone()));
} else if words_is_empty || active_words_card.as_ref().map_or(false, |c| c.is_disliked()) { } else if words_is_empty || active_words_card.as_ref().map_or(false, |c| c.is_disliked()) {
// State C — Resolved empty OR card disliked: centered dimmed sparkle badge (opacity 0.50, non-clickable) // State C — Resolved empty OR card disliked: centered dimmed sparkle badge (`opacity: 0.4`, non-clickable)
let sp_c = Pos2::new(cx, ai_y); let sp_c = Pos2::new(cx, ai_y);
let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0);
let meteor_r = Rect::from_xywh( let meteor_r = Rect::from_xywh(
@ -1029,30 +1130,31 @@ pub fn render_my_vibe(
glow_sz, glow_sz,
); );
ctx.dl() ctx.dl()
.push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(72)); .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(66));
ctx.draw_icon( ctx.draw_icon(
Icon::AiSparkles, Icon::AiSparkles,
Rect::from_center_size(sp_c, Vec2::splat(24.0)), Rect::from_center_size(sp_c, Vec2::splat(28.0)),
pal.text_bright.scale_alpha(0.50), pal.text_bright.scale_alpha(0.40),
); );
} else { } else {
// State D — Loading OR offline visual fixture: official rotating 5.129.0 `words.loading-phrase-*` // State D — Loading OR offline visual fixture: official rotating 5.129.0 `words.loading-phrase-*`
// (Index 0 at `t == 0.0` matches `my_vibe.jpg` & lossless CDP `test_ext_02` pixel-for-pixel; // (`.WordsCard_badge_loading` pulses `scale(1) -> scale(1.1)` over 1.25s alternate)
// clicking while loading does NOTHING — zero fake Vibe-settings modal!) let pulse_scale = 1.0 + 0.10 * load_pulse_t;
let ai_rect = Rect::from_center_size(Pos2::new(cx, ai_y), Vec2::new(380.0, 48.0)); let g_sz = glow_sz * pulse_scale;
let sp_c = Pos2::new(ai_rect.left() + 29.0, ai_y); let ai_rect = Rect::from_center_size(Pos2::new(cx, ai_y), Vec2::new(400.0, 48.0));
let sp_c = Pos2::new(ai_rect.left() + 24.0, ai_y);
let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0); let badge_tl = Pos2::new(sp_c.x - 24.0, sp_c.y - 24.0);
let meteor_r = Rect::from_xywh( let meteor_r = Rect::from_xywh(
badge_tl.x - glow_sz * 0.25, badge_tl.x - g_sz * 0.25,
badge_tl.y - glow_sz * 0.43, badge_tl.y - g_sz * 0.43,
glow_sz, g_sz,
glow_sz, g_sz,
); );
ctx.dl() ctx.dl()
.push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166)); .push_image(meteor_r, meteor_tex, 0.0, Color::WHITE.with_alpha(166));
ctx.draw_icon( ctx.draw_icon(
Icon::AiSparkles, Icon::AiSparkles,
Rect::from_center_size(sp_c, Vec2::splat(24.0)), Rect::from_center_size(sp_c, Vec2::splat(28.0 * pulse_scale)),
pal.text_bright, pal.text_bright,
); );
let phrases = if ru { let phrases = if ru {
@ -1078,8 +1180,8 @@ pub fn render_my_vibe(
("Using the ", "AI power to collect interesting stuff") ("Using the ", "AI power to collect interesting stuff")
}; };
let ai_spans = [ let ai_spans = [
RichSpan::new(lead, TextStyle::medium(14.0, pal.text_secondary)), RichSpan::new(lead, TextStyle::medium(16.0, pal.text_secondary).with_line_height(24.0)),
RichSpan::new(rest, TextStyle::medium(14.0, pal.text_primary)), RichSpan::new(rest, TextStyle::medium(16.0, pal.text_bright).with_line_height(24.0)),
]; ];
ctx.draw_rich_text(&ai_spans, ai_text_r, Some(1), TextAlign::Left); ctx.draw_rich_text(&ai_spans, ai_text_r, Some(1), TextAlign::Left);
} else { } else {
@ -1095,7 +1197,10 @@ pub fn render_my_vibe(
} }
} }
// 9. BOTTOM-RIGHT VERSION BADGE (`APP_VERSION` = `0.1.5`, or `0.1.5 → {ver}` when update available!) // 9. BOTTOM-RIGHT VERSION BADGE (exact `.MainPage_beta__y32vb` in `5b3a6ee99e2bd1b8.css:255-282`
// + `4362-2ce1c1620f867094.js`: `Caption type="text" size="s" weight="medium"` = 13px Medium,
// `color: --ym-controls-color-primary-text-enabled`, `padding: 4px 8px`, `border-radius: 16px`,
// `margin-block-end: 12px`).
let (ver_label, ver_col) = if let Some(ref upd) = app.available_update { let (ver_label, ver_col) = if let Some(ref upd) = app.available_update {
( (
format!("{} → {}", APP_VERSION, upd.version), format!("{} → {}", APP_VERSION, upd.version),
@ -1108,12 +1213,12 @@ pub fn render_my_vibe(
} else { } else {
(APP_VERSION.to_string(), pal.text_secondary) (APP_VERSION.to_string(), pal.text_secondary)
}; };
let ver_style = TextStyle::bold(13.5, ver_col); let ver_style = TextStyle::medium(13.0, ver_col);
let ver_w = (ctx.measure_text(&ver_label, ver_style, None).x + 16.0) let ver_w = (ctx.measure_text(&ver_label, ver_style, None).x + 16.0)
.max(46.0) .max(46.0)
.ceil(); .ceil();
let ver_r = Rect::from_xywh( let ver_r = Rect::from_xywh(
(rect.right() - ver_w - 16.0).floor(), (rect.right() - ver_w - 12.0).floor(),
(rect.bottom() - 38.0).floor(), (rect.bottom() - 38.0).floor(),
ver_w, ver_w,
26.0, 26.0,
@ -1199,14 +1304,30 @@ pub fn render_my_vibe(
ctx.request_repaint(); ctx.request_repaint();
} }
let slides_per_view = (rect.height() / 106.0).floor().clamp(4.0, 9.0); // Exact `.VibePage_wheel__E_p8_` (`max-height: 1200PX` pure px, `5b3a6ee99e2bd1b8.css:3759`)
let slide_step = ((rect.height() - 12.0) / slides_per_view).max(106.0); // + `slidesPerView = clamp(floor(clientHeight_px / 106), 4, 9)` (`1631.1d3ade3cea83d910.js:709`)
let wheel_cy = rect.center_y() + 9.0; // + `.WheelDesktop_wrapper__IXHUc` (`max-width: min(80%, 37.5rem); margin-inline-start: auto`).
let wheel_h = (rect.bottom() - page_top).min(1200.0 / rem_scale);
let slides_per_view = ((wheel_h * rem_scale) / 106.0).floor().clamp(4.0, 9.0);
let slide_step = (wheel_h / slides_per_view).max(106.0 / rem_scale);
let wheel_cy = (page_top + rect.bottom()) * 0.5;
let wheel_top = wheel_cy - wheel_h * 0.5;
let wheel_bot = wheel_top + wheel_h;
let wrapper_w = (left_w * 0.80).min(600.0);
let wrapper_left = if raw_screen_w >= 1060.0 {
rect.left() + left_w - wrapper_w
} else {
rect.left()
};
let half_slots = (slides_per_view * 0.5).ceil() as i32 + 2; let half_slots = (slides_per_view * 0.5).ceil() as i32 + 2;
let base_slot = scroll_pos.round() as i32; let base_slot = scroll_pos.round() as i32;
let time_s = ctx.input.time as f32; let time_s = ctx.input.time as f32;
ctx.push_clip(wheel_rect, 0.0); let wheel_clip_rect = Rect::from_min_max(
Pos2::new(wheel_rect.left(), wheel_top),
Pos2::new(wheel_rect.right(), wheel_bot),
);
ctx.push_clip(wheel_clip_rect, 0.0);
for offset in -half_slots..=half_slots { for offset in -half_slots..=half_slots {
let slot_idx = base_slot + offset; let slot_idx = base_slot + offset;
let progress = slot_idx as f32 - scroll_pos; let progress = slot_idx as f32 - scroll_pos;
@ -1223,21 +1344,26 @@ pub fn render_my_vibe(
} else { } else {
0.0 0.0
}; };
let translate_x = 120.0 * (1.0 + theta.cos()); // `120px` in `1631.1d3ade3cea83d910.js:150` is pure `px` (`translate3d(120*(1+cos)px,0,0)`),
let arc_x = rect.left() + 123.0 + translate_x; // not `rem`, so divide by `rem_scale` on >=1920px viewports.
let translate_x = (120.0 / rem_scale) * (1.0 + theta.cos());
let arc_x = wrapper_left + 40.0 + translate_x;
let row_cy = wheel_cy + progress * slide_step; let row_cy = wheel_cy + progress * slide_step;
if row_cy < rect.top() - 70.0 || row_cy > rect.bottom() + 70.0 { if row_cy < wheel_top - 40.0 || row_cy > wheel_bot + 40.0 {
continue; continue;
} }
let u = ((a - 0.42) / 0.58).clamp(0.0, 1.0); let u = ((a - 0.42) / 0.58).clamp(0.0, 1.0);
let smooth = u * u * (3.0 - 2.0 * u); let smooth = u * u * (3.0 - 2.0 * u);
let arc_fade = (1.0 - 0.86 * smooth).clamp(0.14, 1.0); let arc_fade = (1.0 - 0.86 * smooth).clamp(0.14, 1.0);
let fade_h = (rect.height() * 0.15).clamp(56.0, 130.0); let fade_h = (wheel_h * 0.15).clamp(56.0, 130.0);
let dist_top = (row_cy - rect.top()).max(0.0); let dist_top = (row_cy - wheel_top).max(0.0);
let dist_bot = (rect.bottom() - row_cy).max(0.0); let dist_bot = (wheel_bot - row_cy).max(0.0);
let y_edge = (dist_top.min(dist_bot) / fade_h).clamp(0.0, 1.0); let y_edge = (dist_top.min(dist_bot) / fade_h).clamp(0.0, 1.0);
let y_smooth = y_edge * y_edge * (3.0 - 2.0 * y_edge); let y_smooth = y_edge * y_edge * (3.0 - 2.0 * y_edge);
if y_smooth <= 0.01 {
continue;
}
let edge_fade = (arc_fade * y_smooth).clamp(0.0, 1.0); let edge_fade = (arc_fade * y_smooth).clamp(0.0, 1.0);
// Uniform 80x80 cover (`5rem x 5rem`) // Uniform 80x80 cover (`5rem x 5rem`)
@ -1267,14 +1393,21 @@ pub fn render_my_vibe(
let is_current_station = let is_current_station =
app.active_vibe_title.eq_ignore_ascii_case(&st.title) && is_playing; app.active_vibe_title.eq_ignore_ascii_case(&st.title) && is_playing;
let cr = if st.is_artist { let is_artist_item = st.is_artist
|| st.item_type == "ARTIST"
|| st.seeds.iter().any(|s| s.starts_with("artist:"))
|| st.subtitle.as_deref().map_or(false, |s| {
let low = s.to_lowercase();
low.contains("артист") || low.contains("исполнител") || low.contains("artist")
});
let cr = if is_artist_item {
CornerRadii::same(40.0) CornerRadii::same(40.0)
} else if st.item_type == "ALBUM" || st.item_type == "NON_MUSIC" { } else if st.item_type == "ALBUM" || st.item_type == "NON_MUSIC" {
CornerRadii::same(6.0) CornerRadii::same(6.0)
} else { } else {
CornerRadii::ZERO CornerRadii::ZERO
}; };
let tint_alpha = if hovered { 1.0 } else { edge_fade }; let tint_alpha = if hovered { y_smooth } else { edge_fade };
let mut drew_tex = false; let mut drew_tex = false;
if let Some(ref uri) = st.cover_uri { if let Some(ref uri) = st.cover_uri {
if let Some((tex_id, _, _)) = covers.get_or_fetch(uri, 200) { if let Some((tex_id, _, _)) = covers.get_or_fetch(uri, 200) {
@ -1291,7 +1424,7 @@ pub fn render_my_vibe(
}; };
ctx.dl() ctx.dl()
.push_rect(icon_rect, cr, placeholder_bg.with_alpha_f32(0.88 * edge_fade)); .push_rect(icon_rect, cr, placeholder_bg.with_alpha_f32(0.88 * edge_fade));
let glyph = if st.is_artist { let glyph = if is_artist_item {
Icon::Note Icon::Note
} else { } else {
Icon::MyVibe Icon::MyVibe
@ -1304,7 +1437,7 @@ pub fn render_my_vibe(
} }
// Glassy inset white rim on circular artist covers // Glassy inset white rim on circular artist covers
if st.is_artist { if is_artist_item {
ctx.dl().push_circle_stroke( ctx.dl().push_circle_stroke(
circle_c, circle_c,
39.5, 39.5,
@ -1315,12 +1448,12 @@ pub fn render_my_vibe(
// Hover Play/Pause overlay OR pulsing 8px yellow dot when playing // Hover Play/Pause overlay OR pulsing 8px yellow dot when playing
if is_playable && hovered { if is_playable && hovered {
if st.is_artist { if is_artist_item {
ctx.dl() ctx.dl()
.push_circle(circle_c, 40.0, css_rgba(0, 0, 0, 120)); .push_circle(circle_c, 40.0, css_rgba(0, 0, 0, (120.0 * y_smooth).round() as u8));
} else { } else {
ctx.dl() ctx.dl()
.push_rect(icon_rect, cr, css_rgba(0, 0, 0, 110)); .push_rect(icon_rect, cr, css_rgba(0, 0, 0, (110.0 * y_smooth).round() as u8));
} }
let icon_hovered = ctx let icon_hovered = ctx
.input .input
@ -1334,19 +1467,19 @@ pub fn render_my_vibe(
Icon::PlayFilled Icon::PlayFilled
}, },
Rect::from_center_size(circle_c, Vec2::splat(play_ic_sz)), Rect::from_center_size(circle_c, Vec2::splat(play_ic_sz)),
Color::WHITE, Color::WHITE.with_alpha_f32(y_smooth),
); );
} else if is_current_station { } else if is_current_station {
let pulse = 0.5 + 0.5 * (time_s * 9.0).sin(); let pulse = 0.5 + 0.5 * (time_s * 9.0).sin();
let dot_r = 3.5 + 1.5 * pulse; let dot_r = 3.5 + 1.5 * pulse;
ctx.dl().push_circle(circle_c, dot_r, pal.yellow); ctx.dl().push_circle(circle_c, dot_r, pal.yellow.with_alpha_f32(y_smooth));
ctx.request_repaint_after(std::time::Duration::from_millis(40)); ctx.request_repaint_after(std::time::Duration::from_millis(40));
} }
// Typography: 16px gap, subtitle 14px Medium secondary, title 16px Medium bright (or accent yellow for Reshuffle) // Typography: 16px gap, subtitle 14px Medium secondary, title 16px Medium bright (or accent yellow for Reshuffle)
let tx = icon_rect.right() + 16.0; let tx = icon_rect.right() + 16.0;
let max_tw = (wheel_rect.right() - tx - 16.0).clamp(180.0, 210.0); let max_tw = (wheel_rect.right() - tx - 16.0).clamp(180.0, 210.0);
let title_alpha = if hovered { 1.0 } else { 0.96 * edge_fade }; let title_alpha = if hovered { y_smooth } else { 0.96 * edge_fade };
let title_col = if is_reshuffle { let title_col = if is_reshuffle {
pal.logo_variant.with_alpha_f32(title_alpha) pal.logo_variant.with_alpha_f32(title_alpha)
} else { } else {

File diff suppressed because it is too large Load diff

View file

@ -103,6 +103,13 @@ pub fn render_player_bar(
if scrub_resp.pressed || scrub_resp.dragged { if scrub_resp.pressed || scrub_resp.dragged {
if let Some(pos) = ctx.input.pointer_pos { 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 frac = ((pos.x - scrub_zone.left()) / scrub_zone.width().max(1.0)).clamp(0.0, 1.0);
if let Some(prev) = shell.pb_scrub_frac {
if frac + 0.0015 < prev {
shell.pb_reverse_until = ctx.input.time + 0.55;
} else if frac > prev + 0.0015 {
shell.pb_reverse_until = 0.0;
}
}
shell.pb_scrub_frac = Some(frac); shell.pb_scrub_frac = Some(frac);
} }
} }
@ -113,16 +120,29 @@ pub fn render_player_bar(
.pointer_pos .pointer_pos
.map(|pos| ((pos.x - scrub_zone.left()) / scrub_zone.width().max(1.0)).clamp(0.0, 1.0)) .map(|pos| ((pos.x - scrub_zone.left()) / scrub_zone.width().max(1.0)).clamp(0.0, 1.0))
.unwrap_or(frac); .unwrap_or(frac);
if commit_frac + 0.004 < progress {
shell.pb_reverse_until = ctx.input.time + 0.75;
}
actions.push(AppAction::SeekFraction(commit_frac)); actions.push(AppAction::SeekFraction(commit_frac));
shell.pb_scrub_frac = None; shell.pb_scrub_frac = None;
} }
} else if scrub_resp.clicked { } else if scrub_resp.clicked {
if let Some(pos) = ctx.input.pointer_pos { 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 frac = ((pos.x - scrub_zone.left()) / scrub_zone.width().max(1.0)).clamp(0.0, 1.0);
if frac + 0.004 < progress {
shell.pb_reverse_until = ctx.input.time + 0.75;
}
actions.push(AppAction::SeekFraction(frac)); actions.push(AppAction::SeekFraction(frac));
} }
} }
// Detect keyboard/SMTC backward seek (`J` / `ArrowLeft`) so Car companion shifts into reverse!
if progress + 0.004 < shell.pb_last_progress && shell.pb_last_progress - progress < 0.5 {
shell.pb_reverse_until = ctx.input.time + 0.65;
}
shell.pb_last_progress = progress;
let reversing = ctx.input.time < shell.pb_reverse_until;
let display_progress = shell.pb_scrub_frac.unwrap_or(progress); let display_progress = shell.pb_scrub_frac.unwrap_or(progress);
// Subtle played split overlay clipped to left progress fraction (exact 5.129.0 `rgba(255,255,255,0.051)`) // Subtle played split overlay clipped to left progress fraction (exact 5.129.0 `rgba(255,255,255,0.051)`)
@ -148,6 +168,8 @@ pub fn render_player_bar(
let bar_y = rect.top() + 2.0; let bar_y = rect.top() + 2.0;
if is_custom_thumb { if is_custom_thumb {
let anim_time = app.fixed_vibe_time.unwrap_or(ctx.input.time as f32); let anim_time = app.fixed_vibe_time.unwrap_or(ctx.input.time as f32);
let bass = if is_playing { app.audio.state.bass() } else { 0.0 };
let energy = if is_playing { app.audio.state.energy() } else { 0.0 };
render_player_bar_companion( render_player_bar_companion(
ctx, ctx,
pal, pal,
@ -158,6 +180,9 @@ pub fn render_player_bar(
display_frac, display_frac,
is_playing, is_playing,
anim_time, anim_time,
bass,
energy,
reversing,
); );
} else { } else {
let bar_r = Rect::from_min_max( let bar_r = Rect::from_min_max(
@ -630,15 +655,38 @@ pub fn render_player_bar(
} }
} }
// 4. Volume button + Exact 44×216 Vertical Hover Popover (Kawase Blur + 1% wheel step) // 4. Volume button (`32×32` `size="xxxs"`) + Exact 5.129.0 `ChangeVolume` Vertical Hover Popover
// (`5b3a6ee99e2bd1b8.css`: `--position-slider-container-block: -13.5rem`, `sliderContainer` `84×216`,
// `wrapperSlider` `44×216`, `pointer-events: none` while closed so hovering empty space above never opens it)
if vol_icon_x >= cx + 184.0 { if vol_icon_x >= cx + 184.0 {
let vol_btn_r = Rect::from_center_size(Pos2::new(vol_icon_x, cy), Vec2::splat(38.0)); let vol_btn_r = Rect::from_center_size(Pos2::new(vol_icon_x, cy), Vec2::splat(32.0));
let vol_resp = ctx.interact(WidgetId::new("pb_r_vol"), vol_btn_r); let vol_resp = ctx.interact(WidgetId::new("pb_r_vol"), vol_btn_r);
let vol_ic = if muted || volume < 0.01 { let vol_ic = if muted || volume < 0.01 {
Icon::VolumeOff Icon::VolumeOff
} else { } else {
Icon::Volume Icon::Volume
}; };
let pop_w = 44.0;
let pop_h = 216.0;
let pop_x = (vol_icon_x - pop_w * 0.5)
.clamp(8.0, (ctx.screen_rect().right() - pop_w - 8.0).max(8.0));
let pop_y = (vol_btn_r.top() - pop_h).max(36.0);
let pop_rect = Rect::from_xywh(pop_x, pop_y, pop_w, pop_h);
// `.ChangeVolume_sliderContainer`: 5.25rem (84px) wide × 13.5rem (216px) tall centered on capsule
let container_rect = Rect::from_xywh(pop_rect.center_x() - 42.0, pop_rect.top(), 84.0, pop_h);
let was_open = shell.pb_vol_hovered;
let container_hovered = ctx
.input
.pointer_pos
.map_or(false, |p| container_rect.contains(p));
let vol_dragging = ctx.input.active_id == Some(WidgetId::new("pb_vol_vslider"));
let show_popover =
!app.fullscreen_open && (vol_resp.hovered || vol_dragging || (was_open && container_hovered));
shell.pb_vol_hovered = show_popover;
let icon_lit = vol_resp.hovered || (show_popover && container_hovered);
let ic_sz = if vol_resp.hovered { 25.2 } else { 24.0 }; let ic_sz = if vol_resp.hovered { 25.2 } else { 24.0 };
if vol_resp.hovered { if vol_resp.hovered {
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
@ -646,25 +694,13 @@ pub fn render_player_bar(
ctx.draw_icon( ctx.draw_icon(
vol_ic, vol_ic,
Rect::from_center_size(vol_btn_r.center(), Vec2::splat(ic_sz)), Rect::from_center_size(vol_btn_r.center(), Vec2::splat(ic_sz)),
if vol_resp.hovered { fg_bright } else { fg_muted }, if icon_lit { fg_bright } else { fg_muted },
); );
if vol_resp.clicked { if vol_resp.clicked {
actions.push(AppAction::ToggleMute); actions.push(AppAction::ToggleMute);
} }
let pop_w = 44.0; let pop_alpha = ctx.animate_bool(WidgetId::new("pb_vol_pop_alpha"), show_popover, 0.22);
let pop_h = 216.0;
let pop_rect = Rect::from_xywh(
(vol_icon_x - pop_w * 0.5).clamp(8.0, (ctx.screen_rect().right() - pop_w - 8.0).max(8.0)),
(rect.top() - pop_h - 4.0).max(36.0),
pop_w,
pop_h,
);
let bridge = vol_btn_r.union(pop_rect);
let pointer_in_bridge = ctx.input.pointer_pos.map_or(false, |p| bridge.contains(p));
let vol_dragging = ctx.input.active_id == Some(WidgetId::new("pb_vol_vslider"));
let show_popover = pointer_in_bridge || vol_dragging;
shell.pb_vol_hovered = show_popover;
if show_popover { if show_popover {
// Exact 1% (0.01) wheel step per notch // Exact 1% (0.01) wheel step per notch
@ -674,7 +710,9 @@ pub fn render_player_bar(
let next = ((volume + delta) * 100.0).round() / 100.0; let next = ((volume + delta) * 100.0).round() / 100.0;
actions.push(AppAction::SetVolume(next.clamp(0.0, 1.0))); actions.push(AppAction::SetVolume(next.clamp(0.0, 1.0)));
} }
}
if pop_alpha > 0.01 && !app.fullscreen_open {
ctx.with_layer(ZLayer::Popover, |ctx| { ctx.with_layer(ZLayer::Popover, |ctx| {
let cur_v = if muted { 0.0 } else { volume }; let cur_v = if muted { 0.0 } else { volume };
let sresp = ym_volume_capsule( let sresp = ym_volume_capsule(
@ -685,6 +723,8 @@ pub fn render_player_bar(
cur_v, cur_v,
false, false,
pal.yellow, pal.yellow,
show_popover,
pop_alpha,
); );
if let Some(new_v) = sresp.value { if let Some(new_v) = sresp.value {
actions.push(AppAction::SetVolume(new_v)); actions.push(AppAction::SetVolume(new_v));

View file

@ -17,11 +17,17 @@ pub fn render_player_bar_companion(
progress: f32, progress: f32,
playing: bool, playing: bool,
time: f32, time: f32,
bass: f32,
energy: f32,
reversing: bool,
) { ) {
let frac = progress.clamp(0.0, 1.0); let frac = progress.clamp(0.0, 1.0);
let track_w = (bar_right - bar_left).max(1.0); let track_w = (bar_right - bar_left).max(1.0);
let fill_x = bar_left + track_w * frac; let fill_x = bar_left + track_w * frac;
let anim_t = if playing { time } else { 0.0 }; let anim_t = if playing { time } else { 0.0 };
// Real-time BPM/bass punch (0..1) from the audio DSP low-pass analyzer
let beat = if playing { (bass * 2.4).clamp(0.0, 1.0) } else { 0.0 };
let pulse = if playing { (energy * 2.0).clamp(0.0, 1.0) } else { 0.0 };
// Subtle base track along top edge // Subtle base track along top edge
let track_r = Rect::from_xywh(bar_left, bar_y - 1.5, track_w, 3.0); let track_r = Rect::from_xywh(bar_left, bar_y - 1.5, track_w, 3.0);
@ -42,16 +48,20 @@ pub fn render_player_bar_companion(
1.5, 1.5,
Color::rgb(0xE8, 0x22, 0x38), Color::rgb(0xE8, 0x22, 0x38),
); );
// Tiny drifting exhaust puffs while driving // Drifting exhaust puffs (shoot right when reversing, left when driving forward!)
if playing && fill_w > 48.0 { if (playing || reversing) && fill_w > 48.0 {
for k in 0..3 { for k in 0..3 {
let phase = ((anim_t * 2.4 + k as f32 * 0.33) % 1.0).clamp(0.0, 1.0); let phase = ((time * (2.4 + beat * 1.4) + k as f32 * 0.33) % 1.0).clamp(0.0, 1.0);
let px = fill_x - 30.0 - phase * 24.0; let px = if reversing {
let py = bar_y - 5.0 - phase * 6.0; fill_x + 30.0 + phase * 22.0
let a = ((1.0 - phase) * 90.0).round() as u8; } else {
if px > bar_left { fill_x - 30.0 - phase * 24.0
};
let py = bar_y - 5.0 - phase * (6.0 + beat * 4.0);
let a = ((1.0 - phase) * (90.0 + beat * 55.0)).round() as u8;
if px > bar_left && px < bar_right {
ctx.dl() ctx.dl()
.push_circle(Pos2::new(px, py), 2.0 + phase * 2.5, css_rgba(220, 224, 232, a)); .push_circle(Pos2::new(px, py), 2.0 + phase * (2.5 + beat * 1.5), css_rgba(220, 224, 232, a));
} }
} }
} }
@ -109,13 +119,14 @@ pub fn render_player_bar_companion(
let max_trail = (fill_w - 6.0).max(0.0); let max_trail = (fill_w - 6.0).max(0.0);
let num_segs = (max_trail / seg_w).ceil() as usize; let num_segs = (max_trail / seg_w).ceil() as usize;
let wave_step = (anim_t * 8.0).floor() as i32; let wave_step = (anim_t * 8.0).floor() as i32;
let wave_amp = 1.0 + beat * 2.2;
for s in 0..num_segs { for s in 0..num_segs {
let sx = bar_left + s as f32 * seg_w; let sx = bar_left + s as f32 * seg_w;
let sw = (fill_x - 6.0 - sx).min(seg_w); let sw = (fill_x - 6.0 - sx).min(seg_w);
if sw <= 0.5 { if sw <= 0.5 {
break; break;
} }
let dy = if ((s as i32 + wave_step) & 1) == 0 { -1.0 } else { 1.0 }; let dy = if ((s as i32 + wave_step) & 1) == 0 { -wave_amp } else { wave_amp };
for (ci, &col) in stripes.iter().enumerate() { for (ci, &col) in stripes.iter().enumerate() {
let sy = bar_y - 11.0 + ci as f32 * 2.0 + dy; let sy = bar_y - 11.0 + ci as f32 * 2.0 + dy;
ctx.dl() ctx.dl()
@ -126,51 +137,110 @@ pub fn render_player_bar_companion(
} }
} }
// Draw the companion anchored cleanly at `(fill_x, bar_y)` // Draw the companion anchored cleanly at `(fill_x, bar_y)` — reactive to real-time bass/BPM!
match style { match style {
PlayerThumbStyle::Standard => {} PlayerThumbStyle::Standard => {}
PlayerThumbStyle::Duck => { PlayerThumbStyle::Duck => {
let bob = if playing { (anim_t * 9.0).sin().abs() * -2.0 } else { 0.0 }; let bob = if playing {
let sz = 32.0; (anim_t * 9.0).sin().abs() * -1.8 - beat * 6.5
} else {
0.0
};
let sz = 32.0 + beat * 2.5;
let r = Rect::from_xywh(fill_x - sz * 0.5, bar_y - sz + 3.0 + bob, sz, sz); 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); ctx.draw_icon(Icon::ThumbDuck, r, Color::WHITE);
} }
PlayerThumbStyle::Car => { PlayerThumbStyle::Car => {
let vib = if playing { (anim_t * 28.0).sin() * 0.6 } else { 0.0 }; let vib = if playing {
(anim_t * 28.0).sin() * (0.5 + beat * 1.4) - beat * 2.2
} else {
0.0
};
let w = 68.0; let w = 68.0;
let h = 21.0; let h = 21.0;
let r = Rect::from_xywh(fill_x - w * 0.52, bar_y - h + 2.0 + vib, w, h); 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 reversing {
if playing && r.right() < bar_right { // Reverse gear: mirror car horizontally + bright white reverse headlight beam to the left!
let beam_w = (bar_right - r.right()).min(26.0); if r.left() > bar_left {
ctx.dl().push_gradient_rect( let beam_w = (r.left() - bar_left).min(26.0 + pulse * 10.0);
Rect::from_xywh(r.right() - 2.0, bar_y - 10.0 + vib, beam_w, 8.0), ctx.dl().push_gradient_rect(
2.0, Rect::from_xywh(r.left() - beam_w + 2.0, bar_y - 10.0 + vib, beam_w, 8.0),
css_rgba(255, 240, 160, 95), 2.0,
css_rgba(255, 240, 160, 0), css_rgba(255, 250, 220, 0),
Vec2::new(1.0, 0.0), css_rgba(255, 250, 220, 120),
); Vec2::new(1.0, 0.0),
);
}
ctx.draw_icon_flipped_x(Icon::ThumbCar, r, Color::WHITE);
} else {
// Forward gear: warm headlight beam pulsing with audio energy
if playing && r.right() < bar_right {
let beam_w = (bar_right - r.right()).min(24.0 + pulse * 14.0);
let beam_a = (85.0 + beat * 65.0).min(165.0).round() as u8;
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, beam_a),
css_rgba(255, 240, 160, 0),
Vec2::new(1.0, 0.0),
);
}
ctx.draw_icon(Icon::ThumbCar, r, Color::WHITE);
} }
ctx.draw_icon(Icon::ThumbCar, r, Color::WHITE);
} }
PlayerThumbStyle::Claudik => { PlayerThumbStyle::Claudik => {
let step = if playing { ((anim_t * 7.0).floor() as u32) & 1 } else { 0 }; let step = if playing {
let bob = if playing && step == 1 { -1.5 } else { 0.0 }; ((anim_t * (7.0 + beat * 3.0)).floor() as u32) & 1
draw_claudik_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.5, step == 1); } else {
0
};
let bob = if playing {
(if step == 1 { -1.5 } else { 0.0 }) - beat * 6.0
} else {
0.0
};
draw_claudik_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.5, step == 1 || beat > 0.45);
} }
PlayerThumbStyle::Antigravity => { PlayerThumbStyle::Antigravity => {
let hover = if playing { (anim_t * 4.5).sin() * 2.2 - 3.5 } else { -2.5 }; let hover = if playing {
draw_antigravity_sprite(ctx, Pos2::new(fill_x, bar_y + hover), 2.5, anim_t, true); (anim_t * 4.5).sin() * 2.0 - 3.0 - beat * 6.5
} else {
-2.5
};
if beat > 0.25 {
ctx.dl().push_circle(
Pos2::new(fill_x, bar_y + hover - 14.0),
12.0 + beat * 8.0,
Color::rgb(0x88, 0x99, 0xFF).scale_alpha(beat * 0.24),
);
}
draw_antigravity_sprite(ctx, Pos2::new(fill_x, bar_y + hover), 2.5 + beat * 0.15, anim_t, true);
} }
PlayerThumbStyle::Ferris => { PlayerThumbStyle::Ferris => {
let step = if playing { ((anim_t * 8.0).floor() as u32) & 1 } else { 0 }; let step = if playing {
let bob = if playing && step == 1 { -1.0 } else { 0.0 }; ((anim_t * (8.0 + beat * 4.0)).floor() as u32) & 1
draw_ferris_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.2, step == 1); } else {
0
};
let bob = if playing {
(if step == 1 { -1.0 } else { 0.0 }) - beat * 6.0
} else {
0.0
};
draw_ferris_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.2, step == 1 || beat > 0.45);
} }
PlayerThumbStyle::Nyan => { PlayerThumbStyle::Nyan => {
let step = if playing { ((anim_t * 9.0).floor() as u32) & 1 } else { 0 }; let step = if playing {
let bob = if playing && step == 1 { -1.5 } else { 0.0 }; ((anim_t * (9.0 + beat * 3.5)).floor() as u32) & 1
draw_nyan_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.0, step == 1); } else {
0
};
let bob = if playing {
(if step == 1 { -1.5 } else { 0.0 }) - beat * 5.5
} else {
0.0
};
draw_nyan_sprite(ctx, Pos2::new(fill_x, bar_y + bob), 2.0, step == 1 || beat > 0.45);
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1312,8 +1312,13 @@ pub fn render_search(
} }
y += 28.0 + 16.0; y += 28.0 + 16.0;
// Discover Playlists horizontal carousel (`190.8px` cards, `16px` gap) // Discover Playlists horizontal carousel: 5 cards per row (`16px` gap),
let pl_w = 190.8_f32; // exact `190.8px` on >=960px content width, responsive 5-up on half-screen.
let pl_w = if content_w >= 960.0 {
190.8_f32
} else {
((content_w - 16.0 * 4.0) / 5.0).clamp(136.0, 190.8)
};
let pl_h = pl_w + 54.0; let pl_h = pl_w + 54.0;
let disc_vp = Rect::from_xywh(x, y, content_w, pl_h); let disc_vp = Rect::from_xywh(x, y, content_w, pl_h);
let disc_scroll_id = WidgetId::new("search_discover_scroll"); let disc_scroll_id = WidgetId::new("search_discover_scroll");

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,8 @@ use crate::app::{AppAction, AppState, Route};
use crate::config::{Language, PinnedItem, ThemeMode}; use crate::config::{Language, PinnedItem, ThemeMode};
use crate::covers::CoverCache; use crate::covers::CoverCache;
use crate::engine::widgets::{ use crate::engine::widgets::{
draw_cover_art, draw_plus_avatar_ring, draw_plus_badge, ym_menu_frame, ym_menu_item, draw_cover_art, draw_plus_avatar_ring, draw_plus_badge, draw_user_avatar, ym_menu_frame,
ym_menu_item,
}; };
use crate::engine::{ use crate::engine::{
css_rgba, Color, CursorKind, Pos2, Rect, TextAlign, TextStyle, UiContext, Vec2, WidgetId, css_rgba, Color, CursorKind, Pos2, Rect, TextAlign, TextStyle, UiContext, Vec2, WidgetId,
@ -46,13 +47,14 @@ pub fn render_sidebar(
52.0, 52.0,
); );
if show_labels { if show_labels {
let (logo_icon, logo_size) = if ru { // Exact desktop 5.129.0 `.NavbarDesktop_logo__Z4jGx svg`: `171x48` at `y = 28` (`32px titlebar - 16px navbar + 12px logoWrapper`)
(Icon::MusicLogoLeftRu, Vec2::new(168.0, 47.1)) let (logo_icon, logo_size, logo_off) = if ru {
(Icon::MusicLogoLeftRu, Vec2::new(171.0, 48.0), Vec2::new(21.0, -4.0))
} else { } else {
(Icon::MusicLogoLeftEn, Vec2::new(135.5, 47.1)) (Icon::MusicLogoLeftEn, Vec2::new(135.5, 47.1), Vec2::new(21.0, -4.0))
}; };
let logo_svg_rect = Rect::from_min_size( let logo_svg_rect = Rect::from_min_size(
Pos2::new(sidebar_rect.left() + 21.0, sidebar_rect.top() - 4.0), Pos2::new(sidebar_rect.left() + logo_off.x, sidebar_rect.top() + logo_off.y),
logo_size, logo_size,
); );
ctx.draw_icon(logo_icon, logo_svg_rect, pal.logo_text); ctx.draw_icon(logo_icon, logo_svg_rect, pal.logo_text);
@ -80,14 +82,14 @@ pub fn render_sidebar(
} }
} }
// Exact 5.129.0 `.NavbarDesktop_collapseButton__XQh9d` (`f43a2cc01fed8ead.css:157-198`): // Exact 5.129.0 `.NavbarDesktop_collapseButton__XQh9d` (`f43a2cc01fed8ead.css:157-198` + `d236a4c44d4081b0.css:374`):
// - 16×28px pill (`width: 1rem`, `border-radius: 6px`), `margin-inline-end: -8px` overhanging // - `Navbar_root` is `12.75rem (204px)` wide after `8px` left inset -> right edge at `x = 212px` (aligned
// right onto the sidebar/content seam on `ZLayer::Drawer` (`z-index: header`) so the content // with nav item pills; `72px` when collapsed). `margin-inline-end: -8px` centers the `16×28px` pill
// card never clips its right half! // (`width: 1rem`, `padding-block: 4px`, `border-radius: 6px`) right on that seam!
// - Smooth 0.20s opacity fade on sidebar OR button hover; 16×16 `xxs` chevron inside; // - Inside: `<Icon size="xxs" />` = `--ym-icon-size-xxs: 1.25rem (20×20px)`.
// tooltip ("Развернуть"/"Expand") shown ONLY when collapsed (`enabled: s`). let col_btn_cx = sidebar_rect.left() + (212.0 * (1.0 - collapse_t) + 72.0 * collapse_t);
let col_btn_rect = Rect::from_center_size( let col_btn_rect = Rect::from_center_size(
Pos2::new(sidebar_rect.right(), sidebar_rect.top() + 20.0), Pos2::new(col_btn_cx, sidebar_rect.top() + 19.5),
Vec2::new(16.0, 28.0), Vec2::new(16.0, 28.0),
); );
let show_col_target = let show_col_target =
@ -116,7 +118,7 @@ pub fn render_sidebar(
} else { } else {
Icon::ArrowLeftXxs Icon::ArrowLeftXxs
}, },
Rect::from_center_size(col_btn_rect.center(), Vec2::splat(16.0)), Rect::from_center_size(col_btn_rect.center(), Vec2::splat(20.0)),
icon_col, icon_col,
); );
if col_resp.hovered { if col_resp.hovered {
@ -384,21 +386,20 @@ pub fn render_sidebar(
let right_reserve = if show_more { 38.0 } else { 10.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 max_tw = (item_r.right() - text_x - right_reserve).max(40.0);
let title_col = if is_active { // Official `.Pin_title__Jw5WW` (`d83e97fd117fd749.css:315`): always `--ym-controls-color-primary-text-enabled_variant`
pal.text_bright let _ = is_active;
} else { // Exact `align-items: center` of two 18px lines inside `item_r` (`.Pin_link__nz6I7`, `d83e97fd117fd749.css:252-269`)
pal.text_primary let lines_top = item_r.center_y() - 18.0;
};
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
&pin.title, &pin.title,
TextStyle::medium(13.0, title_col), TextStyle::medium(13.0, pal.text_primary),
Rect::from_xywh(text_x, item_r.top() + 9.0, max_tw, 19.0), Rect::from_xywh(text_x, lines_top, max_tw, 18.0),
TextAlign::Left, TextAlign::Left,
); );
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
&pin.subtitle, &pin.subtitle,
TextStyle::medium(13.0, pal.text_secondary), TextStyle::medium(13.0, pal.text_secondary),
Rect::from_xywh(text_x, item_r.top() + 28.0, max_tw, 18.0), Rect::from_xywh(text_x, lines_top + 18.0, max_tw, 18.0),
TextAlign::Left, TextAlign::Left,
); );
@ -518,48 +519,15 @@ pub fn render_sidebar(
let prof_resp = ctx.interact(WidgetId::new("sidebar_profile_btn"), profile_hit); let prof_resp = ctx.interact(WidgetId::new("sidebar_profile_btn"), profile_hit);
let has_plus = app.account.as_ref().map_or(false, |a| a.has_plus); let has_plus = app.account.as_ref().map_or(false, |a| a.has_plus);
// Exact CSS `.UserIcon_root__X0jg9` (`2.125rem = 34px`) + `.UserIcon_root_withPlus__pRhgW:after` (`scale(1.208)` on 56px SVG w/ 2px stroke)
if has_plus { if has_plus {
draw_plus_avatar_ring(ctx, avatar_center, 20.54, 1.47); draw_plus_avatar_ring(ctx, avatar_center, 20.54, 1.47);
ctx.dl().push_circle(avatar_center, 18.8, pal.bg_basic); ctx.dl().push_circle(avatar_center, 19.07, pal.bg_basic);
} }
let avatar_diam = 34.0; let avatar_diam = 34.0;
let avatar_rect = Rect::from_center_size(avatar_center, Vec2::splat(avatar_diam));
let avatar_uri = app.account.as_ref().and_then(|a| a.avatar_uri.as_deref()); let avatar_uri = app.account.as_ref().and_then(|a| a.avatar_uri.as_deref());
if avatar_uri.is_some() { draw_user_avatar(ctx, pal, covers, avatar_center, avatar_diam, avatar_uri, has_plus);
draw_cover_art(
ctx,
pal,
covers,
avatar_rect,
avatar_uri,
"user_avatar",
avatar_diam * 0.5,
true,
false,
);
ctx.dl()
.push_circle_stroke(avatar_center, avatar_diam * 0.5 + 0.4, 1.5, pal.bg_basic);
} else {
if !has_plus {
ctx.dl()
.push_circle_stroke(avatar_center, 20.0, 1.5, pal.border_control);
}
ctx.dl().push_circle(avatar_center, avatar_diam * 0.5, pal.chip_bg);
let initials = app
.account
.as_ref()
.and_then(|a| a.display_name.chars().next())
.unwrap_or(if ru { 'Я' } else { 'Y' })
.to_uppercase()
.to_string();
ctx.draw_text_ellipsis(
&initials,
TextStyle::bold(15.0, pal.logo_text),
avatar_rect,
TextAlign::Center,
);
}
let mut plus_clicked = false; let mut plus_clicked = false;
if show_labels { if show_labels {
@ -691,7 +659,7 @@ fn render_profile_card_popup(
Color::rgb(0x26, 0x26, 0x33) Color::rgb(0x26, 0x26, 0x33)
}; };
let id_text_secondary = if is_dark { let id_text_secondary = if is_dark {
css_rgba(240, 240, 255, 118) css_rgba(240, 240, 255, 117) // exact rgba(240, 240, 255, 0.46)
} else { } else {
Color::rgb(0x85, 0x88, 0x9E) Color::rgb(0x85, 0x88, 0x9E)
}; };
@ -701,18 +669,19 @@ fn render_profile_card_popup(
css_rgba(180, 184, 204, 36) css_rgba(180, 184, 204, 36)
}; };
let id_separator = if is_dark { let id_separator = if is_dark {
css_rgba(250, 250, 255, 22) css_rgba(250, 250, 255, 20) // exact rgba(250, 250, 255, 0.08)
} else { } else {
css_rgba(38, 38, 51, 22) css_rgba(38, 38, 51, 20)
}; };
let card_w = 320.0; // Exact live `https://yandex.ru/user-id` dimensions: inner root 312px (8px padding -> 296px rows)
let header_h = if logged_in { 144.0 } else { 198.0 }; let card_w = 312.0;
let group1_h = 54.0 + if logged_in { 44.0 * 5.0 } else { 44.0 * 3.0 }; let header_h = if logged_in { 160.0 } else { 198.0 };
let sep_h = 13.0; // 6px top + 1px line + 6px bottom let group1_h = 60.0 + if logged_in { 44.0 * 5.0 } else { 44.0 * 3.0 };
let sep_h = 17.0; // 8px bottom group padding + 1px divider + 8px top group padding
let group2_h = 44.0; let group2_h = 44.0;
let group3_h = if logged_in { sep_h + 44.0 * 2.0 } else { 0.0 }; let group3_h = if logged_in { sep_h + 44.0 * 2.0 } else { 0.0 };
let card_h = header_h + group1_h + sep_h + group2_h + group3_h + 10.0; let card_h = header_h + group1_h + sep_h + group2_h + group3_h + 12.0;
let screen = ctx.screen_rect(); let screen = ctx.screen_rect();
let card_x = (sidebar_rect.left() + 20.0).min((screen.right() - card_w - 12.0).max(8.0)); let card_x = (sidebar_rect.left() + 20.0).min((screen.right() - card_w - 12.0).max(8.0));
@ -733,8 +702,8 @@ fn render_profile_card_popup(
ctx.dl() ctx.dl()
.push_rect_bordered(card_rect, 24.0, card_bg, 1.0, card_border); .push_rect_bordered(card_rect, 24.0, card_bg, 1.0, card_border);
// 1. Top Overlay Bar (`_overlap_1v1kx_1`): 41×20 Yandex ID vector logo + 32×32 circular Close `×` // 1. Top Overlay Bar (`_panel_1v1kx_43`): 41×20 Yandex ID logo @ (24,24) + 44×44 Close button w/ 24×24 icon @ (264,24)
let logo_r = Rect::from_xywh(card_rect.left() + 16.0, card_rect.top() + 16.0, 41.0, 20.0); let logo_r = Rect::from_xywh(card_rect.left() + 24.0, card_rect.top() + 24.0, 41.0, 20.0);
let logo_icon = match (ru, is_dark) { let logo_icon = match (ru, is_dark) {
(true, true) => Icon::YandexIdLogoRuDark, (true, true) => Icon::YandexIdLogoRuDark,
(true, false) => Icon::YandexIdLogoRuLight, (true, false) => Icon::YandexIdLogoRuLight,
@ -751,20 +720,17 @@ fn render_profile_card_popup(
close_popup = true; close_popup = true;
} }
let close_r = Rect::from_xywh(card_rect.right() - 44.0, card_rect.top() + 10.0, 32.0, 32.0); let close_r = Rect::from_xywh(card_rect.right() - 58.0, card_rect.top() + 14.0, 44.0, 44.0);
let close_resp = ctx.interact(WidgetId::new("prof_card_close"), close_r); let close_resp = ctx.interact(WidgetId::new("prof_card_close"), close_r);
if close_resp.hovered { if close_resp.hovered {
ctx.dl().push_circle(close_r.center(), 16.0, id_row_hover); ctx.dl().push_circle(close_r.center(), 22.0, id_row_hover);
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
} }
// Official `.UserID-CloseButton_colorScheme_dark` (`#fafaff`) / `_light` (`#262633`), 24×24 SVG
ctx.draw_icon( ctx.draw_icon(
Icon::Close, Icon::Close,
Rect::from_center_size(close_r.center(), Vec2::splat(18.0)), Rect::from_center_size(close_r.center(), Vec2::splat(24.0)),
if close_resp.hovered { id_text_primary,
id_text_primary
} else {
id_text_secondary
},
); );
if close_resp.clicked { if close_resp.clicked {
close_popup = true; close_popup = true;
@ -773,28 +739,33 @@ fn render_profile_card_popup(
// 2. Header: Logged In (`cv`) vs Logged Out (`Av`) // 2. Header: Logged In (`cv`) vs Logged Out (`Av`)
let mut y = card_rect.top() + header_h; let mut y = card_rect.top() + header_h;
if let Some(ref acc) = app.account { if let Some(ref acc) = app.account {
let avatar_center = Pos2::new(card_rect.center_x(), card_rect.top() + 20.0 + 28.0); // Exact `UserId-Avatar` @ (128, 24) 56×56 inside `56 * 1.208 = 67.65px` Plus ring (2.4px stroke)
let av_diam = 56.0;
let av_r = av_diam * 0.5;
let avatar_center = Pos2::new(card_rect.center_x(), card_rect.top() + 24.0 + av_r);
if acc.has_plus { if acc.has_plus {
draw_plus_avatar_ring(ctx, avatar_center, 31.0, 2.0); draw_plus_avatar_ring(ctx, avatar_center, 33.8, 2.4);
ctx.dl().push_circle(avatar_center, 29.0, card_bg); ctx.dl().push_circle(avatar_center, 31.4, card_bg);
} }
let av_rect = Rect::from_center_size(avatar_center, Vec2::splat(56.0)); let av_rect = Rect::from_center_size(avatar_center, Vec2::splat(av_diam));
if acc.avatar_uri.is_some() { let mut drew_avatar = false;
draw_cover_art( if let Some(uri) = acc.avatar_uri.as_deref() {
ctx, if let Some((tex_id, _, _, tw, th)) = covers.get_or_fetch_with_size(uri, 256) {
pal, let uv = crate::engine::widgets::cover_fit_uv(tw, th, av_rect, 0.5);
covers, ctx.dl().push_image_uv(
av_rect, av_rect,
acc.avatar_uri.as_deref(), tex_id,
"profile_popup_avatar", uv,
28.0, crate::engine::CornerRadii::same(av_r),
true, Color::WHITE,
false, );
); drew_avatar = true;
} else { }
}
if !drew_avatar {
ctx.dl().push_circle( ctx.dl().push_circle(
avatar_center, avatar_center,
28.0, av_r,
if is_dark { if is_dark {
Color::rgb(0x32, 0x32, 0x3B) Color::rgb(0x32, 0x32, 0x3B)
} else { } else {
@ -817,15 +788,16 @@ fn render_profile_card_popup(
); );
} }
let name_y = card_rect.top() + 20.0 + 56.0 + 10.0; // Exact `_title_1d6ve_1` @ y=90 (18px Medium, line-height 22px) + `_caption_1d6ve_12` @ y=114 (14px Regular, line-height 18px)
let name_y = card_rect.top() + 90.0;
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
&acc.display_name, &acc.display_name,
TextStyle::bold(16.0, id_text_primary), TextStyle::medium(18.0, id_text_primary),
Rect::from_center_size(Pos2::new(card_rect.center_x(), name_y + 11.0), Vec2::new(260.0, 22.0)), Rect::from_center_size(Pos2::new(card_rect.center_x(), name_y + 11.0), Vec2::new(260.0, 22.0)),
TextAlign::Center, TextAlign::Center,
); );
let sub_y = name_y + 22.0 + 2.0; let sub_y = card_rect.top() + 114.0;
let contact_str = acc let contact_str = acc
.default_email .default_email
.as_deref() .as_deref()
@ -833,7 +805,7 @@ fn render_profile_card_popup(
.unwrap_or(&acc.login); .unwrap_or(&acc.login);
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
contact_str, contact_str,
TextStyle::regular(13.0, id_text_secondary), TextStyle::regular(14.0, id_text_secondary),
Rect::from_center_size(Pos2::new(card_rect.center_x(), sub_y + 9.0), Vec2::new(260.0, 18.0)), Rect::from_center_size(Pos2::new(card_rect.center_x(), sub_y + 9.0), Vec2::new(260.0, 18.0)),
TextAlign::Center, TextAlign::Center,
); );
@ -912,7 +884,7 @@ fn render_profile_card_popup(
subtitle: Option<&str>, subtitle: Option<&str>,
has_chevron: bool, has_chevron: bool,
active: bool, active: bool,
right_plus_badge: Option<&str>| right_plus_points: Option<u64>|
-> (bool, bool, Rect) { -> (bool, bool, Rect) {
let r = Rect::from_xywh(row_x, y_pos, row_w, row_h); let r = Rect::from_xywh(row_x, y_pos, row_w, row_h);
let resp = ctx.interact(WidgetId::new(id), r); let resp = ctx.interact(WidgetId::new(id), r);
@ -922,52 +894,76 @@ fn render_profile_card_popup(
if resp.hovered { if resp.hovered {
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
} }
// Exact `padding: 10px 16px`, `24×24` icon @ `x+16..x+40` (center `x+28`), text @ `x+56` (`16px` Regular)
let icon_y = if subtitle.is_some() {
r.top() + 22.0
} else {
r.center_y()
};
ctx.draw_icon( ctx.draw_icon(
ic, ic,
Rect::from_center_size(Pos2::new(r.left() + 24.0, r.center_y()), Vec2::splat(24.0)), Rect::from_center_size(Pos2::new(r.left() + 28.0, icon_y), Vec2::splat(24.0)),
ic_tint, ic_tint,
); );
let tx = r.left() + 48.0; let tx = r.left() + 56.0;
let right_reserve = if right_plus_badge.is_some() { let right_reserve = if right_plus_points.is_some() {
68.0 72.0
} else if has_chevron { } else if has_chevron {
32.0 32.0
} else { } else {
12.0 16.0
}; };
let tw = (r.right() - tx - right_reserve).max(40.0); let tw = (r.right() - tx - right_reserve).max(40.0);
if let Some(sub) = subtitle { if let Some(sub) = subtitle {
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
title, title,
TextStyle::medium(14.5, id_text_primary), TextStyle::regular(16.0, id_text_primary),
Rect::from_xywh(tx, r.top() + 8.0, tw, 20.0), Rect::from_xywh(tx, r.top() + 10.0, tw, 20.0),
TextAlign::Left, TextAlign::Left,
); );
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
sub, sub,
TextStyle::regular(12.5, id_text_secondary), TextStyle::regular(14.0, id_text_secondary),
Rect::from_xywh(tx, r.top() + 29.0, tw, 17.0), Rect::from_xywh(tx, r.top() + 32.0, tw, 18.0),
TextAlign::Left, TextAlign::Left,
); );
} else { } else {
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
title, title,
TextStyle::medium(14.5, id_text_primary), TextStyle::regular(16.0, id_text_primary),
Rect::from_xywh(tx, r.top(), tw, r.height()), Rect::from_xywh(tx, r.top(), tw, r.height()),
TextAlign::Left, TextAlign::Left,
); );
} }
if let Some(badge_txt) = right_plus_badge { if let Some(points) = right_plus_points {
let bw = (ctx.measure_text(badge_txt, TextStyle::bold(11.5, Color::WHITE), None).x // Exact `._badge_gi7z8_1` (`padding: 3px 6px`, `gap: 4px`, `height: 24px`, `border-radius: 12px`,
+ 18.0) // `._text_gi7z8_8` `16px` Medium `line-height: 16px`, `16×16` Plus SVG, aligned @ `r.top + 10`, `r.right - 16`)
.max(46.0); let pts_str = format_plus_points(points);
let br = Rect::from_xywh(r.right() - bw - 10.0, r.center_y() - 10.0, bw, 20.0); let txt_style = TextStyle::medium(16.0, Color::WHITE);
ctx.dl().push_plus_gradient_rect(br, 10.0, 1.0); let txt_w = ctx.measure_text(&pts_str, txt_style, None).x;
let icon_sz = 16.0;
let h_pad = 6.0;
let gap = 4.0;
let bw = (h_pad + txt_w + gap + icon_sz + h_pad).max(43.0);
let bh = 24.0;
let pill_y = if subtitle.is_some() {
r.top() + 10.0
} else {
r.center_y() - bh * 0.5
};
let br = Rect::from_xywh(r.right() - bw - 16.0, pill_y, bw, bh);
ctx.dl().push_plus_gradient_rect(br, bh * 0.5, 1.0);
ctx.draw_text_ellipsis( ctx.draw_text_ellipsis(
badge_txt, &pts_str,
TextStyle::bold(11.5, Color::WHITE), txt_style,
br, Rect::from_xywh(br.left() + h_pad, br.top(), txt_w + 2.0, bh),
TextAlign::Center, TextAlign::Left,
);
let ic_center = Pos2::new(br.right() - h_pad - icon_sz * 0.5, br.center_y());
ctx.draw_icon(
Icon::Plus,
Rect::from_center_size(ic_center, Vec2::splat(icon_sz)),
Color::WHITE,
); );
} else if has_chevron { } else if has_chevron {
ctx.draw_icon( ctx.draw_icon(
@ -981,7 +977,7 @@ fn render_profile_card_popup(
let draw_separator = |ctx: &mut UiContext, y_pos: f32| { let draw_separator = |ctx: &mut UiContext, y_pos: f32| {
ctx.dl().push_rect( ctx.dl().push_rect(
Rect::from_xywh(card_rect.left() + 16.0, y_pos + 6.0, card_w - 32.0, 1.0), Rect::from_xywh(card_rect.left() + 24.0, y_pos + 8.0, card_w - 48.0, 1.0),
0.0, 0.0,
id_separator, id_separator,
); );
@ -989,7 +985,7 @@ fn render_profile_card_popup(
// 3. Menu Group 1 (`r.Menu`) // 3. Menu Group 1 (`r.Menu`)
// Row 1 — Plus (`54px`) // Row 1 — Plus (`54px`)
let (plus_title, plus_sub, plus_pill) = if has_plus { let (plus_title, plus_sub, plus_points) = if has_plus {
( (
if ru { "Плюс" } else { "Plus" }, if ru { "Плюс" } else { "Plus" },
if ru { if ru {
@ -997,7 +993,7 @@ fn render_profile_card_popup(
} else { } else {
"Subscription is active" "Subscription is active"
}, },
Some(if ru { "Плюс" } else { "Plus" }), Some(app.account.as_ref().and_then(|a| a.plus_balance).unwrap_or(0)),
) )
} else { } else {
( (
@ -1018,14 +1014,14 @@ fn render_profile_card_popup(
ctx, ctx,
"prof_plus", "prof_plus",
y, y,
54.0, 60.0,
Icon::ProfilePlusXxs, Icon::ProfilePlusXxs,
Color::WHITE, // multi-stop gradient SVG id_text_primary,
plus_title, plus_title,
Some(plus_sub), Some(plus_sub),
false, false,
false, false,
plus_pill, plus_points,
); );
if h { if h {
shell.sidebar_lang_open = false; shell.sidebar_lang_open = false;
@ -1035,7 +1031,7 @@ fn render_profile_card_popup(
actions.push(AppAction::OpenUrl("https://plus.yandex.ru".into())); actions.push(AppAction::OpenUrl("https://plus.yandex.ru".into()));
close_popup = true; close_popup = true;
} }
y += 54.0; y += 60.0;
// Row 2 — Account management (logged in) // Row 2 — Account management (logged in)
if logged_in { if logged_in {
@ -1409,3 +1405,32 @@ fn render_profile_card_popup(
shell.sidebar_lang_open = false; shell.sidebar_lang_open = false;
} }
} }
fn format_plus_points(points: u64) -> String {
let s = points.to_string();
if s.len() <= 3 {
return s;
}
let mut out = String::with_capacity(s.len() + s.len() / 3);
for (i, ch) in s.chars().enumerate() {
if i > 0 && (s.len() - i) % 3 == 0 {
out.push(' ');
}
out.push(ch);
}
out
}
#[cfg(test)]
mod tests {
use super::format_plus_points;
#[test]
fn format_plus_points_groups_thousands() {
assert_eq!(format_plus_points(0), "0");
assert_eq!(format_plus_points(42), "42");
assert_eq!(format_plus_points(999), "999");
assert_eq!(format_plus_points(1000), "1 000");
assert_eq!(format_plus_points(1234567), "1 234 567");
}
}

View file

@ -1,9 +1,59 @@
use crate::app::{AppState, WindowCommand}; use crate::app::{AppState, WindowCommand, WindowResizeDirection};
use crate::engine::{ use crate::engine::{
css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, TextAlign, TextStyle, UiContext, Vec2, css_rgba, Color, CornerRadii, CursorKind, Pos2, Rect, TextAlign, TextStyle, UiContext, Vec2,
WidgetId, YmPalette, ZLayer, TITLEBAR_BTN_WIDTH, TITLEBAR_HEIGHT, WidgetId, YmPalette, ZLayer, TITLEBAR_BTN_WIDTH, TITLEBAR_HEIGHT,
}; };
/// Hit-test invisible resize borders around a frameless (unmaximized) window.
/// Returns the matched `WindowResizeDirection` and its corresponding cursor icon.
pub fn hit_test_resize_border(screen: Rect, pos: Pos2) -> Option<(WindowResizeDirection, CursorKind)> {
const EDGE: f32 = 6.0;
const TOP_EDGE: f32 = 5.0;
const CORNER: f32 = 12.0;
let on_left = pos.x < screen.left() + EDGE;
let on_right = pos.x >= screen.right() - EDGE;
let on_top = pos.y < screen.top() + TOP_EDGE;
let on_bottom = pos.y >= screen.bottom() - EDGE;
if !on_left && !on_right && !on_top && !on_bottom {
return None;
}
let near_left = pos.x < screen.left() + CORNER;
let near_right = pos.x >= screen.right() - CORNER;
let near_top = pos.y < screen.top() + CORNER;
let near_bottom = pos.y >= screen.bottom() - CORNER;
let dir = match (on_left, on_right, on_top, on_bottom) {
(true, _, true, _) => WindowResizeDirection::NorthWest,
(_, true, true, _) => WindowResizeDirection::NorthEast,
(true, _, _, true) => WindowResizeDirection::SouthWest,
(_, true, _, true) => WindowResizeDirection::SouthEast,
(true, _, _, _) if near_top => WindowResizeDirection::NorthWest,
(true, _, _, _) if near_bottom => WindowResizeDirection::SouthWest,
(_, true, _, _) if near_top => WindowResizeDirection::NorthEast,
(_, true, _, _) if near_bottom => WindowResizeDirection::SouthEast,
(_, _, true, _) if near_left => WindowResizeDirection::NorthWest,
(_, _, true, _) if near_right => WindowResizeDirection::NorthEast,
(_, _, _, true) if near_left => WindowResizeDirection::SouthWest,
(_, _, _, true) if near_right => WindowResizeDirection::SouthEast,
(true, _, _, _) => WindowResizeDirection::West,
(_, true, _, _) => WindowResizeDirection::East,
(_, _, true, _) => WindowResizeDirection::North,
(_, _, _, true) => WindowResizeDirection::South,
_ => return None,
};
let cursor = match dir {
WindowResizeDirection::North | WindowResizeDirection::South => CursorKind::ResizeVertical,
WindowResizeDirection::East | WindowResizeDirection::West => CursorKind::ResizeHorizontal,
WindowResizeDirection::NorthWest | WindowResizeDirection::SouthEast => CursorKind::ResizeNwSe,
WindowResizeDirection::NorthEast | WindowResizeDirection::SouthWest => CursorKind::ResizeNeSw,
};
Some((dir, cursor))
}
/// Exact Yandex Music Desktop 5.129.0 floating transparent 32px TitleBar (`TitleBar_root__QjdOZ`): /// Exact Yandex Music Desktop 5.129.0 floating transparent 32px TitleBar (`TitleBar_root__QjdOZ`):
/// - Floats over My Vibe full-bleed canvas AND FullscreenPlayer on `ZLayer::Titlebar` /// - Floats over My Vibe full-bleed canvas AND FullscreenPlayer on `ZLayer::Titlebar`
/// - Drag region + double-click to toggle maximize /// - Drag region + double-click to toggle maximize
@ -47,15 +97,33 @@ pub fn render_titlebar(
TITLEBAR_HEIGHT, TITLEBAR_HEIGHT,
); );
// Frameless window resize border hit-testing (skipped when maximized so caption buttons
// remain clickable at the very top-right pixel).
let resize_hit = if !is_maximized {
ctx.input
.pointer_pos
.and_then(|pos| hit_test_resize_border(screen, pos))
} else {
None
};
if let Some((dir, cursor)) = resize_hit {
ctx.set_cursor(cursor);
if ctx.input.left_pressed {
cmd = WindowCommand::DragResize(dir);
}
}
// Block pointer hit-testing underneath the 32px titlebar overlay // Block pointer hit-testing underneath the 32px titlebar overlay
ctx.register_blocker(rect); ctx.register_blocker(rect);
// Drag + double-click maximize region // Drag + double-click maximize region (suppressed while pointer is on the top resize strip)
let drag_resp = ctx.interact(WidgetId::new("ym_tb_drag"), drag_r); let drag_resp = ctx.interact(WidgetId::new("ym_tb_drag"), drag_r);
if drag_resp.double_clicked { if resize_hit.is_none() {
cmd = WindowCommand::ToggleMaximize; if drag_resp.double_clicked {
} else if drag_resp.drag_started { cmd = WindowCommand::ToggleMaximize;
cmd = WindowCommand::DragWindow; } else if drag_resp.drag_started {
cmd = WindowCommand::DragWindow;
}
} }
// Optional lightweight Vulkan Perf HUD in the titlebar center // Optional lightweight Vulkan Perf HUD in the titlebar center
@ -85,7 +153,7 @@ pub fn render_titlebar(
// 1. Minimize (`windows-menu.roll-up`) // 1. Minimize (`windows-menu.roll-up`)
let min_resp = ctx.interact(WidgetId::new("ym_tb_min"), min_r); let min_resp = ctx.interact(WidgetId::new("ym_tb_min"), min_r);
if min_resp.hovered { if min_resp.hovered && resize_hit.is_none() {
ctx.dl().push_rect(min_r, 0.0, btn_hover_bg); ctx.dl().push_rect(min_r, 0.0, btn_hover_bg);
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
ctx.show_tooltip(min_r, i18n.roll_up()); ctx.show_tooltip(min_r, i18n.roll_up());
@ -96,13 +164,13 @@ pub fn render_titlebar(
0.5, 0.5,
icon_col, icon_col,
); );
if min_resp.clicked { if min_resp.clicked && resize_hit.is_none() {
cmd = WindowCommand::Minimize; cmd = WindowCommand::Minimize;
} }
// 2. Maximize / Windows 11 Restore double-square (`windows-menu.unwrap`) // 2. Maximize / Windows 11 Restore double-square (`windows-menu.unwrap`)
let max_resp = ctx.interact(WidgetId::new("ym_tb_max"), max_r); let max_resp = ctx.interact(WidgetId::new("ym_tb_max"), max_r);
if max_resp.hovered { if max_resp.hovered && resize_hit.is_none() {
ctx.dl().push_rect(max_r, 0.0, btn_hover_bg); ctx.dl().push_rect(max_r, 0.0, btn_hover_bg);
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
ctx.show_tooltip(max_r, i18n.unwrap()); ctx.show_tooltip(max_r, i18n.unwrap());
@ -132,19 +200,20 @@ pub fn render_titlebar(
let sq = Rect::from_center_size(xc, Vec2::splat(10.0)); let sq = Rect::from_center_size(xc, Vec2::splat(10.0));
ctx.dl().push_rect_bordered(sq, CornerRadii::same(1.5), Color::TRANSPARENT, 1.0, icon_col); ctx.dl().push_rect_bordered(sq, CornerRadii::same(1.5), Color::TRANSPARENT, 1.0, icon_col);
} }
if max_resp.clicked { if max_resp.clicked && resize_hit.is_none() {
cmd = WindowCommand::ToggleMaximize; cmd = WindowCommand::ToggleMaximize;
} }
// 3. Close (`windows-menu.close`, exact `#F23F42` hover in BOTH themes) // 3. Close (`windows-menu.close`, exact `#F23F42` hover in BOTH themes)
let close_resp = ctx.interact(WidgetId::new("ym_tb_close"), close_r); let close_resp = ctx.interact(WidgetId::new("ym_tb_close"), close_r);
if close_resp.hovered { let close_hov = close_resp.hovered && resize_hit.is_none();
if close_hov {
ctx.dl().push_rect(close_r, 0.0, pal.close_red); ctx.dl().push_rect(close_r, 0.0, pal.close_red);
ctx.set_cursor(CursorKind::Pointer); ctx.set_cursor(CursorKind::Pointer);
ctx.show_tooltip(close_r, i18n.close()); ctx.show_tooltip(close_r, i18n.close());
} }
let cc = Pos2::new(close_r.center_x().round(), close_r.center_y().round()); let cc = Pos2::new(close_r.center_x().round(), close_r.center_y().round());
let cc_col = if close_resp.hovered { let cc_col = if close_hov {
Color::WHITE Color::WHITE
} else { } else {
icon_col icon_col
@ -153,10 +222,56 @@ pub fn render_titlebar(
.push_line(Pos2::new(cc.x - 4.8, cc.y - 4.8), Pos2::new(cc.x + 4.8, cc.y + 4.8), 1.1, cc_col); .push_line(Pos2::new(cc.x - 4.8, cc.y - 4.8), Pos2::new(cc.x + 4.8, cc.y + 4.8), 1.1, cc_col);
ctx.dl() ctx.dl()
.push_line(Pos2::new(cc.x + 4.8, cc.y - 4.8), Pos2::new(cc.x - 4.8, cc.y + 4.8), 1.1, cc_col); .push_line(Pos2::new(cc.x + 4.8, cc.y - 4.8), Pos2::new(cc.x - 4.8, cc.y + 4.8), 1.1, cc_col);
if close_resp.clicked { if close_resp.clicked && resize_hit.is_none() {
cmd = WindowCommand::Close; cmd = WindowCommand::Close;
} }
}); });
cmd cmd
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hit_test_resize_border_all_edges_and_corners() {
let s = Rect::from_xywh(0.0, 0.0, 1280.0, 800.0);
assert_eq!(
hit_test_resize_border(s, Pos2::new(2.0, 2.0)),
Some((WindowResizeDirection::NorthWest, CursorKind::ResizeNwSe))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(1278.0, 2.0)),
Some((WindowResizeDirection::NorthEast, CursorKind::ResizeNeSw))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(2.0, 798.0)),
Some((WindowResizeDirection::SouthWest, CursorKind::ResizeNeSw))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(1278.0, 798.0)),
Some((WindowResizeDirection::SouthEast, CursorKind::ResizeNwSe))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(640.0, 2.0)),
Some((WindowResizeDirection::North, CursorKind::ResizeVertical))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(640.0, 798.0)),
Some((WindowResizeDirection::South, CursorKind::ResizeVertical))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(2.0, 400.0)),
Some((WindowResizeDirection::West, CursorKind::ResizeHorizontal))
);
assert_eq!(
hit_test_resize_border(s, Pos2::new(1278.0, 400.0)),
Some((WindowResizeDirection::East, CursorKind::ResizeHorizontal))
);
// Interior titlebar drag region (below top 5px strip) must NOT trigger resize
assert_eq!(hit_test_resize_border(s, Pos2::new(400.0, 16.0)), None);
// Center of screen must NOT trigger resize
assert_eq!(hit_test_resize_border(s, Pos2::new(640.0, 400.0)), None);
}
}

View file

@ -47,8 +47,6 @@ pub struct VulkanContext {
command_pool: vk::CommandPool, command_pool: vk::CommandPool,
command_buffers: Vec<vk::CommandBuffer>, command_buffers: Vec<vk::CommandBuffer>,
upload_cmd_buf: vk::CommandBuffer,
upload_fence: vk::Fence,
image_available: Vec<vk::Semaphore>, image_available: Vec<vk::Semaphore>,
render_finished: Vec<vk::Semaphore>, render_finished: Vec<vk::Semaphore>,
in_flight: Vec<vk::Fence>, in_flight: Vec<vk::Fence>,
@ -272,6 +270,8 @@ impl VulkanContext {
upload_cmd_buf, upload_cmd_buf,
upload_fence, upload_fence,
)?; )?;
device.free_command_buffers(command_pool, &[upload_cmd_buf]);
device.destroy_fence(upload_fence, None);
// Exact official Yandex desktop My Vibe offscreen render target (`desktopSizePx = 650x650`) // Exact official Yandex desktop My Vibe offscreen render target (`desktopSizePx = 650x650`)
// — 100% lossless visuals; GPU savings come from CPU-hoisted push constants + early radial reject. // — 100% lossless visuals; GPU savings come from CPU-hoisted push constants + early radial reject.
@ -309,8 +309,6 @@ impl VulkanContext {
direct_framebuffers, direct_framebuffers,
command_pool, command_pool,
command_buffers, command_buffers,
upload_cmd_buf,
upload_fence,
image_available, image_available,
render_finished, render_finished,
in_flight, in_flight,
@ -421,18 +419,6 @@ impl VulkanContext {
self.device.wait_for_fences(&[fence], true, u64::MAX)?; self.device.wait_for_fences(&[fence], true, u64::MAX)?;
self.ui_renderer.flush_deferred_frees(&self.device, frame_idx); self.ui_renderer.flush_deferred_frees(&self.device, frame_idx);
if !uploads.is_empty() {
self.ui_renderer.process_uploads(
&self.device,
&self.mem_props,
self.graphics_queue,
self.upload_cmd_buf,
self.upload_fence,
frame_idx,
uploads,
)?;
}
let use_scene_blur = let use_scene_blur =
self.swapchain_supports_transfer_dst && !display_list.blur_regions.is_empty(); self.swapchain_supports_transfer_dst && !display_list.blur_regions.is_empty();
if use_scene_blur { if use_scene_blur {
@ -487,6 +473,17 @@ impl VulkanContext {
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT), .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
)?; )?;
// Upload newly arrived covers & glyph atlas regions inline on this frame's command buffer
if !uploads.is_empty() {
self.ui_renderer.record_uploads_into_cmd(
&self.device,
&self.mem_props,
cmd,
frame_idx,
uploads,
)?;
}
// 1. Render My Vibe offscreen GPU shader only when active AND parameters changed // 1. Render My Vibe offscreen GPU shader only when active AND parameters changed
if let Some(vp) = vibe_push { if let Some(vp) = vibe_push {
if self.last_vibe_push != Some(vp) { if self.last_vibe_push != Some(vp) {
@ -742,7 +739,6 @@ impl Drop for VulkanContext {
for f in self.in_flight.drain(..) { for f in self.in_flight.drain(..) {
self.device.destroy_fence(f, None); self.device.destroy_fence(f, None);
} }
self.device.destroy_fence(self.upload_fence, None);
self.device.destroy_command_pool(self.command_pool, None); self.device.destroy_command_pool(self.command_pool, None);
for fb in self.direct_framebuffers.drain(..) { for fb in self.direct_framebuffers.drain(..) {
self.device.destroy_framebuffer(fb, None); self.device.destroy_framebuffer(fb, None);

View file

@ -42,12 +42,20 @@ struct KawaseTargets {
src_extent: vk::Extent2D, src_extent: vk::Extent2D,
half_extent: vk::Extent2D, half_extent: vk::Extent2D,
quarter_extent: vk::Extent2D, quarter_extent: vk::Extent2D,
eighth_extent: vk::Extent2D,
sixteenth_extent: vk::Extent2D,
half_image: AllocatedImage, half_image: AllocatedImage,
quarter_image: AllocatedImage, quarter_image: AllocatedImage,
eighth_image: AllocatedImage,
sixteenth_image: AllocatedImage,
half_fb: vk::Framebuffer, half_fb: vk::Framebuffer,
quarter_fb: vk::Framebuffer, quarter_fb: vk::Framebuffer,
eighth_fb: vk::Framebuffer,
sixteenth_fb: vk::Framebuffer,
half_ds: vk::DescriptorSet, half_ds: vk::DescriptorSet,
quarter_ds: vk::DescriptorSet, quarter_ds: vk::DescriptorSet,
eighth_ds: vk::DescriptorSet,
sixteenth_ds: vk::DescriptorSet,
} }
/// Pure `ash` Vulkan 1.2 Uber-SDF UI Renderer + 2-Pass Dual Kawase Backdrop Blur Engine. /// Pure `ash` Vulkan 1.2 Uber-SDF UI Renderer + 2-Pass Dual Kawase Backdrop Blur Engine.
@ -78,7 +86,7 @@ pub struct UiVulkanRenderer {
ssbo_sets: Vec<vk::DescriptorSet>, ssbo_sets: Vec<vk::DescriptorSet>,
instance_buffers: Vec<AllocatedBuffer>, instance_buffers: Vec<AllocatedBuffer>,
staging_buffer: AllocatedBuffer, staging_buffers: Vec<AllocatedBuffer>,
} }
impl UiVulkanRenderer { impl UiVulkanRenderer {
@ -340,12 +348,15 @@ impl UiVulkanRenderer {
blur_src_sets.push(bsrc_ds); blur_src_sets.push(bsrc_ds);
} }
let staging_buffer = AllocatedBuffer::new_host_visible( let mut staging_buffers = Vec::with_capacity(MAX_FRAMES_IN_FLIGHT);
device, for _ in 0..MAX_FRAMES_IN_FLIGHT {
mem_props, staging_buffers.push(AllocatedBuffer::new_host_visible(
2 * 1024 * 1024, device,
vk::BufferUsageFlags::TRANSFER_SRC, mem_props,
)?; 1024 * 1024,
vk::BufferUsageFlags::TRANSFER_SRC,
)?);
}
let mut renderer = Self { let mut renderer = Self {
ssbo_set_layout, ssbo_set_layout,
@ -365,7 +376,7 @@ impl UiVulkanRenderer {
deferred_frees, deferred_frees,
ssbo_sets, ssbo_sets,
instance_buffers, instance_buffers,
staging_buffer, staging_buffers,
}; };
// Upload default 1x1 white texture at NONE_TEXTURE_ID so set 1 is always bound validly // Upload default 1x1 white texture at NONE_TEXTURE_ID so set 1 is always bound validly
@ -396,10 +407,13 @@ impl UiVulkanRenderer {
.filter_map(|t| t.image.as_ref().map(|i| i.byte_size)) .filter_map(|t| t.image.as_ref().map(|i| i.byte_size))
.sum(); .sum();
let blur_bytes: u64 = self.blur_targets.as_ref().map_or(0, |bt| { let blur_bytes: u64 = self.blur_targets.as_ref().map_or(0, |bt| {
bt.half_image.byte_size + bt.quarter_image.byte_size bt.half_image.byte_size
+ bt.quarter_image.byte_size
+ bt.eighth_image.byte_size
+ bt.sixteenth_image.byte_size
}); });
let buf_bytes: u64 = self.instance_buffers.iter().map(|b| b.size).sum::<u64>() let buf_bytes: u64 = self.instance_buffers.iter().map(|b| b.size).sum::<u64>()
+ self.staging_buffer.size; + self.staging_buffers.iter().map(|b| b.size).sum::<u64>();
tex_bytes + blur_bytes + buf_bytes tex_bytes + blur_bytes + buf_bytes
} }
@ -462,9 +476,16 @@ impl UiVulkanRenderer {
let _ = device.device_wait_idle(); let _ = device.device_wait_idle();
device.destroy_framebuffer(old.half_fb, None); device.destroy_framebuffer(old.half_fb, None);
device.destroy_framebuffer(old.quarter_fb, None); device.destroy_framebuffer(old.quarter_fb, None);
let _ = device.free_descriptor_sets(self.descriptor_pool, &[old.half_ds, old.quarter_ds]); device.destroy_framebuffer(old.eighth_fb, None);
device.destroy_framebuffer(old.sixteenth_fb, None);
let _ = device.free_descriptor_sets(
self.descriptor_pool,
&[old.half_ds, old.quarter_ds, old.eighth_ds, old.sixteenth_ds],
);
old.half_image.destroy(device); old.half_image.destroy(device);
old.quarter_image.destroy(device); old.quarter_image.destroy(device);
old.eighth_image.destroy(device);
old.sixteenth_image.destroy(device);
} }
let half_extent = vk::Extent2D { let half_extent = vk::Extent2D {
@ -475,6 +496,14 @@ impl UiVulkanRenderer {
width: (src_extent.width / 4).max(1), width: (src_extent.width / 4).max(1),
height: (src_extent.height / 4).max(1), height: (src_extent.height / 4).max(1),
}; };
let eighth_extent = vk::Extent2D {
width: (src_extent.width / 8).max(1),
height: (src_extent.height / 8).max(1),
};
let sixteenth_extent = vk::Extent2D {
width: (src_extent.width / 16).max(1),
height: (src_extent.height / 16).max(1),
};
let usage = vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED; let usage = vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::SAMPLED;
let half_image = AllocatedImage::new_2d( let half_image = AllocatedImage::new_2d(
@ -493,28 +522,43 @@ impl UiVulkanRenderer {
format, format,
usage, usage,
)?; )?;
let eighth_image = AllocatedImage::new_2d(
device,
mem_props,
eighth_extent.width,
eighth_extent.height,
format,
usage,
)?;
let sixteenth_image = AllocatedImage::new_2d(
device,
mem_props,
sixteenth_extent.width,
sixteenth_extent.height,
format,
usage,
)?;
let half_fb = device.create_framebuffer( let make_fb = |view: vk::ImageView, ext: vk::Extent2D| -> Result<vk::Framebuffer> {
&vk::FramebufferCreateInfo::default() Ok(device.create_framebuffer(
.render_pass(self.blur_render_pass) &vk::FramebufferCreateInfo::default()
.attachments(std::slice::from_ref(&half_image.view)) .render_pass(self.blur_render_pass)
.width(half_extent.width) .attachments(std::slice::from_ref(&view))
.height(half_extent.height) .width(ext.width)
.layers(1), .height(ext.height)
None, .layers(1),
)?; None,
let quarter_fb = device.create_framebuffer( )?)
&vk::FramebufferCreateInfo::default() };
.render_pass(self.blur_render_pass) let half_fb = make_fb(half_image.view, half_extent)?;
.attachments(std::slice::from_ref(&quarter_image.view)) let quarter_fb = make_fb(quarter_image.view, quarter_extent)?;
.width(quarter_extent.width) let eighth_fb = make_fb(eighth_image.view, eighth_extent)?;
.height(quarter_extent.height) let sixteenth_fb = make_fb(sixteenth_image.view, sixteenth_extent)?;
.layers(1),
None,
)?;
let half_ds = self.allocate_and_write_tex_descriptor(device, half_image.view)?; let half_ds = self.allocate_and_write_tex_descriptor(device, half_image.view)?;
let quarter_ds = self.allocate_and_write_tex_descriptor(device, quarter_image.view)?; let quarter_ds = self.allocate_and_write_tex_descriptor(device, quarter_image.view)?;
let eighth_ds = self.allocate_and_write_tex_descriptor(device, eighth_image.view)?;
let sixteenth_ds = self.allocate_and_write_tex_descriptor(device, sixteenth_image.view)?;
self.register_external_texture(device, BLUR_TEXTURE_ID, half_image.view)?; self.register_external_texture(device, BLUR_TEXTURE_ID, half_image.view)?;
@ -522,12 +566,20 @@ impl UiVulkanRenderer {
src_extent, src_extent,
half_extent, half_extent,
quarter_extent, quarter_extent,
eighth_extent,
sixteenth_extent,
half_image, half_image,
quarter_image, quarter_image,
eighth_image,
sixteenth_image,
half_fb, half_fb,
quarter_fb, quarter_fb,
eighth_fb,
sixteenth_fb,
half_ds, half_ds,
quarter_ds, quarter_ds,
eighth_ds,
sixteenth_ds,
}); });
Ok(()) Ok(())
} }
@ -545,7 +597,8 @@ impl UiVulkanRenderer {
} }
} }
/// Execute the 2-pass Dual Kawase Blur (Full -> Half -> Quarter -> Half) reading `blur_src_sets[frame_idx]`. /// Execute multi-level Dual Kawase Blur (up to 1/16 pyramid for smooth CSS `blur(14px)` frosted glass)
/// reading `blur_src_sets[frame_idx]` and outputting to `half_image` (`BLUR_TEXTURE_ID`).
/// Caller must ensure `src_image` is in `SHADER_READ_ONLY_OPTIMAL` before calling! /// Caller must ensure `src_image` is in `SHADER_READ_ONLY_OPTIMAL` before calling!
pub unsafe fn record_kawase_blur( pub unsafe fn record_kawase_blur(
&self, &self,
@ -557,9 +610,22 @@ impl UiVulkanRenderer {
let Some(bt) = &self.blur_targets else { let Some(bt) = &self.blur_targets else {
return; return;
}; };
let offset = radius.clamp(0.5, 4.0); let r = radius.clamp(0.5, 4.0);
// Pick pyramid depth so per-pass offset stays in the ghost-free 0.75..1.5 range:
// - r <= 2.0: 2 levels (Half -> Quarter -> Half)
// - r <= 3.0: 3 levels (Half -> Quarter -> Eighth -> Quarter -> Half)
// - r > 3.0: 4 levels (Half -> Quarter -> Eighth -> Sixteenth -> Eighth -> Quarter -> Half, sigma ~14px)
let (levels, offset) = if r > 3.0 {
(4u32, (0.95 + (r - 3.0) * 0.45).clamp(0.95, 1.5))
} else if r > 2.0 {
(3u32, (0.90 + (r - 2.0) * 0.45).clamp(0.90, 1.45))
} else {
(2u32, (0.75 + r * 0.55).clamp(0.75, 1.85))
};
// Pass 1: Downsample Full -> Half let inv = |ext: vk::Extent2D| [1.0 / ext.width.max(1) as f32, 1.0 / ext.height.max(1) as f32];
// Downsample 1: Full -> Half
self.record_blur_subpass( self.record_blur_subpass(
device, device,
cmd, cmd,
@ -568,16 +634,13 @@ impl UiVulkanRenderer {
bt.half_extent, bt.half_extent,
self.blur_src_sets[frame_idx], self.blur_src_sets[frame_idx],
BlurPushConstants { BlurPushConstants {
texel_size: [ texel_size: inv(bt.src_extent),
1.0 / bt.src_extent.width.max(1) as f32,
1.0 / bt.src_extent.height.max(1) as f32,
],
offset, offset,
_pad: 0.0, _pad: 0.0,
}, },
); );
// Pass 2: Downsample Half -> Quarter // Downsample 2: Half -> Quarter
self.record_blur_subpass( self.record_blur_subpass(
device, device,
cmd, cmd,
@ -586,16 +649,79 @@ impl UiVulkanRenderer {
bt.quarter_extent, bt.quarter_extent,
bt.half_ds, bt.half_ds,
BlurPushConstants { BlurPushConstants {
texel_size: [ texel_size: inv(bt.half_extent),
1.0 / bt.half_extent.width.max(1) as f32, offset,
1.0 / bt.half_extent.height.max(1) as f32,
],
offset: offset * 1.25,
_pad: 0.0, _pad: 0.0,
}, },
); );
// Pass 3: Upsample Quarter -> Half (BLUR_TEXTURE_ID samples half_image with linear filter!) if levels >= 3 {
// Downsample 3: Quarter -> Eighth
self.record_blur_subpass(
device,
cmd,
self.blur_down_pipeline,
bt.eighth_fb,
bt.eighth_extent,
bt.quarter_ds,
BlurPushConstants {
texel_size: inv(bt.quarter_extent),
offset,
_pad: 0.0,
},
);
}
if levels >= 4 {
// Downsample 4: Eighth -> Sixteenth
self.record_blur_subpass(
device,
cmd,
self.blur_down_pipeline,
bt.sixteenth_fb,
bt.sixteenth_extent,
bt.eighth_ds,
BlurPushConstants {
texel_size: inv(bt.eighth_extent),
offset,
_pad: 0.0,
},
);
// Upsample: Sixteenth -> Eighth
self.record_blur_subpass(
device,
cmd,
self.blur_up_pipeline,
bt.eighth_fb,
bt.eighth_extent,
bt.sixteenth_ds,
BlurPushConstants {
texel_size: inv(bt.sixteenth_extent),
offset,
_pad: 0.0,
},
);
}
if levels >= 3 {
// Upsample: Eighth -> Quarter
self.record_blur_subpass(
device,
cmd,
self.blur_up_pipeline,
bt.quarter_fb,
bt.quarter_extent,
bt.eighth_ds,
BlurPushConstants {
texel_size: inv(bt.eighth_extent),
offset,
_pad: 0.0,
},
);
}
// Final Upsample: Quarter -> Half (BLUR_TEXTURE_ID samples half_image with linear filter)
self.record_blur_subpass( self.record_blur_subpass(
device, device,
cmd, cmd,
@ -604,11 +730,8 @@ impl UiVulkanRenderer {
bt.half_extent, bt.half_extent,
bt.quarter_ds, bt.quarter_ds,
BlurPushConstants { BlurPushConstants {
texel_size: [ texel_size: inv(bt.quarter_extent),
1.0 / bt.quarter_extent.width.max(1) as f32, offset,
1.0 / bt.quarter_extent.height.max(1) as f32,
],
offset: offset * 1.25,
_pad: 0.0, _pad: 0.0,
}, },
); );
@ -671,6 +794,7 @@ impl UiVulkanRenderer {
} }
/// Execute queued `TextureUpload`s (RGBA8 premultiplied covers/icons + R8 glyph atlas + frees). /// Execute queued `TextureUpload`s (RGBA8 premultiplied covers/icons + R8 glyph atlas + frees).
/// Standalone synchronous upload helper (used for startup 1x1 texture and headless tests).
pub unsafe fn process_uploads( pub unsafe fn process_uploads(
&mut self, &mut self,
device: &ash::Device, device: &ash::Device,
@ -684,8 +808,40 @@ impl UiVulkanRenderer {
if uploads.is_empty() { if uploads.is_empty() {
return Ok(()); return Ok(());
} }
device.reset_fences(&[upload_fence])?;
device.reset_command_buffer(upload_cmd, vk::CommandBufferResetFlags::empty())?;
device.begin_command_buffer(
upload_cmd,
&vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
)?;
let has_copy = self.record_uploads_into_cmd(device, mem_props, upload_cmd, frame_idx, uploads)?;
device.end_command_buffer(upload_cmd)?;
if has_copy {
let submit =
vk::SubmitInfo::default().command_buffers(std::slice::from_ref(&upload_cmd));
device.queue_submit(queue, &[submit], upload_fence)?;
device.wait_for_fences(&[upload_fence], true, u64::MAX)?;
}
Ok(())
}
// First calculate total staging size required to batch all pixel uploads in one GPU submit. /// Record texture uploads directly into the active frame's command buffer using its per-frame
/// staging buffer (zero extra `vkQueueSubmit`, zero CPU `wait_for_fences` stall during scroll!).
/// Caller must have already waited on `in_flight[frame_idx]` and begun `upload_cmd`.
pub unsafe fn record_uploads_into_cmd(
&mut self,
device: &ash::Device,
mem_props: &vk::PhysicalDeviceMemoryProperties,
upload_cmd: vk::CommandBuffer,
frame_idx: usize,
uploads: &[TextureUpload],
) -> Result<bool> {
if uploads.is_empty() {
return Ok(false);
}
// First calculate total staging size required to batch all pixel uploads in one pass.
let mut total_bytes: u64 = 0; let mut total_bytes: u64 = 0;
let mut has_copy = false; let mut has_copy = false;
for up in uploads { for up in uploads {
@ -701,10 +857,10 @@ impl UiVulkanRenderer {
} }
} }
if has_copy && total_bytes > self.staging_buffer.size { let staging_idx = frame_idx % self.staging_buffers.len();
let _ = device.device_wait_idle(); if has_copy && total_bytes > self.staging_buffers[staging_idx].size {
self.staging_buffer.destroy(device); self.staging_buffers[staging_idx].destroy(device);
self.staging_buffer = AllocatedBuffer::new_host_visible( self.staging_buffers[staging_idx] = AllocatedBuffer::new_host_visible(
device, device,
mem_props, mem_props,
total_bytes.next_power_of_two(), total_bytes.next_power_of_two(),
@ -712,18 +868,7 @@ impl UiVulkanRenderer {
)?; )?;
} }
if has_copy {
device.reset_fences(&[upload_fence])?;
device.reset_command_buffer(upload_cmd, vk::CommandBufferResetFlags::empty())?;
device.begin_command_buffer(
upload_cmd,
&vk::CommandBufferBeginInfo::default()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT),
)?;
}
let mut staging_offset: u64 = 0; let mut staging_offset: u64 = 0;
let _ = frame_idx;
let defer_frames = (MAX_FRAMES_IN_FLIGHT as u8).max(2); let defer_frames = (MAX_FRAMES_IN_FLIGHT as u8).max(2);
for up in uploads { for up in uploads {
match up { match up {
@ -788,7 +933,7 @@ impl UiVulkanRenderer {
); );
staging_offset = (staging_offset + 15) & !15; staging_offset = (staging_offset + 15) & !15;
let dst_ptr = (self.staging_buffer.mapped as *mut u8).add(staging_offset as usize); let dst_ptr = (self.staging_buffers[staging_idx].mapped as *mut u8).add(staging_offset as usize);
std::ptr::copy_nonoverlapping(pixels.as_ptr(), dst_ptr, pixels.len()); std::ptr::copy_nonoverlapping(pixels.as_ptr(), dst_ptr, pixels.len());
transition_image_mip_range( transition_image_mip_range(
@ -821,7 +966,7 @@ impl UiVulkanRenderer {
}); });
device.cmd_copy_buffer_to_image( device.cmd_copy_buffer_to_image(
upload_cmd, upload_cmd,
self.staging_buffer.buffer, self.staging_buffers[staging_idx].buffer,
vk_img, vk_img,
vk::ImageLayout::TRANSFER_DST_OPTIMAL, vk::ImageLayout::TRANSFER_DST_OPTIMAL,
&[region], &[region],
@ -949,7 +1094,7 @@ impl UiVulkanRenderer {
} }
staging_offset = (staging_offset + 15) & !15; staging_offset = (staging_offset + 15) & !15;
let dst_ptr = (self.staging_buffer.mapped as *mut u8).add(staging_offset as usize); let dst_ptr = (self.staging_buffers[staging_idx].mapped as *mut u8).add(staging_offset as usize);
std::ptr::copy_nonoverlapping(pixels.as_ptr(), dst_ptr, pixels.len()); std::ptr::copy_nonoverlapping(pixels.as_ptr(), dst_ptr, pixels.len());
transition_image_layout( transition_image_layout(
@ -984,7 +1129,7 @@ impl UiVulkanRenderer {
}); });
device.cmd_copy_buffer_to_image( device.cmd_copy_buffer_to_image(
upload_cmd, upload_cmd,
self.staging_buffer.buffer, self.staging_buffers[staging_idx].buffer,
img.image, img.image,
vk::ImageLayout::TRANSFER_DST_OPTIMAL, vk::ImageLayout::TRANSFER_DST_OPTIMAL,
&[region], &[region],
@ -1007,15 +1152,7 @@ impl UiVulkanRenderer {
} }
} }
if has_copy { Ok(has_copy)
device.end_command_buffer(upload_cmd)?;
let submit =
vk::SubmitInfo::default().command_buffers(std::slice::from_ref(&upload_cmd));
device.queue_submit(queue, &[submit], upload_fence)?;
device.wait_for_fences(&[upload_fence], true, u64::MAX)?;
}
Ok(())
} }
/// Upload the frame's `UiInstance` slice into the per-frame SSBO before command recording. /// Upload the frame's `UiInstance` slice into the per-frame SSBO before command recording.
@ -1174,8 +1311,12 @@ impl UiVulkanRenderer {
if let Some(mut bt) = self.blur_targets.take() { if let Some(mut bt) = self.blur_targets.take() {
device.destroy_framebuffer(bt.half_fb, None); device.destroy_framebuffer(bt.half_fb, None);
device.destroy_framebuffer(bt.quarter_fb, None); device.destroy_framebuffer(bt.quarter_fb, None);
device.destroy_framebuffer(bt.eighth_fb, None);
device.destroy_framebuffer(bt.sixteenth_fb, None);
bt.half_image.destroy(device); bt.half_image.destroy(device);
bt.quarter_image.destroy(device); bt.quarter_image.destroy(device);
bt.eighth_image.destroy(device);
bt.sixteenth_image.destroy(device);
} }
for (_, mut tex) in self.deferred_frees.drain(..) { for (_, mut tex) in self.deferred_frees.drain(..) {
if let Some(mut img) = tex.image.take() { if let Some(mut img) = tex.image.take() {
@ -1190,7 +1331,9 @@ impl UiVulkanRenderer {
for buf in &mut self.instance_buffers { for buf in &mut self.instance_buffers {
buf.destroy(device); buf.destroy(device);
} }
self.staging_buffer.destroy(device); for buf in &mut self.staging_buffers {
buf.destroy(device);
}
device.destroy_sampler(self.sampler_linear, None); device.destroy_sampler(self.sampler_linear, None);
device.destroy_pipeline(self.blur_down_pipeline, None); device.destroy_pipeline(self.blur_down_pipeline, None);
device.destroy_pipeline(self.blur_up_pipeline, None); device.destroy_pipeline(self.blur_up_pipeline, None);

View file

@ -402,6 +402,8 @@ fn build_reference_matched_shell(
default_email: None, default_email: None,
has_plus: true, has_plus: true,
avatar_uri: Some("test.local/avatar_marwy/%%".into()), avatar_uri: Some("test.local/avatar_marwy/%%".into()),
plus_balance: Some(0),
collection_hue: None,
}); });
let mut app = AppState::new_visual_test( let mut app = AppState::new_visual_test(

View file

@ -108,6 +108,8 @@ fn make_base_shell(
default_email: Some("marwy@yandex.ru".into()), default_email: Some("marwy@yandex.ru".into()),
has_plus: true, has_plus: true,
avatar_uri: None, avatar_uri: None,
plus_balance: Some(0),
collection_hue: None,
}); });
let track = Track { let track = Track {
id: "t_1".into(), id: "t_1".into(),
@ -897,8 +899,8 @@ fn test_ext_09_light_theme_zero_dark_surfaces_and_high_contrast() {
shell_px shell_px
); );
// 2. Content card whitespace (right margin x=1240, y=220) MUST be pure #FFFFFF (255, 255, 255), NOT #121212! // 2. Content card whitespace (right padding gutter x=1256, y=220) MUST be pure #FFFFFF (255, 255, 255), NOT #121212!
let card_px = img.get_pixel(1240, 220).0; let card_px = img.get_pixel(1256, 220).0;
assert!( assert!(
card_px[0] >= 245 && card_px[1] >= 245 && card_px[2] >= 245, card_px[0] >= 245 && card_px[1] >= 245 && card_px[2] >= 245,
"[{}] Light theme content card should be #FFFFFF, got {:?}", "[{}] Light theme content card should be #FFFFFF, got {:?}",
@ -1905,30 +1907,35 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
genre: Some("electronic".into()), genre: Some("electronic".into()),
is_explicit: false, is_explicit: false,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}; };
shell.app.landing.rich_new_releases = vec![ shell.app.landing.rich_new_releases = vec![
NewReleaseItem { NewReleaseItem {
album: mk_album("nr1", "Neon Horizon", "SALUKI"), album: mk_album("nr1", "Neon Horizon", "SALUKI"),
artist_cover_uri: None, artist_cover_uri: None,
cover_color: Some("#3B4CA8".into()), cover_color: Some("#3B4CA8".into()),
average_color: Some("#27316E".into()),
release_date: Some("2026-11-20".into()), release_date: Some("2026-11-20".into()),
}, },
NewReleaseItem { NewReleaseItem {
album: mk_album("nr2", "Velvet Pulse", "Mirele"), album: mk_album("nr2", "Velvet Pulse", "Mirele"),
artist_cover_uri: None, artist_cover_uri: None,
cover_color: Some("#7B2D5F".into()), cover_color: Some("#7B2D5F".into()),
average_color: Some("#521D3F".into()),
release_date: Some("2026-11-18".into()), release_date: Some("2026-11-18".into()),
}, },
NewReleaseItem { NewReleaseItem {
album: mk_album("nr3", "Night Drive", "SLAVA MARLOW"), album: mk_album("nr3", "Night Drive", "SLAVA MARLOW"),
artist_cover_uri: None, artist_cover_uri: None,
cover_color: Some("#1E6B52".into()), cover_color: Some("#1E6B52".into()),
average_color: Some("#144737".into()),
release_date: Some("2026-11-15".into()), release_date: Some("2026-11-15".into()),
}, },
NewReleaseItem { NewReleaseItem {
album: mk_album("nr4", "Solar Flare", "OG BLESS"), album: mk_album("nr4", "Solar Flare", "OG BLESS"),
artist_cover_uri: None, artist_cover_uri: None,
cover_color: Some("#8F4A1E".into()), cover_color: Some("#8F4A1E".into()),
average_color: Some("#5E3114".into()),
release_date: Some("2026-11-12".into()), release_date: Some("2026-11-12".into()),
}, },
]; ];
@ -1941,6 +1948,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
header: "Vibe".into(), header: "Vibe".into(),
seeds: vec!["mood:energetic".into()], seeds: vec!["mood:energetic".into()],
color_hex: Some("#D94E2A".into()), color_hex: Some("#D94E2A".into()),
wave_text_hex: None,
background_image_url: None, background_image_url: None,
image_url: None, image_url: None,
}, },
@ -1949,6 +1957,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
header: "Vibe".into(), header: "Vibe".into(),
seeds: vec!["mood:calm".into()], seeds: vec!["mood:calm".into()],
color_hex: Some("#2F55A4".into()), color_hex: Some("#2F55A4".into()),
wave_text_hex: None,
background_image_url: None, background_image_url: None,
image_url: None, image_url: None,
}, },
@ -1957,6 +1966,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
header: "Vibe".into(), header: "Vibe".into(),
seeds: vec!["genre:electronic".into()], seeds: vec!["genre:electronic".into()],
color_hex: Some("#7C3AED".into()), color_hex: Some("#7C3AED".into()),
wave_text_hex: None,
background_image_url: None, background_image_url: None,
image_url: None, image_url: None,
}, },
@ -1969,6 +1979,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
header: "Vibe".into(), header: "Vibe".into(),
seeds: vec!["activity:workout".into()], seeds: vec!["activity:workout".into()],
color_hex: Some("#0F766E".into()), color_hex: Some("#0F766E".into()),
wave_text_hex: None,
background_image_url: None, background_image_url: None,
image_url: None, image_url: None,
}], }],
@ -2118,6 +2129,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
cashback_title: Some("Кешбэк 15%".into()), cashback_title: Some("Кешбэк 15%".into()),
cover_color: Some("#4C2A85".into()), cover_color: Some("#4C2A85".into()),
event_kind: Some("concert".into()), event_kind: Some("concert".into()),
content_rating: Some("18+".into()),
}, },
ConcertItem { ConcertItem {
id: "con_2".into(), id: "con_2".into(),
@ -2134,6 +2146,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
cashback_title: None, cashback_title: None,
cover_color: Some("#1D5B79".into()), cover_color: Some("#1D5B79".into()),
event_kind: Some("concert".into()), event_kind: Some("concert".into()),
content_rating: Some("16+".into()),
}, },
ConcertItem { ConcertItem {
id: "con_3".into(), id: "con_3".into(),
@ -2150,6 +2163,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
cashback_title: None, cashback_title: None,
cover_color: Some("#8C2F39".into()), cover_color: Some("#8C2F39".into()),
event_kind: Some("concert".into()), event_kind: Some("concert".into()),
content_rating: Some("16+".into()),
}, },
ConcertItem { ConcertItem {
id: "con_4".into(), id: "con_4".into(),
@ -2166,6 +2180,7 @@ fn test_ext_17_for_you_collection_concerts_words_fullscreen() {
cashback_title: None, cashback_title: None,
cover_color: Some("#2D4F1E".into()), cover_color: Some("#2D4F1E".into()),
event_kind: Some("concert".into()), event_kind: Some("concert".into()),
content_rating: Some("18+".into()),
}, },
]; ];
@ -2470,6 +2485,7 @@ fn test_ext_18_qa_sync_lyrics_scroll_concerts_duplicate_albums() {
genre: Some("pop".into()), genre: Some("pop".into()),
is_explicit: false, is_explicit: false,
content_type: Some("album".into()), content_type: Some("album".into()),
..Default::default()
}; };
let std_alb = mk_dup("alb_std", None); let std_alb = mk_dup("alb_std", None);
let dlx_alb = mk_dup("alb_dlx", Some("Deluxe")); let dlx_alb = mk_dup("alb_dlx", Some("Deluxe"));
@ -2544,6 +2560,9 @@ fn test_ext_15_release_notes_modal_update_notification_and_download_ring() {
html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v9.9.9".into(), html_url: "https://git.tatar/marwy/yandex-music-rs/releases/tag/v9.9.9".into(),
date: "2026-11-28".into(), date: "2026-11-28".into(),
body: "## Новое\n- Тестовое обновление".into(), body: "## Новое\n- Тестовое обновление".into(),
asset_name: None,
asset_url: None,
sha256sums_url: None,
}); });
shell.app.release_notes_modal_open = true; shell.app.release_notes_modal_open = true;
@ -2586,6 +2605,16 @@ fn test_ext_19_official_settings_sound_quality_equalizer_and_shortcuts_modals()
assert!(img_sc.width() == NATIVE_W && img_sc.height() == NATIVE_H); assert!(img_sc.width() == NATIVE_W && img_sc.height() == NATIVE_H);
shell.app.shortcuts_modal_open = false; shell.app.shortcuts_modal_open = false;
shell.app.clear_memory_modal_open = true;
let img_cm = render_single_frame(&mut vk, &mut shell, 0.056);
assert!(img_cm.width() == NATIVE_W && img_cm.height() == NATIVE_H);
shell.app.clear_memory_modal_open = false;
shell.app.about_app_modal_open = true;
let img_ab = render_single_frame(&mut vk, &mut shell, 0.060);
assert!(img_ab.width() == NATIVE_W && img_ab.height() == NATIVE_H);
shell.app.about_app_modal_open = false;
for &style in yandex_music_rs::config::PlayerThumbStyle::ALL { for &style in yandex_music_rs::config::PlayerThumbStyle::ALL {
shell.app.config.player_thumb = style; shell.app.config.player_thumb = style;
let img_th = render_single_frame(&mut vk, &mut shell, 0.064); let img_th = render_single_frame(&mut vk, &mut shell, 0.064);