Port Kaleido Desktop to macOS

macOS (Apple silicon) now plays, browses and updates like Windows:

- Video: libmpv's render API draws into a CAOpenGLLayer beneath the
  WKWebView, with the miniplayer rectangle, HDR passthrough through
  extended dynamic range (PQ/BT.2020) and display-sleep prevention.
- Window: native traffic lights on the top bar's centre line, hidden
  with the player's controls; the page's caption buttons are Windows-only.
- Interface: macOS shortcut labels (⌘K, ⌘[, ⌃⌘F), Plex identifies the
  player as a Mac, and header values are kept ASCII (Mac computer names
  usually contain a curly apostrophe).
- The window appears without waiting for an animation frame, which
  WKWebView doesn't run in a hidden window.
- Credentials: release builds use the Keychain and are signed with a
  lasting self-signed certificate so access survives updates; debug
  builds keep tokens in a private file to avoid prompts on every rebuild.
- Bundling: scripts/fetch-libmpv.sh makes Homebrew's libmpv and its
  libraries self-contained; scripts/build.sh builds the .app, .dmg and
  signed update archive.

Releases now carry both platforms: publish-release.mjs uploads each
machine's build into one release, and update-manifest.mjs writes the
feed from that release's assets, refusing while a platform is missing.

The updater uses a new signing key (public key in tauri.conf.json), so
existing installs must be reinstalled once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah Kuntz 2026-11-02 15:14:40 -07:00
parent a3c05e9062
commit 7d0803481b
39 changed files with 1191 additions and 230 deletions

View file

@ -44,6 +44,7 @@ pub fn run() {
player::player_command,
player::player_set,
player::player_get,
player::window_buttons,
system::secret_get,
system::secret_set,
system::secret_delete,

View file

@ -192,6 +192,21 @@ impl Mpv {
}
}
/// The raw client handle, for platform code using parts of libmpv this
/// binding doesn't wrap (the render API).
pub fn raw_handle(&self) -> *mut c_void {
self.handle
}
/// Looks up another libmpv function by name.
///
/// # Safety
/// `T` must be the function's exact pointer type.
pub unsafe fn symbol<T: Copy>(&self, name: &str) -> Option<T> {
let name = CString::new(name).ok()?;
self.api._lib.get::<T>(name.as_bytes_with_nul()).ok().map(|s| *s)
}
fn error(&self, code: c_int) -> String {
unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() }
}

View file

@ -1,5 +1,5 @@
//! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK
//! view, then implement `VideoSurface` here.
//! view, then implement `VideoSurface` here (see macos.rs for the same idea).
//!
//! Browsing, downloads, settings and updates already work here; only native
//! video composition remains to be written.
@ -20,8 +20,11 @@ impl VideoSurface {
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
Vec::new()
}
pub fn start(&mut self, _: &std::sync::Arc<Mpv>) -> Result<(), String> {
Ok(())
}
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
pub fn show(&mut self, _: bool) {}
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)>) {}
}
@ -31,6 +34,16 @@ pub fn gpu_names() -> Vec<String> {
Vec::new()
}
pub fn device_name() -> String {
std::fs::read_to_string("/etc/hostname").map(|h| h.trim().to_string()).ok().filter(|h| !h.is_empty()).unwrap_or_else(|| "Linux PC".into())
}
pub fn os_version() -> String {
String::new()
}
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
let _ = rx.recv();

View file

