Kaleido-Desktop/src-tauri/src/platform/windows.rs
Elijah 00d72e70f4 Create Kaleido Desktop, a cinematic Plex client for Windows
Tauri 2 shell with a React/TypeScript interface and libmpv playback composed
beneath the web view (DirectComposition on Windows). Shared code with per-OS
platform modules and configs so macOS and Linux can follow.

- Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home
- Home, Movies and TV Shows (Discover, Library, Collections), search, people
- Title pages with logos, ratings, cast, extras, seasons and episodes
- Direct play with Plex conversion fallback, tracks, markers, autoplay
- Metadata editing, artwork, fix match, refresh, analyze and deletion
- Resumable offline downloads
- App settings and Plex server administration with a live dashboard
- Signed updater feed and Forgejo CI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 16:26:37 -07:00

133 lines
4.6 KiB
Rust

//! Windows: DirectComposition video surface, libmpv names and power requests.
use std::ffi::c_void;
use tauri::{Runtime, WebviewWindow};
use ::windows::core::{IUnknown, Interface};
use ::windows::Win32::Foundation::{HWND, RECT};
use ::windows::Win32::Graphics::DirectComposition::*;
use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
use crate::mpv::Mpv;
pub struct VideoSurface {
attached: usize,
device: IDCompositionDevice,
_target: IDCompositionTarget,
root: IDCompositionVisual,
visible: bool,
pub width: i32,
pub height: i32,
}
// DirectComposition objects may be used from any thread when access is
// serialized; the surface always sits behind PlayerState's mutex.
unsafe impl Send for VideoSurface {}
fn client_size(hwnd: HWND) -> (i32, i32) {
let mut rect = RECT::default();
unsafe {
let _ = GetClientRect(hwnd, &mut rect);
}
((rect.right - rect.left).max(16), (rect.bottom - rect.top).max(16))
}
impl VideoSurface {
pub fn create<R: Runtime>(window: &WebviewWindow<R>) -> Result<VideoSurface, String> {
let hwnd = HWND(window.hwnd().map_err(|e| e.to_string())?.0 as _);
unsafe {
let device: IDCompositionDevice =
DCompositionCreateDevice2(None).map_err(|e| format!("DirectComposition is unavailable: {e}"))?;
// topmost = false: the visual tree is composed behind the window's children.
let target = device.CreateTargetForHwnd(hwnd, false).map_err(|e| e.to_string())?;
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 {
attached: 0,
device,
_target: target,
root,
visible: false,
width,
height,
})
}
}
/// mpv renders into a composition swapchain (`display-swapchain`), shown
/// in a DirectComposition visual behind the web view's child windows.
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
vec![
("vo", "gpu-next".into()),
("gpu-api", "d3d11".into()),
("d3d11-output-mode", "composition".into()),
("d3d11-composition-size", format!("{}x{}", self.width, self.height)),
]
}
pub fn on_property(&mut self, name: &str, value: &serde_json::Value) {
if name == "display-swapchain" {
self.attach(value.as_i64().unwrap_or(0) as usize);
}
}
/// Shows mpv's current swapchain; mpv recreates it with its video output.
fn attach(&mut self, swapchain: usize) {
if swapchain == self.attached {
return;
}
self.attached = swapchain;
unsafe {
let raw = swapchain as *mut c_void;
let result = match IUnknown::from_raw_borrowed(&raw) {
Some(unknown) if swapchain != 0 => self.root.SetContent(unknown),
_ => self.root.SetContent(None::<&IUnknown>),
};
if let Err(e) = result {
eprintln!("[video] could not attach swapchain: {e}");
}
let _ = self.device.Commit();
}
}
pub fn show(&mut self, visible: bool) {
if self.visible == visible {
return;
}
self.visible = visible;
unsafe {
let _ = if visible { self._target.SetRoot(&self.root) } else { self._target.SetRoot(None::<&IDCompositionVisual>) };
let _ = self.device.Commit();
}
}
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>) {
let Ok(h) = window.hwnd() else { return };
let (w, h) = client_size(HWND(h.0 as _));
if (w, h) == (self.width, self.height) {
return;
}
self.width = w;
self.height = h;
if let Some(mpv) = mpv {
let _ = mpv.set_property("d3d11-composition-size", &serde_json::Value::String(format!("{w}x{h}")));
}
}
}
/// mpv properties the surface needs to observe.
pub const SURFACE_PROPERTIES: &[&str] = &["display-swapchain"];
/// File names libmpv may have on this platform.
pub const MPV_LIBRARIES: &[&str] = &["libmpv-2.dll", "mpv-2.dll"];
/// Keeps the display awake until `rx` closes or receives.
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
use ::windows::Win32::System::Power::*;
unsafe {
SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED);
let _ = rx.recv();
SetThreadExecutionState(ES_CONTINUOUS);
}
}