From c70aeede74926be23921462ef661acc795bb5581 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 22:08:36 -0700 Subject: [PATCH 01/22] Publish the 0.1.0-beta.13 update feed (Windows) Co-Authored-By: Claude Opus 5.5 --- updates/latest.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/updates/latest.json b/updates/latest.json index ab27ed0..0dc98e9 100644 --- a/updates/latest.json +++ b/updates/latest.json @@ -1,11 +1,11 @@ { - "version": "0.1.0-beta.12", - "notes": "A smoother miniplayer on Windows.\r\n\r\n- 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.\r\n- 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.\r\n- Using its buttons no longer takes focus from the main window, so keyboard shortcuts keep working.\r\n- On Mac the miniplayer is unchanged for now.", - "pub_date": "2026-11-05T00:39:18.979Z", + "version": "0.1.0-beta.13", + "notes": "A gentler automatic intro skip, and home screens that keep up with your other Plex apps.\n\n- \"Skip automatically\" for intros (and credits) now waits a moment first: the Skip button reads \"Skipping intro\" and fills as it counts down, then skips. Pause, seek or press any key before then to keep watching; the button stays as a regular Skip intro for the rest of the intro. Click it to skip straight away.\n- Choose how long it waits in Settings → Playback → Automatic skip delay (3, 5 or 10 seconds, or straight away as before). It's 5 seconds by default.\n- Jumping into the middle of an intro yourself no longer skips it automatically.\n- Fixed: Continue Watching, a show's next episode, and watched marks didn't update after watching something on another device (a TV, a phone) while Kaleido stayed open. They now refresh when you switch back to Kaleido, and Continue Watching also refreshes every minute while it's on screen.", + "pub_date": "2026-11-05T05:08:29.690Z", "platforms": { "windows-x86_64": { - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFZXbUR6ZDBPS0tDSWNEK1RTbkJMOGl4ZFVKUHRqWGZRbHpFU1ZuS01QM0RlU1pTRW5PN25KNFlDbUJ5dzRDS0hSRm5DQjU4ZlNsdm1ITjlXY09HMXdvPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzODM5MTM1CWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjEyX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMC1iZXRhLjEyClNZQ3RxSkMzaDZxZE1IWnJnM0xVcmt2T2VwZEQ5eWFjcTM4SThnV2M0aGxoeE5DZ0gwQ3UwcWNIYUZlVERxVDN2ZGpsamxkZlAwbHJZSWtnOGd0YUN3PT0K", - "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.12/Kaleido_0.1.0-beta.12_x64-setup.exe" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFpSemIrYjVoY3M5NDZQbTI3aVB6RDhCbXpZbXl4d2dJYWUzWitlbXBNWnNOT29BZU11SzI3cVY5dXhjcHNNUmI0Ly83NXJGT3BVdHA2enBBMCtHK2d3PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzODU1MjkwCWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjEzX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMC1iZXRhLjEzClg4bllva1Nib0pUOTJXQlc5VUQrRmxXUUo5R1FUWVY0UCtuV2l4K2NOaHQ4UUF0MlVBd2VnVUlpKzhQVWpHTnFUQWE0K2NrZnJtYW05ZCtDRFg5TkJ3PT0K", + "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.13/Kaleido_0.1.0-beta.13_x64-setup.exe" } } } From 8755d167357146501e483caaee0dad962f8777d9 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 22:41:12 -0700 Subject: [PATCH 02/22] Fix playback, account, download and library bugs found in review - Clear cached library data when the account or profile behind the server connection changes, not only on Home user switches. - TitleArt falls back to the title when there is no server, so the player no longer crashes offline. - Playback keeps the server it started on: progress, watched state and transcodes never go to a server selected later, a download only reports to its own server, and switching account or server ends a stream from the old one. - Closing or replacing playback during setup can no longer start the file afterwards. - Transcodes save the chosen audio/subtitle tracks on the server before starting (and name them in the request), apply the language and subtitle preferences, and keep the current tracks across quality changes. - Offline playback saves its resume point and watched count in the download's metadata. - Download tasks take over from a previous task for the same title only after it exits, and pause/remove stay wired to the current task. - Downloads prefer a single-file version and refuse split ones instead of saving only part one. - Download artwork is named per file, so episodes in one season folder no longer overwrite or delete each other's images. - Library grids refetch loaded pages when the cache is invalidated. - Request timeouts and cancellation also cover the response body. - Hero rotation resumes after being scrolled back into view. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/downloads.rs | 127 +++++++++++++--- src/app/queries.ts | 9 +- src/downloads/store.ts | 15 +- src/player/store.ts | 260 ++++++++++++++++++++++++++------- src/plex/client.ts | 40 +++-- src/plex/playback.ts | 4 + src/screens/LibraryBrowser.tsx | 27 ++++ src/ui/Hero.tsx | 9 +- src/ui/media.tsx | 7 +- 9 files changed, 399 insertions(+), 99 deletions(-) diff --git a/src-tauri/src/downloads.rs b/src-tauri/src/downloads.rs index 2d3490c..89c183c 100644 --- a/src-tauri/src/downloads.rs +++ b/src-tauri/src/downloads.rs @@ -5,8 +5,9 @@ //! server-relative source path; resuming after a restart asks the interface for //! a freshly signed URL. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -47,10 +48,19 @@ pub struct Item { pub speed: u64, } +/// The transfer task that currently owns a download (and its `.part` file). +struct Worker { + generation: u64, + cancel: watch::Sender, + /// Closes once the task has exited and let go of the file. + done: watch::Receiver<()>, +} + pub struct Downloads { items: Mutex>, dir: Mutex>, - cancels: Mutex>>, + workers: Mutex>, + generation: AtomicU64, permits: Arc, client: reqwest::Client, } @@ -60,7 +70,8 @@ impl Default for Downloads { Downloads { items: Mutex::new(Vec::new()), dir: Mutex::new(None), - cancels: Mutex::new(HashMap::new()), + workers: Mutex::new(HashMap::new()), + generation: AtomicU64::new(0), permits: Arc::new(Semaphore::new(MAX_ACTIVE)), client: reqwest::Client::builder() .connect_timeout(Duration::from_secs(20)) @@ -168,8 +179,11 @@ pub async fn download_start(app: AppHandle, request: StartRequest let mut meta = request.meta.clone(); if let Value::Object(map) = &mut meta { let mut local = serde_json::Map::new(); + // Episodes share their season's folder, so artwork is named after the file it + // belongs to: one episode's still never replaces another's. + let stem = file_path.file_stem().and_then(|s| s.to_str()).map(sanitize).unwrap_or_else(|| sanitize(&request.id)); for (name, url) in &request.assets { - let target = folder.join(format!(".{}.jpg", sanitize(name))); + let target = folder.join(format!(".{stem}.{}.jpg", sanitize(name))); if fetch_to(&state.client, url, &target).await.is_ok() { local.insert(name.clone(), Value::String(target.display().to_string())); } @@ -204,21 +218,48 @@ async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result< tokio::fs::write(target, bytes).await.map_err(|e| e.to_string()) } +/// Starts a transfer task for `id`, taking over from any task still running for it: +/// that one is cancelled and the new one waits for it to exit before touching the file. fn spawn(app: AppHandle, id: String, url: String) { + let state = app.state::(); + let generation = state.generation.fetch_add(1, Ordering::Relaxed); let (tx, rx) = watch::channel(false); - app.state::().cancels.lock().insert(id.clone(), tx); + let (done_tx, done_rx) = watch::channel(()); + let previous = state.workers.lock().insert(id.clone(), Worker { generation, cancel: tx, done: done_rx }); + let previous = previous.map(|w| { + let _ = w.cancel.send(true); + w.done + }); tauri::async_runtime::spawn(async move { + // Held until this task ends: whoever waits on `done` then knows the file is free. + let _done = done_tx; + let took_over = previous.is_some(); + if let Some(done) = previous { + exited(done).await; + } + let stopped = rx.clone(); + if *stopped.borrow() { + release(&app, &id, generation); + return; + } let permits = app.state::().permits.clone(); let _permit = tokio::select! { p = permits.acquire_owned() => p, - _ = cancelled(rx.clone()) => return, + _ = cancelled(rx.clone()) => { release(&app, &id, generation); return; } }; - let result = transfer(&app, &id, &url, rx).await; - app.state::().cancels.lock().remove(&id); + // The task it replaced may have finished the file just as it was stopped. + let result = if took_over && finished_file(&app, &id) { Ok(true) } else { transfer(&app, &id, &url, rx).await }; + release(&app, &id, generation); + // Once paused, removed or replaced, the outcome is no longer this task's to + // report, except a finished file, which is complete whatever happened since. + if *stopped.borrow() && !matches!(result, Ok(true)) { + return; + } match result { Ok(true) => { update(&app, &id, |i| { i.status = Status::Completed; + i.error = None; i.speed = 0; i.received = i.total.max(i.received); }); @@ -236,6 +277,30 @@ fn spawn(app: AppHandle, id: String, url: String) { }); } +/// Drops the worker entry, unless a newer task has taken it over. +fn release(app: &AppHandle, id: &str, generation: u64) { + let state = app.state::(); + let mut workers = state.workers.lock(); + if workers.get(id).map(|w| w.generation) == Some(generation) { + workers.remove(id); + } +} + +/// The download's file is in place and nothing is left to transfer. +fn finished_file(app: &AppHandle, id: &str) -> bool { + let Some(path) = app.state::().items.lock().iter().find(|i| i.id == id).map(|i| PathBuf::from(&i.file_path)) else { return false }; + path.exists() && !part_path(&path).exists() +} + +fn part_path(path: &Path) -> PathBuf { + path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin"))) +} + +/// Resolves once a worker task has exited. +async fn exited(mut done: watch::Receiver<()>) { + while done.changed().await.is_ok() {} +} + async fn cancelled(mut rx: watch::Receiver) { while !*rx.borrow() { if rx.changed().await.is_err() { @@ -248,10 +313,7 @@ async fn cancelled(mut rx: watch::Receiver) { async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch::Receiver) -> Result { let Some(item) = app.state::().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 part_path = part_path(&final_path); let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0); let client = app.state::().client.clone(); @@ -259,7 +321,10 @@ async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch 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 response = tokio::select! { + r = request.send() => r.map_err(|e| format!("Could not reach the server: {e}"))?, + _ = cancelled(rx.clone()) => return Ok(false), + }; 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()); @@ -336,10 +401,14 @@ async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch Ok(true) } -fn cancel(app: &AppHandle, id: &str) { - if let Some(tx) = app.state::().cancels.lock().remove(id) { - let _ = tx.send(true); - } +/// Stops the transfer for `id`, if one is running; the receiver closes once it has exited. +/// The entry stays until then, so a task started meanwhile knows to wait for it. +fn cancel(app: &AppHandle, id: &str) -> Option> { + let state = app.state::(); + let workers = state.workers.lock(); + let worker = workers.get(id)?; + let _ = worker.cancel.send(true); + Some(worker.done.clone()) } #[tauri::command] @@ -356,7 +425,7 @@ pub fn download_pause(app: AppHandle, id: String) { #[tauri::command] pub fn download_resume(app: AppHandle, id: String, url: String) { - cancel(&app, &id); + // `spawn` takes over from a transfer still winding down. update(&app, &id, |i| { i.status = Status::Queued; i.error = None; @@ -366,7 +435,7 @@ pub fn download_resume(app: AppHandle, id: String, url: String) { #[tauri::command] pub async fn download_remove(app: AppHandle, id: String, delete_files: bool) -> Result<(), String> { - cancel(&app, &id); + let running = cancel(&app, &id); let removed = { let state = app.state::(); let mut items = state.items.lock(); @@ -375,14 +444,24 @@ pub async fn download_remove(app: AppHandle, id: String, delete_f }; 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 the cancelled transfer release its file handle first. + if let Some(done) = running { + let _ = tokio::time::timeout(Duration::from_secs(10), exited(done)).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; + let _ = tokio::fs::remove_file(part_path(&path)).await; + // Older downloads shared artwork between a season's episodes: keep what others still use. + let in_use: HashSet = app + .state::() + .items + .lock() + .iter() + .filter_map(|i| i.meta.get("localAssets").and_then(Value::as_object)) + .flat_map(|a| a.values().filter_map(Value::as_str).map(str::to_owned)) + .collect(); if let Value::Object(assets) = &item.meta["localAssets"] { for v in assets.values() { - if let Some(p) = v.as_str() { + if let Some(p) = v.as_str().filter(|p| !in_use.contains(*p)) { let _ = tokio::fs::remove_file(p).await; } } diff --git a/src/app/queries.ts b/src/app/queries.ts index 80e5bb9..e3aceb3 100644 --- a/src/app/queries.ts +++ b/src/app/queries.ts @@ -1,7 +1,7 @@ import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query'; import * as api from '../plex/api'; import type { Item, Section } from '../plex/types'; -import { useServer } from './session'; +import { useServer, useSession } from './session'; import { useSettings } from './settings'; export const queryClient = new QueryClient({ @@ -27,6 +27,13 @@ export const PROGRESS = { ...WATCH_STATE, staleTime: 15_000, refetchInterval: 60 // app doesn't change visibility, so a window focus counts as well. window.addEventListener('focus', () => queryClient.getQueryCache().onFocus()); +// Keys carry the server but not the account, and another account (or a Home profile) on +// the same server sees different watch state and libraries. Whenever the credentials +// behind the connection change, nothing cached under the old ones may be shown. +useSession.subscribe((st, prev) => { + if (prev.server && st.server !== prev.server && st.server?.token !== prev.server.token) queryClient.clear(); +}); + /** Every key starts with the server so switching servers never mixes caches. */ export function useKey(...parts: unknown[]) { const server = useServer(); diff --git a/src/downloads/store.ts b/src/downloads/store.ts index 9820dc8..d56474e 100644 --- a/src/downloads/store.ts +++ b/src/downloads/store.ts @@ -52,12 +52,16 @@ function sanitize(s: string) { return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled'; } -/** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */ -function slim(raw: any) { +/** + * Trims metadata kept for offline display: no extras, related hubs or raw blobs, and + * only the version downloaded, so its streams describe the file that plays. + */ +function slim(raw: any, mediaIndex: number) { const { Extras, Related, OnDeck, ...rest } = raw ?? {}; void Extras; void Related; void OnDeck; + if (Array.isArray(rest.Media) && rest.Media[mediaIndex]) rest.Media = [rest.Media[mediaIndex]]; return rest; } @@ -102,9 +106,12 @@ export const useDownloads = create((set, get) => ({ try { await get().init(); const item = await api.metadata(server, input.id); - const media = item.media[0]; + // A download is one file. A version split across several (CD1, CD2) would be + // kept as its first part only, so prefer a version in one piece. + const media = item.media.find((m) => m.parts.length === 1) ?? item.media[0]; const part = media?.parts[0]; if (!part) throw new Error('This title has no downloadable file.'); + if (media.parts.length > 1) throw new Error('This title is split across several files, which Kaleido can’t download yet.'); const id = get().idFor(item.id); if (get().items.some((d) => d.id === id && d.status !== 'failed')) { toast('This title is already in Downloads.'); @@ -129,7 +136,7 @@ export const useDownloads = create((set, get) => ({ url: server.signed(part.key, { download: 1 }), folder, fileName: sanitize(baseName), - meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta, + meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw, item.media.indexOf(media)) } satisfies DownloadMeta, assets, }, }); diff --git a/src/player/store.ts b/src/player/store.ts index ea32564..3b1439d 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -2,12 +2,14 @@ import { create } from 'zustand'; import * as api from '../plex/api'; import { directUrl, previewUrl, reportTimeline, stopTranscode, transcodeUrl, type Delivery } from '../plex/playback'; import type { Item, Stream } from '../plex/types'; +import type { PlexServer } from '../plex/client'; import { useSession } from '../app/session'; +import { useDownloads, type Download } from '../downloads/store'; import { useSettings, SUBTITLE_MARGIN, type Preferences, type Quality, type Upscaling } from '../app/settings'; import { followVideoSize, noteMpvLog, requestEnhancement, watchPerformance } from './enhance'; import { channelLabel } from '../app/format'; import { invalidateLibrary } from '../app/queries'; -import { keepAwake, isNative, win } from '../platform/native'; +import { invoke, keepAwake, isNative, win } from '../platform/native'; import { mpv, type MpvEvent, type MpvTrack } from './engine'; import { toast } from '../ui/overlays'; import { stopThemeMusic } from './theme'; @@ -32,6 +34,8 @@ export interface PlayOptions { /** A local file path (offline download). */ localFile?: string; quality?: Quality; + /** Keep these track choices (UI keys) instead of applying the preferences again. */ + tracks?: { audioKey: string; subKey: string }; } interface PlayerState { @@ -113,7 +117,16 @@ let loadToken = 0; let wasFullscreenBeforePlay = false; let pendingExternal: Track | null = null; -const server = () => useSession.getState().server; +/** + * The server this playback belongs to, fixed when it starts. Progress, watched state + * and transcodes always go there, never to whichever server is selected later. A + * download plays without one unless its own server is the one connected. + */ +let playServer: PlexServer | null = null; +/** The download being played, whose saved metadata keeps the offline resume point. */ +let playDownload: Download | null = null; + +const server = () => playServer; /** * mpv applies its volume on a cubic curve, so halfway on a linear slider was @@ -218,8 +231,34 @@ async function applySubtitleStyle(prefs: Preferences = useSettings.getState()) { } } +/** A download's watch was counted this session; its resume point stays cleared. */ +let localScrobbled = false; + +/** + * Keeps a download's resume point (or, once watched, its watch count) in its saved + * metadata, which is all an offline title has to resume from. + */ +function saveLocalProgress(watched = false) { + const d = playDownload; + const { item, position, delivery, firstFrame } = usePlayer.getState(); + // Before the first frame the position is only where it was asked to start. + if (!d || !item || delivery?.mode !== 'local' || !firstFrame || (localScrobbled && !watched)) return; + const raw = { ...(d.meta.raw ?? {}) }; + if (watched) { + if (localScrobbled) return; + localScrobbled = true; + raw.viewOffset = 0; + raw.viewCount = (Number(raw.viewCount) || 0) + 1; + raw.lastViewedAt = Math.floor(Date.now() / 1000); + } else raw.viewOffset = Math.max(0, Math.round(position * 1000)); + const meta = { ...d.meta, raw }; + playDownload = { ...d, meta }; + invoke('download_write_meta', { id: d.id, meta }).catch(() => {}); +} + /** Reports progress to Plex; resolves true if the reply says the stream was stopped. */ function report(state: 'playing' | 'paused' | 'buffering' | 'stopped'): Promise { + if (state === 'paused' || state === 'stopped') saveLocalProgress(); const s = server(); const { item, position, delivery } = usePlayer.getState(); if (!s || !item || !session || item.type === 'clip') return Promise.resolve(false); @@ -266,9 +305,11 @@ function onTerminated(text: string) { function checkScrobble() { const { item, position, duration } = usePlayer.getState(); const s = server(); - if (!item || !s || scrobbled || !duration || item.type === 'clip') return; + if (!item || scrobbled || !duration || item.type === 'clip') return; const percent = useSettings.getState().watchedPercent; if (position / duration >= percent / 100) { + saveLocalProgress(true); + if (!s) return; scrobbled = true; api .setWatched(s, item.id, true) @@ -317,25 +358,12 @@ function stopCountdown() { countdownTimer = null; } -/** Applies Plex/user track preferences once mpv has loaded the file. */ -async function applyInitialTracks(tracks: MpvTrack[]) { - const st = usePlayer.getState(); - const prefs = useSettings.getState(); - const direct = st.delivery?.mode !== 'transcode'; - const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external); - - let audio = st.audioTracks; - let subs = st.subTracks; - if (direct) { - audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId })); - subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId })); - // Files without Plex stream info (offline) use mpv's own list. - if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel); - if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel); - } - - // Audio: preferred language, else Plex's selection, else the file default. - let audioKey = st.audioKey; +/** + * The tracks to play: a choice already made is kept ('' audio and '__init' subtitles + * mean none yet), otherwise the preferred audio language, then Plex's selection, then + * the file default; subtitles follow the subtitle mode. + */ +function preferredTracks(audio: Track[], subs: Track[], prefs: Preferences, audioKey = '', subKey = '__init') { if (!audioKey) { const lang = prefs.audioLanguage; audioKey = @@ -345,8 +373,6 @@ async function applyInitialTracks(tracks: MpvTrack[]) { audio[0]?.key || ''; } - // Subtitles: follow the subtitle mode. - let subKey = st.subKey; if (subKey === '__init') { const lang = prefs.subtitleLanguage || audio.find((t) => t.key === audioKey)?.language || ''; const inLang = subs.filter((t) => !lang || t.language === lang); @@ -364,6 +390,87 @@ async function applyInitialTracks(tracks: MpvTrack[]) { subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? ''; } } + return { audioKey, subKey }; +} + +type Selection = { audioStreamID?: string; subtitleStreamID?: string }; + +/** The item with Plex's stream selection updated locally to match `sel`. */ +function withSelection(item: Item, mediaIndex: number, sel: Selection): Item { + const media = item.media.map((m, i) => + i !== mediaIndex + ? m + : { + ...m, + parts: m.parts.map((p) => ({ + ...p, + streams: p.streams.map((x) => + x.streamType === 2 && sel.audioStreamID !== undefined + ? { ...x, selected: x.id === sel.audioStreamID } + : x.streamType === 3 && sel.subtitleStreamID !== undefined + ? { ...x, selected: x.id === sel.subtitleStreamID } + : x, + ), + })), + }, + ); + return { ...item, media }; +} + +const streamId = (tracks: Track[], key: string) => tracks.find((t) => t.key === key)?.stream?.id; + +/** + * What Plex must be told so its selection on this media matches the given streams + * (subtitle '' is none, undefined leaves either as it is). Empty if it already does. + */ +function selectionFor(item: Item, mediaIndex: number, audioId: string | undefined, subId: string | undefined): Selection { + const streams = item.media[mediaIndex]?.parts.flatMap((p) => p.streams) ?? []; + const sel: Selection = {}; + if (audioId && !streams.some((x) => x.streamType === 2 && x.selected && x.id === audioId)) sel.audioStreamID = audioId; + if (subId !== undefined && (streams.find((x) => x.streamType === 3 && x.selected)?.id ?? '') !== subId) sel.subtitleStreamID = subId || '0'; + return sel; +} + +/** Saves a track choice on the server; resolves to the item with that selection. */ +async function saveSelection(s: PlexServer, item: Item, mediaIndex: number, sel: Selection): Promise { + const part = item.media[mediaIndex]?.parts[0]; + if (!part || (sel.audioStreamID === undefined && sel.subtitleStreamID === undefined)) return item; + await api.selectStreams(s, part.id, sel); + return withSelection(item, mediaIndex, sel); +} + +/** Saves a choice made during direct play, so other Plex apps (and a later conversion) use it too. */ +function rememberSelection(st: PlayerState, audioId: string | undefined, subId: string | undefined) { + const s = server(); + const { item, mediaIndex } = st; + if (!s || !item) return; + const sel = selectionFor(item, mediaIndex, audioId, subId); + saveSelection(s, item, mediaIndex, sel) + .then(() => { + const now = usePlayer.getState(); + if (now.item?.id === item.id && now.mediaIndex === mediaIndex) usePlayer.setState({ item: withSelection(now.item, mediaIndex, sel) }); + }) + .catch(() => {}); +} + +/** Applies Plex/user track preferences once mpv has loaded the file. */ +async function applyInitialTracks(tracks: MpvTrack[]) { + const st = usePlayer.getState(); + const prefs = useSettings.getState(); + const direct = st.delivery?.mode !== 'transcode'; + const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external); + + let audio = st.audioTracks; + let subs = st.subTracks; + if (direct) { + audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId })); + subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId })); + // Files without Plex stream info (offline) use mpv's own list. + if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel); + if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel); + } + + const { audioKey, subKey } = preferredTracks(audio, subs, prefs, st.audioKey, st.subKey); usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey }); if (direct) { const a = audio.find((t) => t.key === audioKey); @@ -501,6 +608,9 @@ function onEvent(e: MpvEvent) { } } +/** The tracks playing now, to carry over when the same media restarts (a choice not made yet stays open). */ +const currentTracks = (st: PlayerState) => ({ audioKey: st.audioKey, subKey: st.subKey }); + /** Direct play failed: retry once through Plex's converter. */ let triedFallback = false; function fallbackAfterError() { @@ -509,7 +619,7 @@ function fallbackAfterError() { triedFallback = true; toast('Direct playback failed. Asking Plex to convert this video.'); usePlayer.setState({ error: '' }); - st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080' }); + st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080', tracks: currentTracks(st) }); } function maybeCredits(pos: number) { @@ -567,7 +677,8 @@ export const usePlayer = create((set, get) => ({ async play(input, opts = {}) { const token = ++loadToken; - const s = server(); + // Closing or starting something else while this one is still setting up wins. + const stale = () => token !== loadToken; const prefs = useSettings.getState(); stopThemeMusic(); stopCountdown(); @@ -576,13 +687,25 @@ export const usePlayer = create((set, get) => ({ return; } const previous = get(); + // The previous title's reporting ends here, against its own server. + if (reportTimer) clearInterval(reportTimer); + reportTimer = null; if (previous.open && previous.item) { report('stopped'); - if (previous.delivery?.session && s) stopTranscode(s, previous.delivery.session); + const ps = server(); + if (previous.delivery?.session && ps) stopTranscode(ps, previous.delivery.session); } + session = ''; + const current = useSession.getState().server; + const download = opts.localFile ? (useDownloads.getState().items.find((d) => d.filePath === opts.localFile) ?? null) : null; + const s = opts.localFile ? (current && download && current.machineId === download.meta.serverId ? current : null) : current; + playServer = s; + playDownload = download; + localScrobbled = false; if (!previous.open) { triedFallback = false; wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false); + if (stale()) return; } set({ open: true, @@ -604,8 +727,8 @@ export const usePlayer = create((set, get) => ({ chapters: [], audioTracks: [], subTracks: [], - audioKey: '', - subKey: '__init', + audioKey: opts.tracks?.audioKey ?? '', + subKey: opts.tracks?.subKey ?? '__init', video: null, fullscreen: wasFullscreenBeforePlay, mini: false, @@ -619,16 +742,16 @@ export const usePlayer = create((set, get) => ({ if (!opts.localFile && s && (!input.media.length || !input.media[0].parts[0]?.streams.length || !input.raw?.Marker)) { item = await api.metadata(s, input.id).catch(() => input); } - if (token !== loadToken) return; + if (stale()) return; const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1)); - const media = item.media[mediaIndex]; + let media = item.media[mediaIndex]; let offsetMs = opts.offsetMs ?? (opts.resume !== false && item.viewOffset && item.viewOffset < item.duration * 0.97 ? item.viewOffset : 0); - startOffsetMs = offsetMs; const local = useSession.getState().connection?.local ?? true; const quality: Quality = opts.quality ?? (local ? prefs.quality : prefs.remoteQuality); - session = crypto.randomUUID(); - sessionAnswered = false; - scrobbled = false; + const streams = media?.parts.flatMap((p) => p.streams) ?? []; + const audioTracks = streams.filter((x) => x.streamType === 2).map(audioTrackFromStream); + const subTracks = streams.filter((x) => x.streamType === 3).map(subTrackFromStream); + let tracks: { audioKey: string; subKey: string } | null = null; let delivery: Delivery; if (opts.localFile) { @@ -638,30 +761,43 @@ export const usePlayer = create((set, get) => ({ } else if (quality === 'original') { delivery = { url: directUrl(s, media), mode: 'direct', label: 'Original', absoluteTime: false }; } else { + // Plex converts (and burns in) the tracks selected on the server, so the chosen + // ones are saved there before the conversion starts, not after. + tracks = preferredTracks(audioTracks, subTracks, prefs, opts.tracks?.audioKey, opts.tracks?.subKey); + const audioStreamID = streamId(audioTracks, tracks.audioKey); + const subtitleStreamID = streamId(subTracks, tracks.subKey) ?? ''; + const base = item; + item = await saveSelection(s, base, mediaIndex, selectionFor(base, mediaIndex, audioStreamID, subtitleStreamID)).catch(() => base); + if (stale()) return; + media = item.media[mediaIndex]; const tsession = crypto.randomUUID(); delivery = { - url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local }), + url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local, audioStreamID, subtitleStreamID: subtitleStreamID || undefined }), mode: 'transcode', session: tsession, label: quality === '2160' ? '4K' : `${quality}p`, absoluteTime: true, }; } + startOffsetMs = offsetMs; + session = crypto.randomUUID(); + sessionAnswered = false; + scrobbled = false; - const streams = media?.parts.flatMap((p) => p.streams) ?? []; set({ item, delivery, mediaIndex, quality, duration: (item.duration || media?.duration || 0) / 1000, - audioTracks: streams.filter((x) => x.streamType === 2).map(audioTrackFromStream), - subTracks: streams.filter((x) => x.streamType === 3).map(subTrackFromStream), + audioTracks, + subTracks, + ...(tracks ?? {}), }); await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough }); if (!unlisten) unlisten = await mpv.on(onEvent); - if (token !== loadToken) return; + if (stale()) return; // mpv keeps pause across files: a title paused and closed would start paused. await mpv.set('pause', false); await mpv.set('mute', false); @@ -669,16 +805,21 @@ export const usePlayer = create((set, get) => ({ await mpv.set('speed', 1); await mpv.set('audio-delay', 0); await applySubtitleStyle(prefs); + if (stale()) return; followVideoSize(); await requestEnhancement(); + if (stale()) return; watchPerformance(true); await mpv.set('force-media-title', item.type === 'episode' ? `${item.grandparentTitle} — ${item.title}` : item.title); + if (stale()) return; await mpv.show(true); + if (stale()) return; const fileOpts = [ delivery.mode === 'transcode' ? 'rebase-start-time=no' : 'rebase-start-time=yes', offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none', ].join(','); await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts); + if (stale()) return; keepAwake(true); report('buffering'); reportTimer && clearInterval(reportTimer); @@ -702,6 +843,10 @@ export const usePlayer = create((set, get) => ({ if (st.item && !st.error) report('stopped'); const s = server(); if (st.delivery?.session && s) stopTranscode(s, st.delivery.session); + // Nothing more is reported for this playback, whatever mpv says while it stops. + session = ''; + playServer = null; + playDownload = null; keepAwake(false); watchPerformance(false); if (isNative) { @@ -794,35 +939,30 @@ export const usePlayer = create((set, get) => ({ const t = st.audioTracks.find((x) => x.key === key); if (!t) return; set({ audioKey: key }); - const s = server(); - const part = st.item?.media[st.mediaIndex]?.parts[0]; - if (s && part && t.stream) api.selectStreams(s, part.id, { audioStreamID: t.stream.id }).catch(() => {}); if (st.delivery?.mode === 'transcode' && st.item) { - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality }); + // The restart saves the choice on the server before converting with it. + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), audioKey: key } }); return; } if (t.mpvId) await mpv.set('aid', t.mpvId).catch(() => {}); + rememberSelection(st, t.stream?.id, undefined); }, async selectSubtitle(key) { const st = get(); set({ subKey: key }); - const s = server(); - const part = st.item?.media[st.mediaIndex]?.parts[0]; - const t = st.subTracks.find((x) => x.key === key); - if (s && part) api.selectStreams(s, part.id, { subtitleStreamID: t?.stream?.id ?? '0' }).catch(() => {}); if (st.delivery?.mode === 'transcode' && st.item) { - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality }); - usePlayer.setState({ subKey: key }); + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), subKey: key } }); return; } await setMpvSubtitle(key); + rememberSelection(st, undefined, streamId(st.subTracks, key) ?? ''); }, async setQuality(q) { const st = get(); if (!st.item || q === st.quality) return; - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q }); + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q, tracks: currentTracks(st) }); }, async selectVersion(index) { @@ -885,6 +1025,24 @@ usePlayer.subscribe((st, prev) => { bridgeMiniWindow(usePlayer); +/** + * Signing out, or switching server or profile, ends a stream from the old one: its + * progress belongs to that account. A download keeps playing, without reporting. + * A reconnect to the same server with the same credentials carries on. + */ +useSession.subscribe((st, prev) => { + const old = prev.server; + if (!old || st.server === old) return; + const same = !!st.server && st.server.machineId === old.machineId && st.server.token === old.token; + if (playServer !== old) return; + if (same) { + playServer = st.server; + return; + } + if (usePlayer.getState().open && !playDownload) usePlayer.getState().close(); + playServer = null; +}); + /** 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) => { diff --git a/src/plex/client.ts b/src/plex/client.ts index 3548c35..a64ce79 100644 --- a/src/plex/client.ts +++ b/src/plex/client.ts @@ -121,23 +121,41 @@ export async function plexRequest(url: string, token: string | null | u const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000); const onAbort = () => controller.abort(); opts.signal?.addEventListener('abort', onAbort); + // The timeout and the caller's cancel cover the body as well as the headers: a reply + // that stalls part way must still end. (Rejects only once aborted.) + const aborted = new Promise((_, reject) => + controller.signal.addEventListener('abort', () => reject(opts.signal?.aborted ? opts.signal.reason : new PlexError('The server took too long to respond.', 0)), { once: true }), + ); + aborted.catch(() => {}); + if (opts.signal?.aborted) controller.abort(); let response: Response; + let text: string; try { - response = await httpFetch(withParams(url, opts.params), { - method: opts.method ?? 'GET', - headers: { ...plexHeaders(token), ...opts.headers }, - body: opts.body ?? undefined, - signal: controller.signal, - }); - } catch (e: any) { - if (opts.signal?.aborted) throw e; - throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0); + try { + response = await Promise.race([ + httpFetch(withParams(url, opts.params), { + method: opts.method ?? 'GET', + headers: { ...plexHeaders(token), ...opts.headers }, + body: opts.body ?? undefined, + signal: controller.signal, + }), + aborted, + ]); + } catch (e: any) { + if (opts.signal?.aborted) throw e; + throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0); + } + if (!response.ok) throw new PlexError(statusMessage(response.status), response.status); + try { + text = await Promise.race([response.text(), aborted]); + } catch (e: any) { + if (opts.signal?.aborted || e instanceof PlexError) throw e; + throw new PlexError('The connection to the server was lost.', 0); + } } finally { clearTimeout(timer); opts.signal?.removeEventListener('abort', onAbort); } - if (!response.ok) throw new PlexError(statusMessage(response.status), response.status); - const text = await response.text(); if (opts.text) return text as unknown as T; if (!text.trim()) return {} as T; try { diff --git a/src/plex/playback.ts b/src/plex/playback.ts index 60408da..39464b1 100644 --- a/src/plex/playback.ts +++ b/src/plex/playback.ts @@ -39,6 +39,10 @@ export function transcodeUrl( path: `/library/metadata/${item.id}`, mediaIndex: opts.mediaIndex, partIndex: 0, + // Plex converts the part's selected streams; callers save the selection first and + // name it here as well. + audioStreamID: opts.audioStreamID, + subtitleStreamID: opts.subtitleStreamID, protocol: 'hls', session: opts.session, offset: (opts.offsetMs / 1000).toFixed(1), diff --git a/src/screens/LibraryBrowser.tsx b/src/screens/LibraryBrowser.tsx index 70d9cae..6d7e9c7 100644 --- a/src/screens/LibraryBrowser.tsx +++ b/src/screens/LibraryBrowser.tsx @@ -236,6 +236,33 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti loadPage(0); }, [loadPage]); + // Pages are copied out of the cache, so nothing re-renders when it is invalidated + // (watched state, edits, deletions, library changes): fetch the loaded ones again. + const loaded = useRef(pages); + loaded.current = pages; + useEffect(() => { + const prefix = JSON.stringify([server.machineId, 'libraryPage', section.id, params]); + const due = new Set(); + let timer: ReturnType | null = null; + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + if (event.type !== 'updated' || event.action.type !== 'invalidate') return; + const key = event.query.queryKey; + const p = key[4]; + if (typeof p !== 'number' || !loaded.current[p] || JSON.stringify(key.slice(0, 4)) !== prefix) return; + due.add(p); + // One pass after the whole invalidation, not one per page as it happens. + timer ??= setTimeout(() => { + timer = null; + for (const page of due) loadPage(page); + due.clear(); + }); + }); + return () => { + unsubscribe(); + if (timer) clearTimeout(timer); + }; + }, [loadPage]); + const gap = 16; const target = CARD_WIDTH[posterSize]; const cols = Math.max(2, Math.floor((width + gap) / (target + gap))); diff --git a/src/ui/Hero.tsx b/src/ui/Hero.tsx index cc85c9c..122163a 100644 --- a/src/ui/Hero.tsx +++ b/src/ui/Hero.tsx @@ -43,14 +43,14 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari img.decode?.().catch(() => {}); }, [upcoming?.id]); + // Pause rotation when the hero is scrolled away; it picks up again on its return. + const [visible, setVisible] = useState(true); useEffect(() => { - if (!rotate || reduced || count < 2 || hover) return; + if (!rotate || reduced || count < 2 || hover || !visible) return; const t = setTimeout(() => go(index + 1), ROTATE_MS); return () => clearTimeout(t); - }, [index, rotate, reduced, count, hover]); + }, [index, rotate, reduced, count, hover, visible]); - // Pause rotation when the hero is scrolled away. - const [visible, setVisible] = useState(true); useEffect(() => { const el = root.current; if (!el) return; @@ -60,7 +60,6 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari }, []); const go = (i: number) => { - if (!visible && i !== index) return; setIndex(((i % count) + count) % count); setCopyKey((k) => k + 1); }; diff --git a/src/ui/media.tsx b/src/ui/media.tsx index da07294..11b9136 100644 --- a/src/ui/media.tsx +++ b/src/ui/media.tsx @@ -1,6 +1,6 @@ import { memo, useEffect, useRef, useState, type ReactNode } from 'react'; import type { Item } from '../plex/types'; -import { useServer } from '../app/session'; +import { useServer, useSession } from '../app/session'; import { useSettings } from '../app/settings'; import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format'; import { itemMenu, openItem, playWithVersion } from '../app/actions'; @@ -90,7 +90,8 @@ export function Facts({ item, withFormats = true, episode = true, children }: { /** Original clear-logo artwork, falling back to the title in type. */ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight = 130, as: As = 'h1' }: { item: Item; logo?: string; className?: string; maxWidth?: number; maxHeight?: number; as?: 'h1' | 'h2' }) { - const server = useServer(); + // The player shows this offline too, where there is no server to draw the logo from. + const server = useSession((s) => s.server); const path = logo ?? item.logo; const [failed, setFailed] = useState(false); const [ready, setReady] = useState(false); @@ -99,7 +100,7 @@ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight setReady(false); }, [path]); const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title; - if (!path || failed) + if (!path || failed || !server) return ( {title} From b5dc5d8666278eddfcc89bf9fecfdd367aabb2ed Mon Sep 17 00:00:00 2001 From: Elijah Date: Fri, 6 Nov 2026 19:29:16 -0700 Subject: [PATCH 03/22] Blend the colour wash between titles and keep full screen for the miniplayer - The backdrop's colour wash is one layer whose corner colours are registered custom properties, so a change of title blends them instead of stacking a half-opacity layer and removing the old one (which made the colour jump). Outgoing artwork fades out before it is removed, and quick changes keep the layer that is on screen. - Going to the miniplayer no longer leaves full screen. Esc while browsing leaves full screen first, Windows' caption buttons show Exit full screen in place of maximize, closing the miniplayer keeps the window as it is, and the player's full-screen state follows changes made outside it. Co-Authored-By: Claude Opus 5.5 --- src/app/App.tsx | 6 +++-- src/app/TopBar.tsx | 26 +++++++++++++----- src/app/format.ts | 21 ++++++++++----- src/player/store.ts | 29 +++++++++++++------- src/styles/app.css | 42 ++++++++++++++++++++++++++--- src/ui/Backdrop.tsx | 65 ++++++++++++++++++++++++++++----------------- 6 files changed, 135 insertions(+), 54 deletions(-) diff --git a/src/app/App.tsx b/src/app/App.tsx index 6623697..c0e8786 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -11,7 +11,7 @@ import { PageLoader } from '../ui/primitives'; import { Splash } from '../screens/Splash'; import { SignIn } from '../screens/SignIn'; import { ServerPicker } from '../screens/ServerPicker'; -import { isMac, win } from '../platform/native'; +import { isMac, isNative, win } from '../platform/native'; import { usePlayer } from '../player/store'; import { PlayerOverlay } from '../player/PlayerOverlay'; import { DialogHost } from '../screens/dialogs/DialogHost'; @@ -111,7 +111,9 @@ function useGlobalShortcuts() { win.isFullscreen().then((fs) => win.setFullscreen(!fs)); } else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) { if (e.key === 'Escape' && document.fullscreenElement) return; - useRouter.getState().back(); + // Esc leaves full screen first (kept from the player when it went to the corner). + if (e.key === 'Escape' && isNative) win.isFullscreen().then((fs) => (fs ? win.setFullscreen(false) : useRouter.getState().back())); + else useRouter.getState().back(); } else if ((e.ctrlKey || e.metaKey) && e.key === ',') { e.preventDefault(); navigate({ name: 'settings', mode: 'app', tab: 'general' }); diff --git a/src/app/TopBar.tsx b/src/app/TopBar.tsx index 3c538fc..6007226 100644 --- a/src/app/TopBar.tsx +++ b/src/app/TopBar.tsx @@ -19,13 +19,21 @@ const NAV = [ /** Caption buttons drawn by the page; macOS shows its own traffic lights instead. */ export function WindowControls() { const [maximized, setMaximized] = useState(false); + const [fullscreen, setFullscreen] = useState(false); useEffect(() => { if (!isNative || isMac) return; let off: (() => void) | undefined; - const sync = () => win.isMaximized().then(setMaximized); + let gone = false; + const sync = () => { + win.isMaximized().then((m) => !gone && setMaximized(m)); + win.isFullscreen().then((f) => !gone && setFullscreen(f)); + }; sync(); - win.onResized(sync).then((u) => (off = u)); - return () => off?.(); + win.onResized(sync).then((u) => (gone ? u() : (off = u))); + return () => { + gone = true; + off?.(); + }; }, []); if (!isNative || isMac) return null; return ( @@ -33,9 +41,15 @@ export function WindowControls() { - + {fullscreen ? ( + + ) : ( + + )} diff --git a/src/app/format.ts b/src/app/format.ts index 47d138a..a41b82d 100644 --- a/src/app/format.ts +++ b/src/app/format.ts @@ -174,17 +174,24 @@ export function plural(n: number, word: string, pluralWord = `${word}s`) { return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`; } -/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */ -export function washGradient(u: Item['ultraBlur'], strength = 1): string { - if (!u) return ''; +/** Hex UltraBlur colors → the wash's four corner colours, each at its own strength. */ +export function washColors(u: Item['ultraBlur'], strength = 1) { + if (!u) return null; const c = (hex: string, a: number) => { const n = parseInt(hex, 16); return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${(a * strength).toFixed(3)})`; }; + return { topRight: c(u.topRight, 0.95), topLeft: c(u.topLeft, 0.7), bottomRight: c(u.bottomRight, 0.55), bottomLeft: c(u.bottomLeft, 0.45) }; +} + +/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */ +export function washGradient(u: Item['ultraBlur'], strength = 1): string { + const c = washColors(u, strength); + if (!c) return ''; return [ - `radial-gradient(ellipse at 100% 0%, ${c(u.topRight, 0.95)} 0%, transparent 62%)`, - `radial-gradient(ellipse at 0% 0%, ${c(u.topLeft, 0.7)} 0%, transparent 55%)`, - `radial-gradient(ellipse at 100% 100%, ${c(u.bottomRight, 0.55)} 0%, transparent 60%)`, - `radial-gradient(ellipse at 0% 100%, ${c(u.bottomLeft, 0.45)} 0%, transparent 60%)`, + `radial-gradient(ellipse at 100% 0%, ${c.topRight} 0%, transparent 62%)`, + `radial-gradient(ellipse at 0% 0%, ${c.topLeft} 0%, transparent 55%)`, + `radial-gradient(ellipse at 100% 100%, ${c.bottomRight} 0%, transparent 60%)`, + `radial-gradient(ellipse at 0% 100%, ${c.bottomLeft} 0%, transparent 60%)`, ].join(', '); } diff --git a/src/player/store.ts b/src/player/store.ts index 3b1439d..ca60b1e 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -702,10 +702,12 @@ export const usePlayer = create((set, get) => ({ playServer = s; playDownload = download; localScrobbled = false; + // From the miniplayer the window may have gone full screen (or left it) since. + const fullscreenNow = await win.isFullscreen().catch(() => false); + if (stale()) return; if (!previous.open) { triedFallback = false; - wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false); - if (stale()) return; + wasFullscreenBeforePlay = fullscreenNow; } set({ open: true, @@ -730,7 +732,7 @@ export const usePlayer = create((set, get) => ({ audioKey: opts.tracks?.audioKey ?? '', subKey: opts.tracks?.subKey ?? '__init', video: null, - fullscreen: wasFullscreenBeforePlay, + fullscreen: fullscreenNow, mini: false, videoGamma: '', enhance: { ...previous.enhance, bypass: false, preparing: false }, @@ -856,8 +858,12 @@ export const usePlayer = create((set, get) => ({ await mpv.show(false).catch(() => {}); } set({ open: false, mini: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false }); - const fs = await win.isFullscreen().catch(() => false); - if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false); + // Closing the full player hands back the window it found; closing the + // miniplayer leaves browsing as it is, full screen or not. + if (!st.mini) { + const fs = await win.isFullscreen().catch(() => false); + if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false); + } if (st.item) invalidateLibrary(); }, @@ -913,12 +919,8 @@ export const usePlayer = create((set, get) => ({ async minimize() { const st = get(); if (!st.open || st.mini) return; + // Full screen stays for browsing; Esc or the window controls leave it. set({ mini: true }); - // Full screen was for the video; browsing goes back to the window. - if (st.fullscreen && !wasFullscreenBeforePlay) { - 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). @@ -1025,6 +1027,13 @@ usePlayer.subscribe((st, prev) => { bridgeMiniWindow(usePlayer); +// Full screen can change outside the player (Esc or the window controls while +// browsing with the miniplayer, the OS): the player's controls follow it. +win.onResized(() => { + if (!usePlayer.getState().open) return; + win.isFullscreen().then((fs) => usePlayer.getState().fullscreen !== fs && usePlayer.setState({ fullscreen: fs }), () => {}); +}); + /** * Signing out, or switching server or profile, ends a stream from the old one: its * progress belongs to that account. A download keeps playing, without reporting. diff --git a/src/styles/app.css b/src/styles/app.css index a1d258e..8f670c6 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -515,6 +515,12 @@ html.splash-arrival .auth-screen { .backdrop-layer.ready { opacity: 1; } +/* The outgoing art fades too, a beat behind the incoming, so nothing of it is + left to vanish through the new art's faded edges. */ +.backdrop-layer.ready.leaving { + opacity: 0; + transition-delay: 180ms; +} /* The colour wash lives outside the clipped backdrop so it can carry on down the page behind the rows, fading out as it goes. */ .backdrop-tint { @@ -528,14 +534,42 @@ html.splash-arrival .auth-screen { -webkit-mask-image: linear-gradient(180deg, #000 0%, rgba(0, 0, 0, 0.75) 45%, transparent 100%); mask-image: linear-gradient(180deg, #000 0%, rgba(0, 0, 0, 0.75) 45%, transparent 100%); } +/* Registered as colours so a change of title blends the wash from one set of + colours to the next, instead of swapping the gradient outright. */ +@property --wash-tr { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-tl { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-br { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-bl { + syntax: ''; + inherits: false; + initial-value: transparent; +} .backdrop-wash { position: absolute; inset: 0; - opacity: 0; - transition: opacity 420ms var(--ease); -} -.backdrop-wash.ready { opacity: 0.5; + background: + radial-gradient(ellipse at 100% 0%, var(--wash-tr) 0%, transparent 62%), + radial-gradient(ellipse at 0% 0%, var(--wash-tl) 0%, transparent 55%), + radial-gradient(ellipse at 100% 100%, var(--wash-br) 0%, transparent 60%), + radial-gradient(ellipse at 0% 100%, var(--wash-bl) 0%, transparent 60%); + transition: + --wash-tr 700ms var(--ease), + --wash-tl 700ms var(--ease), + --wash-br 700ms var(--ease), + --wash-bl 700ms var(--ease); } .backdrop-art { position: absolute; diff --git a/src/ui/Backdrop.tsx b/src/ui/Backdrop.tsx index 15116b6..f3338a9 100644 --- a/src/ui/Backdrop.tsx +++ b/src/ui/Backdrop.tsx @@ -1,21 +1,25 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, type CSSProperties } from 'react'; import type { Item } from '../plex/types'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; -import { art, washGradient } from '../app/format'; +import { art, washColors } from '../app/format'; interface Layer { key: number; src: string; - wash: string; + blur: Item['ultraBlur']; ready: boolean; } +/** How long an outgoing layer lingers: its fade (with delay) plus a margin. */ +const LEAVE_MS = 700; + /** * Artwork-led page background. The image sits top-right and fades into the * page toward its left and bottom edges; the UltraBlur colour wash tints the - * page beneath it and carries on down behind the rows. Changes crossfade; the - * outgoing layer stays until the new image has decoded. + * page beneath it and carries on down behind the rows. Artwork crossfades + * once the new image has decoded, and the wash's colours blend into the new + * title's at the same moment (registered custom properties, app.css). */ export function Backdrop({ item, className = '', width = 1600, height = 900, wash: forceWash }: { item: Item | null | undefined; className?: string; width?: number; height?: number; wash?: Item['ultraBlur'] }) { const server = useServer(); @@ -25,39 +29,50 @@ export function Backdrop({ item, className = '', width = 1600, height = 900, was const path = item ? art.backdrop(item) : ''; const src = path ? server.image(path, width, height) : ''; const blur = forceWash ?? item?.ultraBlur ?? null; - const wash = colorWash && blur ? washGradient(blur) : ''; + const blurKey = blur ? `${blur.topLeft}${blur.topRight}${blur.bottomRight}${blur.bottomLeft}` : ''; useEffect(() => { - if (!src && !wash) return; + if (!src && !blur) return; setLayers((prev) => { - if (prev.length && prev[prev.length - 1].src === src) { - // Same art, maybe new wash. - return prev.map((l, i) => (i === prev.length - 1 ? { ...l, wash } : l)); - } - return [...prev.slice(-1), { key: ++counter.current, src, wash, ready: !src }]; + const last = prev[prev.length - 1]; + // Same art, maybe new colours: the wash blends to them in place. + if (last && last.src === src) return prev.map((l) => (l === last ? { ...l, blur } : l)); + // Keep only what is on screen (the newest layer that has shown) under the new one. + const shown = prev.filter((l) => l.ready).slice(-1); + return [...shown, { key: ++counter.current, src, blur, ready: !src }]; }); - }, [src, wash]); + }, [src, blurKey]); - const onReady = (key: number) => - setLayers((prev) => { - const idx = prev.findIndex((l) => l.key === key); - if (idx < 0) return prev; - const next = prev.map((l) => (l.key === key ? { ...l, ready: true } : l)); - // Drop older layers once the newest is visible (after its fade). - setTimeout(() => setLayers((p) => (p.length > 1 && p[p.length - 1].key === key ? p.slice(-1) : p)), 500); - return next; - }); + const onReady = (key: number) => setLayers((prev) => (prev.some((l) => l.key === key && !l.ready) ? prev.map((l) => (l.key === key ? { ...l, ready: true } : l)) : prev)); + + // Once the newest layer is in, the ones beneath fade out and then go. + const newest = layers[layers.length - 1]; + useEffect(() => { + if (!newest?.ready || layers.length < 2) return; + const t = setTimeout(() => setLayers((p) => (p[p.length - 1]?.key === newest.key ? p.slice(-1) : p)), LEAVE_MS); + return () => clearTimeout(t); + }, [newest?.key, newest?.ready, layers.length]); + + let top = -1; + layers.forEach((l, i) => l.ready && (top = i)); + const colors = top >= 0 ? washColors(layers[top].blur) : null; + const washStyle = { + '--wash-tr': colors?.topRight ?? 'transparent', + '--wash-tl': colors?.topLeft ?? 'transparent', + '--wash-br': colors?.bottomRight ?? 'transparent', + '--wash-bl': colors?.bottomLeft ?? 'transparent', + } as CSSProperties; return ( <> {colorWash && (