@ -1,37 +1,531 @@
//! macOS: render mpv through its render API (libplacebo) into a CAMetalLayer
//! placed beneath the WKWebView, then implement `VideoSurface` here.
//! macOS: libmpv's render API (OpenGL) draws into a CAOpenGLLayer hosted by a
//! view placed beneath the WKWebView; libmpv names, power assertions, window
//! buttons and host details.
//!
//! Browsing, downloads, settings and updates already work here; only native
//! video composition remains to be written.
//! OpenGL is deprecated on macOS but still supported (on Metal); it is the
//! render API libmpv offers, and what IINA and other mpv front ends use.
#![allow(deprecated)]
use std::ffi::{c_char, c_int, c_void, CStr};
use std::ptr::{self, NonNull};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use std::sync::Arc;
use objc2::rc::Retained;
use objc2::{define_class, msg_send, AllocAnyThread, DefinedClass, MainThreadMarker};
use objc2_app_kit::{NSAutoresizingMaskOptions, NSView, NSWindow, NSWindowButton, NSWindowOrderingMode};
use objc2_core_foundation::CFTimeInterval;
use objc2_core_graphics::{kCGColorSpaceITUR_2100_PQ, CGColorSpace};
use objc2_core_video::CVTimeStamp;
use objc2_foundation::{NSNumber, NSPoint, NSRect, NSSize, NSString};
use objc2_open_gl::*;
use objc2_quartz_core::{CALayer, CAOpenGLLayer, CATransaction};
use parking_lot::Mutex;
use tauri::{Runtime, WebviewWindow};
use crate::mpv::Mpv;
pub const SURFACE_PROPERTIES: &[&str] = &[];
pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"];
// —— OpenGL ————————————————————————————————————————————————————————————
pub struct VideoSurface;
const GL_COLOR_BUFFER_BIT: u32 = 0x4000;
const GL_VIEWPORT: u32 = 0x0BA2;
const GL_DRAW_FRAMEBUFFER_BINDING: u32 = 0x8CA6;
const GL_RGBA16F: c_int = 0x881A;
const RTLD_LAZY: c_int = 0x1;
impl VideoSurface {
pub fn create<R: Runtime>(_: &WebviewWindow<R>) -> Result<VideoSurface, String> {
Err("Video playback is not available on this platform yet.".into())
}
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
Vec::new()
}
pub fn on_property(&mut self, _: &str, _: &serde_json::Value) {}
pub fn show(&mut self, _: 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)>) {}
#[link(name = "OpenGL", kind = "framework")]
extern "C" {
fn glGetIntegerv(pname: u32, data: *mut i32);
fn glClearColor(r: f32, g: f32, b: f32, a: f32);
fn glClear(mask: u32);
fn glFlush();
}
/// Not needed yet: the only GPU-specific tier (RTX Video) is Windows-only.
extern "C" {
fn dlopen(path: *const c_char, mode: c_int) -> *mut c_void;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
/// mpv resolves OpenGL functions through this (`ctx` is OpenGL.framework's handle).
extern "C" fn get_proc_address(ctx: *mut c_void, name: *const c_char) -> *mut c_void {
unsafe { dlsym(ctx, name) }
}
/// A 3.2 core context; 16-bit float colour (needed for HDR) when the renderer
/// offers it. Returns whether it got float colour.
unsafe fn create_gl_context() -> Result<(CGLContextObj, CGLPixelFormatObj, bool), String> {
let base = [
CGLPixelFormatAttribute::CGLPFAOpenGLProfile.0,
CGLOpenGLProfile::CGLOGLPVersion_3_2_Core.0,
CGLPixelFormatAttribute::CGLPFAAccelerated.0,
CGLPixelFormatAttribute::CGLPFADoubleBuffer.0,
CGLPixelFormatAttribute::CGLPFAAllowOfflineRenderers.0,
CGLPixelFormatAttribute::CGLPFASupportsAutomaticGraphicsSwitching.0,
];
let deep = [CGLPixelFormatAttribute::CGLPFAColorSize.0, 64, CGLPixelFormatAttribute::CGLPFAColorFloat.0];
for extra in [&deep[..], &[]] {
let mut attrs: Vec<CGLPixelFormatAttribute> = base.iter().chain(extra).map(|&a| CGLPixelFormatAttribute(a)).collect();
attrs.push(CGLPixelFormatAttribute(0));
let mut pf: CGLPixelFormatObj = ptr::null_mut();
let mut count = 0;
CGLChoosePixelFormat(NonNull::new_unchecked(attrs.as_mut_ptr()), NonNull::from(&mut pf), NonNull::from(&mut count));
if pf.is_null() {
continue;
}
let mut ctx: CGLContextObj = ptr::null_mut();
CGLCreateContext(pf, ptr::null_mut(), NonNull::from(&mut ctx));
if !ctx.is_null() {
return Ok((ctx, pf, !extra.is_empty()));
}
CGLReleasePixelFormat(pf);
}
Err("OpenGL is unavailable, so video can't be shown.".into())
}
// —— mpv render API ————————————————————————————————————————————————————
const RENDER_PARAM_API_TYPE: c_int = 1;
const RENDER_PARAM_OPENGL_INIT_PARAMS: c_int = 2;
const RENDER_PARAM_OPENGL_FBO: c_int = 3;
const RENDER_PARAM_FLIP_Y: c_int = 4;
const RENDER_UPDATE_FRAME: u64 = 1;
#[repr(C)]
struct RenderParam {
kind: c_int,
data: *mut c_void,
}
#[repr(C)]
struct OpenGlInitParams {
get_proc_address: extern "C" fn(*mut c_void, *const c_char) -> *mut c_void,
get_proc_address_ctx: *mut c_void,
}
#[repr(C)]
struct OpenGlFbo {
fbo: c_int,
w: c_int,
h: c_int,
internal_format: c_int,
}
type RenderCtx = *mut c_void;
/// An mpv render context and the functions that drive it. Every call happens
/// with the layer's OpenGL context locked and current, as libmpv requires.
struct Render {
ctx: RenderCtx,
render: unsafe extern "C" fn(RenderCtx, *mut RenderParam) -> c_int,
update: unsafe extern "C" fn(RenderCtx) -> u64,
report_swap: unsafe extern "C" fn(RenderCtx),
}
unsafe impl Send for Render {}
unsafe impl Sync for Render {}
/// libmpv calls this from its own threads when a frame is ready; it may not
/// call back into libmpv, so it only wakes the render thread.
extern "C" fn on_update(wake: *mut c_void) {
let wake = unsafe { &*(wake as *const SyncSender<()>) };
let _ = wake.try_send(());
}
// —— The video layer ———————————————————————————————————————————————————
struct LayerIvars {
cgl: CGLContextObj,
pixel_format: CGLPixelFormatObj,
/// The framebuffer holds 16-bit floats (so mpv needn't dither to 8 bits).
float: bool,
render: Mutex<Option<Arc<Render>>>,
}
define_class!(
#[unsafe(super(CAOpenGLLayer, CALayer))]
#[name = "KaleidoVideoLayer"]
#[ivars = LayerIvars]
struct VideoLayer;
impl VideoLayer {
#[unsafe(method(copyCGLPixelFormatForDisplayMask:))]
fn copy_pixel_format(&self, _mask: u32) -> CGLPixelFormatObj {
unsafe { CGLRetainPixelFormat(self.ivars().pixel_format) }
}
#[unsafe(method(copyCGLContextForPixelFormat:))]
fn copy_context(&self, _pf: CGLPixelFormatObj) -> CGLContextObj {
unsafe { CGLRetainContext(self.ivars().cgl) }
}
#[unsafe(method(releaseCGLContext:))]
fn release_context(&self, ctx: CGLContextObj) {
unsafe { CGLReleaseContext(ctx) }
}
#[unsafe(method(canDrawInCGLContext:pixelFormat:forLayerTime:displayTime:))]
fn can_draw(&self, _ctx: CGLContextObj, _pf: CGLPixelFormatObj, _t: CFTimeInterval, _ts: *const CVTimeStamp) -> bool {
true
}
#[unsafe(method(drawInCGLContext:pixelFormat:forLayerTime:displayTime:))]
fn draw(&self, ctx: CGLContextObj, _pf: CGLPixelFormatObj, _t: CFTimeInterval, _ts: *const CVTimeStamp) {
let render = self.ivars().render.lock().clone();
unsafe {
CGLLockContext(ctx);
CGLSetCurrentContext(ctx);
match render {
Some(r) => {
let mut fbo = 0;
let mut viewport = [0i32; 4];
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &mut fbo);
glGetIntegerv(GL_VIEWPORT, viewport.as_mut_ptr());
let mut target = OpenGlFbo { fbo, w: viewport[2], h: viewport[3], internal_format: if self.ivars().float { GL_RGBA16F } else { 0 } };
let mut flip: c_int = 1;
let mut params = [
RenderParam { kind: RENDER_PARAM_OPENGL_FBO, data: &mut target as *mut _ as *mut c_void },
RenderParam { kind: RENDER_PARAM_FLIP_Y, data: &mut flip as *mut _ as *mut c_void },
RenderParam { kind: 0, data: ptr::null_mut() },
];
(r.render)(r.ctx, params.as_mut_ptr());
}
None => {
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
}
}
glFlush();
CGLUnlockContext(ctx);
}
}
}
);
// The layer is drawn from the render thread as well as by Core Animation;
// its mutable state is behind a mutex and the CGL context lock.
unsafe impl Send for VideoLayer {}
unsafe impl Sync for VideoLayer {}
impl VideoLayer {
fn new(cgl: CGLContextObj, pixel_format: CGLPixelFormatObj, float: bool) -> Retained<VideoLayer> {
let this = VideoLayer::alloc().set_ivars(LayerIvars { cgl, pixel_format, float, render: Mutex::new(None) });
let layer: Retained<VideoLayer> = unsafe { msg_send![super(this), init] };
layer.setAsynchronous(false);
layer.setNeedsDisplayOnBoundsChange(true);
layer.setOpaque(true);
layer
}
}
/// Redraws whenever mpv has a new frame. Drawing off the main thread needs an
/// explicit flush for Core Animation to pick the frame up.
fn render_loop(layer: Retained<VideoLayer>, wake: Receiver<()>) {
let cgl = layer.ivars().cgl;
while wake.recv().is_ok() {
let Some(render) = layer.ivars().render.lock().clone() else { continue };
let flags = unsafe {
CGLLockContext(cgl);
CGLSetCurrentContext(cgl);
let flags = (render.update)(render.ctx);
CGLUnlockContext(cgl);
flags
};
if flags & RENDER_UPDATE_FRAME != 0 {
layer.display();
CATransaction::flush();
unsafe {
CGLLockContext(cgl);
CGLSetCurrentContext(cgl);
(render.report_swap)(render.ctx);
CGLUnlockContext(cgl);
}
}
}
}
// —— VideoSurface ——————————————————————————————————————————————————————
/// The view is only touched on the main thread; the layer is also drawn by the
/// render thread and reconfigured for HDR inside explicit transactions.
struct Ui {
view: Retained<NSView>,
layer: Retained<VideoLayer>,
}
unsafe impl Send for Ui {}
unsafe impl Sync for Ui {}
pub struct VideoSurface {
ui: Arc<Ui>,
wake: &'static SyncSender<()>,
wake_rx: Option<Receiver<()>>,
/// Where the video is drawn, in physical pixels; `None` fills the window.
rect: Option<(i32, i32, i32, i32)>,
mpv: Option<Arc<Mpv>>,
/// HDR passthrough is on (the `target-colorspace-hint` option, as on Windows).
passthrough: bool,
/// The layer is showing HDR in extended dynamic range.
edr: bool,
}
/// Runs `f` on the main thread with the window's web view and waits for it.
fn on_main<R: Runtime, T: Send + 'static>(
window: &WebviewWindow<R>,
f: impl FnOnce(&NSView, &NSWindow) -> T + Send + 'static,
) -> Result<T, String> {
let (tx, rx) = std::sync::mpsc::channel();
window
.with_webview(move |webview| unsafe {
let view = &*(webview.inner() as *const NSView);
let window = &*(webview.ns_window() as *const NSWindow);
let _ = tx.send(f(view, window));
})
.map_err(|e| e.to_string())?;
rx.recv().map_err(|e| e.to_string())
}
/// Places the video view: the whole web view, or a rectangle of it given in
/// physical pixels from the top left (the web page's coordinates).
fn place(ui: &Ui, webview: &NSView, window: &NSWindow, rect: Option<(i32, i32, i32, i32)>) {
let bounds = webview.frame();
let scale = window.backingScaleFactor();
let frame = match rect {
None => bounds,
Some((x, y, w, h)) => {
let (x, y, w, h) = (x as f64 / scale, y as f64 / scale, (w.max(16)) as f64 / scale, (h.max(16)) as f64 / scale);
let flipped = unsafe { webview.superview() }.is_some_and(|s| s.isFlipped());
let top = if flipped { bounds.origin.y + y } else { bounds.origin.y + bounds.size.height - y - h };
NSRect::new(NSPoint::new(bounds.origin.x + x, top), NSSize::new(w, h))
}
};
ui.view.setFrame(frame);
ui.view.setAutoresizingMask(if rect.is_none() {
NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewHeightSizable
} else {
NSAutoresizingMaskOptions::ViewNotSizable
});
if ui.layer.contentsScale() != scale {
ui.layer.setContentsScale(scale);
}
}
impl VideoSurface {
pub fn create<R: Runtime>(window: &WebviewWindow<R>) -> Result<VideoSurface, String> {
let (cgl, pixel_format, float) = unsafe { create_gl_context()? };
let layer = VideoLayer::new(cgl, pixel_format, float);
let ui = on_main(window, move |webview, window| unsafe {
let view = NSView::initWithFrame(MainThreadMarker::new_unchecked().alloc(), webview.frame());
// Layer-hosting: set the layer before asking for one.
view.setLayer(Some(&layer));
view.setWantsLayer(true);
view.setHidden(true);
// Let the video show through wherever the page is transparent.
let no = NSNumber::new_bool(false);
let _: () = msg_send![webview, setValue: &*no, forKey: &*NSString::from_str("drawsBackground")];
if let Some(parent) = webview.superview() {
parent.addSubview_positioned_relativeTo(&view, NSWindowOrderingMode::Below, Some(webview));
}
let ui = Ui { view, layer };
place(&ui, webview, window, None);
ui
})?;
let (wake, wake_rx) = sync_channel::<()>(1);
Ok(VideoSurface {
ui: Arc::new(ui),
wake: Box::leak(Box::new(wake)),
wake_rx: Some(wake_rx),
rect: None,
mpv: None,
passthrough: false,
edr: false,
})
}
/// mpv renders through the render API (`vo=libmpv`). Its window is forced
/// open only once the render context exists (`start`).
pub fn mpv_options(&self) -> Vec<(&'static str, String)> {
vec![("vo", "libmpv".into()), ("force-window", "no".into())]
}
/// Creates mpv's render context on the layer's OpenGL context and starts
/// the render thread. Runs once, after `mpv_initialize`.
pub fn start(&mut self, mpv: &Arc<Mpv>) -> Result<(), String> {
let Some(wake_rx) = self.wake_rx.take() else { return Ok(()) };
let hint = mpv.get_property("target-colorspace-hint").unwrap_or_default();
self.passthrough = (hint == serde_json::Value::Bool(true) || hint == "yes") && self.ui.layer.ivars().float;
self.mpv = Some(mpv.clone());
type Create = unsafe extern "C" fn(*mut RenderCtx, *mut c_void, *mut RenderParam) -> c_int;
type SetCallback = unsafe extern "C" fn(RenderCtx, extern "C" fn(*mut c_void), *mut c_void);
unsafe {
let missing = |name: &str| format!("libmpv is missing {name}");
let create: Create = mpv.symbol("mpv_render_context_create").ok_or_else(|| missing("mpv_render_context_create"))?;
let set_callback: SetCallback = mpv.symbol("mpv_render_context_set_update_callback").ok_or_else(|| missing("the render API"))?;
let render = mpv.symbol("mpv_render_context_render").ok_or_else(|| missing("the render API"))?;
let update = mpv.symbol("mpv_render_context_update").ok_or_else(|| missing("the render API"))?;
let report_swap = mpv.symbol("mpv_render_context_report_swap").ok_or_else(|| missing("the render API"))?;
let gl = dlopen(c"/System/Library/Frameworks/OpenGL.framework/OpenGL".as_ptr(), RTLD_LAZY);
let mut init = OpenGlInitParams { get_proc_address, get_proc_address_ctx: gl };
let mut params = [
RenderParam { kind: RENDER_PARAM_API_TYPE, data: c"opengl".as_ptr() as *mut c_void },
RenderParam { kind: RENDER_PARAM_OPENGL_INIT_PARAMS, data: &mut init as *mut _ as *mut c_void },
RenderParam { kind: 0, data: ptr::null_mut() },
];
let cgl = self.ui.layer.ivars().cgl;
let mut ctx: RenderCtx = ptr::null_mut();
CGLLockContext(cgl);
CGLSetCurrentContext(cgl);
let code = create(&mut ctx, mpv.raw_handle(), params.as_mut_ptr());
CGLUnlockContext(cgl);
if code < 0 || ctx.is_null() {
return Err(format!("The video renderer couldn't start ({code})."));
}
set_callback(ctx, on_update, self.wake as *const SyncSender<()> as *mut c_void);
*self.ui.layer.ivars().render.lock() = Some(Arc::new(Render { ctx, render, update, report_swap }));
}
let layer = self.ui.layer.clone();
std::thread::Builder::new()
.name("mpv-render".into())
.spawn(move || render_loop(layer, wake_rx))
.map_err(|e| e.to_string())?;
mpv.set_property("force-window", &serde_json::Value::Bool(true))
}
/// HDR passthrough: for PQ or HLG video, mpv outputs PQ (BT.2020) instead of
/// tone-mapping to SDR, and the layer shows it in extended dynamic range, so
/// macOS maps it to the display's HDR headroom. SDR video uses the defaults.
pub fn on_property(&mut self, name: &str, value: &serde_json::Value) {
if name != "video-params/gamma" {
return;
}
let edr = self.passthrough && matches!(value.as_str(), Some("pq" | "hlg"));
if edr == self.edr {
return;
}
self.edr = edr;
if let Some(mpv) = &self.mpv {
let target = |v: &str| serde_json::Value::String(v.into());
let (trc, prim) = if edr { ("pq", "bt.2020") } else { ("auto", "auto") };
let _ = mpv.set_property("target-trc", &target(trc));
let _ = mpv.set_property("target-prim", &target(prim));
}
// Layer properties may change off the main thread inside a transaction.
let layer = &self.ui.layer;
CATransaction::begin();
layer.setWantsExtendedDynamicRangeContent(edr);
let pq = if edr { CGColorSpace::with_name(Some(unsafe { kCGColorSpaceITUR_2100_PQ })) } else { None };
layer.setColorspace(pq.as_deref());
CATransaction::commit();
}
pub fn show<R: Runtime>(&mut self, window: &WebviewWindow<R>, visible: bool) {
let ui = self.ui.clone();
let _ = window.run_on_main_thread(move || {
ui.view.setHidden(!visible);
if visible {
ui.layer.setNeedsDisplay();
}
});
}
/// Keeps the video view matched to the web view, or to the miniplayer
/// rectangle when one is set.
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, _: Option<&Mpv>) {
let ui = self.ui.clone();
let rect = self.rect;
let _ = window.with_webview(move |webview| unsafe {
let view = &*(webview.inner() as *const NSView);
let window = &*(webview.ns_window() as *const NSWindow);
place(&ui, view, window, rect);
});
}
pub fn set_rect<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>, rect: Option<(i32, i32, i32, i32)>) {
self.rect = rect;
self.fit(window, mpv);
}
}
/// mpv properties the surface needs to observe.
pub const SURFACE_PROPERTIES: &[&str] = &["video-params/gamma"];
/// File names libmpv may have on this platform.
pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"];
/// Not needed: the only GPU-specific tier (RTX Video) is Windows-only.
pub fn gpu_names() -> Vec<String> {
Vec::new()
}
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
// TODO(macOS): IOPMAssertionCreateWithName(PreventUserIdleDisplaySleep).
let _ = rx.recv();
/// The Mac's name as set in System Settings → General → Sharing.
pub fn device_name() -> String {
objc2_foundation::NSHost::currentHost()
.localizedName()
.map(|n| n.to_string())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "Mac".into())
}
/// macOS version, e.g. "15.4".
pub fn os_version() -> String {
let v = objc2_foundation::NSProcessInfo::processInfo().operatingSystemVersion();
if v.patchVersion > 0 {
format!("{}.{}.{}", v.majorVersion, v.minorVersion, v.patchVersion)
} else {
format!("{}.{}", v.majorVersion, v.minorVersion)
}
}
/// Shows or hides the traffic lights (they fade with the player's controls).
pub fn set_window_buttons<R: Runtime>(window: &WebviewWindow<R>, visible: bool) {
let Ok(ns_window) = window.ns_window() else { return };
let ns_window = ns_window as usize;
let _ = window.run_on_main_thread(move || unsafe {
let window = &*(ns_window as *const NSWindow);
for kind in [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton] {
if let Some(button) = window.standardWindowButton(kind) {
button.setHidden(!visible);
}
}
// AppKit lays the buttons out again at their default place; the window's
// view restores the configured position (trafficLightPosition) when drawn.
if let Some(view) = window.contentView() {
view.setNeedsDisplay(true);
}
});
}
// —— Power —————————————————————————————————————————————————————————————
type CFStringRef = *const c_void;
const CF_STRING_ENCODING_UTF8: u32 = 0x0800_0100;
const IOPM_ASSERTION_LEVEL_ON: u32 = 255;
#[link(name = "CoreFoundation", kind = "framework")]
extern "C" {
fn CFStringCreateWithCString(alloc: *const c_void, s: *const c_char, encoding: u32) -> CFStringRef;
fn CFRelease(cf: *const c_void);
}
#[link(name = "IOKit", kind = "framework")]
extern "C" {
fn IOPMAssertionCreateWithName(kind: CFStringRef, level: u32, name: CFStringRef, id: *mut u32) -> i32;
fn IOPMAssertionRelease(id: u32) -> i32;
}
/// Keeps the display awake until `rx` closes or receives.
pub fn hold_awake(rx: Receiver<()>) {
let cf = |s: &CStr| unsafe { CFStringCreateWithCString(ptr::null(), s.as_ptr(), CF_STRING_ENCODING_UTF8) };
let kind = cf(c"PreventUserIdleDisplaySleep");
let name = cf(c"Kaleido is playing video");
let mut id = 0u32;
let held = unsafe { IOPMAssertionCreateWithName(kind, IOPM_ASSERTION_LEVEL_ON, name, &mut id) } == 0;
let _ = rx.recv();
unsafe {
if held {
IOPMAssertionRelease(id);
}
CFRelease(kind);
CFRelease(name);
}
}

