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>
This commit is contained in:
Elijah 2026-10-30 16:26:37 -07:00
commit 00d72e70f4
121 changed files with 25315 additions and 0 deletions

6368
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

63
src-tauri/Cargo.toml Normal file
View file

@ -0,0 +1,63 @@
[package]
name = "kaleido"
version = "0.1.0"
description = "Kaleido — a Plex client for Windows"
authors = ["Elijah"]
edition = "2021"
[lib]
name = "kaleido_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["protocol-asset"] }
tauri-plugin-http = "2"
tauri-plugin-dialog = "2"
tauri-plugin-opener = "2"
tauri-plugin-window-state = "2"
tauri-plugin-updater = "2"
tauri-plugin-process = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
libloading = "0.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util", "sync", "time"] }
reqwest = { version = "0.12", default-features = false, features = ["stream", "rustls-tls", "json"] }
futures-util = "0.3"
fs2 = "0.4"
parking_lot = "0.12"
once_cell = "1"
log = "0.4"
# Credentials use each OS's native store: Credential Manager, Keychain, Secret Service.
[target.'cfg(target_os = "macos")'.dependencies]
keyring = { version = "3", features = ["apple-native"] }
[target.'cfg(target_os = "linux")'.dependencies]
keyring = { version = "3", features = ["sync-secret-service", "crypto-rust"] }
[target.'cfg(windows)'.dependencies]
keyring = { version = "3", features = ["windows-native"] }
windows = { version = "0.61", features = [
"Win32_Foundation",
"Win32_UI_WindowsAndMessaging",
"Win32_Graphics_Gdi",
"Win32_System_LibraryLoader",
"Win32_UI_Shell",
"Win32_System_Power",
"Win32_Storage_FileSystem",
"Win32_Graphics_DirectComposition",
"Win32_Graphics_Dxgi",
"Win32_Graphics_Dxgi_Common",
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D11",
"Foundation_Numerics",
] }
[profile.release]
codegen-units = 1
lto = true
opt-level = 3
strip = true

3
src-tauri/build.rs Normal file
View file

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View file

