Release Kaleido Desktop 0.1.0-beta.12
All checks were successful
Validate Kaleido Desktop / validate (push) Successful in 1m22s

On Windows the miniplayer is now a window of its own (mini.rs, mini.html):
a borderless window owned by the main one that the video moves into
(VideoSurface::set_host swaps composition targets in one commit). Dragging
moves the whole window, so video and controls move together with no edge
flicker; release glides it to the nearest corner or the one it's flicked
towards, remembered, and it follows the main window. Its page mirrors the
player over events (mini:state / mini:action). Shown and hidden natively
without activation, so the main window keeps focus. macOS keeps the
in-page miniplayer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-04 17:35:08 -07:00
parent c3d2f4b6a7
commit 8ed44c2fe4
22 changed files with 871 additions and 26 deletions

View file

@ -1,5 +1,14 @@
# Changelog
## 0.1.0-beta.12
A smoother miniplayer on Windows.
- The miniplayer is now a small window of its own, so dragging it moves the video and its controls together: the video keeps playing smoothly as you move it, with no flicker around its edges.
- Letting go snaps it to the nearest corner of the window, or the corner you flick it towards, and it remembers that corner. It stays in place as the window moves or resizes.
- Using its buttons no longer takes focus from the main window, so keyboard shortcuts keep working.
- On Mac the miniplayer is unchanged for now.
## 0.1.0-beta.11
Fixes the app freezing when leaving full screen for the miniplayer, and adds local hang and crash reports.

View file