View file

@ -2,11 +2,13 @@
//! Each platform file exposes the same items:
//!
//! - `VideoSurface`: composes mpv's output beneath the web view
//! (`create`, `mpv_options`, `on_property`, `show`, `fit`, `set_rect`).
//! (`create`, `mpv_options`, `start`, `on_property`, `show`, `fit`, `set_rect`).
//! - `SURFACE_PROPERTIES`: mpv properties the surface observes.
//! - `MPV_LIBRARIES`: libmpv file names to look for.
//! - `hold_awake`: prevents display sleep until the receiver closes.
//! - `gpu_names`: the graphics adapters, by name.
//! - `device_name`, `os_version`: how the computer identifies itself to Plex.
//! - `set_window_buttons`: shows or hides native window buttons (macOS).
#[cfg(target_os = "windows")]
mod windows;

View file

@ -69,6 +69,11 @@ impl VideoSurface {
]
}
/// Nothing to set up once mpv is initialized: it creates its swapchain itself.
pub fn start(&mut self, _: &std::sync::Arc<Mpv>) -> Result<(), String> {
Ok(())
}
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);
@ -94,7 +99,7 @@ impl VideoSurface {
}
}
pub fn show(&mut self, visible: bool) {
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, visible: bool) {
if self.visible == visible {
return;
}
@ -141,7 +146,6 @@ 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.
/// Hardware graphics adapters as DXGI names them (e.g. "NVIDIA GeForce RTX 4080").
pub fn gpu_names() -> Vec<String> {
use ::windows::Win32::Graphics::Dxgi::*;
@ -165,6 +169,19 @@ pub fn gpu_names() -> Vec<String> {
names
}
/// The computer's name, as Plex shows it.
pub fn device_name() -> String {
std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into())
}
pub fn os_version() -> String {
"11".into()
}
/// Windows draws its own caption buttons in the page.
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
/// Keeps the display awake until `rx` closes or receives.
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
use ::windows::Win32::System::Power::*;
unsafe {

View file

@ -71,7 +71,9 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?;
set("keep-open", "yes")?;
set("idle", "yes")?;
set("force-window", "yes")?;
if !render_options.iter().any(|(k, _)| *k == "force-window") {
set("force-window", "yes")?;
}
set("osc", "no")?;
set("osd-level", "0")?;
set("input-default-bindings", "no")?;
@ -107,6 +109,9 @@ fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts
}
mpv.request_log_messages("warn");
mpv.initialize()?;
if let Some(surface) = app.state::<PlayerState>().surface.lock().as_mut() {
surface.start(&mpv)?;
}
for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() {
mpv.observe(i as u64 + 1, name);
}
@ -183,7 +188,7 @@ pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>
let mut surface = state.surface.lock();
if let Some(surface) = surface.as_mut() {
surface.fit(&window, mpv.as_deref());
surface.show(visible);
surface.show(&window, visible);
}
Ok(())
}
@ -225,6 +230,13 @@ pub async fn player_get<R: Runtime>(app: AppHandle<R>, name: String) -> Result<V
player(&app)?.get_property(&name)
}
/// Shows or hides the native window buttons where the OS draws them (the
/// macOS traffic lights fade with the player's controls).
#[tauri::command]
pub fn window_buttons<R: Runtime>(window: WebviewWindow<R>, visible: bool) {
crate::platform::set_window_buttons(&window, visible);
}
/// Keeps the video surface matched to the window's client area.
pub fn on_resize<R: Runtime>(window: &WebviewWindow<R>) {
let app = window.app_handle();

View file

@ -13,9 +13,14 @@ fn entry(key: &str) -> Result<keyring::Entry, String> {
keyring::Entry::new(SERVICE, key).map_err(|e| e.to_string())
}
/// Secrets (Plex tokens) live in Windows Credential Manager, never in plain files.
/// Secrets (Plex tokens) live in the OS's credential store (Windows Credential
/// Manager, the macOS Keychain), never in plain files; except in macOS debug
/// builds, see `dev_secrets`.
#[tauri::command]
pub fn secret_get(key: String) -> Result<Option<String>, String> {
pub fn secret_get<R: Runtime>(app: AppHandle<R>, key: String) -> Result<Option<String>, String> {
if let Some(path) = dev_secrets(&app) {
return Ok(read_dev_secrets(&path).get(&key).and_then(|v| v.as_str()).map(String::from));
}
match entry(&key)?.get_password() {
Ok(v) => Ok(Some(v)),
Err(keyring::Error::NoEntry) => Ok(None),
@ -24,18 +29,66 @@ pub fn secret_get(key: String) -> Result<Option<String>, String> {
}
#[tauri::command]
pub fn secret_set(key: String, value: String) -> Result<(), String> {
entry(&key)?.set_password(&value).map_err(|e| e.to_string())
pub fn secret_set<R: Runtime>(app: AppHandle<R>, key: String, value: String) -> Result<(), String> {
if let Some(path) = dev_secrets(&app) {
let mut all = read_dev_secrets(&path);
all.insert(key, Value::String(value));
return write_dev_secrets(&path, &all);
}
let entry = entry(&key)?;
match entry.set_password(&value) {
Ok(()) => Ok(()),
// A Keychain item left by a differently signed build can be impossible to
// update yet still block adding; replacing it recovers.
Err(keyring::Error::PlatformFailure(_)) if cfg!(target_os = "macos") => {
let _ = entry.delete_credential();
entry.set_password(&value).map_err(|e| e.to_string())
}
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
pub fn secret_delete(key: String) -> Result<(), String> {
pub fn secret_delete<R: Runtime>(app: AppHandle<R>, key: String) -> Result<(), String> {
if let Some(path) = dev_secrets(&app) {
let mut all = read_dev_secrets(&path);
all.remove(&key);
return write_dev_secrets(&path, &all);
}
match entry(&key)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
}
}
/// macOS ties Keychain access to the app's code signature, and every debug
/// build is a new unsigned binary, so the Keychain would ask for permission
/// after each rebuild. Debug builds there keep secrets in a private file in the
/// app data folder instead (development only, like the `.env` sign-in).
fn dev_secrets<R: Runtime>(app: &AppHandle<R>) -> Option<std::path::PathBuf> {
if !(cfg!(debug_assertions) && cfg!(target_os = "macos")) {
return None;
}
app.path().app_data_dir().ok().map(|d| d.join("dev-secrets.json"))
}
fn read_dev_secrets(path: &std::path::Path) -> serde_json::Map<String, Value> {
std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
fn write_dev_secrets(path: &std::path::Path, all: &serde_json::Map<String, Value>) -> Result<(), String> {
use std::io::Write;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
}
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let mut file = options.open(path).map_err(|e| e.to_string())?;
file.write_all(Value::Object(all.clone()).to_string().as_bytes()).map_err(|e| e.to_string())
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AppInfo {
@ -43,6 +96,7 @@ pub struct AppInfo {
data_dir: String,
default_download_dir: String,
platform: String,
os_version: String,
device_name: String,
/// Graphics adapters by name (decides which upscaling tiers are offered).
gpus: Vec<String>,
@ -63,7 +117,8 @@ pub fn app_info<R: Runtime>(app: AppHandle<R>) -> AppInfo {
data_dir: data,
default_download_dir: downloads,
platform: std::env::consts::OS.to_string(),
device_name: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "Windows PC".into()),
os_version: crate::platform::os_version(),
device_name: crate::platform::device_name(),
gpus: crate::platform::gpu_names(),
}
}