@ -0,0 +1,47 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Kaleido main window",
"windows": [
"main"
],
"permissions": [
"core:default",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-maximize",
"core:window:allow-unmaximize",
"core:window:allow-close",
"core:window:allow-start-dragging",
"core:window:allow-set-fullscreen",
"core:window:allow-is-fullscreen",
"core:window:allow-is-maximized",
"core:window:allow-show",
"core:window:allow-set-focus",
"core:window:allow-set-title",
"dialog:default",
"opener:default",
"opener:allow-open-path",
"opener:allow-reveal-item-in-dir",
"window-state:default",
{
"identifier": "http:default",
"allow": [
{
"url": "https://*"
},
{
"url": "http://*"
},
{
"url": "https://*:*"
},
{
"url": "http://*:*"
}
]
},
"updater:default",
"process:allow-restart"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

428
src-tauri/src/downloads.rs Normal file
View file

@ -0,0 +1,428 @@
//! Offline downloads: resumable HTTP transfers of Plex media parts with a small
//! JSON catalog, so downloaded titles stay browsable and playable offline.
//!
//! URLs carrying Plex tokens are only held in memory. The catalog stores the
//! server-relative source path; resuming after a restart asks the interface for
//! a freshly signed URL.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use futures_util::StreamExt;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tauri::{AppHandle, Emitter, Manager, Runtime};
use tokio::io::AsyncWriteExt;
use tokio::sync::{watch, Semaphore};
const MAX_ACTIVE: usize = 2;
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
#[serde(rename_all = "lowercase")]
pub enum Status {
Queued,
Downloading,
Paused,
Completed,
Failed,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Item {
pub id: String,
pub file_path: String,
pub total: u64,
pub received: u64,
pub status: Status,
#[serde(default)]
pub error: Option<String>,
#[serde(default)]
pub meta: Value,
pub created_at: u64,
#[serde(default)]
pub speed: u64,
}
pub struct Downloads {
items: Mutex<Vec<Item>>,
dir: Mutex<Option<PathBuf>>,
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
permits: Arc<Semaphore>,
client: reqwest::Client,
}
impl Default for Downloads {
fn default() -> Self {
Downloads {
items: Mutex::new(Vec::new()),
dir: Mutex::new(None),
cancels: Mutex::new(HashMap::new()),
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
client: reqwest::Client::builder()
.connect_timeout(Duration::from_secs(20))
.user_agent("Kaleido")
.build()
.expect("http client"),
}
}
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
fn catalog_path<R: Runtime>(app: &AppHandle<R>) -> PathBuf {
crate::system::data_dir(app).join("downloads.json")
}
fn save<R: Runtime>(app: &AppHandle<R>) {
let state = app.state::<Downloads>();
let items = state.items.lock().clone();
let path = catalog_path(app);
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(text) = serde_json::to_string_pretty(&items) {
let tmp = path.with_extension("json.tmp");
if std::fs::write(&tmp, text).is_ok() {
let _ = std::fs::rename(tmp, path);
}
}
}
/// Loads the catalog at startup. Interrupted transfers become paused: their
/// signed URLs were never persisted.
pub fn restore<R: Runtime>(app: &AppHandle<R>) {
let Ok(text) = std::fs::read_to_string(catalog_path(app)) else { return };
let Ok(mut items) = serde_json::from_str::<Vec<Item>>(&text) else { return };
for item in items.iter_mut() {
if matches!(item.status, Status::Downloading | Status::Queued) {
// Marked so the interface resumes it once it has a signed URL again.
item.status = Status::Paused;
item.error = Some("interrupted".into());
}
if item.status == Status::Completed && !Path::new(&item.file_path).exists() {
item.status = Status::Failed;
item.error = Some("The downloaded file is missing.".into());
}
item.speed = 0;
}
*app.state::<Downloads>().items.lock() = items;
}
fn update<R: Runtime>(app: &AppHandle<R>, id: &str, f: impl FnOnce(&mut Item)) -> Option<Item> {
let state = app.state::<Downloads>();
let mut items = state.items.lock();
let item = items.iter_mut().find(|i| i.id == id)?;
f(item);
let snapshot = item.clone();
drop(items);
let _ = app.emit("download", &snapshot);
Some(snapshot)
}
fn sanitize(name: &str) -> String {
let cleaned: String = name
.chars()
.map(|c| if "<>:\"/\\|?*".contains(c) || c.is_control() { '_' } else { c })
.collect();
let trimmed = cleaned.trim().trim_end_matches('.').to_string();
if trimmed.is_empty() {
"Untitled".into()
} else {
trimmed.chars().take(120).collect()
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StartRequest {
id: String,
url: String,
folder: String,
file_name: String,
#[serde(default)]
meta: Value,
/// Artwork to keep with the download: name → signed URL.
#[serde(default)]
assets: HashMap<String, String>,
}
#[tauri::command]
pub async fn download_start<R: Runtime>(app: AppHandle<R>, request: StartRequest) -> Result<Item, String> {
let state = app.state::<Downloads>();
let dir = state.dir.lock().clone().ok_or("Choose a download folder first.")?;
// The folder may be nested ("Show/Season 1"); sanitize each component.
let folder = request
.folder
.split(['/', '\\'])
.filter(|c| !c.trim().is_empty() && *c != "." && *c != "..")
.fold(dir.clone(), |p, c| p.join(sanitize(c)));
tokio::fs::create_dir_all(&folder).await.map_err(|e| format!("Cannot create the download folder: {e}"))?;
let file_path = folder.join(sanitize(&request.file_name));
let mut meta = request.meta.clone();
if let Value::Object(map) = &mut meta {
let mut local = serde_json::Map::new();
for (name, url) in &request.assets {
let target = folder.join(format!(".{}.jpg", sanitize(name)));
if fetch_to(&state.client, url, &target).await.is_ok() {
local.insert(name.clone(), Value::String(target.display().to_string()));
}
}
map.insert("localAssets".into(), Value::Object(local));
}
let item = Item {
id: request.id.clone(),
file_path: file_path.display().to_string(),
total: 0,
received: 0,
status: Status::Queued,
error: None,
meta,
created_at: now(),
speed: 0,
};
{
let mut items = state.items.lock();
items.retain(|i| i.id != item.id);
items.insert(0, item.clone());
}
save(&app);
let _ = app.emit("download", &item);
spawn(app.clone(), request.id, request.url);
Ok(item)
}
async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result<(), String> {
let bytes = client.get(url).send().await.map_err(|e| e.to_string())?.error_for_status().map_err(|e| e.to_string())?.bytes().await.map_err(|e| e.to_string())?;
tokio::fs::write(target, bytes).await.map_err(|e| e.to_string())
}
fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
let (tx, rx) = watch::channel(false);
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
tauri::async_runtime::spawn(async move {
let permits = app.state::<Downloads>().permits.clone();
let _permit = tokio::select! {
p = permits.acquire_owned() => p,
_ = cancelled(rx.clone()) => return,
};
let result = transfer(&app, &id, &url, rx).await;
app.state::<Downloads>().cancels.lock().remove(&id);
match result {
Ok(true) => {
update(&app, &id, |i| {
i.status = Status::Completed;
i.speed = 0;
i.received = i.total.max(i.received);
});
}
Ok(false) => {}
Err(e) => {
update(&app, &id, |i| {
i.status = Status::Failed;
i.error = Some(e);
i.speed = 0;
});
}
}
save(&app);
});
}
async fn cancelled(mut rx: watch::Receiver<bool>) {
while !*rx.borrow() {
if rx.changed().await.is_err() {
std::future::pending::<()>().await;
}
}
}
/// Returns Ok(true) when complete, Ok(false) when paused/removed.
async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch::Receiver<bool>) -> Result<bool, String> {
let Some(item) = app.state::<Downloads>().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) };
let final_path = PathBuf::from(&item.file_path);
let part_path = final_path.with_extension(format!(
"{}.part",
final_path.extension().and_then(|e| e.to_str()).unwrap_or("bin")
));
let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);
let client = app.state::<Downloads>().client.clone();
let mut request = client.get(url);
if existing > 0 {
request = request.header("Range", format!("bytes={existing}-"));
}
let response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?;
let status = response.status();
if status.as_u16() == 401 || status.as_u16() == 403 {
return Err("The server does not allow downloads for this account.".into());
}
if !status.is_success() {
return Err(format!("The server could not provide this file ({status})."));
}
let resumed = status.as_u16() == 206;
let start = if resumed { existing } else { 0 };
let total = response.content_length().map(|l| l + start).unwrap_or(0);
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(resumed)
.truncate(!resumed)
.open(&part_path)
.await
.map_err(|e| format!("Cannot write the download: {e}"))?;
update(app, id, |i| {
i.status = Status::Downloading;
i.total = total;
i.received = start;
i.error = None;
});
save(app);
let mut stream = response.bytes_stream();
let mut received = start;
let mut last_emit = Instant::now();
let mut last_save = Instant::now();
let mut window_bytes = 0u64;
let mut window_start = Instant::now();
let mut speed = 0u64;
loop {
if *rx.borrow() {
file.flush().await.ok();
return Ok(false);
}
let chunk = tokio::select! {
c = stream.next() => c,
_ = cancelled(rx.clone()) => { file.flush().await.ok(); return Ok(false); }
};
let Some(chunk) = chunk else { break };
let chunk = chunk.map_err(|e| format!("The transfer was interrupted: {e}"))?;
file.write_all(&chunk).await.map_err(|e| format!("Cannot write the download: {e}"))?;
received += chunk.len() as u64;
window_bytes += chunk.len() as u64;
let elapsed = window_start.elapsed();
if elapsed >= Duration::from_secs(1) {
speed = (window_bytes as f64 / elapsed.as_secs_f64()) as u64;
window_bytes = 0;
window_start = Instant::now();
}
if last_emit.elapsed() >= Duration::from_millis(250) {
last_emit = Instant::now();
update(app, id, |i| {
i.received = received;
i.speed = speed;
});
}
if last_save.elapsed() >= Duration::from_secs(5) {
last_save = Instant::now();
save(app);
}
}
file.flush().await.map_err(|e| e.to_string())?;
drop(file);
if total > 0 && received < total {
return Err("The transfer ended early. Resume to continue.".into());
}
tokio::fs::rename(&part_path, &final_path).await.map_err(|e| format!("Cannot finish the download: {e}"))?;
update(app, id, |i| i.received = received);
Ok(true)
}
fn cancel<R: Runtime>(app: &AppHandle<R>, id: &str) {
if let Some(tx) = app.state::<Downloads>().cancels.lock().remove(id) {
let _ = tx.send(true);
}
}
#[tauri::command]
pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
cancel(&app, &id);
update(&app, &id, |i| {
if i.status != Status::Completed {
i.status = Status::Paused;
i.speed = 0;
}
});
save(&app);
}
#[tauri::command]
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
cancel(&app, &id);
update(&app, &id, |i| {
i.status = Status::Queued;
i.error = None;
});
spawn(app, id, url);
}
#[tauri::command]
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
cancel(&app, &id);
let removed = {
let state = app.state::<Downloads>();
let mut items = state.items.lock();
let pos = items.iter().position(|i| i.id == id);
pos.map(|p| items.remove(p))
};
if let (Some(item), true) = (removed, delete_files) {
let path = PathBuf::from(&item.file_path);
// Give the cancelled transfer a moment to release its file handle.
tokio::time::sleep(Duration::from_millis(150)).await;
let _ = tokio::fs::remove_file(&path).await;
let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin")));
let _ = tokio::fs::remove_file(&part).await;
if let Value::Object(assets) = &item.meta["localAssets"] {
for v in assets.values() {
if let Some(p) = v.as_str() {
let _ = tokio::fs::remove_file(p).await;
}
}
}
// Remove now-empty folders (season, then show), never the download root.
let root = app.state::<Downloads>().dir.lock().clone();
let mut folder = path.parent().map(|p| p.to_path_buf());
while let Some(f) = folder {
if Some(&f) == root.as_ref() || tokio::fs::remove_dir(&f).await.is_err() {
break;
}
folder = f.parent().map(|p| p.to_path_buf());
}
}
save(&app);
let _ = app.emit("download-removed", &id);
Ok(())
}
#[tauri::command]
pub fn download_list<R: Runtime>(app: AppHandle<R>) -> Vec<Item> {
app.state::<Downloads>().items.lock().clone()
}
#[tauri::command]
pub fn download_set_dir<R: Runtime>(app: AppHandle<R>, dir: String) -> Result<(), String> {
let path = PathBuf::from(dir);
std::fs::create_dir_all(&path).map_err(|e| format!("Cannot use this folder: {e}"))?;
*app.state::<Downloads>().dir.lock() = Some(path);
Ok(())
}
#[tauri::command]
pub fn download_write_meta<R: Runtime>(app: AppHandle<R>, id: String, meta: Value) {
update(&app, &id, |i| {
let assets = i.meta.get("localAssets").cloned();
i.meta = meta;
if let (Some(a), Value::Object(m)) = (assets, &mut i.meta) {
m.insert("localAssets".into(), a);
}
});
save(&app);
}

