964 lines
34 KiB
Rust
964 lines
34 KiB
Rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||
|
||
use std::sync::Arc;
|
||
use std::time::{Duration, Instant};
|
||
|
||
use winit::application::ApplicationHandler;
|
||
use winit::dpi::{LogicalSize, PhysicalSize};
|
||
use winit::event::WindowEvent;
|
||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||
use winit::window::{Window, WindowAttributes, WindowId};
|
||
|
||
use yandex_music_rs::app::{AppAction, WindowCommand};
|
||
use yandex_music_rs::engine::types::TextureUpload;
|
||
use yandex_music_rs::engine::{CursorKind, DisplayList, Vec2};
|
||
use yandex_music_rs::gl::GlContext;
|
||
use yandex_music_rs::native::{run_auth_webview_subprocess, NativeDesktop, NativeEvent};
|
||
use yandex_music_rs::telemetry;
|
||
use yandex_music_rs::views::YandexMusicShell;
|
||
use yandex_music_rs::vulkan::vibe_renderer::VibePushConstants;
|
||
use yandex_music_rs::vulkan::VulkanContext;
|
||
|
||
const BG_POLL_INTERVAL: Duration = Duration::from_millis(350);
|
||
const CURSOR_REDRAW_INTERVAL: Duration = Duration::from_millis(16);
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
enum RendererPreference {
|
||
Auto,
|
||
Vulkan,
|
||
OpenGl,
|
||
}
|
||
|
||
fn parse_renderer_preference() -> RendererPreference {
|
||
let parse_val = |raw: &str| -> Option<RendererPreference> {
|
||
match raw.trim().to_ascii_lowercase().as_str() {
|
||
"auto" => Some(RendererPreference::Auto),
|
||
"vulkan" | "vk" => Some(RendererPreference::Vulkan),
|
||
"gl" | "opengl" | "gl33" => Some(RendererPreference::OpenGl),
|
||
_ => None,
|
||
}
|
||
};
|
||
|
||
let mut args = std::env::args().skip(1);
|
||
while let Some(arg) = args.next() {
|
||
if let Some(v) = arg.strip_prefix("--renderer=") {
|
||
if let Some(pref) = parse_val(v) {
|
||
return pref;
|
||
}
|
||
} else if arg == "--renderer" {
|
||
if let Some(v) = args.next() {
|
||
if let Some(pref) = parse_val(&v) {
|
||
return pref;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if let Ok(env_val) = std::env::var("YM_RENDERER") {
|
||
if let Some(pref) = parse_val(&env_val) {
|
||
return pref;
|
||
}
|
||
}
|
||
|
||
RendererPreference::Auto
|
||
}
|
||
|
||
enum RenderBackend {
|
||
Vulkan(VulkanContext),
|
||
OpenGl(GlContext),
|
||
}
|
||
|
||
impl RenderBackend {
|
||
fn name(&self) -> &'static str {
|
||
match self {
|
||
Self::Vulkan(_) => "Vulkan",
|
||
Self::OpenGl(_) => "OpenGL 3.3 Core",
|
||
}
|
||
}
|
||
|
||
fn gpu_name(&self) -> &str {
|
||
match self {
|
||
Self::Vulkan(vk) => &vk.gpu_name,
|
||
Self::OpenGl(gl) => &gl.gpu_name,
|
||
}
|
||
}
|
||
|
||
fn estimated_vram_bytes(&self) -> u64 {
|
||
match self {
|
||
Self::Vulkan(vk) => vk.estimated_vram_bytes(),
|
||
Self::OpenGl(gl) => gl.estimated_vram_bytes(),
|
||
}
|
||
}
|
||
|
||
fn is_surface_dirty(&self) -> bool {
|
||
match self {
|
||
Self::Vulkan(vk) => vk.swapchain_dirty,
|
||
Self::OpenGl(_) => false,
|
||
}
|
||
}
|
||
|
||
fn resize(&mut self, width: u32, height: u32) {
|
||
if width == 0 || height == 0 {
|
||
return;
|
||
}
|
||
match self {
|
||
Self::Vulkan(vk) => vk.swapchain_dirty = true,
|
||
Self::OpenGl(gl) => gl.resize(width, height),
|
||
}
|
||
}
|
||
|
||
#[allow(clippy::too_many_arguments)]
|
||
fn render_frame(
|
||
&mut self,
|
||
window: &Window,
|
||
size: PhysicalSize<u32>,
|
||
display_list: &DisplayList,
|
||
uploads: &[TextureUpload],
|
||
scale_factor: f32,
|
||
clear_color: [f32; 4],
|
||
vibe_push: Option<VibePushConstants>,
|
||
) -> anyhow::Result<()> {
|
||
match self {
|
||
Self::Vulkan(vk) => {
|
||
vk.render_frame(window, display_list, uploads, scale_factor, clear_color, vibe_push)
|
||
}
|
||
Self::OpenGl(gl) => {
|
||
gl.render_frame(size, scale_factor, clear_color, vibe_push, uploads, display_list)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn build_window_attrs(init_w: f64, init_h: f64) -> WindowAttributes {
|
||
let mut attrs = WindowAttributes::default()
|
||
.with_title("Яндекс Музыка")
|
||
.with_inner_size(LogicalSize::new(init_w, init_h))
|
||
.with_min_inner_size(LogicalSize::new(768.0, 650.0))
|
||
.with_decorations(false) // Custom frameless 32px Yandex TitleBar!
|
||
.with_resizable(true);
|
||
#[cfg(target_os = "linux")]
|
||
{
|
||
use winit::platform::wayland::WindowAttributesExtWayland;
|
||
use winit::platform::x11::WindowAttributesExtX11;
|
||
attrs = WindowAttributesExtX11::with_name(attrs, "yandex-music-rs", "yandex-music-rs");
|
||
attrs = WindowAttributesExtWayland::with_name(attrs, "yandex-music-rs", "yandex-music-rs");
|
||
}
|
||
if let Some(icon) = yandex_music_rs::native::load_window_icon() {
|
||
attrs = attrs.with_window_icon(Some(icon));
|
||
}
|
||
attrs
|
||
}
|
||
|
||
fn init_vulkan_backend(
|
||
event_loop: &ActiveEventLoop,
|
||
init_w: f64,
|
||
init_h: f64,
|
||
) -> anyhow::Result<(Arc<Window>, RenderBackend)> {
|
||
let window = Arc::new(event_loop.create_window(build_window_attrs(init_w, init_h))?);
|
||
let vk = VulkanContext::new(&window)?;
|
||
Ok((window, RenderBackend::Vulkan(vk)))
|
||
}
|
||
|
||
fn init_opengl_backend(
|
||
event_loop: &ActiveEventLoop,
|
||
init_w: f64,
|
||
init_h: f64,
|
||
) -> anyhow::Result<(Arc<Window>, RenderBackend)> {
|
||
let (window, gl) = GlContext::create_window_and_context(event_loop, build_window_attrs(init_w, init_h))?;
|
||
Ok((window, RenderBackend::OpenGl(gl)))
|
||
}
|
||
|
||
struct AppRunner {
|
||
runtime: tokio::runtime::Runtime,
|
||
// Drop GPU backend BEFORE the native winit Window so Vulkan/GL surfaces destroy cleanly!
|
||
backend: Option<RenderBackend>,
|
||
window: Option<Arc<Window>>,
|
||
shell: Option<YandexMusicShell>,
|
||
native: Option<NativeDesktop>,
|
||
next_repaint: Option<Instant>,
|
||
last_render_at: Instant,
|
||
last_bg_poll: Instant,
|
||
last_frame_hash: Option<u64>,
|
||
window_visible: bool,
|
||
window_focused: bool,
|
||
window_occluded: bool,
|
||
frames_rendered: u64,
|
||
#[cfg(windows)]
|
||
power_save_blocked: bool,
|
||
last_cursor: CursorKind,
|
||
last_window_title: &'static str,
|
||
#[cfg(windows)]
|
||
last_dwm_dark: Option<bool>,
|
||
}
|
||
|
||
impl AppRunner {
|
||
fn new() -> Self {
|
||
// Lean 2-worker Tokio runtime to keep thread stacks & RAM minimal!
|
||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||
.worker_threads(2)
|
||
.thread_name("ym-net")
|
||
.enable_all()
|
||
.build()
|
||
.expect("Failed to create Tokio runtime");
|
||
|
||
let now = Instant::now();
|
||
Self {
|
||
runtime,
|
||
backend: None,
|
||
window: None,
|
||
shell: None,
|
||
native: None,
|
||
next_repaint: Some(now),
|
||
last_render_at: now - Duration::from_secs(1),
|
||
last_bg_poll: now,
|
||
last_frame_hash: None,
|
||
window_visible: true,
|
||
window_focused: true,
|
||
window_occluded: false,
|
||
frames_rendered: 0,
|
||
#[cfg(windows)]
|
||
power_save_blocked: false,
|
||
last_cursor: CursorKind::Default,
|
||
last_window_title: "",
|
||
#[cfg(windows)]
|
||
last_dwm_dark: None,
|
||
}
|
||
}
|
||
|
||
fn is_window_renderable(&self) -> bool {
|
||
if !self.window_visible || self.window_occluded {
|
||
return false;
|
||
}
|
||
let Some(window) = self.window.as_ref() else {
|
||
return false;
|
||
};
|
||
if window.is_minimized().unwrap_or(false) {
|
||
return false;
|
||
}
|
||
let size = window.inner_size();
|
||
size.width > 0 && size.height > 0
|
||
}
|
||
|
||
fn schedule_repaint_at(&mut self, deadline: Instant) {
|
||
self.next_repaint = Some(match self.next_repaint {
|
||
Some(prev) => prev.min(deadline),
|
||
None => deadline,
|
||
});
|
||
}
|
||
|
||
fn request_immediate_redraw(&mut self, force_present: bool) {
|
||
if force_present {
|
||
self.last_frame_hash = None;
|
||
}
|
||
self.next_repaint = None;
|
||
if self.is_window_renderable() {
|
||
if let Some(w) = self.window.as_ref() {
|
||
w.request_redraw();
|
||
}
|
||
}
|
||
}
|
||
|
||
fn shutdown_and_exit(&mut self, event_loop: &ActiveEventLoop) {
|
||
#[cfg(windows)]
|
||
if self.power_save_blocked {
|
||
set_power_save_blocker(false);
|
||
self.power_save_blocked = false;
|
||
}
|
||
if let Some(ref mut shell) = self.shell {
|
||
shell.app.graceful_shutdown();
|
||
}
|
||
event_loop.exit();
|
||
}
|
||
|
||
fn sync_os_playback_and_power(&mut self) {
|
||
let Some(shell) = self.shell.as_ref() else {
|
||
return;
|
||
};
|
||
let playing = shell.app.is_audio_playing();
|
||
if let Some(ref mut native) = self.native {
|
||
let pos_ms = shell.app.position_ms();
|
||
native.sync_playback(shell.app.current_track(), playing, pos_ms);
|
||
}
|
||
#[cfg(windows)]
|
||
if playing != self.power_save_blocked {
|
||
self.power_save_blocked = playing;
|
||
set_power_save_blocker(playing);
|
||
}
|
||
}
|
||
|
||
fn poll_native_events(&mut self, event_loop: &ActiveEventLoop) -> bool {
|
||
let (Some(window), Some(shell), Some(native)) = (
|
||
self.window.as_ref(),
|
||
self.shell.as_mut(),
|
||
self.native.as_mut(),
|
||
) else {
|
||
return false;
|
||
};
|
||
|
||
let mut should_exit = false;
|
||
let mut need_redraw = false;
|
||
let mut force_present = false;
|
||
let events = native.poll_events();
|
||
for nev in events {
|
||
match nev {
|
||
NativeEvent::ShowWindow => {
|
||
self.window_visible = true;
|
||
self.window_occluded = false;
|
||
window.set_visible(true);
|
||
window.set_minimized(false);
|
||
window.focus_window();
|
||
native.set_window_visible_label(true);
|
||
need_redraw = true;
|
||
force_present = true;
|
||
}
|
||
NativeEvent::ToggleWindow => {
|
||
let visible = self.window_visible
|
||
&& window.is_visible().unwrap_or(true)
|
||
&& !window.is_minimized().unwrap_or(false);
|
||
if visible {
|
||
self.window_visible = false;
|
||
window.set_visible(false);
|
||
native.set_window_visible_label(false);
|
||
} else {
|
||
self.window_visible = true;
|
||
self.window_occluded = false;
|
||
window.set_visible(true);
|
||
window.set_minimized(false);
|
||
window.focus_window();
|
||
native.set_window_visible_label(true);
|
||
need_redraw = true;
|
||
force_present = true;
|
||
}
|
||
}
|
||
NativeEvent::CheckUpdates => {
|
||
self.window_visible = true;
|
||
self.window_occluded = false;
|
||
window.set_visible(true);
|
||
window.set_minimized(false);
|
||
window.focus_window();
|
||
native.set_window_visible_label(true);
|
||
shell.app.check_for_updates();
|
||
need_redraw = true;
|
||
force_present = true;
|
||
}
|
||
NativeEvent::QuitApp => {
|
||
should_exit = true;
|
||
}
|
||
NativeEvent::Play => {
|
||
shell.app.dispatch(AppAction::Play);
|
||
need_redraw = true;
|
||
}
|
||
NativeEvent::Pause => {
|
||
shell.app.dispatch(AppAction::Pause);
|
||
need_redraw = true;
|
||
}
|
||
NativeEvent::TogglePlay => {
|
||
shell.app.dispatch(AppAction::TogglePlay);
|
||
need_redraw = true;
|
||
}
|
||
NativeEvent::Next => {
|
||
shell.app.dispatch(AppAction::Next);
|
||
need_redraw = true;
|
||
}
|
||
NativeEvent::Prev => {
|
||
shell.app.dispatch(AppAction::Prev);
|
||
need_redraw = true;
|
||
}
|
||
NativeEvent::Stop => {
|
||
shell.app.dispatch(AppAction::Stop);
|
||
need_redraw = true;
|
||
}
|
||
NativeEvent::SeekMs(ms) => {
|
||
shell.app.dispatch(AppAction::SeekMs(ms));
|
||
need_redraw = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
if should_exit {
|
||
self.shutdown_and_exit(event_loop);
|
||
return true;
|
||
}
|
||
if need_redraw {
|
||
self.request_immediate_redraw(force_present);
|
||
}
|
||
false
|
||
}
|
||
|
||
fn render(&mut self, event_loop: &ActiveEventLoop) {
|
||
if !self.is_window_renderable() {
|
||
self.next_repaint = None;
|
||
return;
|
||
}
|
||
|
||
let (Some(window), Some(backend), Some(shell)) = (
|
||
self.window.as_ref(),
|
||
self.backend.as_mut(),
|
||
self.shell.as_mut(),
|
||
) else {
|
||
return;
|
||
};
|
||
|
||
let size = window.inner_size();
|
||
if size.width == 0 || size.height == 0 {
|
||
self.next_repaint = None;
|
||
return;
|
||
}
|
||
|
||
self.last_render_at = Instant::now();
|
||
|
||
let sf = (window.scale_factor() as f32).max(0.5);
|
||
let logical = Vec2::new(size.width as f32 / sf, size.height as f32 / sf);
|
||
let is_max = window.is_maximized();
|
||
let elapsed = shell.elapsed_secs();
|
||
|
||
let (frame, win_cmd) = shell.render_frame(logical, sf, elapsed, is_max);
|
||
|
||
// Sync cursor icon
|
||
if frame.cursor != self.last_cursor {
|
||
self.last_cursor = frame.cursor;
|
||
window.set_cursor(frame.cursor.to_winit());
|
||
}
|
||
|
||
// Sync localized window title (`"Яндекс Музыка"` RU / `"Yandex Music"` EN)
|
||
let title = shell.window_title();
|
||
if title != self.last_window_title {
|
||
self.last_window_title = title;
|
||
window.set_title(title);
|
||
}
|
||
|
||
// Sync Windows 11 DWM immersive dark mode dynamically to `palette.is_dark`
|
||
#[cfg(windows)]
|
||
{
|
||
let is_dark = shell.is_dark();
|
||
if self.last_dwm_dark != Some(is_dark) {
|
||
self.last_dwm_dark = Some(is_dark);
|
||
apply_win11_dwm_style(window, is_dark);
|
||
}
|
||
}
|
||
|
||
// Execute any custom titlebar window command
|
||
let mut request_graceful_exit = false;
|
||
match win_cmd {
|
||
WindowCommand::None => {}
|
||
WindowCommand::DragWindow => {
|
||
let _ = window.drag_window();
|
||
}
|
||
WindowCommand::Minimize => window.set_minimized(true),
|
||
WindowCommand::ToggleMaximize => window.set_maximized(!window.is_maximized()),
|
||
WindowCommand::Close => {
|
||
if shell.app.config.close_to_tray {
|
||
self.window_visible = false;
|
||
window.set_visible(false);
|
||
if let Some(ref native) = self.native {
|
||
native.set_window_visible_label(false);
|
||
}
|
||
} else {
|
||
request_graceful_exit = true;
|
||
}
|
||
}
|
||
}
|
||
|
||
if request_graceful_exit {
|
||
self.shutdown_and_exit(event_loop);
|
||
return;
|
||
}
|
||
|
||
let clear_col = shell.palette.clear_color_f32();
|
||
let vibe_push = shell.vibe_push_constants();
|
||
|
||
// Dirty-frame skip: if the UI display list, blur regions, clear color, and Vibe push
|
||
// constants are byte-identical to the last presented frame (and no texture uploads or
|
||
// swapchain resize occurred), skip Vulkan submit & DWM present completely! (0% GPU!)
|
||
let frame_hash = compute_frame_hash(
|
||
&frame.display_list,
|
||
clear_col,
|
||
vibe_push,
|
||
size.width,
|
||
size.height,
|
||
sf,
|
||
);
|
||
let skip_gpu_present = self.window_visible
|
||
&& frame.texture_uploads.is_empty()
|
||
&& !backend.is_surface_dirty()
|
||
&& self.last_frame_hash == Some(frame_hash);
|
||
|
||
if self.window_visible && !skip_gpu_present {
|
||
if let Err(e) = backend.render_frame(
|
||
window,
|
||
size,
|
||
&frame.display_list,
|
||
&frame.texture_uploads,
|
||
sf,
|
||
clear_col,
|
||
vibe_push,
|
||
) {
|
||
log::error!("{} render error: {:?}", backend.name(), e);
|
||
self.last_frame_hash = None;
|
||
} else {
|
||
self.last_frame_hash = Some(frame_hash);
|
||
shell.app.perf.tick(backend.estimated_vram_bytes());
|
||
self.frames_rendered += 1;
|
||
|
||
// Trim cold GPU shader-compiler driver pages right after initial warmup
|
||
if self.frames_rendered == 4 || (self.frames_rendered % 1800 == 0) {
|
||
telemetry::PerfTelemetry::trim_working_set();
|
||
shell.app.perf.sample_memory();
|
||
}
|
||
}
|
||
}
|
||
|
||
// Compute adaptive next repaint interval (`None` = purely event-driven, 0 FPS idle!)
|
||
let ui_delay = frame.repaint_after.map(|d| {
|
||
if !self.window_focused && !shell.ui.animator.needs_repaint() {
|
||
// Throttle decorative indicators (pulsing dot, caret) when unfocused
|
||
d.max(Duration::from_millis(250))
|
||
} else {
|
||
d
|
||
}
|
||
});
|
||
let bg_delay = shell.continuous_repaint_interval(self.window_focused);
|
||
let next_delay = match (ui_delay, bg_delay) {
|
||
(Some(a), Some(b)) => Some(a.min(b)),
|
||
(Some(a), None) => Some(a),
|
||
(None, Some(b)) => Some(b),
|
||
(None, None) => None,
|
||
};
|
||
self.next_repaint = if self.window_visible {
|
||
next_delay.map(|d| Instant::now() + d)
|
||
} else {
|
||
None
|
||
};
|
||
|
||
// Sync Windows SMTC metadata, playback state & power-save blocker
|
||
self.sync_os_playback_and_power();
|
||
|
||
// Poll any queued tray / SMTC events after frame submit
|
||
let _ = self.poll_native_events(event_loop);
|
||
}
|
||
}
|
||
|
||
impl ApplicationHandler for AppRunner {
|
||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||
if self.window.is_some() {
|
||
return;
|
||
}
|
||
|
||
// Exact Yandex Music Desktop window geometry (1280×800 default, min 768×650, overridable via --size=WxH)
|
||
let (init_w, init_h) = std::env::args()
|
||
.find_map(|a| {
|
||
let s = a.strip_prefix("--size=")?;
|
||
let (w, h) = s.split_once('x')?;
|
||
Some((w.parse::<f64>().ok()?, h.parse::<f64>().ok()?))
|
||
})
|
||
.unwrap_or((1280.0, 800.0));
|
||
|
||
let pref = parse_renderer_preference();
|
||
let (window, backend) = match pref {
|
||
RendererPreference::OpenGl => init_opengl_backend(event_loop, init_w, init_h)
|
||
.expect("Failed to initialize OpenGL 3.3 Core renderer (--renderer=gl)"),
|
||
RendererPreference::Vulkan => init_vulkan_backend(event_loop, init_w, init_h)
|
||
.expect("Failed to initialize Vulkan renderer (--renderer=vulkan)"),
|
||
RendererPreference::Auto => {
|
||
if VulkanContext::has_hardware_vulkan() {
|
||
match init_vulkan_backend(event_loop, init_w, init_h) {
|
||
Ok(pair) => pair,
|
||
Err(vk_err) => {
|
||
log::warn!(
|
||
"Hardware Vulkan init failed ({vk_err:#}); falling back to OpenGL 3.3 Core"
|
||
);
|
||
init_opengl_backend(event_loop, init_w, init_h).unwrap_or_else(|gl_err| {
|
||
panic!(
|
||
"Both Vulkan ({vk_err:#}) and OpenGL 3.3 Core ({gl_err:#}) failed to initialize"
|
||
)
|
||
})
|
||
}
|
||
}
|
||
} else {
|
||
log::info!(
|
||
"No hardware Vulkan GPU detected; selecting OpenGL 3.3 Core hardware backend"
|
||
);
|
||
match init_opengl_backend(event_loop, init_w, init_h) {
|
||
Ok(pair) => pair,
|
||
Err(gl_err) => {
|
||
log::warn!(
|
||
"OpenGL 3.3 Core init failed ({gl_err:#}); falling back to Vulkan (CPU/lavapipe)"
|
||
);
|
||
init_vulkan_backend(event_loop, init_w, init_h).unwrap_or_else(|vk_err| {
|
||
panic!(
|
||
"Both OpenGL 3.3 Core ({gl_err:#}) and Vulkan fallback ({vk_err:#}) failed to initialize"
|
||
)
|
||
})
|
||
}
|
||
}
|
||
}
|
||
}
|
||
};
|
||
|
||
log::info!(
|
||
"Active GPU renderer: {} — {}",
|
||
backend.name(),
|
||
backend.gpu_name()
|
||
);
|
||
let gpu_name = format!("{} — {}", backend.name(), backend.gpu_name());
|
||
|
||
let mut shell = YandexMusicShell::new(self.runtime.handle().clone(), gpu_name);
|
||
if let Some(uri) = std::env::args().find(|a| a.starts_with("yandexmusic://")) {
|
||
shell.app.handle_deeplink(&uri);
|
||
}
|
||
|
||
let init_title = shell.window_title();
|
||
window.set_title(init_title);
|
||
self.last_window_title = init_title;
|
||
|
||
#[cfg(windows)]
|
||
{
|
||
let init_dark = shell.is_dark();
|
||
apply_win11_dwm_style(&window, init_dark);
|
||
self.last_dwm_dark = Some(init_dark);
|
||
}
|
||
|
||
let native = NativeDesktop::new(&window, shell.app.config.language.is_ru());
|
||
|
||
self.backend = Some(backend);
|
||
self.window = Some(window.clone());
|
||
self.shell = Some(shell);
|
||
self.native = Some(native);
|
||
self.window_visible = true;
|
||
self.window_focused = true;
|
||
self.window_occluded = false;
|
||
self.last_frame_hash = None;
|
||
window.request_redraw();
|
||
}
|
||
|
||
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
|
||
let is_cursor_moved = matches!(event, WindowEvent::CursorMoved { .. });
|
||
let mut wants_redraw = false;
|
||
if let Some(shell) = self.shell.as_mut() {
|
||
wants_redraw = shell.handle_winit_event(&event);
|
||
}
|
||
|
||
if wants_redraw && self.is_window_renderable() {
|
||
if is_cursor_moved {
|
||
// Coalesce high-polling mouse moves to max 60 Hz instead of spiking to 240 FPS!
|
||
let next_slot = self.last_render_at + CURSOR_REDRAW_INTERVAL;
|
||
if Instant::now() >= next_slot {
|
||
if let Some(w) = self.window.as_ref() {
|
||
w.request_redraw();
|
||
}
|
||
} else {
|
||
self.schedule_repaint_at(next_slot);
|
||
}
|
||
} else if let Some(w) = self.window.as_ref() {
|
||
w.request_redraw();
|
||
}
|
||
}
|
||
|
||
match event {
|
||
WindowEvent::CloseRequested => {
|
||
let close_to_tray = self
|
||
.shell
|
||
.as_ref()
|
||
.map_or(false, |s| s.app.config.close_to_tray);
|
||
if close_to_tray {
|
||
self.window_visible = false;
|
||
self.next_repaint = None;
|
||
if let Some(w) = self.window.as_ref() {
|
||
w.set_visible(false);
|
||
}
|
||
if let Some(ref native) = self.native {
|
||
native.set_window_visible_label(false);
|
||
}
|
||
} else {
|
||
self.shutdown_and_exit(event_loop);
|
||
}
|
||
}
|
||
WindowEvent::Focused(focused) => {
|
||
self.window_focused = focused;
|
||
if let Some(shell) = self.shell.as_mut() {
|
||
shell.app.on_window_focus_changed(focused);
|
||
}
|
||
if focused {
|
||
self.request_immediate_redraw(true);
|
||
} else if let Some(shell) = self.shell.as_ref() {
|
||
self.next_repaint = shell
|
||
.continuous_repaint_interval(false)
|
||
.map(|d| Instant::now() + d);
|
||
}
|
||
}
|
||
WindowEvent::Occluded(occluded) => {
|
||
self.window_occluded = occluded;
|
||
if occluded {
|
||
self.next_repaint = None;
|
||
} else {
|
||
self.request_immediate_redraw(true);
|
||
}
|
||
}
|
||
WindowEvent::Resized(new_size) => {
|
||
self.last_frame_hash = None;
|
||
if let Some(backend) = self.backend.as_mut() {
|
||
if new_size.width > 0 && new_size.height > 0 {
|
||
backend.resize(new_size.width, new_size.height);
|
||
}
|
||
}
|
||
if new_size.width > 0 && new_size.height > 0 {
|
||
if let Some(w) = self.window.as_ref() {
|
||
w.request_redraw();
|
||
}
|
||
} else {
|
||
self.next_repaint = None;
|
||
}
|
||
}
|
||
WindowEvent::RedrawRequested => {
|
||
self.render(event_loop);
|
||
}
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||
if self.poll_native_events(event_loop) {
|
||
return;
|
||
}
|
||
|
||
let now = Instant::now();
|
||
|
||
// Lightweight CPU-only background service poll (async API, covers, track finish, SMTC)
|
||
if now.duration_since(self.last_bg_poll) >= BG_POLL_INTERVAL {
|
||
self.last_bg_poll = now;
|
||
let bg_dirty = self
|
||
.shell
|
||
.as_mut()
|
||
.map_or(false, |s| s.poll_background_events());
|
||
self.sync_os_playback_and_power();
|
||
if bg_dirty && self.is_window_renderable() {
|
||
self.schedule_repaint_at(now);
|
||
}
|
||
}
|
||
|
||
let next_bg = self.last_bg_poll + BG_POLL_INTERVAL;
|
||
|
||
// Hidden / minimized / occluded: zero GPU work, sleep until next lightweight CPU poll!
|
||
if !self.is_window_renderable() {
|
||
event_loop.set_control_flow(ControlFlow::WaitUntil(next_bg));
|
||
return;
|
||
}
|
||
|
||
if let Some(deadline) = self.next_repaint {
|
||
if now >= deadline {
|
||
self.next_repaint = None;
|
||
if let Some(w) = self.window.as_ref() {
|
||
w.request_redraw();
|
||
}
|
||
event_loop.set_control_flow(ControlFlow::WaitUntil(next_bg));
|
||
} else {
|
||
event_loop.set_control_flow(ControlFlow::WaitUntil(deadline.min(next_bg)));
|
||
}
|
||
} else {
|
||
// Static idle page -> 0 FPS Vulkan rendering; wake only on input or periodic CPU poll!
|
||
event_loop.set_control_flow(ControlFlow::WaitUntil(next_bg));
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 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.
|
||
fn compute_frame_hash(
|
||
dl: &DisplayList,
|
||
clear_col: [f32; 4],
|
||
vibe_push: Option<VibePushConstants>,
|
||
width: u32,
|
||
height: u32,
|
||
scale_factor: f32,
|
||
) -> u64 {
|
||
const OFFSET: u64 = 0xcbf29ce484222325;
|
||
const PRIME: u64 = 0x100000001b3;
|
||
let mut h = OFFSET;
|
||
|
||
#[inline(always)]
|
||
fn mix_u64(h: &mut u64, v: u64) {
|
||
*h ^= v;
|
||
*h = h.wrapping_mul(PRIME);
|
||
}
|
||
|
||
mix_u64(&mut h, ((width as u64) << 32) | (height as u64));
|
||
mix_u64(&mut h, scale_factor.to_bits() as u64);
|
||
for c in clear_col {
|
||
mix_u64(&mut h, c.to_bits() as u64);
|
||
}
|
||
|
||
if let Some(vp) = vibe_push {
|
||
mix_u64(&mut h, 1);
|
||
for v in [
|
||
vp.time,
|
||
vp.energy,
|
||
vp.bass,
|
||
vp.hue_shift,
|
||
vp.playing,
|
||
vp.light_mode,
|
||
vp.track_sat,
|
||
vp.track_light,
|
||
] {
|
||
mix_u64(&mut h, v.to_bits() as u64);
|
||
}
|
||
} else {
|
||
mix_u64(&mut h, 0);
|
||
}
|
||
|
||
mix_u64(&mut h, dl.blur_regions.len() as u64);
|
||
for br in &dl.blur_regions {
|
||
mix_u64(&mut h, br.instance_index as u64);
|
||
mix_u64(&mut h, br.rect.x.to_bits() as u64);
|
||
mix_u64(&mut h, br.rect.y.to_bits() as u64);
|
||
mix_u64(&mut h, br.rect.w.to_bits() as u64);
|
||
mix_u64(&mut h, br.rect.h.to_bits() as u64);
|
||
mix_u64(&mut h, br.radius.to_bits() as u64);
|
||
}
|
||
|
||
let raw = bytemuck::cast_slice::<_, u8>(&dl.instances);
|
||
mix_u64(&mut h, raw.len() as u64);
|
||
let mut chunks = raw.chunks_exact(8);
|
||
for chunk in &mut chunks {
|
||
let word = u64::from_ne_bytes(chunk.try_into().unwrap());
|
||
mix_u64(&mut h, word);
|
||
}
|
||
for &b in chunks.remainder() {
|
||
mix_u64(&mut h, b as u64);
|
||
}
|
||
h
|
||
}
|
||
|
||
/// Enable native Windows 11 rounded corners + dynamic DWM dark/light mode synced to `palette.is_dark`
|
||
#[cfg(windows)]
|
||
fn apply_win11_dwm_style(window: &Window, is_dark: bool) {
|
||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||
use windows_sys::Win32::Graphics::Dwm::{
|
||
DwmSetWindowAttribute, DWMWA_USE_IMMERSIVE_DARK_MODE, DWMWA_WINDOW_CORNER_PREFERENCE,
|
||
DWMWCP_ROUND,
|
||
};
|
||
|
||
if let Ok(handle) = window.window_handle() {
|
||
if let RawWindowHandle::Win32(win32) = handle.as_raw() {
|
||
let hwnd = win32.hwnd.get() as *mut std::ffi::c_void;
|
||
unsafe {
|
||
// Sync Win32 tray/context menus (`uxtheme.dll`) to current theme
|
||
#[link(name = "kernel32")]
|
||
extern "system" {
|
||
fn LoadLibraryA(lp_lib_file_name: *const u8) -> *mut std::ffi::c_void;
|
||
fn GetProcAddress(
|
||
h_module: *mut std::ffi::c_void,
|
||
lp_proc_name: *const u8,
|
||
) -> *mut std::ffi::c_void;
|
||
}
|
||
let h_ux = LoadLibraryA(b"uxtheme.dll\0".as_ptr());
|
||
if !h_ux.is_null() {
|
||
// Ordinal 135: SetPreferredAppMode(ForceDark = 2, ForceLight = 3)
|
||
let p_set = GetProcAddress(h_ux, 135usize as *const u8);
|
||
if !p_set.is_null() {
|
||
let f: extern "system" fn(i32) -> i32 = std::mem::transmute(p_set);
|
||
f(if is_dark { 2 } else { 3 });
|
||
}
|
||
// Ordinal 136: FlushMenuThemes()
|
||
let p_flush = GetProcAddress(h_ux, 136usize as *const u8);
|
||
if !p_flush.is_null() {
|
||
let f: extern "system" fn() = std::mem::transmute(p_flush);
|
||
f();
|
||
}
|
||
}
|
||
|
||
let dark: u32 = if is_dark { 1 } else { 0 };
|
||
DwmSetWindowAttribute(
|
||
hwnd,
|
||
DWMWA_USE_IMMERSIVE_DARK_MODE as u32,
|
||
&dark as *const _ as *const _,
|
||
std::mem::size_of::<u32>() as u32,
|
||
);
|
||
let round: u32 = DWMWCP_ROUND as u32;
|
||
DwmSetWindowAttribute(
|
||
hwnd,
|
||
DWMWA_WINDOW_CORNER_PREFERENCE as u32,
|
||
&round as *const _ as *const _,
|
||
std::mem::size_of::<u32>() as u32,
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Exact Electron `powerSaveBlocker.start("prevent-app-suspension")` parity on Windows
|
||
#[cfg(windows)]
|
||
fn set_power_save_blocker(prevent_sleep: bool) {
|
||
use windows_sys::Win32::System::Power::{
|
||
SetThreadExecutionState, ES_CONTINUOUS, ES_SYSTEM_REQUIRED,
|
||
};
|
||
unsafe {
|
||
let flags = if prevent_sleep {
|
||
ES_CONTINUOUS | ES_SYSTEM_REQUIRED
|
||
} else {
|
||
ES_CONTINUOUS
|
||
};
|
||
SetThreadExecutionState(flags);
|
||
}
|
||
}
|
||
|
||
/// Exact Electron `requestSingleInstanceLock()` parity on Windows
|
||
#[cfg(windows)]
|
||
fn acquire_single_instance_lock() -> bool {
|
||
use std::ffi::OsStr;
|
||
use std::os::windows::ffi::OsStrExt;
|
||
use windows_sys::Win32::Foundation::{GetLastError, ERROR_ALREADY_EXISTS};
|
||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||
FindWindowW, SetForegroundWindow, ShowWindow, SW_RESTORE,
|
||
};
|
||
|
||
#[link(name = "kernel32")]
|
||
extern "system" {
|
||
fn CreateMutexW(
|
||
lp_mutex_attributes: *const std::ffi::c_void,
|
||
b_initial_owner: i32,
|
||
lp_name: *const u16,
|
||
) -> *mut std::ffi::c_void;
|
||
}
|
||
|
||
let name: Vec<u16> = OsStr::new("Local\\YandexMusicRust_SingleInstance_Mutex")
|
||
.encode_wide()
|
||
.chain(Some(0))
|
||
.collect();
|
||
unsafe {
|
||
let handle = CreateMutexW(std::ptr::null(), 1, name.as_ptr());
|
||
if !handle.is_null() && GetLastError() == ERROR_ALREADY_EXISTS {
|
||
for title_str in ["Яндекс Музыка", "Yandex Music"] {
|
||
let title: Vec<u16> = OsStr::new(title_str)
|
||
.encode_wide()
|
||
.chain(Some(0))
|
||
.collect();
|
||
let existing = FindWindowW(std::ptr::null(), title.as_ptr());
|
||
if !existing.is_null() {
|
||
ShowWindow(existing, SW_RESTORE);
|
||
SetForegroundWindow(existing);
|
||
break;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
}
|
||
true
|
||
}
|
||
|
||
fn main() {
|
||
// Isolated zero-resident-RAM WebView2 OAuth subprocess (exits immediately after login!)
|
||
if std::env::args().any(|a| a == "--auth-webview") {
|
||
run_auth_webview_subprocess();
|
||
return;
|
||
}
|
||
|
||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init();
|
||
#[cfg(windows)]
|
||
if !acquire_single_instance_lock() {
|
||
return;
|
||
}
|
||
|
||
let event_loop = EventLoop::new().expect("Failed to create winit event loop");
|
||
let mut runner = AppRunner::new();
|
||
event_loop.run_app(&mut runner).expect("Event loop error");
|
||
}
|