973 lines
34 KiB
Rust
973 lines
34 KiB
Rust
//! Native Windows desktop integrations matching Yandex Music Electron `index.js`:
|
||
//! 1. System Tray icon + context menu (`tray-icon`)
|
||
//! 2. Windows SMTC (System Media Transport Controls — lockscreen/volume overlay via `souvlaki`)
|
||
//! 3. Isolated zero-resident-RAM WebView2 OAuth subprocess (`--auth-webview` via `wry`)
|
||
|
||
#[derive(Debug, Clone)]
|
||
pub enum NativeEvent {
|
||
ShowWindow,
|
||
ToggleWindow,
|
||
CheckUpdates,
|
||
OpenUrl(&'static str),
|
||
QuitApp,
|
||
Play,
|
||
Pause,
|
||
TogglePlay,
|
||
Next,
|
||
Prev,
|
||
Stop,
|
||
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
|
||
// =============================================================================
|
||
#[cfg(windows)]
|
||
mod imp {
|
||
use super::tray_menu_win;
|
||
use super::{NativeEvent, TrayLabels};
|
||
use crate::api::models::Track;
|
||
use crate::api::signing::extract_oauth_token;
|
||
use crate::api::YANDEX_OAUTH_URL;
|
||
use crate::covers::CoverCache;
|
||
use crossbeam_channel::{unbounded, Receiver, Sender};
|
||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||
use souvlaki::{
|
||
MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition,
|
||
PlatformConfig,
|
||
};
|
||
use std::io::{BufRead, BufReader, Write};
|
||
use std::process::{Command, Stdio};
|
||
use std::time::Duration;
|
||
use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
|
||
use winit::application::ApplicationHandler;
|
||
use winit::dpi::LogicalSize;
|
||
use winit::event::WindowEvent;
|
||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||
use winit::window::{Window, WindowAttributes, WindowId};
|
||
|
||
const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:";
|
||
|
||
pub struct NativeDesktop {
|
||
tray: Option<TrayIcon>,
|
||
is_ru: bool,
|
||
is_dark: bool,
|
||
window_visible: bool,
|
||
smtc: Option<MediaControls>,
|
||
tx_events: Sender<NativeEvent>,
|
||
rx_events: Receiver<NativeEvent>,
|
||
last_track_id: Option<String>,
|
||
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 {
|
||
pub fn new(window: &Window, is_ru: bool) -> Self {
|
||
let labels = TrayLabels::for_lang(is_ru);
|
||
let tray = (|| -> Option<TrayIcon> {
|
||
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()
|
||
.with_tooltip(labels.tooltip)
|
||
.with_icon(icon)
|
||
.build()
|
||
.ok()
|
||
})();
|
||
|
||
// 2. Build Windows SMTC (`souvlaki::MediaControls`) bound to our Win32 HWND
|
||
let (tx_events, rx_events): (Sender<NativeEvent>, Receiver<NativeEvent>) = unbounded();
|
||
let tx_smtc = tx_events.clone();
|
||
let smtc = (|| -> Option<MediaControls> {
|
||
let hwnd = match window.window_handle().ok()?.as_raw() {
|
||
RawWindowHandle::Win32(h) => h.hwnd.get() as *mut std::ffi::c_void,
|
||
_ => return None,
|
||
};
|
||
let config = PlatformConfig {
|
||
dbus_name: "yandex_music_rs",
|
||
display_name: "Яндекс Музыка",
|
||
hwnd: Some(hwnd),
|
||
};
|
||
let mut controls = MediaControls::new(config).ok()?;
|
||
controls
|
||
.attach(move |ev: MediaControlEvent| {
|
||
let mapped = match ev {
|
||
MediaControlEvent::Play => Some(NativeEvent::Play),
|
||
MediaControlEvent::Pause => Some(NativeEvent::Pause),
|
||
MediaControlEvent::Toggle => Some(NativeEvent::TogglePlay),
|
||
MediaControlEvent::Next => Some(NativeEvent::Next),
|
||
MediaControlEvent::Previous => Some(NativeEvent::Prev),
|
||
MediaControlEvent::Stop => Some(NativeEvent::Stop),
|
||
MediaControlEvent::SetPosition(MediaPosition(dur)) => {
|
||
Some(NativeEvent::SeekMs(dur.as_millis() as u64))
|
||
}
|
||
_ => None,
|
||
};
|
||
if let Some(m) = mapped {
|
||
let _ = tx_smtc.send(m);
|
||
}
|
||
})
|
||
.ok()?;
|
||
Some(controls)
|
||
})();
|
||
|
||
Self {
|
||
tray,
|
||
is_ru,
|
||
is_dark: true,
|
||
window_visible: true,
|
||
smtc,
|
||
tx_events,
|
||
rx_events,
|
||
last_track_id: None,
|
||
last_playing: None,
|
||
can_prev: false,
|
||
can_next: false,
|
||
}
|
||
}
|
||
|
||
pub fn set_dark_mode(&mut self, is_dark: bool) {
|
||
self.is_dark = is_dark;
|
||
}
|
||
|
||
pub fn set_language(&mut self, is_ru: bool) {
|
||
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> {
|
||
let mut out = Vec::new();
|
||
|
||
while let Ok(ev) = self.rx_events.try_recv() {
|
||
out.push(ev);
|
||
}
|
||
|
||
while let Ok(ev) = TrayIconEvent::receiver().try_recv() {
|
||
match ev {
|
||
TrayIconEvent::Click {
|
||
button: MouseButton::Left,
|
||
button_state: MouseButtonState::Up,
|
||
..
|
||
} => {
|
||
tray_menu_win::close_tray_menu();
|
||
out.push(NativeEvent::ToggleWindow);
|
||
}
|
||
TrayIconEvent::Click {
|
||
button: MouseButton::Right,
|
||
button_state: MouseButtonState::Up,
|
||
..
|
||
} => {
|
||
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,
|
||
);
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
out
|
||
}
|
||
|
||
pub fn sync_playback(
|
||
&mut self,
|
||
track: Option<&Track>,
|
||
is_playing: bool,
|
||
position_ms: u64,
|
||
can_prev: bool,
|
||
can_next: bool,
|
||
) {
|
||
self.can_prev = can_prev;
|
||
self.can_next = can_next;
|
||
let Some(ref mut smtc) = self.smtc else {
|
||
self.last_playing = Some(is_playing);
|
||
return;
|
||
};
|
||
|
||
let track_id = track.map(|t| t.id.as_str());
|
||
if track_id != self.last_track_id.as_deref() {
|
||
self.last_track_id = track_id.map(String::from);
|
||
if let Some(tr) = track {
|
||
let artists = tr.artists_string();
|
||
let cover_url = tr
|
||
.cover_uri
|
||
.as_deref()
|
||
.map(|u| CoverCache::format_url(u, 400));
|
||
let _ = smtc.set_metadata(MediaMetadata {
|
||
title: Some(&tr.title),
|
||
artist: Some(&artists),
|
||
album: tr.album_title.as_deref(),
|
||
cover_url: cover_url.as_deref(),
|
||
duration: Some(Duration::from_millis(tr.duration_ms)),
|
||
});
|
||
} else {
|
||
let _ = smtc.set_playback(MediaPlayback::Stopped);
|
||
self.last_playing = None;
|
||
return;
|
||
}
|
||
}
|
||
|
||
if track.is_some() && self.last_playing != Some(is_playing) {
|
||
self.last_playing = Some(is_playing);
|
||
let progress = Some(MediaPosition(Duration::from_millis(position_ms)));
|
||
let state = if is_playing {
|
||
MediaPlayback::Playing { progress }
|
||
} else {
|
||
MediaPlayback::Paused { progress }
|
||
};
|
||
let _ = smtc.set_playback(state);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Exact official Yandex Music Desktop 5.129.0 32×32 tray icon (`resources/assets/icons/icon_32x32.png`)
|
||
fn build_tray_icon() -> Option<tray_icon::Icon> {
|
||
let png_bytes = include_bytes!("../../assets/icons/tray_32.png");
|
||
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
|
||
let (w, h) = img.dimensions();
|
||
tray_icon::Icon::from_rgba(img.into_raw(), w, h).ok()
|
||
}
|
||
|
||
/// Exact official Yandex Music Desktop 5.129.0 48×48 window/taskbar icon (`resources/assets/icons/icon_48x48.png`)
|
||
pub fn load_window_icon() -> Option<winit::window::Icon> {
|
||
let png_bytes = include_bytes!("../../assets/icons/app_48.png");
|
||
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
|
||
let (w, h) = img.dimensions();
|
||
winit::window::Icon::from_rgba(img.into_raw(), w, h).ok()
|
||
}
|
||
|
||
// =========================================================================
|
||
// ISOLATED ZERO-RESIDENT-RAM WEBVIEW2 OAUTH SUBPROCESS (`--auth-webview`)
|
||
// =========================================================================
|
||
|
||
struct AuthWebViewApp {
|
||
window: Option<Window>,
|
||
_webview: Option<wry::WebView>,
|
||
}
|
||
|
||
impl ApplicationHandler for AuthWebViewApp {
|
||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||
if self.window.is_some() {
|
||
return;
|
||
}
|
||
let attrs = WindowAttributes::default()
|
||
.with_title("Вход — Яндекс ID")
|
||
.with_inner_size(LogicalSize::new(480.0, 680.0))
|
||
.with_resizable(true);
|
||
let window = match event_loop.create_window(attrs) {
|
||
Ok(w) => w,
|
||
Err(_) => {
|
||
event_loop.exit();
|
||
return;
|
||
}
|
||
};
|
||
|
||
let emit_and_exit = |url: &str| -> bool {
|
||
if url.contains("access_token=") {
|
||
if let Some(tok) = extract_oauth_token(url) {
|
||
println!("{}{}", OAUTH_TOKEN_PREFIX, tok);
|
||
let _ = std::io::stdout().flush();
|
||
std::process::exit(0);
|
||
}
|
||
}
|
||
true
|
||
};
|
||
|
||
// Watch both full navigations AND hash/fragment updates (`#access_token=...`)
|
||
let init_js = r#"
|
||
(function() {
|
||
function check() {
|
||
try {
|
||
var h = window.location.href || '';
|
||
if (h.indexOf('access_token=') !== -1) {
|
||
window.ipc.postMessage(h);
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
check();
|
||
window.addEventListener('hashchange', check);
|
||
setInterval(check, 250);
|
||
})();
|
||
"#;
|
||
|
||
let webview = wry::WebViewBuilder::new()
|
||
.with_url(YANDEX_OAUTH_URL)
|
||
.with_initialization_script(init_js)
|
||
.with_navigation_handler(move |url| emit_and_exit(&url))
|
||
.with_ipc_handler(move |req| {
|
||
let _ = emit_and_exit(req.body());
|
||
})
|
||
.build(&window);
|
||
|
||
match webview {
|
||
Ok(wv) => {
|
||
self.window = Some(window);
|
||
self._webview = Some(wv);
|
||
}
|
||
Err(e) => {
|
||
eprintln!("WebView2 init failed: {}", e);
|
||
std::process::exit(2);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn window_event(
|
||
&mut self,
|
||
event_loop: &ActiveEventLoop,
|
||
_id: WindowId,
|
||
event: WindowEvent,
|
||
) {
|
||
if matches!(event, WindowEvent::CloseRequested) {
|
||
event_loop.exit();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Entry point for the short-lived `--auth-webview` subprocess.
|
||
/// Exits immediately upon capturing the OAuth token — 0 bytes of WebView2 stay in main app RAM!
|
||
pub fn run_auth_webview_subprocess() {
|
||
let event_loop = match EventLoop::new() {
|
||
Ok(el) => el,
|
||
Err(_) => std::process::exit(1),
|
||
};
|
||
let mut app = AuthWebViewApp {
|
||
window: None,
|
||
_webview: None,
|
||
};
|
||
let _ = event_loop.run_app(&mut app);
|
||
}
|
||
|
||
/// Spawn the isolated `--auth-webview` subprocess and return the captured OAuth token.
|
||
pub fn spawn_auth_webview_subprocess() -> anyhow::Result<String> {
|
||
let exe = std::env::current_exe()?;
|
||
let mut child = Command::new(exe)
|
||
.arg("--auth-webview")
|
||
.stdout(Stdio::piped())
|
||
.stderr(Stdio::null())
|
||
.spawn()?;
|
||
|
||
let stdout = child
|
||
.stdout
|
||
.take()
|
||
.ok_or_else(|| anyhow::anyhow!("Missing auth subprocess stdout"))?;
|
||
let reader = BufReader::new(stdout);
|
||
for line in reader.lines() {
|
||
if let Ok(l) = line {
|
||
if let Some(tok) = l.strip_prefix(OAUTH_TOKEN_PREFIX) {
|
||
let _ = child.wait();
|
||
return Ok(tok.trim().to_string());
|
||
}
|
||
}
|
||
}
|
||
let status = child.wait()?;
|
||
if status.code() == Some(2) {
|
||
anyhow::bail!("WebView2 runtime unavailable")
|
||
}
|
||
anyhow::bail!("Окно входа закрыто")
|
||
}
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
mod imp {
|
||
use super::{
|
||
NativeEvent, TrayLabels, RECOMMENDATIONS_URL, SUPPORT_CHAT_URL, TERMS_OF_USE_URL,
|
||
};
|
||
use crate::api::models::Track;
|
||
use crossbeam_channel::{unbounded, Receiver, Sender};
|
||
use ksni::blocking::{Handle, TrayMethods};
|
||
use std::io::{BufRead, BufReader};
|
||
use std::process::{Command, Stdio};
|
||
use std::sync::Arc;
|
||
use winit::window::Window;
|
||
|
||
const OAUTH_TOKEN_PREFIX: &str = "YM_OAUTH_TOKEN:";
|
||
|
||
struct LinuxTray {
|
||
tx: Sender<NativeEvent>,
|
||
icons: Arc<Vec<ksni::Icon>>,
|
||
is_ru: bool,
|
||
window_visible: bool,
|
||
is_playing: bool,
|
||
can_prev: bool,
|
||
can_next: bool,
|
||
track_summary: String,
|
||
}
|
||
|
||
impl ksni::Tray for LinuxTray {
|
||
fn id(&self) -> String {
|
||
"yandex-music-rs".into()
|
||
}
|
||
|
||
fn category(&self) -> ksni::Category {
|
||
ksni::Category::ApplicationStatus
|
||
}
|
||
|
||
fn title(&self) -> String {
|
||
TrayLabels::for_lang(self.is_ru).tooltip.into()
|
||
}
|
||
|
||
fn icon_name(&self) -> String {
|
||
"yandex-music-rs".into()
|
||
}
|
||
|
||
fn icon_pixmap(&self) -> Vec<ksni::Icon> {
|
||
(*self.icons).clone()
|
||
}
|
||
|
||
fn tool_tip(&self) -> ksni::ToolTip {
|
||
ksni::ToolTip {
|
||
icon_name: "yandex-music-rs".into(),
|
||
icon_pixmap: Vec::new(),
|
||
title: self.title(),
|
||
description: self.track_summary.clone(),
|
||
}
|
||
}
|
||
|
||
fn activate(&mut self, _x: i32, _y: i32) {
|
||
let _ = self.tx.send(NativeEvent::ToggleWindow);
|
||
}
|
||
|
||
fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
|
||
use ksni::menu::*;
|
||
let labels = TrayLabels::for_lang(self.is_ru);
|
||
let toggle_label = if self.window_visible {
|
||
labels.roll_up
|
||
} else {
|
||
labels.unwrap
|
||
};
|
||
let play_label = if self.is_playing {
|
||
labels.pause
|
||
} else {
|
||
labels.play
|
||
};
|
||
|
||
vec![
|
||
StandardItem {
|
||
label: toggle_label.into(),
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::ToggleWindow);
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.into(),
|
||
StandardItem {
|
||
label: labels.check_updates.into(),
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::CheckUpdates);
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.into(),
|
||
MenuItem::Separator,
|
||
StandardItem {
|
||
label: play_label.into(),
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::TogglePlay);
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.into(),
|
||
StandardItem {
|
||
label: labels.prev.into(),
|
||
enabled: self.can_prev,
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::Prev);
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.into(),
|
||
StandardItem {
|
||
label: labels.next.into(),
|
||
enabled: self.can_next,
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::Next);
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.into(),
|
||
MenuItem::Separator,
|
||
SubMenu {
|
||
label: labels.about.into(),
|
||
submenu: vec![
|
||
StandardItem {
|
||
label: labels.terms.into(),
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::OpenUrl(TERMS_OF_USE_URL));
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.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()
|
||
}
|
||
.into(),
|
||
MenuItem::Separator,
|
||
StandardItem {
|
||
label: labels.quit.into(),
|
||
activate: Box::new(|this: &mut Self| {
|
||
let _ = this.tx.send(NativeEvent::QuitApp);
|
||
}),
|
||
..Default::default()
|
||
}
|
||
.into(),
|
||
]
|
||
}
|
||
}
|
||
|
||
fn decode_ksni_icon(png_bytes: &[u8]) -> Option<ksni::Icon> {
|
||
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
|
||
let (w, h) = img.dimensions();
|
||
let mut data = img.into_raw();
|
||
for px in data.chunks_exact_mut(4) {
|
||
px.rotate_right(1); // RGBA -> ARGB32 network byte order (SNI spec)
|
||
}
|
||
Some(ksni::Icon {
|
||
width: w as i32,
|
||
height: h as i32,
|
||
data,
|
||
})
|
||
}
|
||
|
||
pub struct NativeDesktop {
|
||
handle: Option<Handle<LinuxTray>>,
|
||
rx: Receiver<NativeEvent>,
|
||
is_ru: bool,
|
||
last_playing: Option<bool>,
|
||
last_track_id: Option<String>,
|
||
last_can_prev: Option<bool>,
|
||
last_can_next: Option<bool>,
|
||
}
|
||
|
||
impl Drop for NativeDesktop {
|
||
fn drop(&mut self) {
|
||
if let Some(ref handle) = self.handle {
|
||
handle.shutdown();
|
||
}
|
||
}
|
||
}
|
||
|
||
impl NativeDesktop {
|
||
pub fn new(_window: &Window, is_ru: bool) -> Self {
|
||
let (tx, rx) = unbounded();
|
||
let mut pixmaps = Vec::with_capacity(2);
|
||
if let Some(ic32) = decode_ksni_icon(include_bytes!("../../assets/icons/tray_32.png")) {
|
||
pixmaps.push(ic32);
|
||
}
|
||
if let Some(ic48) = decode_ksni_icon(include_bytes!("../../assets/icons/app_48.png")) {
|
||
pixmaps.push(ic48);
|
||
}
|
||
let tray = LinuxTray {
|
||
tx,
|
||
icons: Arc::new(pixmaps),
|
||
is_ru,
|
||
window_visible: true,
|
||
is_playing: false,
|
||
can_prev: false,
|
||
can_next: false,
|
||
track_summary: String::new(),
|
||
};
|
||
let handle = tray.assume_sni_available(true).spawn().ok();
|
||
Self {
|
||
handle,
|
||
rx,
|
||
is_ru,
|
||
last_playing: None,
|
||
last_track_id: None,
|
||
last_can_prev: Some(false),
|
||
last_can_next: Some(false),
|
||
}
|
||
}
|
||
|
||
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 {
|
||
handle.update(move |t| {
|
||
t.window_visible = visible;
|
||
});
|
||
}
|
||
}
|
||
|
||
pub fn poll_events(&self) -> Vec<NativeEvent> {
|
||
let mut out = Vec::new();
|
||
while let Ok(ev) = self.rx.try_recv() {
|
||
out.push(ev);
|
||
}
|
||
out
|
||
}
|
||
|
||
pub fn sync_playback(
|
||
&mut self,
|
||
track: Option<&Track>,
|
||
is_playing: bool,
|
||
_pos_ms: u64,
|
||
can_prev: bool,
|
||
can_next: bool,
|
||
) {
|
||
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
|
||
&& self.last_can_prev == Some(can_prev)
|
||
&& self.last_can_next == Some(can_next)
|
||
{
|
||
return;
|
||
}
|
||
self.last_playing = Some(is_playing);
|
||
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
|
||
.map(|tr| {
|
||
let artists = tr.artists_string();
|
||
if artists.is_empty() {
|
||
tr.title.clone()
|
||
} else {
|
||
format!("{} — {}", artists, tr.title)
|
||
}
|
||
})
|
||
.unwrap_or_default();
|
||
if let Some(ref handle) = self.handle {
|
||
handle.update(move |t| {
|
||
t.is_playing = is_playing;
|
||
t.can_prev = can_prev;
|
||
t.can_next = can_next;
|
||
t.track_summary = summary;
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
pub fn load_window_icon() -> Option<winit::window::Icon> {
|
||
let png_bytes = include_bytes!("../../assets/icons/app_icon.png");
|
||
let img = image::load_from_memory(png_bytes).ok()?.to_rgba8();
|
||
let (w, h) = img.dimensions();
|
||
winit::window::Icon::from_rgba(img.into_raw(), w, h).ok()
|
||
}
|
||
|
||
/// Entry point for the short-lived `yandex-music-auth` subprocess on Linux (GTK3 + WebKitGTK).
|
||
/// Compiled ONLY when `--features linux-webview` is enabled so the main player binary has
|
||
/// zero `libwebkit2gtk` / `libjavascriptcoregtk` / `libgtk-3` DT_NEEDED dependencies!
|
||
#[cfg(feature = "linux-webview")]
|
||
pub fn run_auth_webview_subprocess() {
|
||
use crate::api::signing::extract_oauth_token;
|
||
use crate::api::YANDEX_OAUTH_URL;
|
||
use gtk::prelude::*;
|
||
use std::io::Write;
|
||
use wry::{WebViewBuilder, WebViewBuilderExtUnix};
|
||
|
||
// Avoid blank WebKitGTK window on NVIDIA/Wayland/VM drivers during OAuth login.
|
||
if std::env::var_os("WEBKIT_DISABLE_DMABUF_RENDERER").is_none() {
|
||
std::env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
|
||
}
|
||
|
||
if gtk::init().is_err() {
|
||
eprintln!("GTK init failed");
|
||
std::process::exit(2);
|
||
}
|
||
|
||
gtk::glib::set_prgname(Some("yandex-music-rs"));
|
||
let window = gtk::Window::new(gtk::WindowType::Toplevel);
|
||
window.set_title("Вход — Яндекс ID");
|
||
window.set_icon_name(Some("yandex-music-rs"));
|
||
window.set_default_size(480, 680);
|
||
window.set_resizable(true);
|
||
window.connect_delete_event(|_, _| {
|
||
gtk::main_quit();
|
||
gtk::glib::Propagation::Proceed
|
||
});
|
||
|
||
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
|
||
window.add(&vbox);
|
||
|
||
let emit_and_exit = |url: &str| -> bool {
|
||
if url.contains("access_token=") {
|
||
if let Some(tok) = extract_oauth_token(url) {
|
||
println!("{}{}", OAUTH_TOKEN_PREFIX, tok);
|
||
let _ = std::io::stdout().flush();
|
||
std::process::exit(0);
|
||
}
|
||
}
|
||
true
|
||
};
|
||
|
||
let init_js = r#"
|
||
(function() {
|
||
function check() {
|
||
try {
|
||
var h = window.location.href || '';
|
||
if (h.indexOf('access_token=') !== -1) {
|
||
window.ipc.postMessage(h);
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
check();
|
||
window.addEventListener('hashchange', check);
|
||
setInterval(check, 250);
|
||
})();
|
||
"#;
|
||
|
||
let webview = WebViewBuilder::new()
|
||
.with_url(YANDEX_OAUTH_URL)
|
||
.with_initialization_script(init_js)
|
||
.with_navigation_handler(move |url| emit_and_exit(&url))
|
||
.with_ipc_handler(move |req| {
|
||
let _ = emit_and_exit(req.body());
|
||
})
|
||
.build_gtk(&vbox);
|
||
|
||
let _webview = match webview {
|
||
Ok(wv) => wv,
|
||
Err(e) => {
|
||
eprintln!("WebKitGTK init failed: {}", e);
|
||
std::process::exit(2);
|
||
}
|
||
};
|
||
|
||
window.show_all();
|
||
gtk::main();
|
||
}
|
||
|
||
#[cfg(not(feature = "linux-webview"))]
|
||
pub fn run_auth_webview_subprocess() {
|
||
eprintln!("yandex-music-auth helper required");
|
||
std::process::exit(2);
|
||
}
|
||
|
||
/// Spawn the isolated `yandex-music-auth` helper binary (or `--auth-webview` if built with
|
||
/// `linux-webview`) and return the captured OAuth token.
|
||
pub fn spawn_auth_webview_subprocess() -> anyhow::Result<String> {
|
||
let exe = std::env::current_exe()?;
|
||
let sibling_helper = exe.with_file_name("yandex-music-auth");
|
||
|
||
let mut child = if sibling_helper.is_file() {
|
||
Command::new(&sibling_helper)
|
||
.stdout(Stdio::piped())
|
||
.stderr(Stdio::null())
|
||
.spawn()?
|
||
} else if let Ok(c) = Command::new("yandex-music-auth")
|
||
.stdout(Stdio::piped())
|
||
.stderr(Stdio::null())
|
||
.spawn()
|
||
{
|
||
c
|
||
} else if cfg!(feature = "linux-webview") {
|
||
Command::new(&exe)
|
||
.arg("--auth-webview")
|
||
.stdout(Stdio::piped())
|
||
.stderr(Stdio::null())
|
||
.spawn()?
|
||
} else {
|
||
anyhow::bail!("WebKitGTK auth helper (yandex-music-auth) unavailable");
|
||
};
|
||
|
||
let stdout = child
|
||
.stdout
|
||
.take()
|
||
.ok_or_else(|| anyhow::anyhow!("Missing auth subprocess stdout"))?;
|
||
let reader = BufReader::new(stdout);
|
||
for line in reader.lines() {
|
||
if let Ok(l) = line {
|
||
if let Some(tok) = l.strip_prefix(OAUTH_TOKEN_PREFIX) {
|
||
let _ = child.wait();
|
||
return Ok(tok.trim().to_string());
|
||
}
|
||
}
|
||
}
|
||
let status = child.wait()?;
|
||
if status.code() == Some(2) {
|
||
anyhow::bail!("WebKitGTK runtime unavailable")
|
||
}
|
||
anyhow::bail!("Окно входа закрыто")
|
||
}
|
||
}
|
||
|
||
#[cfg(not(any(windows, target_os = "linux")))]
|
||
mod imp {
|
||
use super::NativeEvent;
|
||
use crate::api::models::Track;
|
||
use winit::window::Window;
|
||
|
||
pub struct NativeDesktop;
|
||
impl NativeDesktop {
|
||
pub fn new(_window: &Window, _is_ru: bool) -> Self {
|
||
Self
|
||
}
|
||
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> {
|
||
Vec::new()
|
||
}
|
||
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> {
|
||
None
|
||
}
|
||
pub fn run_auth_webview_subprocess() {}
|
||
pub fn spawn_auth_webview_subprocess() -> anyhow::Result<String> {
|
||
anyhow::bail!("WebView2 auth is only available on Windows")
|
||
}
|
||
}
|
||
|
||
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");
|
||
}
|
||
}
|