64
src-tauri/src/lib.rs Normal file
View file

@ -0,0 +1,64 @@
mod downloads;
mod mpv;
mod platform;
mod player;
mod system;
use tauri::{Manager, WindowEvent};
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_process::init())
.plugin(
tauri_plugin_window_state::Builder::default()
.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
| tauri_plugin_window_state::StateFlags::MAXIMIZED,
)
.build(),
)
.manage(player::PlayerState::default())
.manage(downloads::Downloads::default())
.setup(|app| {
let handle = app.handle().clone();
downloads::restore(&handle);
if let Some(window) = app.get_webview_window("main") {
let w = window.clone();
window.on_window_event(move |event| {
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
player::on_resize(&w);
}
});
}
Ok(())
})
.invoke_handler(tauri::generate_handler![
player::player_init,
player::player_show,
player::player_command,
player::player_set,
player::player_get,
system::secret_get,
system::secret_set,
system::secret_delete,
system::app_info,
system::dev_session,
system::keep_awake,
system::disk_space,
system::save_url,
downloads::download_start,
downloads::download_pause,
downloads::download_resume,
downloads::download_remove,
downloads::download_list,
downloads::download_set_dir,
downloads::download_write_meta,
])
.run(tauri::generate_context!())
.expect("error while running Kaleido");
}

6
src-tauri/src/main.rs Normal file
View file

@ -0,0 +1,6 @@
// Prevents an additional console window on Windows in release.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
kaleido_lib::run()
}

370
src-tauri/src/mpv.rs Normal file
View file