@ -82,8 +82,17 @@ into the display's HDR headroom; SDR video returns both to their defaults.
on demand. Timeline reports every 10 seconds (and when playback stalls) make the session appear in
Plex; a reply carrying a termination (the server owner stopped the stream) stops
playback and shows their message. The title is marked watched at the configured percentage. The player's back arrow (or Esc)
shrinks playback into a miniplayer: the video is drawn in a corner rectangle and the
interface stays visible around it, with a matching hole masked out of the page
shrinks playback into a miniplayer. On Windows it is a window of its own
(`src-tauri/src/mini.rs`, page `mini.html` → `src/mini/`): a small borderless window
owned by the main one, which the video moves into (`VideoSurface::set_host`, one
composition target per window, swapped in a single commit). Dragging moves that whole
window, so video and controls never drift apart; letting go glides it to a corner of
the main window (or the one it's flicked towards), and it follows the main window as
that moves or resizes. Its page mirrors the player from the main window and sends its
buttons back (`player/miniWindow.ts`, events `mini:state` / `mini:action`). The video
moves into it once the main page is opaque again, and back before the page turns
transparent, so neither window flashes. On macOS the miniplayer stays inside the page:
the video is drawn in a corner rectangle with a matching hole masked out of the page
(`html.player-mini`).
- **Upscaling** (`player/enhance.ts`): Performance and Balanced set mpv's scalers and
debanding and load shaders bundled from `src-tauri/shaders/` (FSRCNNX 16, nlmeans,

12
mini.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en" class="mini-window">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Kaleido</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/mini/main.tsx"></script>
</body>
</html>

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "kaleido-desktop",
"version": "0.1.0-beta.11",
"version": "0.1.0-beta.12",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaleido-desktop",
"version": "0.1.0-beta.11",
"version": "0.1.0-beta.12",
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@tanstack/react-query": "^5.105.0",

View file

@ -1,7 +1,7 @@
{
"name": "kaleido-desktop",
"private": true,
"version": "0.1.0-beta.11",
"version": "0.1.0-beta.12",
"type": "module",
"scripts": {
"dev": "vite",

2
src-tauri/Cargo.lock generated
View file

@ -2173,7 +2173,7 @@ dependencies = [
[[package]]
name = "kaleido"
version = "0.1.0-beta.11"
version = "0.1.0-beta.12"
dependencies = [
"fs2",
"futures-util",

View file

@ -1,6 +1,6 @@
[package]
name = "kaleido"
version = "0.1.0-beta.11"
version = "0.1.0-beta.12"
description = "Kaleido — a Plex client for Windows"
authors = ["Elijah"]
edition = "2021"
@ -67,6 +67,8 @@ windows = { version = "0.61", features = [
"Win32_System_Kernel",
"Win32_System_Memory",
"Win32_System_Threading",
# The miniplayer window's rounded corners (mini.rs).
"Win32_Graphics_Dwm",
] }
[profile.release]

View file

@ -1,9 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Kaleido main window",
"description": "Kaleido main window and miniplayer window",
"windows": [
"main"
"main",
"mini"
],
"permissions": [
"core:default",

View file

@ -1,5 +1,6 @@
mod diagnostics;
mod downloads;
mod mini;
mod mpv;
mod platform;
mod player;
@ -16,6 +17,8 @@ pub fn run() {
.plugin(tauri_plugin_process::init())
.plugin(
tauri_plugin_window_state::Builder::default()
// The miniplayer window is always placed from the main window (mini.rs).
.with_denylist(&["mini"])
.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
@ -24,6 +27,7 @@ pub fn run() {
.build(),
)
.manage(player::PlayerState::default())
.manage(mini::MiniState::default())
.manage(downloads::Downloads::default())
.setup(|app| {
let handle = app.handle().clone();
@ -32,6 +36,10 @@ pub fn run() {
if let Some(window) = app.get_webview_window("main") {
let w = window.clone();
window.on_window_event(move |event| {
// On the UI thread: places the miniplayer window without waiting on anything.
if let WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
mini::follow_main(&w);
}
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
// Never on the UI thread: the player's locks may be held by a
// command that is itself waiting on the UI thread (see player.rs).
@ -65,6 +73,11 @@ pub fn run() {
downloads::download_list,
downloads::download_set_dir,
downloads::download_write_meta,
mini::mini_show,
mini::mini_hide,
mini::mini_drag_start,
mini::mini_drag,
mini::mini_snap,
diagnostics::debug_freeze_ui,
diagnostics::debug_crash,
])

334
src-tauri/src/mini.rs Normal file
View file

@ -0,0 +1,334 @@
//! 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<R: Runtime>(main: &WebviewWindow<R>) -> Option<Bounds> {
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<Corner>,
/// 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<Option<Drag>>,
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<R: Runtime>(app: &AppHandle<R>, mini: &WebviewWindow<R>, (x, y): (i32, i32)) {
let (fx, fy) = *app.state::<MiniState>().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<R: Runtime>(app: &AppHandle<R>, mini: &WebviewWindow<R>) -> Result<(i32, i32), String> {
let pos = mini.outer_position().map_err(|e| e.to_string())?;
let (fx, fy) = *app.state::<MiniState>().frame.lock();
Ok((pos.x + fx, pos.y + fy))
}
fn main_window<R: Runtime>(app: &AppHandle<R>) -> Result<WebviewWindow<R>, 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<R: Runtime>(app: &AppHandle<R>) -> Result<WebviewWindow<R>, 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<R: Runtime>(app: &AppHandle<R>) {
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<R: Runtime>(app: AppHandle<R>, corner: String) -> Result<(), String> {
if !crate::platform::SEPARATE_MINI {
return unsupported();
}
let state = app.state::<MiniState>();
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<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {
if !crate::platform::SEPARATE_MINI {
return unsupported();
}
let state = app.state::<MiniState>();
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<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {
let state = app.state::<MiniState>();
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<R: Runtime>(app: AppHandle<R>, dx: f64, dy: f64) -> Result<(), String> {
let Some(drag) = *app.state::<MiniState>().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<R: Runtime>(app: AppHandle<R>, vx: f64, vy: f64) -> Result<String, String> {
let state = app.state::<MiniState>();
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::<MiniState>();
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<R: Runtime>(main: &WebviewWindow<R>) {
let app = main.app_handle();
let Some(state) = app.try_state::<MiniState>() 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));
}

View file

@ -27,6 +27,11 @@ impl VideoSurface {
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: bool) {}
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
pub fn set_rect<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>, _: Option<(i32, i32, i32, i32)>) {}
/// The video stays in the main window here (`SEPARATE_MINI` is false).
pub fn set_host(&mut self, _: Option<isize>, _: Option<&Mpv>) -> Result<(), String> {
Ok(())
}
}
/// Not needed yet: the only GPU-specific tier (RTX Video) is Windows-only.
@ -58,3 +63,18 @@ pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
/// Crashes are left to the system's crash reporter here.
pub fn install_crash_handler() {}
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
/// The miniplayer stays inside the main window's page here (PlayerOverlay).
pub const SEPARATE_MINI: bool = false;
pub fn host_handle<R: Runtime>(_: &WebviewWindow<R>) -> Option<isize> {
None
}
pub fn style_mini_window(_: isize) {}
pub fn show_inactive(_: isize) {}
pub fn hide_window(_: isize) {}

View file

@ -451,6 +451,11 @@ impl VideoSurface {
self.rect = rect;
self.fit(window, mpv);
}
/// The video stays in the main window here (`SEPARATE_MINI` is false).
pub fn set_host(&mut self, _: Option<isize>, _: Option<&Mpv>) -> Result<(), String> {
Ok(())
}
}
/// mpv properties the surface needs to observe.
@ -546,3 +551,18 @@ pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
/// Crashes are left to the system's crash reporter here.
pub fn install_crash_handler() {}
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
/// The miniplayer stays inside the main window's page here (PlayerOverlay).
pub const SEPARATE_MINI: bool = false;
pub fn host_handle<R: Runtime>(_: &WebviewWindow<R>) -> Option<isize> {
None
}
pub fn style_mini_window(_: isize) {}
pub fn show_inactive(_: isize) {}
pub fn hide_window(_: isize) {}

View file

@ -10,12 +10,15 @@ use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
use crate::mpv::Mpv;
pub struct VideoSurface {
/// The window, kept so fitting needn't ask the UI thread for it (Tauri's
/// `hwnd()` waits on the UI thread when called from elsewhere).
/// The window showing the video now: the main window, or the miniplayer's
/// (`set_host`). Window handles are kept so fitting needn't ask the UI
/// thread for them (Tauri's `hwnd()` waits on the UI thread elsewhere).
hwnd: HWND,
main: HWND,
attached: usize,
device: IDCompositionDevice,
_target: IDCompositionTarget,
/// One composition target per window the video has been shown in.
targets: Vec<(isize, IDCompositionTarget)>,
root: IDCompositionVisual,
visible: bool,
/// Where the video is drawn, in client pixels; `None` fills the window.
@ -47,12 +50,12 @@ impl VideoSurface {
let root = device.CreateVisual().map_err(|e| e.to_string())?;
let (width, height) = client_size(hwnd);
device.Commit().map_err(|e| e.to_string())?;
let _ = &target;
Ok(VideoSurface {
hwnd,
main: hwnd,
attached: 0,
device,
_target: target,
targets: vec![(hwnd.0 as isize, target)],
root,
visible: false,
rect: None,
@ -103,20 +106,59 @@ impl VideoSurface {
}
}
fn target(&self, hwnd: HWND) -> Option<&IDCompositionTarget> {
self.targets.iter().find(|(h, _)| *h == hwnd.0 as isize).map(|(_, t)| t)
}
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, visible: bool) {
if self.visible == visible {
return;
}
self.visible = visible;
if let Some(target) = self.target(self.hwnd) {
unsafe {
let _ = if visible { self._target.SetRoot(&self.root) } else { self._target.SetRoot(None::<&IDCompositionVisual>) };
let _ = if visible { target.SetRoot(&self.root) } else { target.SetRoot(None::<&IDCompositionVisual>) };
let _ = self.device.Commit();
}
}
}
/// Moves the video to another window (the miniplayer's, a raw `HWND`), or
/// back to the main window with `None`, filling its client area. Both
/// changes go out in one commit, so the video is never shown twice.
pub fn set_host(&mut self, host: Option<isize>, mpv: Option<&Mpv>) -> Result<(), String> {
let next = host.map(|h| HWND(h as _)).unwrap_or(self.main);
if next == self.hwnd {
return Ok(());
}
unsafe {
if self.target(next).is_none() {
// Behind the window's children (its web view), as in the main window.
let target = self.device.CreateTargetForHwnd(next, false).map_err(|e| e.to_string())?;
self.targets.push((next.0 as isize, target));
}
if self.visible {
if let Some(old) = self.target(self.hwnd) {
let _ = old.SetRoot(None::<&IDCompositionVisual>);
}
if let Some(new) = self.target(next) {
let _ = new.SetRoot(&self.root);
}
}
}
self.hwnd = next;
self.rect = None;
self.fit_host(mpv);
Ok(())
}
/// Matches mpv's composition size and the visual's position to the
/// window's client area, or to the miniplayer rectangle when one is set.
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, mpv: Option<&Mpv>) {
self.fit_host(mpv);
}
fn fit_host(&mut self, mpv: Option<&Mpv>) {
let (cw, ch) = client_size(self.hwnd);
let (x, y, w, h) = match self.rect {
Some((x, y, w, h)) => (x, y, w.max(16), h.max(16)),
@ -184,6 +226,49 @@ pub fn os_version() -> String {
/// Windows draws its own caption buttons in the page.
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
/// The miniplayer is a window of its own here: the video moves into it, so
/// dragging moves video and controls together.
pub const SEPARATE_MINI: bool = true;
/// The window's handle, for `VideoSurface::set_host`. Asks the UI thread, so
/// never call it while holding a lock the UI thread may wait on.
pub fn host_handle<R: Runtime>(window: &WebviewWindow<R>) -> Option<isize> {
window.hwnd().ok().map(|h| h.0 as isize)
}
/// Rounded corners (Windows 11) and no activation on click, so the main
/// window keeps focus and its keyboard shortcuts while the miniplayer is used.
pub fn style_mini_window(hwnd: isize) {
use ::windows::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND};
use ::windows::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, SetWindowLongPtrW, GWL_EXSTYLE, WS_EX_NOACTIVATE};
let hwnd = HWND(hwnd as _);
unsafe {
let preference = DWMWCP_ROUND;
let _ = DwmSetWindowAttribute(hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, &preference as *const _ as *const c_void, std::mem::size_of_val(&preference) as u32);
let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE.0 as isize);
}
}
/// Shows a window without activating it (Tauri's `show` activates).
pub fn show_inactive(hwnd: isize) {
use ::windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_SHOWNOACTIVATE};
unsafe {
let _ = ShowWindow(HWND(hwnd as _), SW_SHOWNOACTIVATE);
}
}
/// Hides a window shown by `show_inactive`. Tauri's `hide` would skip it: it
/// never saw the window shown, so believes it hidden already.
pub fn hide_window(hwnd: isize) {
use ::windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_HIDE};
unsafe {
let _ = ShowWindow(HWND(hwnd as _), SW_HIDE);
}
}
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
use ::windows::Win32::System::Diagnostics::Debug::{

View file

@ -180,13 +180,29 @@ fn player<R: Runtime>(app: &AppHandle<R>) -> Result<Arc<Mpv>, String> {
#[tauri::command]
pub async fn player_init<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, options: Option<InitOptions>) -> Result<(), String> {
let state = app.state::<PlayerState>();
{
let mut guard = state.mpv.lock();
if guard.is_none() {
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
}
}
// Outside the lock: creating a window waits on the UI thread.
crate::mini::prepare(&app);
Ok(())
}
/// Moves the video into another window (the miniplayer's, mini.rs) or back to
/// the main one. Off the UI thread only (it takes the player's locks).
pub fn set_video_host<R: Runtime>(app: &AppHandle<R>, host: Option<isize>) -> Result<(), String> {
let state = app.state::<PlayerState>();
let mpv = state.mpv.lock().clone();
let mut surface = state.surface.lock();
match surface.as_mut() {
Some(surface) => surface.set_host(host, mpv.as_deref()),
None => Ok(()),
}
}
#[tauri::command]
pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, visible: bool) -> Result<(), String> {
let state = app.state::<PlayerState>();

View file

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Kaleido",
"version": "0.1.0-beta.11",
"version": "0.1.0-beta.12",
"identifier": "tv.kaleido.desktop",
"build": {
"beforeDevCommand": "npm run dev",

153
src/mini/main.tsx Normal file
View file

@ -0,0 +1,153 @@
/**
* The miniplayer window's page (mini.html; src-tauri/src/mini.rs). The video
* is drawn beneath this transparent page by the native side; this page draws
* the controls, mirrors the main window's player (src/player/miniWindow.ts)
* and sends its buttons back. Dragging moves the whole window natively.
*/
import { StrictMode, useEffect, useState, type PointerEvent as ReactPointerEvent } from 'react';
import { createRoot } from 'react-dom/client';
import { invoke } from '@tauri-apps/api/core';
import { emitTo, listen } from '@tauri-apps/api/event';
import '@fontsource-variable/inter';
import '../styles/base.css';
import '../styles/ui.css';
import '../styles/player.css';
import './mini.css';
import { Icon } from '../ui/Icon';
import { MINI_CORNER_KEY, type MiniAction, type MiniState } from './types';
const send = (type: MiniAction) => emitTo('main', 'mini:action', { type }).catch(() => {});
window.addEventListener('contextmenu', (e) => e.preventDefault());
/**
* Drags the window: moves go to the native side one at a time, latest first
* (each is relative to where the drag began), and letting go glides it to a
* corner. A drag that ends over a button doesn't press it.
*/
function startDrag(e: ReactPointerEvent<HTMLElement>) {
if (e.button !== 0) return;
const el = e.currentTarget;
const pointer = e.pointerId;
const origin = { x: e.screenX, y: e.screenY };
const trail: { t: number; x: number; y: number }[] = [];
let dragging = false;
let started: Promise<unknown> | null = null;
let inFlight: Promise<unknown> | null = null;
let latest: { dx: number; dy: number } | null = null;
const pump = () => {
if (inFlight || !latest || !started) return;
const next = latest;
latest = null;
inFlight = started
.then(() => invoke('mini_drag', next))
.catch(() => {})
.finally(() => {
inFlight = null;
pump();
});
};
const move = (ev: PointerEvent) => {
const dx = ev.screenX - origin.x;
const dy = ev.screenY - origin.y;
trail.push({ t: ev.timeStamp, x: ev.screenX, y: ev.screenY });
while (trail.length > 2 && ev.timeStamp - trail[0].t > 100) trail.shift();
if (!dragging) {
if (Math.hypot(dx, dy) < 4) return;
dragging = true;
document.documentElement.classList.add('dragging');
el.setPointerCapture(pointer);
started = invoke('mini_drag_start').catch(() => {});
}
latest = { dx, dy };
pump();
};
const up = async () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
window.removeEventListener('pointercancel', up);
if (!dragging) return;
document.documentElement.classList.remove('dragging');
const swallow = (c: MouseEvent) => {
c.stopPropagation();
c.preventDefault();
};
window.addEventListener('click', swallow, { capture: true, once: true });
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
const first = trail[0];
const last = trail[trail.length - 1];
const dt = first && last ? Math.max(1, last.t - first.t) : 1;
const vx = first && last ? (last.x - first.x) / dt : 0;
const vy = first && last ? (last.y - first.y) / dt : 0;
// The last move lands before the glide begins.
while (inFlight || latest) await (inFlight ?? Promise.resolve(pump()));
const corner = await invoke<string>('mini_snap', { vx, vy }).catch(() => '');
if (corner) localStorage.setItem(MINI_CORNER_KEY, corner);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
window.addEventListener('pointercancel', up);
}
function Mini() {
const [s, setS] = useState<MiniState | null>(null);
useEffect(() => {
const unlisten = listen<MiniState>('mini:state', (e) => setS(e.payload));
unlisten.then(() => send('ready'));
return () => void unlisten.then((f) => f());
}, []);
if (!s) return <div className="mini-player loading" />;
const pct = s.duration ? Math.min(100, (s.position / s.duration) * 100) : 0;
return (
<div className={`mini-player${s.loading || s.error ? ' loading' : ''}`} onPointerDown={startDrag} onDoubleClick={() => send('expand')}>
<div className="mini-scrim" />
<div className="mini-top">
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => send('expand')}>
<Icon name="expand" size={17} />
</button>
<button className="mini-icon" aria-label="Stop playback" title="Close" onClick={() => send('close')}>
<Icon name="x" size={18} />
</button>
</div>
<div className="mini-center">
{(s.loading || s.buffering) && !s.error ? (
<span className="spinner" style={{ width: 30, height: 30 }} aria-label="Loading" />
) : s.error ? (
<span className="mini-error">Playback stopped</span>
) : (
<>
<button className="mini-icon" aria-label="Back 10 seconds" onClick={() => send('back')}>
<Icon name="replay10" size={22} />
</button>
<button className="mini-icon big" aria-label={s.paused ? 'Play' : 'Pause'} onClick={() => send('toggle')}>
<Icon name={s.paused || s.ended ? 'play' : 'pause'} size={26} />
</button>
<button className="mini-icon" aria-label="Forward 10 seconds" onClick={() => send('forward')}>
<Icon name="forward10" size={22} />
</button>
</>
)}
</div>
<div className="mini-caption">
<b>{s.title}</b>
{s.subtitle && <span>{s.subtitle}</span>}
</div>
<div className="mini-progress">
<i style={{ width: `${pct}%` }} />
</div>
</div>
);
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
<Mini />
</StrictMode>,
);

32
src/mini/mini.css Normal file
View file

@ -0,0 +1,32 @@
/* The miniplayer window (mini.html): the page is transparent over the video
and the box fills the window, whose corners Windows rounds. */
html.mini-window,
html.mini-window body,
html.mini-window #root {
height: 100%;
margin: 0;
overflow: hidden;
background: transparent;
}
html.mini-window .mini-player {
position: absolute;
inset: 0;
width: auto;
height: auto;
border-radius: 0;
box-shadow: none;
animation: none;
cursor: default;
}
html.mini-window.dragging .mini-player {
cursor: grabbing;
}
/* While dragged, the title stays and the buttons step back. */
html.mini-window.dragging .mini-scrim,
html.mini-window.dragging .mini-caption {
opacity: 1;
}
html.mini-window.dragging .mini-top,
html.mini-window.dragging .mini-center {
opacity: 0;
}

17
src/mini/types.ts Normal file
View file

@ -0,0 +1,17 @@
/** What the miniplayer window shows, sent from the main window (src/player/miniWindow.ts). */
export interface MiniState {
title: string;
subtitle: string;
paused: boolean;
ended: boolean;
position: number;
duration: number;
loading: boolean;
buffering: boolean;
error: boolean;
}
/** Buttons and gestures in the miniplayer window, carried out by the main window's player. */
export type MiniAction = 'ready' | 'toggle' | 'back' | 'forward' | 'expand' | 'close';
export const MINI_CORNER_KEY = 'kaleido.miniCorner';

View file

@ -10,6 +10,7 @@ import { win, isNative } from '../platform/native';
import { WindowControls } from '../app/TopBar';
import { navigate } from '../app/router';
import { mpv } from './engine';
import { separateMini } from './miniWindow';
import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance';
import { toast } from '../ui/overlays';
import type { Item } from '../plex/types';
@ -887,7 +888,8 @@ export function PlayerOverlay() {
}, [chromeHidden]);
if (!st.open || !st.item) return null;
if (st.mini) return <MiniPlayer />;
// On Windows the miniplayer is a window of its own (miniWindow.ts).
if (st.mini) return separateMini ? null : <MiniPlayer />;
const item = st.item;
const loading = !st.firstFrame && !st.error;
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;

97
src/player/miniWindow.ts Normal file
View file

@ -0,0 +1,97 @@
/**
* The miniplayer as a window of its own (Windows, src-tauri/src/mini.rs): the
* video moves into it, so it drags as one piece. This side keeps its page
* (src/mini/) up to date and carries out its buttons; macOS keeps the
* in-page miniplayer (PlayerOverlay).
*/
import { hostOS, invoke, isNative, listen } from '../platform/native';
import { episodeLabel } from '../app/format';
import { MINI_CORNER_KEY, type MiniAction, type MiniState } from '../mini/types';
import type { Item } from '../plex/types';
export const separateMini = isNative && hostOS === 'windows';
export async function showMiniWindow() {
await invoke('mini_show', { corner: localStorage.getItem(MINI_CORNER_KEY) ?? 'br' });
}
/** Moves the video back to the main window; harmless when already there. */
export async function hideMiniWindow() {
await invoke('mini_hide').catch(() => {});
}
interface PlayerView {
open: boolean;
mini: boolean;
item: Item | null;
paused: boolean;
ended: boolean;
position: number;
duration: number;
firstFrame: boolean;
buffering: boolean;
error: string;
}
interface PlayerActions {
togglePause(): void;
seekBy(delta: number): void;
expand(): void;
close(): Promise<void>;
}
function view(st: PlayerView): MiniState {
const item = st.item;
return {
title: item ? (item.type === 'episode' ? item.grandparentTitle : item.title) : '',
subtitle: item?.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : '',
paused: st.paused,
ended: st.ended,
position: st.position,
duration: st.duration,
loading: !st.firstFrame && !st.error,
buffering: st.buffering,
error: !!st.error,
};
}
/** Mirrors the player into the miniplayer window and listens for its buttons. */
export function bridgeMiniWindow(store: { getState(): PlayerView & PlayerActions; subscribe(listener: (st: PlayerView, prev: PlayerView) => void): () => void }) {
if (!separateMini) return;
let lastSent = 0;
let pending: ReturnType<typeof setTimeout> | null = null;
const send = async () => {
pending = null;
lastSent = Date.now();
const st = store.getState();
if (!st.open) return;
const { emitTo } = await import('@tauri-apps/api/event');
emitTo('mini', 'mini:state', view(st)).catch(() => {});
};
store.subscribe((st, prev) => {
if (!st.open || !st.mini) return;
// Everything but the position goes straight away; the position a few times a second.
const a = view(st);
const b = view(prev);
const only = (Object.keys(a) as (keyof MiniState)[]).every((k) => k === 'position' || a[k] === b[k]);
if (!only || st.mini !== prev.mini) {
if (pending) clearTimeout(pending);
send();
} else if (!pending) {
pending = setTimeout(send, Math.max(0, 250 - (Date.now() - lastSent)));
}
});
listen<{ type: MiniAction }>('mini:action', ({ type }) => {
const st = store.getState();
if (type === 'ready') return send();
if (!st.open) return;
if (type === 'toggle') st.togglePause();
else if (type === 'back') st.seekBy(-10);
else if (type === 'forward') st.seekBy(10);
else if (type === 'expand') st.expand();
else if (type === 'close') st.close();
});
}

View file

@ -11,6 +11,7 @@ import { keepAwake, isNative, win } from '../platform/native';
import { mpv, type MpvEvent, type MpvTrack } from './engine';
import { toast } from '../ui/overlays';
import { stopThemeMusic } from './theme';
import { bridgeMiniWindow, hideMiniWindow, separateMini, showMiniWindow } from './miniWindow';
export interface Track {
key: string; // stable UI key
@ -700,6 +701,8 @@ export const usePlayer = create<PlayerState>((set, get) => ({
keepAwake(false);
watchPerformance(false);
if (isNative) {
// From the miniplayer window, the video goes home first (and stays hidden).
if (separateMini && st.mini) await hideMiniWindow();
await mpv.command('stop').catch(() => {});
await mpv.show(false).catch(() => {});
}
@ -767,10 +770,19 @@ export const usePlayer = create<PlayerState>((set, get) => ({
await win.setFullscreen(false).catch(() => {});
set({ fullscreen: false });
}
if (separateMini) {
// Once the page is opaque again (no video in it), the video moves into
// the miniplayer's own window (miniWindow.ts).
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
if (get().open && get().mini) await showMiniWindow().catch((e) => console.warn('[mini]', e));
}
},
expand() {
if (get().mini) set({ mini: false });
if (!get().mini) return;
// The video comes back behind the still-opaque page before it turns transparent.
if (separateMini) hideMiniWindow().finally(() => set({ mini: false }));
else set({ mini: false });
},
async selectAudio(key) {
@ -854,15 +866,21 @@ export const usePlayer = create<PlayerState>((set, get) => ({
usePlayer.subscribe((st, prev) => {
if (st.firstFrame !== prev.firstFrame || st.open !== prev.open || st.error !== prev.error || st.mini !== prev.mini) {
const html = document.documentElement.classList;
html.toggle('video-active', st.open && st.firstFrame && !st.error);
// With a miniplayer window, the video has left this page entirely.
html.toggle('video-active', st.open && st.firstFrame && !st.error && !(st.mini && separateMini));
html.toggle('player-open', st.open && !st.mini);
html.toggle('player-mini', st.open && st.mini);
}
// However the miniplayer is left (expanding, playing another title, closing),
// the video returns to the whole window.
if (prev.mini && !st.mini && isNative) mpv.rect(null).catch(() => {});
if (prev.mini && !st.mini && isNative) {
if (separateMini) hideMiniWindow();
else mpv.rect(null).catch(() => {});
}
});
bridgeMiniWindow(usePlayer);
/** Subtitle look changes apply to the playing video straight away. */
const SUBTITLE_PREFS = ['subtitleScale', 'subtitleColor', 'subtitleEdge', 'subtitleBox', 'subtitleBold', 'subtitlePosition'] as const;
useSettings.subscribe((prefs, prev) => {

View file

@ -34,5 +34,10 @@ export default defineConfig({
plugins: [react(), devSession()],
clearScreen: false,
server: { port: 1420, strictPort: true, watch: { ignored: ['**/src-tauri/**'] } },
build: { target: 'es2022', chunkSizeWarningLimit: 1500 },
build: {
target: 'es2022',
chunkSizeWarningLimit: 1500,
// The miniplayer window has a page of its own (src/mini/).
rollupOptions: { input: { main: path.resolve(import.meta.dirname, 'index.html'), mini: path.resolve(import.meta.dirname, 'mini.html') } },
},
});