//! The miniplayer as a window of its own (where `platform::SEPARATE_MINI`): //! a small borderless window owned by the main one, which the video moves //! into. Dragging moves the whole window, so video and controls move as one; //! letting go glides it to a corner of the main window. Its page is //! `mini.html` (src/mini/), which mirrors the player's state from the main //! window and sends its buttons back (src/player/miniWindow.ts). //! //! Positions are physical screen pixels. Never hold `MiniState`'s locks while //! calling a window getter: off the UI thread those wait for it (player.rs). use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::Duration; use parking_lot::Mutex; use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent}; const LABEL: &str = "mini"; /// Logical pixels, as in the page's former in-window miniplayer (player.css). const MARGIN: f64 = 24.0; /// Top corners sit below the main window's navigation bar (64px). const TOP_INSET: f64 = 64.0 + 12.0; const SNAP: Duration = Duration::from_millis(260); /// How far a flick carries the box when choosing a corner (ms of travel). const FLICK_MS: f64 = 220.0; #[derive(Clone, Copy, PartialEq)] enum Corner { TopLeft, TopRight, BottomLeft, BottomRight, } impl Corner { fn parse(s: &str) -> Corner { match s { "tl" => Corner::TopLeft, "tr" => Corner::TopRight, "bl" => Corner::BottomLeft, _ => Corner::BottomRight, } } fn name(self) -> &'static str { match self { Corner::TopLeft => "tl", Corner::TopRight => "tr", Corner::BottomLeft => "bl", Corner::BottomRight => "br", } } } /// The main window's client area on screen and the miniplayer's size there. #[derive(Clone, Copy)] struct Bounds { left: i32, top: i32, width: i32, height: i32, mini_w: i32, mini_h: i32, scale: f64, } impl Bounds { fn of(main: &WebviewWindow) -> Option { let pos = main.inner_position().ok()?; let size = main.inner_size().ok()?; let scale = main.scale_factor().ok()?; // As the page sized it: 26% of the window's width, 300 to 440 logical pixels, 16:9. let w = (size.width as f64 / scale * 0.26).clamp(300.0, 440.0); Some(Bounds { left: pos.x, top: pos.y, width: size.width as i32, height: size.height as i32, mini_w: (w * scale).round() as i32, mini_h: (w * 9.0 / 16.0 * scale).round() as i32, scale, }) } fn corner(&self, corner: Corner) -> (i32, i32) { let margin = (MARGIN * self.scale).round() as i32; let x = match corner { Corner::TopLeft | Corner::BottomLeft => self.left + margin, _ => self.left + self.width - self.mini_w - margin, }; let y = match corner { Corner::TopLeft | Corner::TopRight => self.top + (TOP_INSET * self.scale).round() as i32, _ => self.top + self.height - self.mini_h - margin, }; (x, y) } /// Keeps the box inside the main window while it's dragged. fn clamp(&self, x: i32, y: i32) -> (i32, i32) { let x = x.clamp(self.left, (self.left + self.width - self.mini_w).max(self.left)); let y = y.clamp(self.top, (self.top + self.height - self.mini_h).max(self.top)); (x, y) } } #[derive(Clone, Copy)] struct Drag { /// Where the window's visible area was when the drag began. start: (i32, i32), bounds: Bounds, } pub struct MiniState { corner: Mutex, /// From the window's outer position to its visible area: Windows keeps an /// invisible resize border around shadowed windows. Positions here are of /// the visible area; `place` converts. frame: Mutex<(i32, i32)>, drag: Mutex>, visible: AtomicBool, /// Dragged or gliding: the main window's moves don't re-place it meanwhile. busy: AtomicBool, /// Bumped to stop a glide that's under way. glide: AtomicU64, } impl Default for MiniState { fn default() -> Self { MiniState { corner: Mutex::new(Corner::BottomRight), frame: Mutex::new((0, 0)), drag: Mutex::new(None), visible: AtomicBool::new(false), busy: AtomicBool::new(false), glide: AtomicU64::new(0) } } } /// Moves the window so its visible area's top left is at `(x, y)`. fn place(app: &AppHandle, mini: &WebviewWindow, (x, y): (i32, i32)) { let (fx, fy) = *app.state::().frame.lock(); let _ = mini.set_position(PhysicalPosition::new(x - fx, y - fy)); } /// Where the visible area is now (outer position plus the frame). fn visible_position(app: &AppHandle, mini: &WebviewWindow) -> Result<(i32, i32), String> { let pos = mini.outer_position().map_err(|e| e.to_string())?; let (fx, fy) = *app.state::().frame.lock(); Ok((pos.x + fx, pos.y + fy)) } fn main_window(app: &AppHandle) -> Result, String> { app.get_webview_window("main").ok_or_else(|| "The main window is gone.".to_string()) } /// The miniplayer window, created hidden the first time (its page is small). fn window(app: &AppHandle) -> Result, String> { if let Some(w) = app.get_webview_window(LABEL) { return Ok(w); } let main = main_window(app)?; let w = WebviewWindowBuilder::new(app, LABEL, WebviewUrl::App("mini.html".into())) .title("Kaleido") .decorations(false) .transparent(true) .shadow(true) .resizable(false) .skip_taskbar(true) .focused(false) .visible(false) .inner_size(440.0, 247.5) // Owned by the main window: kept just above it, hidden when it's minimized. .parent(&main) .map_err(|e| e.to_string())? .build() .map_err(|e| e.to_string())?; if let Some(hwnd) = crate::platform::host_handle(&w) { crate::platform::style_mini_window(hwnd); } // mpv draws at the window's size; resizing happens off the UI thread (player.rs). let handle = app.clone(); w.on_window_event(move |event| { if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event { let handle = handle.clone(); tauri::async_runtime::spawn_blocking(move || { if let Some(main) = handle.get_webview_window("main") { crate::player::on_resize(&main); } }); } }); Ok(w) } /// Creates the window ahead of its first use, so going to the miniplayer is instant. pub fn prepare(app: &AppHandle) { if crate::platform::SEPARATE_MINI { let _ = window(app); } } fn unsupported() -> Result<(), String> { Err("The miniplayer window isn't used on this platform.".into()) } /// Moves the video into the miniplayer window and shows it in `corner`. #[tauri::command] pub async fn mini_show(app: AppHandle, corner: String) -> Result<(), String> { if !crate::platform::SEPARATE_MINI { return unsupported(); } let state = app.state::(); let corner = Corner::parse(&corner); *state.corner.lock() = corner; state.glide.fetch_add(1, Ordering::SeqCst); state.busy.store(false, Ordering::SeqCst); let mini = window(&app)?; let bounds = Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?; let _ = mini.set_size(PhysicalSize::new(bounds.mini_w as u32, bounds.mini_h as u32)); if let (Ok(outer), Ok(inner)) = (mini.outer_position(), mini.inner_position()) { *state.frame.lock() = (inner.x - outer.x, inner.y - outer.y); } place(&app, &mini, bounds.corner(corner)); let hwnd = crate::platform::host_handle(&mini).ok_or("The miniplayer window has no handle.")?; crate::player::set_video_host(&app, Some(hwnd))?; crate::platform::show_inactive(hwnd); state.visible.store(true, Ordering::SeqCst); Ok(()) } /// Moves the video back to the main window and hides the miniplayer window. #[tauri::command] pub async fn mini_hide(app: AppHandle) -> Result<(), String> { if !crate::platform::SEPARATE_MINI { return unsupported(); } let state = app.state::(); state.visible.store(false, Ordering::SeqCst); state.glide.fetch_add(1, Ordering::SeqCst); *state.drag.lock() = None; crate::player::set_video_host(&app, None)?; if let Some(mini) = app.get_webview_window(LABEL) { // Shown natively (without activation), so hidden natively too. if let Some(hwnd) = crate::platform::host_handle(&mini) { crate::platform::hide_window(hwnd); } } Ok(()) } #[tauri::command] pub async fn mini_drag_start(app: AppHandle) -> Result<(), String> { let state = app.state::(); state.busy.store(true, Ordering::SeqCst); state.glide.fetch_add(1, Ordering::SeqCst); let mini = window(&app)?; let bounds = Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?; let start = visible_position(&app, &mini)?; *state.drag.lock() = Some(Drag { start, bounds }); Ok(()) } /// Follows the pointer: `dx`/`dy` are logical pixels moved since the drag began. #[tauri::command] pub async fn mini_drag(app: AppHandle, dx: f64, dy: f64) -> Result<(), String> { let Some(drag) = *app.state::().drag.lock() else { return Ok(()) }; let b = drag.bounds; let to = b.clamp(drag.start.0 + (dx * b.scale).round() as i32, drag.start.1 + (dy * b.scale).round() as i32); if let Some(mini) = app.get_webview_window(LABEL) { place(&app, &mini, to); } Ok(()) } /// Ends a drag: glides to the corner nearest where the box is heading (a flick, /// `vx`/`vy` in logical pixels per millisecond, carries it on) and returns it. #[tauri::command] pub async fn mini_snap(app: AppHandle, vx: f64, vy: f64) -> Result { let state = app.state::(); let drag = state.drag.lock().take(); let mini = window(&app)?; let b = match drag { Some(d) => d.bounds, None => Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?, }; let from = visible_position(&app, &mini)?; let cx = from.0 as f64 + b.mini_w as f64 / 2.0 + vx * FLICK_MS * b.scale; let cy = from.1 as f64 + b.mini_h as f64 / 2.0 + vy * FLICK_MS * b.scale; let left = cx < b.left as f64 + b.width as f64 / 2.0; let top = cy < b.top as f64 + b.height as f64 / 2.0; let corner = match (top, left) { (true, true) => Corner::TopLeft, (true, false) => Corner::TopRight, (false, true) => Corner::BottomLeft, (false, false) => Corner::BottomRight, }; *state.corner.lock() = corner; let to = b.corner(corner); let generation = state.glide.fetch_add(1, Ordering::SeqCst) + 1; // Ease out over SNAP, a step per display frame; stops if another drag starts. let handle = app.clone(); std::thread::spawn(move || { let state = handle.state::(); let steps = (SNAP.as_millis() / 8) as i32; let start = std::time::Instant::now(); for i in 1..=steps { if state.glide.load(Ordering::SeqCst) != generation { return; } let t = (start.elapsed().as_secs_f64() / SNAP.as_secs_f64()).min(1.0); let e = 1.0 - (1.0 - t).powi(3); let x = from.0 + ((to.0 - from.0) as f64 * e).round() as i32; let y = from.1 + ((to.1 - from.1) as f64 * e).round() as i32; place(&handle, &mini, (x, y)); if t >= 1.0 || i == steps { break; } std::thread::sleep(Duration::from_millis(8)); } place(&handle, &mini, to); if state.glide.load(Ordering::SeqCst) == generation { state.busy.store(false, Ordering::SeqCst); } }); Ok(corner.name().into()) } /// Keeps the miniplayer in its corner as the main window moves or resizes. /// Runs on the UI thread (window events), where window getters answer directly. pub fn follow_main(main: &WebviewWindow) { let app = main.app_handle(); let Some(state) = app.try_state::() else { return }; if !state.visible.load(Ordering::SeqCst) || state.busy.load(Ordering::SeqCst) { return; } let Some(mini) = app.get_webview_window(LABEL) else { return }; let Some(bounds) = Bounds::of(main) else { return }; let corner = *state.corner.lock(); let _ = mini.set_size(PhysicalSize::new(bounds.mini_w as u32, bounds.mini_h as u32)); place(&app, &mini, bounds.corner(corner)); }