@ -0,0 +1,370 @@
//! A small, dynamically loaded binding to libmpv's client API.
//!
//! libmpv is loaded at runtime (`libmpv-2.dll` beside the executable, or the
//! repository's `vendor/mpv` folder during development) so the application can
//! still start, browse and report a useful error if the library is missing.
use std::ffi::{c_char, c_int, c_void, CStr, CString};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use libloading::Library;
use serde_json::{Map, Number, Value};
const FORMAT_NONE: c_int = 0;
const FORMAT_STRING: c_int = 1;
const FORMAT_FLAG: c_int = 3;
const FORMAT_INT64: c_int = 4;
const FORMAT_DOUBLE: c_int = 5;
const FORMAT_NODE: c_int = 6;
const FORMAT_NODE_ARRAY: c_int = 7;
const FORMAT_NODE_MAP: c_int = 8;
pub const EVENT_NONE: c_int = 0;
pub const EVENT_SHUTDOWN: c_int = 1;
pub const EVENT_LOG_MESSAGE: c_int = 2;
pub const EVENT_START_FILE: c_int = 6;
pub const EVENT_END_FILE: c_int = 7;
pub const EVENT_FILE_LOADED: c_int = 8;
pub const EVENT_PLAYBACK_RESTART: c_int = 21;
pub const EVENT_PROPERTY_CHANGE: c_int = 22;
pub const EVENT_SEEK: c_int = 20;
#[repr(C)]
#[derive(Clone, Copy)]
union NodeValue {
string: *mut c_char,
flag: c_int,
int64: i64,
double: f64,
list: *mut NodeList,
}
#[repr(C)]
pub struct Node {
u: NodeValue,
format: c_int,
}
#[repr(C)]
struct NodeList {
num: c_int,
values: *mut Node,
keys: *mut *mut c_char,
}
#[repr(C)]
pub struct RawEvent {
pub event_id: c_int,
pub error: c_int,
pub reply_userdata: u64,
pub data: *mut c_void,
}
#[repr(C)]
struct EventProperty {
name: *const c_char,
format: c_int,
data: *mut c_void,
}
#[repr(C)]
struct EventEndFile {
reason: c_int,
error: c_int,
playlist_entry_id: i64,
playlist_insert_id: i64,
playlist_insert_num_entries: c_int,
}
#[repr(C)]
struct EventLogMessage {
prefix: *const c_char,
level: *const c_char,
text: *const c_char,
log_level: c_int,
}
type Handle = *mut c_void;
struct Api {
_lib: Library,
create: unsafe extern "C" fn() -> Handle,
initialize: unsafe extern "C" fn(Handle) -> c_int,
terminate_destroy: unsafe extern "C" fn(Handle),
set_option_string: unsafe extern "C" fn(Handle, *const c_char, *const c_char) -> c_int,
command: unsafe extern "C" fn(Handle, *mut *const c_char) -> c_int,
set_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int,
get_property: unsafe extern "C" fn(Handle, *const c_char, c_int, *mut c_void) -> c_int,
observe_property: unsafe extern "C" fn(Handle, u64, *const c_char, c_int) -> c_int,
wait_event: unsafe extern "C" fn(Handle, f64) -> *mut RawEvent,
free_node_contents: unsafe extern "C" fn(*mut Node),
error_string: unsafe extern "C" fn(c_int) -> *const c_char,
request_log_messages: unsafe extern "C" fn(Handle, *const c_char) -> c_int,
}
/// Candidate locations for libmpv, in priority order: bundled resources, the
/// executable's folder, the repository's `vendor/mpv/<os>` (development), and
/// finally bare names for the system library search path.
pub fn library_candidates(resource_dir: Option<PathBuf>) -> Vec<PathBuf> {
let os = if cfg!(target_os = "windows") {
"windows"
} else if cfg!(target_os = "macos") {
"macos"
} else {
"linux"
};
let mut dirs: Vec<PathBuf> = Vec::new();
if let Some(dir) = resource_dir {
dirs.push(dir.join("lib"));
dirs.push(dir);
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
dirs.push(dir.to_path_buf());
dirs.push(dir.join("../Frameworks"));
}
}
dirs.push(Path::new(env!("CARGO_MANIFEST_DIR")).join("../vendor/mpv").join(os));
let mut out: Vec<PathBuf> = dirs
.iter()
.flat_map(|d| crate::platform::MPV_LIBRARIES.iter().map(move |n| d.join(n)))
.filter(|p| p.exists())
.collect();
out.extend(crate::platform::MPV_LIBRARIES.iter().map(PathBuf::from));
out
}
pub struct Mpv {
api: Api,
handle: Handle,
}
// libmpv's client API is thread safe: every function may be called from any thread.
unsafe impl Send for Mpv {}
unsafe impl Sync for Mpv {}
#[derive(Debug)]
pub enum Event {
Shutdown,
StartFile,
FileLoaded,
PlaybackRestart,
Seek,
EndFile { reason: &'static str, error: Option<String> },
Property { name: String, value: Value },
Log { level: String, prefix: String, text: String },
Other,
}
impl Mpv {
pub fn load(candidates: &[PathBuf]) -> Result<Arc<Mpv>, String> {
unsafe {
let lib = candidates
.iter()
.find_map(|p| Library::new(p).ok())
.ok_or_else(|| "libmpv was not found. Reinstall Kaleido to restore video playback.".to_string())?;
macro_rules! sym {
($name:literal) => {
*lib.get(concat!($name, "\0").as_bytes()).map_err(|e| format!("libmpv is missing {}: {e}", $name))?
};
}
let api = Api {
create: sym!("mpv_create"),
initialize: sym!("mpv_initialize"),
terminate_destroy: sym!("mpv_terminate_destroy"),
set_option_string: sym!("mpv_set_option_string"),
command: sym!("mpv_command"),
set_property: sym!("mpv_set_property"),
get_property: sym!("mpv_get_property"),
observe_property: sym!("mpv_observe_property"),
wait_event: sym!("mpv_wait_event"),
free_node_contents: sym!("mpv_free_node_contents"),
error_string: sym!("mpv_error_string"),
request_log_messages: sym!("mpv_request_log_messages"),
_lib: lib,
};
let handle = (api.create)();
if handle.is_null() {
return Err("libmpv could not create a player.".into());
}
Ok(Arc::new(Mpv { api, handle }))
}
}
fn error(&self, code: c_int) -> String {
unsafe { CStr::from_ptr((self.api.error_string)(code)).to_string_lossy().into_owned() }
}
fn check(&self, code: c_int, what: &str) -> Result<(), String> {
if code < 0 {
Err(format!("{what}: {}", self.error(code)))
} else {
Ok(())
}
}
pub fn set_option(&self, name: &str, value: &str) -> Result<(), String> {
let n = CString::new(name).unwrap();
let v = CString::new(value).unwrap();
self.check(unsafe { (self.api.set_option_string)(self.handle, n.as_ptr(), v.as_ptr()) }, name)
}
pub fn initialize(&self) -> Result<(), String> {
self.check(unsafe { (self.api.initialize)(self.handle) }, "initialize")
}
pub fn request_log_messages(&self, level: &str) {
let l = CString::new(level).unwrap();
unsafe { (self.api.request_log_messages)(self.handle, l.as_ptr()) };
}
pub fn command(&self, args: &[String]) -> Result<(), String> {
let owned: Vec<CString> = args.iter().map(|a| CString::new(a.as_str()).unwrap_or_default()).collect();
let mut ptrs: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();
ptrs.push(std::ptr::null());
let what = args.first().cloned().unwrap_or_default();
self.check(unsafe { (self.api.command)(self.handle, ptrs.as_mut_ptr()) }, &what)
}
pub fn set_property(&self, name: &str, value: &Value) -> Result<(), String> {
let n = CString::new(name).unwrap();
// Scalars use their native formats; anything else goes through a string.
unsafe {
let code = match value {
Value::Bool(b) => {
let mut v: c_int = *b as c_int;
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_FLAG, &mut v as *mut _ as *mut c_void)
}
Value::Number(num) if num.is_i64() => {
let mut v: i64 = num.as_i64().unwrap();
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_INT64, &mut v as *mut _ as *mut c_void)
}
Value::Number(num) => {
let mut v: f64 = num.as_f64().unwrap_or(0.0);
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_DOUBLE, &mut v as *mut _ as *mut c_void)
}
Value::String(s) => {
let c = CString::new(s.as_str()).unwrap_or_default();
let mut p = c.as_ptr();
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_STRING, &mut p as *mut _ as *mut c_void)
}
Value::Null => {
let c = CString::new("no").unwrap();
let mut p = c.as_ptr();
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_STRING, &mut p as *mut _ as *mut c_void)
}
other => {
let c = CString::new(other.to_string()).unwrap_or_default();
let mut p = c.as_ptr();
(self.api.set_property)(self.handle, n.as_ptr(), FORMAT_STRING, &mut p as *mut _ as *mut c_void)
}
};
self.check(code, name)
}
}
pub fn get_property(&self, name: &str) -> Result<Value, String> {
let n = CString::new(name).unwrap();
unsafe {
let mut node: Node = std::mem::zeroed();
let code = (self.api.get_property)(self.handle, n.as_ptr(), FORMAT_NODE, &mut node as *mut _ as *mut c_void);
self.check(code, name)?;
let value = node_to_json(&node);
(self.api.free_node_contents)(&mut node);
Ok(value)
}
}
pub fn observe(&self, id: u64, name: &str) {
let n = CString::new(name).unwrap();
unsafe { (self.api.observe_property)(self.handle, id, n.as_ptr(), FORMAT_NODE) };
}
/// Blocks for up to `timeout` seconds. Only one thread may wait for events.
pub fn wait_event(&self, timeout: f64) -> Option<Event> {
unsafe {
let ev = &*(self.api.wait_event)(self.handle, timeout);
Some(match ev.event_id {
EVENT_NONE => return None,
EVENT_SHUTDOWN => Event::Shutdown,
EVENT_START_FILE => Event::StartFile,
EVENT_FILE_LOADED => Event::FileLoaded,
EVENT_PLAYBACK_RESTART => Event::PlaybackRestart,
EVENT_SEEK => Event::Seek,
EVENT_END_FILE => {
let data = &*(ev.data as *const EventEndFile);
let reason = match data.reason {
0 => "eof",
2 => "stop",
3 => "quit",
4 => "error",
5 => "redirect",
_ => "unknown",
};
let error = if data.reason == 4 { Some(self.error(data.error)) } else { None };
Event::EndFile { reason, error }
}
EVENT_PROPERTY_CHANGE => {
let data = &*(ev.data as *const EventProperty);
let name = CStr::from_ptr(data.name).to_string_lossy().into_owned();
let value = if data.format == FORMAT_NODE && !data.data.is_null() {
node_to_json(&*(data.data as *const Node))
} else {
Value::Null
};
Event::Property { name, value }
}
EVENT_LOG_MESSAGE => {
let data = &*(ev.data as *const EventLogMessage);
Event::Log {
level: CStr::from_ptr(data.level).to_string_lossy().into_owned(),
prefix: CStr::from_ptr(data.prefix).to_string_lossy().into_owned(),
text: CStr::from_ptr(data.text).to_string_lossy().trim_end().to_string(),
}
}
_ => Event::Other,
})
}
}
}
impl Drop for Mpv {
fn drop(&mut self) {
unsafe { (self.api.terminate_destroy)(self.handle) }
}
}
unsafe fn node_to_json(node: &Node) -> Value {
match node.format {
FORMAT_STRING => {
if node.u.string.is_null() {
Value::Null
} else {
Value::String(CStr::from_ptr(node.u.string).to_string_lossy().into_owned())
}
}
FORMAT_FLAG => Value::Bool(node.u.flag != 0),
FORMAT_INT64 => Value::Number(node.u.int64.into()),
FORMAT_DOUBLE => Number::from_f64(node.u.double).map(Value::Number).unwrap_or(Value::Null),
FORMAT_NODE_ARRAY => {
let list = &*node.u.list;
let mut out = Vec::with_capacity(list.num.max(0) as usize);
for i in 0..list.num as isize {
out.push(node_to_json(&*list.values.offset(i)));
}
Value::Array(out)
}
FORMAT_NODE_MAP => {
let list = &*node.u.list;
let mut out = Map::new();
for i in 0..list.num as isize {
let key = CStr::from_ptr(*list.keys.offset(i)).to_string_lossy().into_owned();
out.insert(key, node_to_json(&*list.values.offset(i)));
}
Value::Object(out)
}
FORMAT_NONE => Value::Null,
_ => Value::Null,
}
}

View file

@ -0,0 +1,31 @@
//! Linux: render mpv through its render API (OpenGL) beneath the WebKitGTK
//! view, then implement `VideoSurface` here.
//!
//! Browsing, downloads, settings and updates already work here; only native
//! video composition remains to be written.
use tauri::{Runtime, WebviewWindow};
use crate::mpv::Mpv;
pub const SURFACE_PROPERTIES: &[&str] = &[];
pub const MPV_LIBRARIES: &[&str] = &["libmpv.so.2", "libmpv.so"];
pub struct VideoSurface;
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 hold_awake(rx: std::sync::mpsc::Receiver<()>) {
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
let _ = rx.recv();
}

View file

@ -0,0 +1,31 @@
//! macOS: render mpv through its render API (libplacebo) into a CAMetalLayer
//! placed beneath the WKWebView, then implement `VideoSurface` here.
//!
//! Browsing, downloads, settings and updates already work here; only native
//! video composition remains to be written.
use tauri::{Runtime, WebviewWindow};
use crate::mpv::Mpv;
pub const SURFACE_PROPERTIES: &[&str] = &[];
pub const MPV_LIBRARIES: &[&str] = &["libmpv.2.dylib", "libmpv.dylib"];
pub struct VideoSurface;
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 hold_awake(rx: std::sync::mpsc::Receiver<()>) {
// TODO(macOS): IOPMAssertionCreateWithName(PreventUserIdleDisplaySleep).
let _ = rx.recv();
}

View file

@ -0,0 +1,23 @@
//! Everything that differs between operating systems lives in this module.
//! Each platform file exposes the same items:
//!
//! - `VideoSurface`: composes mpv's output beneath the web view
//! (`create`, `mpv_options`, `on_property`, `show`, `fit`).
//! - `SURFACE_PROPERTIES`: mpv properties the surface observes.
//! - `MPV_LIBRARIES`: libmpv file names to look for.
//! - `hold_awake`: prevents display sleep until the receiver closes.
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
pub use self::windows::*;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
pub use self::macos::*;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
pub use self::linux::*;

View file

@ -0,0 +1,133 @@
//! 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);
}
}

207
src-tauri/src/player.rs Normal file
View file

@ -0,0 +1,207 @@
//! Video playback: one long-lived libmpv instance whose output is composed
//! beneath the (transparent) web view, so the interface draws its controls
//! directly over the video. How the video reaches the screen is platform
//! specific; see `platform::VideoSurface`.
use std::sync::Arc;
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use serde::Deserialize;
use serde_json::{json, Value};
use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
use crate::mpv::{self, Event, Mpv};
use crate::platform::VideoSurface;
#[derive(Default)]
pub struct PlayerState {
mpv: Mutex<Option<Arc<Mpv>>>,
surface: Mutex<Option<VideoSurface>>,
}
/// Properties streamed to the interface as they change.
const OBSERVED: &[&str] = &[
"time-pos",
"duration",
"pause",
"paused-for-cache",
"cache-buffering-state",
"demuxer-cache-time",
"eof-reached",
"idle-active",
"track-list",
"volume",
"mute",
"speed",
"sub-delay",
"audio-delay",
"video-params",
"hwdec-current",
"chapter-list",
"seeking",
];
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct InitOptions {
#[serde(default)]
pub hwdec: Option<String>,
#[serde(default)]
pub hdr: Option<bool>,
#[serde(default)]
pub extra: Vec<(String, String)>,
}
fn emit<R: Runtime>(app: &AppHandle<R>, payload: Value) {
let _ = app.emit("mpv", payload);
}
fn create_player<R: Runtime>(app: &AppHandle<R>, window: &WebviewWindow<R>, opts: &InitOptions) -> Result<Arc<Mpv>, String> {
let resource_dir = app.path().resource_dir().ok();
let mpv = Mpv::load(&mpv::library_candidates(resource_dir))?;
let surface = VideoSurface::create(window)?;
let render_options = surface.mpv_options();
*app.state::<PlayerState>().surface.lock() = Some(surface);
let set = |k: &str, v: &str| mpv.set_option(k, v);
for (k, v) in &render_options {
set(k, v)?;
}
set("hwdec", opts.hwdec.as_deref().unwrap_or("auto-safe"))?;
set("keep-open", "yes")?;
set("idle", "yes")?;
set("force-window", "yes")?;
set("osc", "no")?;
set("osd-level", "0")?;
set("input-default-bindings", "no")?;
set("input-vo-keyboard", "no")?;
set("input-cursor", "no")?;
set("cursor-autohide", "no")?;
set("terminal", "no")?;
set("ytdl", "no")?;
set("sub-auto", "no")?;
set("audio-client-name", "Kaleido")?;
set("title", "Kaleido")?;
set("cache", "yes")?;
set("demuxer-max-bytes", "300MiB")?;
set("demuxer-max-back-bytes", "100MiB")?;
set("demuxer-readahead-secs", "30")?;
set("network-timeout", "30")?;
set("hr-seek", "yes")?;
set("background-color", "#000000")?;
set("user-agent", "Kaleido")?;
if opts.hdr.unwrap_or(true) {
let _ = set("target-colorspace-hint", "yes");
}
for (k, v) in &opts.extra {
let _ = set(k, v);
}
mpv.request_log_messages("warn");
mpv.initialize()?;
for (i, name) in OBSERVED.iter().chain(crate::platform::SURFACE_PROPERTIES).enumerate() {
mpv.observe(i as u64 + 1, name);
}
let events = mpv.clone();
let app = app.clone();
std::thread::Builder::new()
.name("mpv-events".into())
.spawn(move || event_loop(app, events))
.map_err(|e| e.to_string())?;
Ok(mpv)
}
fn event_loop<R: Runtime>(app: AppHandle<R>, mpv: Arc<Mpv>) {
let mut last_time = Instant::now() - Duration::from_secs(1);
let mut last_pos = -1.0f64;
loop {
let Some(event) = mpv.wait_event(1.0) else { continue };
match event {
Event::Shutdown => break,
Event::StartFile => emit(&app, json!({"type": "start-file"})),
Event::FileLoaded => emit(&app, json!({"type": "file-loaded"})),
Event::PlaybackRestart => emit(&app, json!({"type": "playback-restart"})),
Event::Seek => emit(&app, json!({"type": "seek"})),
Event::EndFile { reason, error } => emit(&app, json!({"type": "end-file", "reason": reason, "error": error})),
Event::Property { name, value } => {
if crate::platform::SURFACE_PROPERTIES.contains(&name.as_str()) {
let state = app.state::<PlayerState>();
let mut surface = state.surface.lock();
if let Some(surface) = surface.as_mut() {
surface.on_property(&name, &value);
}
continue;
}
if name == "time-pos" {
// Positions change every frame; a few updates a second suffice.
let pos = value.as_f64().unwrap_or(-1.0);
let now = Instant::now();
if now.duration_since(last_time) < Duration::from_millis(200) && (pos - last_pos).abs() < 1.5 {
continue;
}
last_time = now;
last_pos = pos;
}
emit(&app, json!({"type": "property", "name": name, "value": value}));
}
Event::Log { level, prefix, text } => {
eprintln!("[mpv {level}] {prefix}: {text}");
emit(&app, json!({"type": "log", "level": level, "prefix": prefix, "text": text}));
}
Event::Other => {}
}
}
}
fn player<R: Runtime>(app: &AppHandle<R>) -> Result<Arc<Mpv>, String> {
app.state::<PlayerState>().mpv.lock().clone().ok_or_else(|| "The player has not started.".to_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())?);
}
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>();
let mpv = state.mpv.lock().clone();
let mut surface = state.surface.lock();
if let Some(surface) = surface.as_mut() {
surface.fit(&window, mpv.as_deref());
surface.show(visible);
}
Ok(())
}
#[tauri::command]
pub async fn player_command<R: Runtime>(app: AppHandle<R>, args: Vec<String>) -> Result<(), String> {
player(&app)?.command(&args)
}
#[tauri::command]
pub async fn player_set<R: Runtime>(app: AppHandle<R>, name: String, value: Value) -> Result<(), String> {
player(&app)?.set_property(&name, &value)
}
#[tauri::command]
pub async fn player_get<R: Runtime>(app: AppHandle<R>, name: String) -> Result<Value, String> {
player(&app)?.get_property(&name)
}
/// 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();
let state = app.state::<PlayerState>();
let mpv = state.mpv.lock().clone();
let mut surface = state.surface.lock();
if let Some(surface) = surface.as_mut() {
surface.fit(window, mpv.as_deref());
}
}

161
src-tauri/src/system.rs Normal file
View file

@ -0,0 +1,161 @@
//! Small platform services: credential storage, app paths, power and disk.
use std::sync::mpsc::{channel, Sender};
use parking_lot::Mutex;
use serde::Serialize;
use serde_json::{json, Value};
use tauri::{AppHandle, Manager, Runtime};
const SERVICE: &str = "tv.kaleido.desktop";
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.
#[tauri::command]
pub fn secret_get(key: String) -> Result<Option<String>, String> {
match entry(&key)?.get_password() {
Ok(v) => Ok(Some(v)),
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
pub fn secret_set(key: String, value: String) -> Result<(), String> {
entry(&key)?.set_password(&value).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn secret_delete(key: String) -> Result<(), String> {
match entry(&key)?.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(e.to_string()),
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AppInfo {
version: String,
data_dir: String,
default_download_dir: String,
platform: String,
device_name: String,
}
#[tauri::command]
pub fn app_info<R: Runtime>(app: AppHandle<R>) -> AppInfo {
let paths = app.path();
let data = paths.app_data_dir().map(|p| p.display().to_string()).unwrap_or_default();
let downloads = paths
.video_dir()
.map(|p| p.join("Kaleido"))
.or_else(|_| paths.app_data_dir().map(|p| p.join("Downloads")))
.map(|p| p.display().to_string())
.unwrap_or_default();
AppInfo {
version: app.package_info().version.to_string(),
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()),
}
}
/// Development builds can start signed in from the repository's ignored `.env`
/// (`PLEX_SERVER_URL`, `PLEX_TOKEN`). Release builds never read it.
#[tauri::command]
pub fn dev_session() -> Option<Value> {
if !cfg!(debug_assertions) {
return None;
}
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let path = std::env::var("KALEIDO_DEV_ENV")
.ok()
.map(std::path::PathBuf::from)
.into_iter()
.chain([root.join(".env"), root.join("../Custom plex client/.env")])
.find(|p| p.exists())?;
let text = std::fs::read_to_string(path).ok()?;
let mut server = None;
let mut token = None;
for line in text.lines() {
if let Some((k, v)) = line.split_once('=') {
let v = v.trim().trim_matches('"').to_string();
match k.trim() {
"PLEX_SERVER_URL" => server = Some(v),
"PLEX_TOKEN" => token = Some(v),
_ => {}
}
}
}
Some(json!({ "server": server?, "token": token? }))
}
static AWAKE: Mutex<Option<Sender<()>>> = Mutex::new(None);
/// Prevents display sleep during playback.
#[tauri::command]
pub fn keep_awake(enabled: bool) {
let mut guard = AWAKE.lock();
if let Some(stop) = guard.take() {
let _ = stop.send(());
}
if !enabled {
return;
}
let (tx, rx) = channel::<()>();
*guard = Some(tx);
std::thread::spawn(move || crate::platform::hold_awake(rx));
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DiskSpace {
free: u64,
total: u64,
}
#[tauri::command]
pub fn disk_space(path: String) -> Result<DiskSpace, String> {
// Walk up to an existing folder; the download folder may not exist yet.
let mut p = std::path::PathBuf::from(&path);
while !p.exists() {
if !p.pop() {
break;
}
}
Ok(DiskSpace {
free: fs2::available_space(&p).map_err(|e| e.to_string())?,
total: fs2::total_space(&p).map_err(|e| e.to_string())?,
})
}
#[allow(dead_code)]
pub fn data_dir<R: Runtime>(app: &AppHandle<R>) -> std::path::PathBuf {
app.path().app_data_dir().unwrap_or_else(|_| std::env::temp_dir().join("Kaleido"))
}
/// Saves a URL (e.g. server logs) to a file the user chose.
#[tauri::command]
pub async fn save_url(url: String, path: String) -> Result<u64, String> {
use futures_util::StreamExt;
use tokio::io::AsyncWriteExt;
let response = reqwest::Client::new().get(&url).send().await.map_err(|e| e.to_string())?;
if !response.status().is_success() {
return Err(format!("The server returned {}", response.status()));
}
let mut file = tokio::fs::File::create(&path).await.map_err(|e| e.to_string())?;
let mut stream = response.bytes_stream();
let mut total = 0u64;
while let Some(chunk) = stream.next().await {
let chunk = chunk.map_err(|e| e.to_string())?;
total += chunk.len() as u64;
file.write_all(&chunk).await.map_err(|e| e.to_string())?;
}
file.flush().await.map_err(|e| e.to_string())?;
Ok(total)
}

64
src-tauri/tauri.conf.json Normal file
View file

@ -0,0 +1,64 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Kaleido",
"version": "0.1.0",
"identifier": "tv.kaleido.desktop",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist"
},
"app": {
"withGlobalTauri": false,
"windows": [
{
"label": "main",
"title": "Kaleido",
"width": 1480,
"height": 900,
"minWidth": 900,
"minHeight": 580,
"center": true,
"decorations": false,
"transparent": false,
"shadow": true,
"visible": false,
"dragDropEnabled": false
}
],
"security": {
"csp": null,
"assetProtocol": {
"enable": true,
"scope": [
"**"
]
}
}
},
"bundle": {
"active": true,
"createUpdaterArtifacts": true,
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"shortDescription": "Kaleido for Plex",
"longDescription": "Kaleido is a cinematic Plex client for the desktop.",
"category": "Video",
"copyright": "\u00a9 Elijah Kuntz",
"publisher": "Kaleido"
},
"plugins": {
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEU0MTA2RjI0OUFFQzU1QzUKUldURlZleWFKRzhRNUlqTTR3U095STFYS3BsUXd2UnZMYlRrQmt3aUk5YU5WSjdqcUxVcHllU1EK",
"endpoints": [
"https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/raw/branch/main/updates/latest.json"
]
}
}
}

View file

@ -0,0 +1,16 @@
{
"$schema": "https://schema.tauri.app/config/2",
"bundle": {
"targets": [
"appimage",
"deb"
],
"linux": {
"deb": {
"depends": [
"libmpv2"
]
}
}
}
}

View file

@ -0,0 +1,15 @@
{
"$schema": "https://schema.tauri.app/config/2",
"bundle": {
"targets": [
"app",
"dmg"
],
"macOS": {
"minimumSystemVersion": "12.0",
"frameworks": [
"../vendor/mpv/macos/libmpv.2.dylib"
]
}
}
}

View file

@ -0,0 +1,45 @@
{
"$schema": "https://schema.tauri.app/config/2",
"app": {
"windows": [
{
"label": "main",
"title": "Kaleido",
"width": 1480,
"height": 900,
"minWidth": 900,
"minHeight": 580,
"center": true,
"decorations": false,
"transparent": true,
"shadow": true,
"visible": false,
"dragDropEnabled": false
}
]
},
"bundle": {
"targets": [
"nsis"
],
"resources": {
"../vendor/mpv/windows/libmpv-2.dll": "libmpv-2.dll"
},
"windows": {
"nsis": {
"installMode": "currentUser",
"installerIcon": "icons/icon.ico"
},
"webviewInstallMode": {
"type": "downloadBootstrapper"
}
}
},
"plugins": {
"updater": {
"windows": {
"installMode": "passive"
}
}
}
}