Compare commits
No commits in common. "main" and "v0.1.0-beta.9" have entirely different histories.
main
...
v0.1.0-bet
56 changed files with 714 additions and 3519 deletions
117
CHANGELOG.md
117
CHANGELOG.md
|
|
@ -1,122 +1,5 @@
|
|||
# Changelog
|
||||
|
||||
## 1.0.1
|
||||
|
||||
A quicker start, a Stop button, and recovery when the server drops out mid-video.
|
||||
|
||||
- Kaleido starts faster: the opening animation is shorter, so you reach your library in about a second.
|
||||
- The player has a Stop button, next to the forward controls, which closes the player completely instead of moving it to the miniplayer.
|
||||
- If your Plex server goes down while you're watching, the player waits for it once the buffered video runs out, then carries on from the same spot when the server is back. Before, it treated the video as finished and Play started it again from the beginning. Pressing Play while it waits tries to reconnect straight away.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
Kaleido is out of beta. This release reworks the show and season pages and smooths out watching a series.
|
||||
|
||||
- Season pages show their episodes as a grid of cards, each with its still, description and watched state, in place of the long episode list.
|
||||
- Click the season's name under the show's logo to switch to another season.
|
||||
- Show pages list seasons once, as a row of posters. A show with only one season shows its episodes directly.
|
||||
- Episodes you've watched stay marked as watched when you rewatch them and stop partway through. The leftover position only shows on the episode you're up to.
|
||||
- When the next episode plays, whether automatically or with Next, it starts from the beginning instead of near the end of an earlier viewing.
|
||||
- Click a show's name under a Continue Watching card to go to the show.
|
||||
- Continue Watching starts at the first title when something new is added, instead of scrolling it off the left edge.
|
||||
- Season posters outside their show's page, such as New Seasons, are labelled with the show's name.
|
||||
- Season pages show the year the season aired, and their Play button agrees with the show page about which episode is next.
|
||||
- Movie and episode pages show the runtime in their details, with the time left on the Resume button.
|
||||
|
||||
## 0.1.0-beta.19
|
||||
|
||||
Up Next fixes.
|
||||
|
||||
- Up Next now opens every time the credits start: going back to the credits and seeking into the episode brings it back when they come round again, and it always opens when an episode reaches the end.
|
||||
- The back arrow and a full-screen button are back at the top of Up Next, so you can return to browsing (playback continues in the miniplayer) or leave full screen.
|
||||
- Click the show's logo to go to its page, with playback moving to the miniplayer.
|
||||
- The Play next episode countdown fills smoothly.
|
||||
- The episode rows are sized to fill the screen instead of leaving a gap at the bottom.
|
||||
- The backdrop now shows the next episode, and its description is easier to read over bright artwork.
|
||||
|
||||
## 0.1.0-beta.18
|
||||
|
||||
A rebuilt Up Next screen that looks and works like the rest of Kaleido.
|
||||
|
||||
- Up Next now uses the same artwork backdrop, colour wash, buttons and cards as the title pages. The credits keep playing in the top-left corner beside the next episode, and the Play next episode button fills as the countdown runs.
|
||||
- The Season and Related shows rows scroll with the side arrows, like every other row, instead of scrollbars. The season row starts at the episode you just watched.
|
||||
- Click the video or press Esc to go back to the credits; at the end of an episode this no longer restarts it from the beginning.
|
||||
- Up Next fits smaller windows, and the window buttons stay visible on Mac while it's open.
|
||||
- Playback settings are a simple list again: Skip intros, Skip movie credits, Automatic skip delay and Autoplay next episode.
|
||||
|
||||
## 0.1.0-beta.17
|
||||
|
||||
- Fix the Up Next countdown stalling when the native video has keyboard focus instead of the webview. Count elapsed time accurately through delayed timer callbacks, and keep the countdown independent of the video's pause state, as on Android TV.
|
||||
- Open Up Next at the first episode credit marker, including after seeking into credits, independently of movie-credit skip preferences. Open the screen immediately while episode context loads, and start autoplay once the next episode is known. Without markers, use the end of the episode as a fallback.
|
||||
- Cancel autoplay on mouse movement, clicks, scrolling or keypresses. A stationary pointer does not cancel it; cancelled autoplay stays cancelled when delayed metadata arrives.
|
||||
- Match the Android TV screen more closely: remove the extra toolbar actions, Cancel autoplay button and autoplay-status text; show only a white video outline on hover or keyboard focus. Use compact episode metadata, full runtime, landscape related shows and captions beneath the artwork.
|
||||
|
||||
## 0.1.0-beta.16
|
||||
|
||||
- Simplify playback settings: group intro, credits and skip-delay choices together, show the delay only when automatic skipping is enabled, and combine the next-episode switch and countdown into one Off / After … seconds selection. Existing preferences are preserved.
|
||||
- Make Up Next readable over bright artwork with a dark backdrop across the page, brighter secondary text and larger synopsis and autoplay hints. The playing video stays at its original brightness.
|
||||
|
||||
## 0.1.0-beta.15
|
||||
|
||||
A new Up Next screen, adapted from Kaleido for Android TV for mouse and keyboard.
|
||||
|
||||
- Replace the corner countdown with a full Up Next screen. Credits keep playing in the top-left corner beside the next episode’s artwork, title, rating and synopsis, with the season and related shows below. The Play next episode button fills during the single countdown.
|
||||
- Click the video or Return to video, or press Esc, to return to the credits. Click Play next episode to start immediately, choose any season episode, or open a related show. Tab and Shift+Tab move between controls with visible keyboard focus.
|
||||
- Click, scroll or press any key to cancel autoplay while keeping Up Next open. Moving the mouse alone leaves the countdown running. The timer pauses while Kaleido is hidden, unfocused or paused, and never restarts after cancellation or returning to the credits.
|
||||
- Respect the credits preference: Skip automatically opens Up Next as episode credits begin; Show button opens it when clicked; Off waits for the episode to end. Episode credits use only the Up Next countdown, independent of the intro/movie skip delay. A series finale shows More to watch without autoplay.
|
||||
|
||||
## 0.1.0-beta.14
|
||||
|
||||
Full screen stays on with the miniplayer, a smoother colour wash, and a round of playback and download fixes.
|
||||
|
||||
- Going back from the full-screen player to the miniplayer now keeps Kaleido in full screen, so you can browse full screen while the video plays in the corner. Press Esc to go back to a window, or on Windows use the new Exit full screen button beside the window controls. Closing the miniplayer leaves the window as it is.
|
||||
- The colour wash behind the featured titles and title pages now blends into the next title's colours instead of jumping when the artwork changes. Clicking quickly through featured titles no longer blanks the background for a moment.
|
||||
- Playback stays with the server it started on: progress and watched marks never go to a server you switch to later, and switching account, profile or server ends playback from the old one. Downloads report only to their own server.
|
||||
- When Plex converts a video, the audio and subtitle tracks you chose (and your language preferences) are now applied, and kept when you change quality.
|
||||
- Watching a download offline now saves where you stopped and marks it watched.
|
||||
- Fixed: playing something offline could crash the player.
|
||||
- Fixed: closing or switching titles while a video was still starting could start it anyway.
|
||||
- Fixed: Home and the libraries could still show the previous account's or profile's titles after switching.
|
||||
- Fixed: titles split into several files were downloaded only in part; Kaleido now picks a single-file version, or says it can't download the title.
|
||||
- Fixed: episodes downloaded into the same season folder could overwrite or delete each other's artwork, and pause or remove could stop working after a download restarted.
|
||||
- Library grids refresh fully when something changes, slow server responses time out properly, and the featured titles start rotating again when you scroll back to them.
|
||||
|
||||
## 0.1.0-beta.13
|
||||
|
||||
A gentler automatic intro skip, and home screens that keep up with your other Plex apps.
|
||||
|
||||
- "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.
|
||||
- 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.
|
||||
- Jumping into the middle of an intro yourself no longer skips it automatically.
|
||||
- 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.
|
||||
|
||||
## 0.1.0-beta.12
|
||||
|
||||
A smoother miniplayer on Windows.
|
||||
|
||||
- The miniplayer is now a small window of its own, so dragging it moves the video and its controls together: the video keeps playing smoothly as you move it, with no flicker around its edges.
|
||||
- Letting go snaps it to the nearest corner of the window, or the corner you flick it towards, and it remembers that corner. It stays in place as the window moves or resizes.
|
||||
- Using its buttons no longer takes focus from the main window, so keyboard shortcuts keep working.
|
||||
- On Mac the miniplayer is unchanged for now.
|
||||
|
||||
## 0.1.0-beta.11
|
||||
|
||||
Fixes the app freezing when leaving full screen for the miniplayer, and adds local hang and crash reports.
|
||||
|
||||
- Fixed: going back from the full-screen player to the miniplayer (or moving or resizing the miniplayer) could freeze the window — it turned see-through and "Not Responding" while the video kept playing. Two parts of the player were each waiting for the other when the window resized at the wrong moment.
|
||||
- When the window stops responding for 5 seconds, or the app crashes, Kaleido now saves a report of what each part of the app was doing in its log folder (`%LOCALAPPDATA%\tv.kaleido.desktop\logs`), so a rare problem can be traced the first time it happens. Reports stay on your computer.
|
||||
|
||||
## 0.1.0-beta.10
|
||||
|
||||
A redesigned player control bar, previous episode, and a movable miniplayer.
|
||||
|
||||
- The player's controls are rearranged the way most media players lay them out: play/pause sits in the centre under the timeline, with 10-second skips either side and previous/next episode beyond those. Volume and the time are on the left; subtitles, settings and full screen stay on the right.
|
||||
- New previous-episode button (and Shift+P) to go back an episode. For episodes both buttons always show, dimmed at the start or end of a show, so play/pause stays put.
|
||||
- The miniplayer can be dragged anywhere in the window. It stays inside the window when it's resized, and remembers where you left it.
|
||||
- Fixed: the Play now and Cancel buttons on the next-episode card during the credits couldn't be clicked (the player's title row covered them). The Skip intro/credits button had the same problem with tall show logos.
|
||||
- Fixed: clicking Skip intro or Skip credits also paused the video.
|
||||
- The featured titles at the top of Home, Movies and TV Shows no longer carry a "Highly rated" / "Recommended" label, and their logo has room above the details line instead of touching it.
|
||||
|
||||
## 0.1.0-beta.9
|
||||
|
||||
Fixes for the Mac version.
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ place (see [Architecture](docs/architecture.md)). Linux builds browse but don't
|
|||
| Enter / Space | Open / play | ↑ / ↓, wheel | Volume |
|
||||
| Menu or Shift+F10 | Title actions | F, double-click | Full screen |
|
||||
| Alt+← (⌘[) / mouse back | Back | C | Next subtitle |
|
||||
| / | Focus search | Shift+P / N | Previous / next episode |
|
||||
| / | Focus search | Shift+N | Next episode |
|
||||
| F11 (⌃⌘F) | Full screen | Esc | Exit full screen, then player |
|
||||
|
||||
Keys in brackets are the macOS equivalents.
|
||||
|
|
|
|||
|
|
@ -82,17 +82,8 @@ into the display's HDR headroom; SDR video returns both to their defaults.
|
|||
on demand. Timeline reports every 10 seconds (and when playback stalls) make the session appear in
|
||||
Plex; a reply carrying a termination (the server owner stopped the stream) stops
|
||||
playback and shows their message. The title is marked watched at the configured percentage. The player's back arrow (or Esc)
|
||||
shrinks playback into a miniplayer. On Windows it is a window of its own
|
||||
(`src-tauri/src/mini.rs`, page `mini.html` → `src/mini/`): a small borderless window
|
||||
owned by the main one, which the video moves into (`VideoSurface::set_host`, one
|
||||
composition target per window, swapped in a single commit). Dragging moves that whole
|
||||
window, so video and controls never drift apart; letting go glides it to a corner of
|
||||
the main window (or the one it's flicked towards), and it follows the main window as
|
||||
that moves or resizes. Its page mirrors the player from the main window and sends its
|
||||
buttons back (`player/miniWindow.ts`, events `mini:state` / `mini:action`). The video
|
||||
moves into it once the main page is opaque again, and back before the page turns
|
||||
transparent, so neither window flashes. On macOS the miniplayer stays inside the page:
|
||||
the video is drawn in a corner rectangle with a matching hole masked out of the page
|
||||
shrinks playback into a miniplayer: the video is drawn in a corner rectangle and the
|
||||
interface stays visible around it, with a matching hole masked out of the page
|
||||
(`html.player-mini`).
|
||||
- **Upscaling** (`player/enhance.ts`): Performance and Balanced set mpv's scalers and
|
||||
debanding and load shaders bundled from `src-tauri/shaders/` (FSRCNNX 16, nlmeans,
|
||||
|
|
|
|||
|
|
@ -47,38 +47,6 @@ Playback tests change real Plex progress; resume an in-progress title near its s
|
|||
position, or restore it afterwards. Selecting audio or subtitle tracks is saved to Plex
|
||||
for that file.
|
||||
|
||||
Up Next (`player/PostPlay.tsx`) opens at an episode's first credits marker, or at the end
|
||||
without markers. The video is drawn into its top-left frame (`player_rect`) behind a
|
||||
matching hole in the page; check that the two line up after resizing, changing display
|
||||
scale and returning to the video. In the browser, open it from the console by setting
|
||||
`postPlay: true` (with `item`, `nextUp`, `episodeContextReady`) on `__kaleido.usePlayer`.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
`src-tauri/src/diagnostics.rs` writes to the app's log folder
|
||||
(`%LOCALAPPDATA%\tv.kaleido.desktop\logs` on Windows); nothing is uploaded.
|
||||
|
||||
- **Hangs**: a watchdog asks the UI thread to answer every second. After 5 seconds of
|
||||
silence it writes `kaleido-hang-<time>-v<version>.dmp` with every thread's stack (once
|
||||
per stall) and notes the stall and the recovery in `diagnostics.log`.
|
||||
- **Crashes** (Windows): an unhandled exception writes `kaleido-crash-…dmp` and logs the
|
||||
exception and faulting module, e.g. `access violation at libmpv-2.dll+0x1234`.
|
||||
- **Panics** are logged with a backtrace.
|
||||
|
||||
The newest five dumps of each kind are kept. To read one, open it in WinDbg with the
|
||||
symbols of the exact build that wrote it: `scripts/build.ps1` keeps each release's
|
||||
`kaleido.exe` and `kaleido.pdb` in `.tools/symbols/<version>/` (release builds keep
|
||||
function names and line tables in the `.pdb`; the installer doesn't change). In WinDbg:
|
||||
`.sympath+ <that folder>`, `.reload`, then `~*k` for every thread's stack.
|
||||
|
||||
Development builds have two test commands: `debug_freeze_ui` (`{ seconds }`, holds the
|
||||
UI thread) and `debug_crash` (an access violation); both refuse to run in release builds.
|
||||
|
||||
Threading rule learned the hard way: Tauri's window getters (`hwnd()`, sizes…) called
|
||||
off the UI thread wait for it to answer, so never call one while holding a lock the UI
|
||||
thread might wait on, and keep window-event handlers from waiting on the player's locks
|
||||
(they run on the UI thread; `lib.rs` hands resize handling to a background thread).
|
||||
|
||||
## App icon
|
||||
|
||||
`src-tauri/icons/app-icon.svg` is the source. Render it to a 1024×1024 `app-icon.png`
|
||||
|
|
|
|||
12
mini.html
12
mini.html
|
|
@ -1,12 +0,0 @@
|
|||
<!doctype html>
|
||||
<html lang="en" class="mini-window">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Kaleido</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/mini/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "kaleido-desktop",
|
||||
"version": "1.0.1",
|
||||
"version": "0.1.0-beta.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "kaleido-desktop",
|
||||
"version": "1.0.1",
|
||||
"version": "0.1.0-beta.9",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@tanstack/react-query": "^5.105.0",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "kaleido-desktop",
|
||||
"private": true,
|
||||
"version": "1.0.1",
|
||||
"version": "0.1.0-beta.9",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
|
|
|||
|
|
@ -21,25 +21,10 @@ if (-not $env:TAURI_SIGNING_PRIVATE_KEY) {
|
|||
}
|
||||
|
||||
if (-not (Test-Path (Join-Path $root "node_modules"))) { npm ci }
|
||||
|
||||
# Symbols for reading hang and crash dumps (diagnostics.rs): keep function names
|
||||
# and line tables in kaleido.pdb. They stay out of the executable.
|
||||
$env:CARGO_PROFILE_RELEASE_STRIP = "none"
|
||||
$env:CARGO_PROFILE_RELEASE_DEBUG = "line-tables-only"
|
||||
$buildArgs = @("tauri", "build")
|
||||
if ($Debug) { $buildArgs += "--debug" }
|
||||
npx @buildArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "Build failed" }
|
||||
|
||||
$profile = if ($Debug) { "debug" } else { "release" }
|
||||
|
||||
# Keep this version's executable and symbols: a dump can only be read with the
|
||||
# exact build that wrote it (.tools/ is ignored).
|
||||
if (-not $Debug) {
|
||||
$version = (Get-Content (Join-Path $root "src-tauri\tauri.conf.json") -Raw | ConvertFrom-Json).version
|
||||
$symbols = Join-Path $root ".tools\symbols\$version"
|
||||
New-Item -ItemType Directory -Force $symbols | Out-Null
|
||||
Copy-Item (Join-Path $root "src-tauri\target\release\kaleido.exe"), (Join-Path $root "src-tauri\target\release\kaleido.pdb") $symbols -Force
|
||||
Write-Host "Symbols kept in $symbols"
|
||||
}
|
||||
Get-ChildItem (Join-Path $root "src-tauri\target\$profile\bundle\nsis") | Select-Object Name, Length
|
||||
|
|
|
|||
2
src-tauri/Cargo.lock
generated
2
src-tauri/Cargo.lock
generated
|
|
@ -2173,7 +2173,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "kaleido"
|
||||
version = "1.0.1"
|
||||
version = "0.1.0-beta.9"
|
||||
dependencies = [
|
||||
"fs2",
|
||||
"futures-util",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "kaleido"
|
||||
version = "1.0.1"
|
||||
version = "0.1.0-beta.9"
|
||||
description = "Kaleido — a Plex client for Windows"
|
||||
authors = ["Elijah"]
|
||||
edition = "2021"
|
||||
|
|
@ -62,13 +62,6 @@ windows = { version = "0.61", features = [
|
|||
"Win32_Graphics_Direct3D",
|
||||
"Win32_Graphics_Direct3D11",
|
||||
"Foundation_Numerics",
|
||||
# Hang and crash dumps (diagnostics.rs).
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
"Win32_System_Kernel",
|
||||
"Win32_System_Memory",
|
||||
"Win32_System_Threading",
|
||||
# The miniplayer window's rounded corners (mini.rs).
|
||||
"Win32_Graphics_Dwm",
|
||||
] }
|
||||
|
||||
[profile.release]
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Kaleido main window and miniplayer window",
|
||||
"description": "Kaleido main window",
|
||||
"windows": [
|
||||
"main",
|
||||
"mini"
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
|
|
|
|||
|
|
@ -1,158 +0,0 @@
|
|||
//! Diagnostics that stay on this computer, in the app's log folder
|
||||
//! (`%LOCALAPPDATA%\tv.kaleido.desktop\logs` on Windows):
|
||||
//!
|
||||
//! - A watchdog: if the UI thread stops answering for `HANG_AFTER`, it writes
|
||||
//! a dump of every thread's stack (`kaleido-hang-*.dmp`), once per stall.
|
||||
//! - Crashes write a dump of the crashing thread and the rest
|
||||
//! (`kaleido-crash-*.dmp`; Windows only), and panics are logged.
|
||||
//! - `diagnostics.log` notes each of these with the time.
|
||||
//!
|
||||
//! Nothing is uploaded. Dumps need the release's `kaleido.pdb` to read; the
|
||||
//! build script keeps one per version (docs/development.md → Diagnostics).
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use tauri::{AppHandle, Manager, Runtime};
|
||||
|
||||
/// How long the UI thread may go without answering before a hang dump.
|
||||
const HANG_AFTER: Duration = Duration::from_secs(5);
|
||||
/// Dumps kept of each kind; older ones are removed.
|
||||
const KEEP_DUMPS: usize = 5;
|
||||
|
||||
static DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||
static ORIGIN: OnceLock<Instant> = OnceLock::new();
|
||||
/// When the UI thread last answered, in ms since `ORIGIN`.
|
||||
static BEAT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
ORIGIN.get_or_init(Instant::now).elapsed().as_millis() as u64
|
||||
}
|
||||
|
||||
/// The folder for logs and dumps, once `start` has run.
|
||||
pub fn dir() -> Option<&'static Path> {
|
||||
DIR.get().map(PathBuf::as_path)
|
||||
}
|
||||
|
||||
/// UTC date and time, e.g. `2026-11-04 16:43:07` (file names use `-` for `:`).
|
||||
fn timestamp() -> String {
|
||||
let secs = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let (days, rem) = (secs / 86_400, secs % 86_400);
|
||||
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
|
||||
let z = days as i64 + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z - era * 146_097;
|
||||
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
format!("{year:04}-{month:02}-{day:02} {:02}:{:02}:{:02}", rem / 3600, rem / 60 % 60, rem % 60)
|
||||
}
|
||||
|
||||
/// Appends a line to `diagnostics.log`.
|
||||
pub fn log(line: &str) {
|
||||
let Some(dir) = dir() else { return };
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("diagnostics.log")) {
|
||||
let _ = writeln!(f, "{} UTC {line}", timestamp());
|
||||
}
|
||||
}
|
||||
|
||||
/// A new dump's path, after removing the oldest of its kind beyond `KEEP_DUMPS`.
|
||||
pub fn dump_path(kind: &str) -> Option<PathBuf> {
|
||||
let dir = dir()?;
|
||||
let prefix = format!("kaleido-{kind}-");
|
||||
if let Ok(entries) = std::fs::read_dir(dir) {
|
||||
let mut old: Vec<PathBuf> = entries
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&prefix) && n.ends_with(".dmp")))
|
||||
.collect();
|
||||
old.sort();
|
||||
while old.len() >= KEEP_DUMPS {
|
||||
let _ = std::fs::remove_file(old.remove(0));
|
||||
}
|
||||
}
|
||||
let name = format!("{prefix}{}-v{}.dmp", timestamp().replace([' ', ':'], "-"), env!("CARGO_PKG_VERSION"));
|
||||
Some(dir.join(name))
|
||||
}
|
||||
|
||||
/// Sets up the log folder, crash and panic reporting, and the hang watchdog.
|
||||
pub fn start<R: Runtime>(app: &AppHandle<R>) {
|
||||
let Ok(dir) = app.path().app_log_dir() else { return };
|
||||
if std::fs::create_dir_all(&dir).is_err() || DIR.set(dir).is_err() {
|
||||
return;
|
||||
}
|
||||
crate::platform::install_crash_handler();
|
||||
|
||||
let previous = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
let thread = std::thread::current();
|
||||
log(&format!(
|
||||
"panic on thread {}: {info}\n{}",
|
||||
thread.name().unwrap_or("unnamed"),
|
||||
std::backtrace::Backtrace::force_capture()
|
||||
));
|
||||
previous(info);
|
||||
}));
|
||||
|
||||
let app = app.clone();
|
||||
let _ = std::thread::Builder::new().name("ui-watchdog".into()).spawn(move || watchdog(app));
|
||||
}
|
||||
|
||||
/// Development builds only: holds the UI thread for `seconds`, to test the watchdog.
|
||||
#[tauri::command]
|
||||
pub fn debug_freeze_ui<R: Runtime>(app: AppHandle<R>, seconds: u64) -> Result<(), String> {
|
||||
if !cfg!(debug_assertions) {
|
||||
return Err("Only available in development builds.".into());
|
||||
}
|
||||
app.run_on_main_thread(move || std::thread::sleep(Duration::from_secs(seconds.min(30)))).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Development builds only: crashes with an access violation, to test crash dumps.
|
||||
#[tauri::command]
|
||||
pub fn debug_crash() -> Result<(), String> {
|
||||
if !cfg!(debug_assertions) {
|
||||
return Err("Only available in development builds.".into());
|
||||
}
|
||||
let _ = std::thread::Builder::new().name("debug-crash".into()).spawn(|| unsafe {
|
||||
std::ptr::null_mut::<u8>().write_volatile(1);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Asks the UI thread to note the time every second; if it hasn't for
|
||||
/// `HANG_AFTER`, the UI thread is stuck: dump every thread's stack.
|
||||
fn watchdog<R: Runtime>(app: AppHandle<R>) {
|
||||
BEAT.store(now_ms(), Ordering::Relaxed);
|
||||
let mut last_tick = now_ms();
|
||||
let mut stalled_since: Option<u64> = None;
|
||||
loop {
|
||||
let _ = app.run_on_main_thread(|| BEAT.store(now_ms(), Ordering::Relaxed));
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
let now = now_ms();
|
||||
// This thread was itself held up (the computer slept): not a hang.
|
||||
if now - last_tick > 3_000 {
|
||||
BEAT.store(now, Ordering::Relaxed);
|
||||
}
|
||||
last_tick = now;
|
||||
let silent = now.saturating_sub(BEAT.load(Ordering::Relaxed));
|
||||
if silent >= HANG_AFTER.as_millis() as u64 {
|
||||
if stalled_since.is_none() {
|
||||
stalled_since = Some(now - silent);
|
||||
let written = dump_path("hang").map(|p| (crate::platform::write_dump(&p), p));
|
||||
match written {
|
||||
Some((Ok(()), path)) => log(&format!("UI thread stopped answering for {}s; wrote {}", silent / 1000, path.display())),
|
||||
Some((Err(e), _)) => log(&format!("UI thread stopped answering for {}s; no dump: {e}", silent / 1000)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
} else if let Some(since) = stalled_since.take() {
|
||||
log(&format!("UI thread answering again after {:.1}s", (now - since) as f64 / 1000.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,9 +5,8 @@
|
|||
//! server-relative source path; resuming after a restart asks the interface for
|
||||
//! a freshly signed URL.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
|
|
@ -48,19 +47,10 @@ 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<bool>,
|
||||
/// Closes once the task has exited and let go of the file.
|
||||
done: watch::Receiver<()>,
|
||||
}
|
||||
|
||||
pub struct Downloads {
|
||||
items: Mutex<Vec<Item>>,
|
||||
dir: Mutex<Option<PathBuf>>,
|
||||
workers: Mutex<HashMap<String, Worker>>,
|
||||
generation: AtomicU64,
|
||||
cancels: Mutex<HashMap<String, watch::Sender<bool>>>,
|
||||
permits: Arc<Semaphore>,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
|
@ -70,8 +60,7 @@ impl Default for Downloads {
|
|||
Downloads {
|
||||
items: Mutex::new(Vec::new()),
|
||||
dir: Mutex::new(None),
|
||||
workers: Mutex::new(HashMap::new()),
|
||||
generation: AtomicU64::new(0),
|
||||
cancels: Mutex::new(HashMap::new()),
|
||||
permits: Arc::new(Semaphore::new(MAX_ACTIVE)),
|
||||
client: reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(20))
|
||||
|
|
@ -179,11 +168,8 @@ pub async fn download_start<R: Runtime>(app: AppHandle<R>, 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!(".{stem}.{}.jpg", sanitize(name)));
|
||||
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()));
|
||||
}
|
||||
|
|
@ -218,48 +204,21 @@ 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<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||
let state = app.state::<Downloads>();
|
||||
let generation = state.generation.fetch_add(1, Ordering::Relaxed);
|
||||
let (tx, rx) = watch::channel(false);
|
||||
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
|
||||
});
|
||||
app.state::<Downloads>().cancels.lock().insert(id.clone(), tx);
|
||||
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::<Downloads>().permits.clone();
|
||||
let _permit = tokio::select! {
|
||||
p = permits.acquire_owned() => p,
|
||||
_ = cancelled(rx.clone()) => { release(&app, &id, generation); return; }
|
||||
_ = cancelled(rx.clone()) => return,
|
||||
};
|
||||
// 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;
|
||||
}
|
||||
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.error = None;
|
||||
i.speed = 0;
|
||||
i.received = i.total.max(i.received);
|
||||
});
|
||||
|
|
@ -277,30 +236,6 @@ fn spawn<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
|||
});
|
||||
}
|
||||
|
||||
/// Drops the worker entry, unless a newer task has taken it over.
|
||||
fn release<R: Runtime>(app: &AppHandle<R>, id: &str, generation: u64) {
|
||||
let state = app.state::<Downloads>();
|
||||
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<R: Runtime>(app: &AppHandle<R>, id: &str) -> bool {
|
||||
let Some(path) = app.state::<Downloads>().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<bool>) {
|
||||
while !*rx.borrow() {
|
||||
if rx.changed().await.is_err() {
|
||||
|
|
@ -313,7 +248,10 @@ async fn cancelled(mut rx: watch::Receiver<bool>) {
|
|||
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 = part_path(&final_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();
|
||||
|
|
@ -321,10 +259,7 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
|
|||
if existing > 0 {
|
||||
request = request.header("Range", format!("bytes={existing}-"));
|
||||
}
|
||||
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 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());
|
||||
|
|
@ -401,14 +336,10 @@ async fn transfer<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str, rx: watch
|
|||
Ok(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<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<watch::Receiver<()>> {
|
||||
let state = app.state::<Downloads>();
|
||||
let workers = state.workers.lock();
|
||||
let worker = workers.get(id)?;
|
||||
let _ = worker.cancel.send(true);
|
||||
Some(worker.done.clone())
|
||||
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]
|
||||
|
|
@ -425,7 +356,7 @@ pub fn download_pause<R: Runtime>(app: AppHandle<R>, id: String) {
|
|||
|
||||
#[tauri::command]
|
||||
pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
||||
// `spawn` takes over from a transfer still winding down.
|
||||
cancel(&app, &id);
|
||||
update(&app, &id, |i| {
|
||||
i.status = Status::Queued;
|
||||
i.error = None;
|
||||
|
|
@ -435,7 +366,7 @@ pub fn download_resume<R: Runtime>(app: AppHandle<R>, id: String, url: String) {
|
|||
|
||||
#[tauri::command]
|
||||
pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_files: bool) -> Result<(), String> {
|
||||
let running = cancel(&app, &id);
|
||||
cancel(&app, &id);
|
||||
let removed = {
|
||||
let state = app.state::<Downloads>();
|
||||
let mut items = state.items.lock();
|
||||
|
|
@ -444,24 +375,14 @@ pub async fn download_remove<R: Runtime>(app: AppHandle<R>, id: String, delete_f
|
|||
};
|
||||
if let (Some(item), true) = (removed, delete_files) {
|
||||
let path = PathBuf::from(&item.file_path);
|
||||
// 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;
|
||||
}
|
||||
// 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 _ = 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<String> = app
|
||||
.state::<Downloads>()
|
||||
.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();
|
||||
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().filter(|p| !in_use.contains(*p)) {
|
||||
if let Some(p) = v.as_str() {
|
||||
let _ = tokio::fs::remove_file(p).await;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,4 @@
|
|||
mod diagnostics;
|
||||
mod downloads;
|
||||
mod mini;
|
||||
mod mpv;
|
||||
mod platform;
|
||||
mod player;
|
||||
|
|
@ -17,8 +15,6 @@ pub fn run() {
|
|||
.plugin(tauri_plugin_process::init())
|
||||
.plugin(
|
||||
tauri_plugin_window_state::Builder::default()
|
||||
// The miniplayer window is always placed from the main window (mini.rs).
|
||||
.with_denylist(&["mini"])
|
||||
.with_state_flags(
|
||||
tauri_plugin_window_state::StateFlags::SIZE
|
||||
| tauri_plugin_window_state::StateFlags::POSITION
|
||||
|
|
@ -27,24 +23,15 @@ pub fn run() {
|
|||
.build(),
|
||||
)
|
||||
.manage(player::PlayerState::default())
|
||||
.manage(mini::MiniState::default())
|
||||
.manage(downloads::Downloads::default())
|
||||
.setup(|app| {
|
||||
let handle = app.handle().clone();
|
||||
diagnostics::start(&handle);
|
||||
downloads::restore(&handle);
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let w = window.clone();
|
||||
window.on_window_event(move |event| {
|
||||
// On the UI thread: places the miniplayer window without waiting on anything.
|
||||
if let WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||
mini::follow_main(&w);
|
||||
}
|
||||
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||
// Never on the UI thread: the player's locks may be held by a
|
||||
// command that is itself waiting on the UI thread (see player.rs).
|
||||
let w = w.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || player::on_resize(&w));
|
||||
player::on_resize(&w);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -73,13 +60,6 @@ pub fn run() {
|
|||
downloads::download_list,
|
||||
downloads::download_set_dir,
|
||||
downloads::download_write_meta,
|
||||
mini::mini_show,
|
||||
mini::mini_hide,
|
||||
mini::mini_drag_start,
|
||||
mini::mini_drag,
|
||||
mini::mini_snap,
|
||||
diagnostics::debug_freeze_ui,
|
||||
diagnostics::debug_crash,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running Kaleido");
|
||||
|
|
|
|||
|
|
@ -1,334 +0,0 @@
|
|||
//! The miniplayer as a window of its own (where `platform::SEPARATE_MINI`):
|
||||
//! a small borderless window owned by the main one, which the video moves
|
||||
//! into. Dragging moves the whole window, so video and controls move as one;
|
||||
//! letting go glides it to a corner of the main window. Its page is
|
||||
//! `mini.html` (src/mini/), which mirrors the player's state from the main
|
||||
//! window and sends its buttons back (src/player/miniWindow.ts).
|
||||
//!
|
||||
//! Positions are physical screen pixels. Never hold `MiniState`'s locks while
|
||||
//! calling a window getter: off the UI thread those wait for it (player.rs).
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewUrl, WebviewWindow, WebviewWindowBuilder, WindowEvent};
|
||||
|
||||
const LABEL: &str = "mini";
|
||||
/// Logical pixels, as in the page's former in-window miniplayer (player.css).
|
||||
const MARGIN: f64 = 24.0;
|
||||
/// Top corners sit below the main window's navigation bar (64px).
|
||||
const TOP_INSET: f64 = 64.0 + 12.0;
|
||||
const SNAP: Duration = Duration::from_millis(260);
|
||||
/// How far a flick carries the box when choosing a corner (ms of travel).
|
||||
const FLICK_MS: f64 = 220.0;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Corner {
|
||||
TopLeft,
|
||||
TopRight,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
}
|
||||
|
||||
impl Corner {
|
||||
fn parse(s: &str) -> Corner {
|
||||
match s {
|
||||
"tl" => Corner::TopLeft,
|
||||
"tr" => Corner::TopRight,
|
||||
"bl" => Corner::BottomLeft,
|
||||
_ => Corner::BottomRight,
|
||||
}
|
||||
}
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Corner::TopLeft => "tl",
|
||||
Corner::TopRight => "tr",
|
||||
Corner::BottomLeft => "bl",
|
||||
Corner::BottomRight => "br",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The main window's client area on screen and the miniplayer's size there.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Bounds {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
mini_w: i32,
|
||||
mini_h: i32,
|
||||
scale: f64,
|
||||
}
|
||||
|
||||
impl Bounds {
|
||||
fn of<R: Runtime>(main: &WebviewWindow<R>) -> Option<Bounds> {
|
||||
let pos = main.inner_position().ok()?;
|
||||
let size = main.inner_size().ok()?;
|
||||
let scale = main.scale_factor().ok()?;
|
||||
// As the page sized it: 26% of the window's width, 300 to 440 logical pixels, 16:9.
|
||||
let w = (size.width as f64 / scale * 0.26).clamp(300.0, 440.0);
|
||||
Some(Bounds {
|
||||
left: pos.x,
|
||||
top: pos.y,
|
||||
width: size.width as i32,
|
||||
height: size.height as i32,
|
||||
mini_w: (w * scale).round() as i32,
|
||||
mini_h: (w * 9.0 / 16.0 * scale).round() as i32,
|
||||
scale,
|
||||
})
|
||||
}
|
||||
|
||||
fn corner(&self, corner: Corner) -> (i32, i32) {
|
||||
let margin = (MARGIN * self.scale).round() as i32;
|
||||
let x = match corner {
|
||||
Corner::TopLeft | Corner::BottomLeft => self.left + margin,
|
||||
_ => self.left + self.width - self.mini_w - margin,
|
||||
};
|
||||
let y = match corner {
|
||||
Corner::TopLeft | Corner::TopRight => self.top + (TOP_INSET * self.scale).round() as i32,
|
||||
_ => self.top + self.height - self.mini_h - margin,
|
||||
};
|
||||
(x, y)
|
||||
}
|
||||
|
||||
/// Keeps the box inside the main window while it's dragged.
|
||||
fn clamp(&self, x: i32, y: i32) -> (i32, i32) {
|
||||
let x = x.clamp(self.left, (self.left + self.width - self.mini_w).max(self.left));
|
||||
let y = y.clamp(self.top, (self.top + self.height - self.mini_h).max(self.top));
|
||||
(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Drag {
|
||||
/// Where the window's visible area was when the drag began.
|
||||
start: (i32, i32),
|
||||
bounds: Bounds,
|
||||
}
|
||||
|
||||
pub struct MiniState {
|
||||
corner: Mutex<Corner>,
|
||||
/// From the window's outer position to its visible area: Windows keeps an
|
||||
/// invisible resize border around shadowed windows. Positions here are of
|
||||
/// the visible area; `place` converts.
|
||||
frame: Mutex<(i32, i32)>,
|
||||
drag: Mutex<Option<Drag>>,
|
||||
visible: AtomicBool,
|
||||
/// Dragged or gliding: the main window's moves don't re-place it meanwhile.
|
||||
busy: AtomicBool,
|
||||
/// Bumped to stop a glide that's under way.
|
||||
glide: AtomicU64,
|
||||
}
|
||||
|
||||
impl Default for MiniState {
|
||||
fn default() -> Self {
|
||||
MiniState { corner: Mutex::new(Corner::BottomRight), frame: Mutex::new((0, 0)), drag: Mutex::new(None), visible: AtomicBool::new(false), busy: AtomicBool::new(false), glide: AtomicU64::new(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the window so its visible area's top left is at `(x, y)`.
|
||||
fn place<R: Runtime>(app: &AppHandle<R>, mini: &WebviewWindow<R>, (x, y): (i32, i32)) {
|
||||
let (fx, fy) = *app.state::<MiniState>().frame.lock();
|
||||
let _ = mini.set_position(PhysicalPosition::new(x - fx, y - fy));
|
||||
}
|
||||
|
||||
/// Where the visible area is now (outer position plus the frame).
|
||||
fn visible_position<R: Runtime>(app: &AppHandle<R>, mini: &WebviewWindow<R>) -> Result<(i32, i32), String> {
|
||||
let pos = mini.outer_position().map_err(|e| e.to_string())?;
|
||||
let (fx, fy) = *app.state::<MiniState>().frame.lock();
|
||||
Ok((pos.x + fx, pos.y + fy))
|
||||
}
|
||||
|
||||
fn main_window<R: Runtime>(app: &AppHandle<R>) -> Result<WebviewWindow<R>, String> {
|
||||
app.get_webview_window("main").ok_or_else(|| "The main window is gone.".to_string())
|
||||
}
|
||||
|
||||
/// The miniplayer window, created hidden the first time (its page is small).
|
||||
fn window<R: Runtime>(app: &AppHandle<R>) -> Result<WebviewWindow<R>, String> {
|
||||
if let Some(w) = app.get_webview_window(LABEL) {
|
||||
return Ok(w);
|
||||
}
|
||||
let main = main_window(app)?;
|
||||
let w = WebviewWindowBuilder::new(app, LABEL, WebviewUrl::App("mini.html".into()))
|
||||
.title("Kaleido")
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.shadow(true)
|
||||
.resizable(false)
|
||||
.skip_taskbar(true)
|
||||
.focused(false)
|
||||
.visible(false)
|
||||
.inner_size(440.0, 247.5)
|
||||
// Owned by the main window: kept just above it, hidden when it's minimized.
|
||||
.parent(&main)
|
||||
.map_err(|e| e.to_string())?
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if let Some(hwnd) = crate::platform::host_handle(&w) {
|
||||
crate::platform::style_mini_window(hwnd);
|
||||
}
|
||||
// mpv draws at the window's size; resizing happens off the UI thread (player.rs).
|
||||
let handle = app.clone();
|
||||
w.on_window_event(move |event| {
|
||||
if let WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } = event {
|
||||
let handle = handle.clone();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
if let Some(main) = handle.get_webview_window("main") {
|
||||
crate::player::on_resize(&main);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(w)
|
||||
}
|
||||
|
||||
/// Creates the window ahead of its first use, so going to the miniplayer is instant.
|
||||
pub fn prepare<R: Runtime>(app: &AppHandle<R>) {
|
||||
if crate::platform::SEPARATE_MINI {
|
||||
let _ = window(app);
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported() -> Result<(), String> {
|
||||
Err("The miniplayer window isn't used on this platform.".into())
|
||||
}
|
||||
|
||||
/// Moves the video into the miniplayer window and shows it in `corner`.
|
||||
#[tauri::command]
|
||||
pub async fn mini_show<R: Runtime>(app: AppHandle<R>, corner: String) -> Result<(), String> {
|
||||
if !crate::platform::SEPARATE_MINI {
|
||||
return unsupported();
|
||||
}
|
||||
let state = app.state::<MiniState>();
|
||||
let corner = Corner::parse(&corner);
|
||||
*state.corner.lock() = corner;
|
||||
state.glide.fetch_add(1, Ordering::SeqCst);
|
||||
state.busy.store(false, Ordering::SeqCst);
|
||||
let mini = window(&app)?;
|
||||
let bounds = Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?;
|
||||
let _ = mini.set_size(PhysicalSize::new(bounds.mini_w as u32, bounds.mini_h as u32));
|
||||
if let (Ok(outer), Ok(inner)) = (mini.outer_position(), mini.inner_position()) {
|
||||
*state.frame.lock() = (inner.x - outer.x, inner.y - outer.y);
|
||||
}
|
||||
place(&app, &mini, bounds.corner(corner));
|
||||
let hwnd = crate::platform::host_handle(&mini).ok_or("The miniplayer window has no handle.")?;
|
||||
crate::player::set_video_host(&app, Some(hwnd))?;
|
||||
crate::platform::show_inactive(hwnd);
|
||||
state.visible.store(true, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves the video back to the main window and hides the miniplayer window.
|
||||
#[tauri::command]
|
||||
pub async fn mini_hide<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {
|
||||
if !crate::platform::SEPARATE_MINI {
|
||||
return unsupported();
|
||||
}
|
||||
let state = app.state::<MiniState>();
|
||||
state.visible.store(false, Ordering::SeqCst);
|
||||
state.glide.fetch_add(1, Ordering::SeqCst);
|
||||
*state.drag.lock() = None;
|
||||
crate::player::set_video_host(&app, None)?;
|
||||
if let Some(mini) = app.get_webview_window(LABEL) {
|
||||
// Shown natively (without activation), so hidden natively too.
|
||||
if let Some(hwnd) = crate::platform::host_handle(&mini) {
|
||||
crate::platform::hide_window(hwnd);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mini_drag_start<R: Runtime>(app: AppHandle<R>) -> Result<(), String> {
|
||||
let state = app.state::<MiniState>();
|
||||
state.busy.store(true, Ordering::SeqCst);
|
||||
state.glide.fetch_add(1, Ordering::SeqCst);
|
||||
let mini = window(&app)?;
|
||||
let bounds = Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?;
|
||||
let start = visible_position(&app, &mini)?;
|
||||
*state.drag.lock() = Some(Drag { start, bounds });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Follows the pointer: `dx`/`dy` are logical pixels moved since the drag began.
|
||||
#[tauri::command]
|
||||
pub async fn mini_drag<R: Runtime>(app: AppHandle<R>, dx: f64, dy: f64) -> Result<(), String> {
|
||||
let Some(drag) = *app.state::<MiniState>().drag.lock() else { return Ok(()) };
|
||||
let b = drag.bounds;
|
||||
let to = b.clamp(drag.start.0 + (dx * b.scale).round() as i32, drag.start.1 + (dy * b.scale).round() as i32);
|
||||
if let Some(mini) = app.get_webview_window(LABEL) {
|
||||
place(&app, &mini, to);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ends a drag: glides to the corner nearest where the box is heading (a flick,
|
||||
/// `vx`/`vy` in logical pixels per millisecond, carries it on) and returns it.
|
||||
#[tauri::command]
|
||||
pub async fn mini_snap<R: Runtime>(app: AppHandle<R>, vx: f64, vy: f64) -> Result<String, String> {
|
||||
let state = app.state::<MiniState>();
|
||||
let drag = state.drag.lock().take();
|
||||
let mini = window(&app)?;
|
||||
let b = match drag {
|
||||
Some(d) => d.bounds,
|
||||
None => Bounds::of(&main_window(&app)?).ok_or("The main window has no size.")?,
|
||||
};
|
||||
let from = visible_position(&app, &mini)?;
|
||||
let cx = from.0 as f64 + b.mini_w as f64 / 2.0 + vx * FLICK_MS * b.scale;
|
||||
let cy = from.1 as f64 + b.mini_h as f64 / 2.0 + vy * FLICK_MS * b.scale;
|
||||
let left = cx < b.left as f64 + b.width as f64 / 2.0;
|
||||
let top = cy < b.top as f64 + b.height as f64 / 2.0;
|
||||
let corner = match (top, left) {
|
||||
(true, true) => Corner::TopLeft,
|
||||
(true, false) => Corner::TopRight,
|
||||
(false, true) => Corner::BottomLeft,
|
||||
(false, false) => Corner::BottomRight,
|
||||
};
|
||||
*state.corner.lock() = corner;
|
||||
let to = b.corner(corner);
|
||||
let generation = state.glide.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
// Ease out over SNAP, a step per display frame; stops if another drag starts.
|
||||
let handle = app.clone();
|
||||
std::thread::spawn(move || {
|
||||
let state = handle.state::<MiniState>();
|
||||
let steps = (SNAP.as_millis() / 8) as i32;
|
||||
let start = std::time::Instant::now();
|
||||
for i in 1..=steps {
|
||||
if state.glide.load(Ordering::SeqCst) != generation {
|
||||
return;
|
||||
}
|
||||
let t = (start.elapsed().as_secs_f64() / SNAP.as_secs_f64()).min(1.0);
|
||||
let e = 1.0 - (1.0 - t).powi(3);
|
||||
let x = from.0 + ((to.0 - from.0) as f64 * e).round() as i32;
|
||||
let y = from.1 + ((to.1 - from.1) as f64 * e).round() as i32;
|
||||
place(&handle, &mini, (x, y));
|
||||
if t >= 1.0 || i == steps {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(8));
|
||||
}
|
||||
place(&handle, &mini, to);
|
||||
if state.glide.load(Ordering::SeqCst) == generation {
|
||||
state.busy.store(false, Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
Ok(corner.name().into())
|
||||
}
|
||||
|
||||
/// Keeps the miniplayer in its corner as the main window moves or resizes.
|
||||
/// Runs on the UI thread (window events), where window getters answer directly.
|
||||
pub fn follow_main<R: Runtime>(main: &WebviewWindow<R>) {
|
||||
let app = main.app_handle();
|
||||
let Some(state) = app.try_state::<MiniState>() else { return };
|
||||
if !state.visible.load(Ordering::SeqCst) || state.busy.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
let Some(mini) = app.get_webview_window(LABEL) else { return };
|
||||
let Some(bounds) = Bounds::of(main) else { return };
|
||||
let corner = *state.corner.lock();
|
||||
let _ = mini.set_size(PhysicalSize::new(bounds.mini_w as u32, bounds.mini_h as u32));
|
||||
place(&app, &mini, bounds.corner(corner));
|
||||
}
|
||||
|
|
@ -27,11 +27,6 @@ impl VideoSurface {
|
|||
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: bool) {}
|
||||
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>) {}
|
||||
pub fn set_rect<R: Runtime>(&mut self, _: &WebviewWindow<R>, _: Option<&Mpv>, _: Option<(i32, i32, i32, i32)>) {}
|
||||
|
||||
/// The video stays in the main window here (`SEPARATE_MINI` is false).
|
||||
pub fn set_host(&mut self, _: Option<isize>, _: Option<&Mpv>) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Not needed yet: the only GPU-specific tier (RTX Video) is Windows-only.
|
||||
|
|
@ -53,28 +48,3 @@ pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
|||
// TODO(Linux): org.freedesktop.ScreenSaver.Inhibit over D-Bus.
|
||||
let _ = rx.recv();
|
||||
}
|
||||
|
||||
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
|
||||
|
||||
/// Hang dumps are Windows-only for now; the watchdog still logs the stall.
|
||||
pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
|
||||
Err("dumps are not written on this platform".into())
|
||||
}
|
||||
|
||||
/// Crashes are left to the system's crash reporter here.
|
||||
pub fn install_crash_handler() {}
|
||||
|
||||
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
|
||||
|
||||
/// The miniplayer stays inside the main window's page here (PlayerOverlay).
|
||||
pub const SEPARATE_MINI: bool = false;
|
||||
|
||||
pub fn host_handle<R: Runtime>(_: &WebviewWindow<R>) -> Option<isize> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn style_mini_window(_: isize) {}
|
||||
|
||||
pub fn show_inactive(_: isize) {}
|
||||
|
||||
pub fn hide_window(_: isize) {}
|
||||
|
|
|
|||
|
|
@ -451,11 +451,6 @@ impl VideoSurface {
|
|||
self.rect = rect;
|
||||
self.fit(window, mpv);
|
||||
}
|
||||
|
||||
/// The video stays in the main window here (`SEPARATE_MINI` is false).
|
||||
pub fn set_host(&mut self, _: Option<isize>, _: Option<&Mpv>) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// mpv properties the surface needs to observe.
|
||||
|
|
@ -541,28 +536,3 @@ pub fn hold_awake(rx: Receiver<()>) {
|
|||
CFRelease(name);
|
||||
}
|
||||
}
|
||||
|
||||
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
|
||||
|
||||
/// Hang dumps are Windows-only for now; the watchdog still logs the stall.
|
||||
pub fn write_dump(_: &std::path::Path) -> Result<(), String> {
|
||||
Err("dumps are not written on this platform".into())
|
||||
}
|
||||
|
||||
/// Crashes are left to the system's crash reporter here.
|
||||
pub fn install_crash_handler() {}
|
||||
|
||||
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
|
||||
|
||||
/// The miniplayer stays inside the main window's page here (PlayerOverlay).
|
||||
pub const SEPARATE_MINI: bool = false;
|
||||
|
||||
pub fn host_handle<R: Runtime>(_: &WebviewWindow<R>) -> Option<isize> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn style_mini_window(_: isize) {}
|
||||
|
||||
pub fn show_inactive(_: isize) {}
|
||||
|
||||
pub fn hide_window(_: isize) {}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@
|
|||
//! - `gpu_names`: the graphics adapters, by name.
|
||||
//! - `device_name`, `os_version`: how the computer identifies itself to Plex.
|
||||
//! - `set_window_buttons`: shows or hides native window buttons (macOS).
|
||||
//! - `write_dump`, `install_crash_handler`: hang and crash dumps (Windows).
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
|
|
|
|||
|
|
@ -10,15 +10,9 @@ use ::windows::Win32::UI::WindowsAndMessaging::GetClientRect;
|
|||
use crate::mpv::Mpv;
|
||||
|
||||
pub struct VideoSurface {
|
||||
/// The window showing the video now: the main window, or the miniplayer's
|
||||
/// (`set_host`). Window handles are kept so fitting needn't ask the UI
|
||||
/// thread for them (Tauri's `hwnd()` waits on the UI thread elsewhere).
|
||||
hwnd: HWND,
|
||||
main: HWND,
|
||||
attached: usize,
|
||||
device: IDCompositionDevice,
|
||||
/// One composition target per window the video has been shown in.
|
||||
targets: Vec<(isize, IDCompositionTarget)>,
|
||||
_target: IDCompositionTarget,
|
||||
root: IDCompositionVisual,
|
||||
visible: bool,
|
||||
/// Where the video is drawn, in client pixels; `None` fills the window.
|
||||
|
|
@ -50,12 +44,11 @@ impl VideoSurface {
|
|||
let root = device.CreateVisual().map_err(|e| e.to_string())?;
|
||||
let (width, height) = client_size(hwnd);
|
||||
device.Commit().map_err(|e| e.to_string())?;
|
||||
let _ = ⌖
|
||||
Ok(VideoSurface {
|
||||
hwnd,
|
||||
main: hwnd,
|
||||
attached: 0,
|
||||
device,
|
||||
targets: vec![(hwnd.0 as isize, target)],
|
||||
_target: target,
|
||||
root,
|
||||
visible: false,
|
||||
rect: None,
|
||||
|
|
@ -106,60 +99,22 @@ impl VideoSurface {
|
|||
}
|
||||
}
|
||||
|
||||
fn target(&self, hwnd: HWND) -> Option<&IDCompositionTarget> {
|
||||
self.targets.iter().find(|(h, _)| *h == hwnd.0 as isize).map(|(_, t)| t)
|
||||
}
|
||||
|
||||
pub fn show<R: Runtime>(&mut self, _: &WebviewWindow<R>, visible: bool) {
|
||||
if self.visible == visible {
|
||||
return;
|
||||
}
|
||||
self.visible = visible;
|
||||
if let Some(target) = self.target(self.hwnd) {
|
||||
unsafe {
|
||||
let _ = if visible { target.SetRoot(&self.root) } else { target.SetRoot(None::<&IDCompositionVisual>) };
|
||||
let _ = self.device.Commit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the video to another window (the miniplayer's, a raw `HWND`), or
|
||||
/// back to the main window with `None`, filling its client area. Both
|
||||
/// changes go out in one commit, so the video is never shown twice.
|
||||
pub fn set_host(&mut self, host: Option<isize>, mpv: Option<&Mpv>) -> Result<(), String> {
|
||||
let next = host.map(|h| HWND(h as _)).unwrap_or(self.main);
|
||||
if next == self.hwnd {
|
||||
return Ok(());
|
||||
}
|
||||
unsafe {
|
||||
if self.target(next).is_none() {
|
||||
// Behind the window's children (its web view), as in the main window.
|
||||
let target = self.device.CreateTargetForHwnd(next, false).map_err(|e| e.to_string())?;
|
||||
self.targets.push((next.0 as isize, target));
|
||||
}
|
||||
if self.visible {
|
||||
if let Some(old) = self.target(self.hwnd) {
|
||||
let _ = old.SetRoot(None::<&IDCompositionVisual>);
|
||||
}
|
||||
if let Some(new) = self.target(next) {
|
||||
let _ = new.SetRoot(&self.root);
|
||||
}
|
||||
}
|
||||
let _ = if visible { self._target.SetRoot(&self.root) } else { self._target.SetRoot(None::<&IDCompositionVisual>) };
|
||||
let _ = self.device.Commit();
|
||||
}
|
||||
self.hwnd = next;
|
||||
self.rect = None;
|
||||
self.fit_host(mpv);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Matches mpv's composition size and the visual's position to the
|
||||
/// window's client area, or to the miniplayer rectangle when one is set.
|
||||
pub fn fit<R: Runtime>(&mut self, _: &WebviewWindow<R>, mpv: Option<&Mpv>) {
|
||||
self.fit_host(mpv);
|
||||
}
|
||||
|
||||
fn fit_host(&mut self, mpv: Option<&Mpv>) {
|
||||
let (cw, ch) = client_size(self.hwnd);
|
||||
pub fn fit<R: Runtime>(&mut self, window: &WebviewWindow<R>, mpv: Option<&Mpv>) {
|
||||
let Ok(h) = window.hwnd() else { return };
|
||||
let (cw, ch) = client_size(HWND(h.0 as _));
|
||||
let (x, y, w, h) = match self.rect {
|
||||
Some((x, y, w, h)) => (x, y, w.max(16), h.max(16)),
|
||||
None => (0, 0, cw, ch),
|
||||
|
|
@ -226,153 +181,6 @@ pub fn os_version() -> String {
|
|||
/// Windows draws its own caption buttons in the page.
|
||||
pub fn set_window_buttons<R: Runtime>(_: &WebviewWindow<R>, _: bool) {}
|
||||
|
||||
// —— Miniplayer window (see mini.rs) ——————————————————————————————————————
|
||||
|
||||
/// The miniplayer is a window of its own here: the video moves into it, so
|
||||
/// dragging moves video and controls together.
|
||||
pub const SEPARATE_MINI: bool = true;
|
||||
|
||||
/// The window's handle, for `VideoSurface::set_host`. Asks the UI thread, so
|
||||
/// never call it while holding a lock the UI thread may wait on.
|
||||
pub fn host_handle<R: Runtime>(window: &WebviewWindow<R>) -> Option<isize> {
|
||||
window.hwnd().ok().map(|h| h.0 as isize)
|
||||
}
|
||||
|
||||
/// Rounded corners (Windows 11) and no activation on click, so the main
|
||||
/// window keeps focus and its keyboard shortcuts while the miniplayer is used.
|
||||
pub fn style_mini_window(hwnd: isize) {
|
||||
use ::windows::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND};
|
||||
use ::windows::Win32::UI::WindowsAndMessaging::{GetWindowLongPtrW, SetWindowLongPtrW, GWL_EXSTYLE, WS_EX_NOACTIVATE};
|
||||
let hwnd = HWND(hwnd as _);
|
||||
unsafe {
|
||||
let preference = DWMWCP_ROUND;
|
||||
let _ = DwmSetWindowAttribute(hwnd, DWMWA_WINDOW_CORNER_PREFERENCE, &preference as *const _ as *const c_void, std::mem::size_of_val(&preference) as u32);
|
||||
let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
|
||||
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | WS_EX_NOACTIVATE.0 as isize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a window without activating it (Tauri's `show` activates).
|
||||
pub fn show_inactive(hwnd: isize) {
|
||||
use ::windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_SHOWNOACTIVATE};
|
||||
unsafe {
|
||||
let _ = ShowWindow(HWND(hwnd as _), SW_SHOWNOACTIVATE);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hides a window shown by `show_inactive`. Tauri's `hide` would skip it: it
|
||||
/// never saw the window shown, so believes it hidden already.
|
||||
pub fn hide_window(hwnd: isize) {
|
||||
use ::windows::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_HIDE};
|
||||
unsafe {
|
||||
let _ = ShowWindow(HWND(hwnd as _), SW_HIDE);
|
||||
}
|
||||
}
|
||||
|
||||
// —— Diagnostics (see diagnostics.rs) ————————————————————————————————————
|
||||
|
||||
use ::windows::Win32::System::Diagnostics::Debug::{
|
||||
MiniDumpWithHandleData, MiniDumpWithThreadInfo, MiniDumpWithUnloadedModules, MiniDumpWriteDump, SetUnhandledExceptionFilter,
|
||||
EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, MINIDUMP_EXCEPTION_INFORMATION, MINIDUMP_TYPE,
|
||||
};
|
||||
use ::windows::Win32::System::Threading::{GetCurrentProcess, GetCurrentProcessId, GetCurrentThreadId};
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
/// Every thread's stack and state, the loaded and unloaded modules and the
|
||||
/// open handles: what a hang or crash needs, in a few megabytes.
|
||||
const DUMP_TYPE: MINIDUMP_TYPE = MINIDUMP_TYPE(MiniDumpWithThreadInfo.0 | MiniDumpWithHandleData.0 | MiniDumpWithUnloadedModules.0);
|
||||
|
||||
fn write_dump_with(path: &Path, exception: Option<*const EXCEPTION_POINTERS>) -> Result<(), String> {
|
||||
let file = std::fs::File::create(path).map_err(|e| e.to_string())?;
|
||||
let info = exception.map(|pointers| MINIDUMP_EXCEPTION_INFORMATION {
|
||||
ThreadId: unsafe { GetCurrentThreadId() },
|
||||
ExceptionPointers: pointers as *mut _,
|
||||
ClientPointers: false.into(),
|
||||
});
|
||||
let file_handle = ::windows::Win32::Foundation::HANDLE(file.as_raw_handle());
|
||||
unsafe {
|
||||
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), file_handle, DUMP_TYPE, info.as_ref().map(|i| i as *const _), None, None)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Dumps this process as it is now (the hang watchdog's snapshot).
|
||||
pub fn write_dump(path: &Path) -> Result<(), String> {
|
||||
write_dump_with(path, None)
|
||||
}
|
||||
|
||||
/// "access violation at libmpv-2.dll+0x1234 (0xC0000005)", for the log.
|
||||
unsafe fn describe(pointers: *const EXCEPTION_POINTERS) -> String {
|
||||
use ::windows::Win32::Foundation::HMODULE;
|
||||
use ::windows::Win32::System::LibraryLoader::*;
|
||||
let Some(record) = (*pointers).ExceptionRecord.as_ref() else { return "unknown exception".into() };
|
||||
let code = record.ExceptionCode.0 as u32;
|
||||
let address = record.ExceptionAddress as usize;
|
||||
let mut module = HMODULE::default();
|
||||
let place = if GetModuleHandleExW(
|
||||
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
::windows::core::PCWSTR(address as *const u16),
|
||||
&mut module,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
let mut name = [0u16; 260];
|
||||
let len = GetModuleFileNameW(Some(module), &mut name) as usize;
|
||||
let path = String::from_utf16_lossy(&name[..len]);
|
||||
let file = path.rsplit('\\').next().unwrap_or(&path).to_string();
|
||||
format!("{file}+{:#x}", address - module.0 as usize)
|
||||
} else {
|
||||
format!("{address:#x}")
|
||||
};
|
||||
let what = match code {
|
||||
0xC000_0005 => "access violation",
|
||||
0xC000_00FD => "stack overflow",
|
||||
0xC000_0409 => "fail-fast (security check)",
|
||||
0xC000_001D => "illegal instruction",
|
||||
0xC000_0094 => "integer division by zero",
|
||||
_ => "exception",
|
||||
};
|
||||
format!("{what} at {place} ({code:#010X})")
|
||||
}
|
||||
|
||||
static PREVIOUS_FILTER: AtomicUsize = AtomicUsize::new(0);
|
||||
static CRASHED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
unsafe extern "system" fn on_crash(pointers: *const EXCEPTION_POINTERS) -> i32 {
|
||||
if !CRASHED.swap(true, Ordering::SeqCst) {
|
||||
let what = describe(pointers);
|
||||
match crate::diagnostics::dump_path("crash") {
|
||||
Some(path) => match write_dump_with(&path, Some(pointers)) {
|
||||
Ok(()) => crate::diagnostics::log(&format!("crash: {what}; wrote {}", path.display())),
|
||||
Err(e) => crate::diagnostics::log(&format!("crash: {what}; no dump: {e}")),
|
||||
},
|
||||
None => crate::diagnostics::log(&format!("crash: {what}")),
|
||||
}
|
||||
}
|
||||
// Then whatever handled it before (Windows Error Reporting by default).
|
||||
match PREVIOUS_FILTER.load(Ordering::SeqCst) {
|
||||
0 => EXCEPTION_CONTINUE_SEARCH,
|
||||
previous => {
|
||||
let previous: unsafe extern "system" fn(*const EXCEPTION_POINTERS) -> i32 = std::mem::transmute(previous);
|
||||
previous(pointers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a dump when the process is about to die of an unhandled exception.
|
||||
/// Called again once libmpv is loaded, in case its runtime replaced it.
|
||||
pub fn install_crash_handler() {
|
||||
unsafe {
|
||||
if let Some(previous) = SetUnhandledExceptionFilter(Some(on_crash)) {
|
||||
if previous as usize != on_crash as *const () as usize {
|
||||
PREVIOUS_FILTER.store(previous as usize, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the display awake until `rx` closes or receives.
|
||||
pub fn hold_awake(rx: std::sync::mpsc::Receiver<()>) {
|
||||
use ::windows::Win32::System::Power::*;
|
||||
|
|
|
|||
|
|
@ -14,10 +14,6 @@ use tauri::{AppHandle, Emitter, Manager, Runtime, WebviewWindow};
|
|||
use crate::mpv::{self, Event, Mpv};
|
||||
use crate::platform::VideoSurface;
|
||||
|
||||
/// Both locks are taken by commands on background threads, and some window
|
||||
/// calls made while holding them (Tauri's getters, such as `hwnd()`) wait for
|
||||
/// the UI thread to answer. So the UI thread must never wait on these locks:
|
||||
/// window events hand their work to a background thread (lib.rs).
|
||||
#[derive(Default)]
|
||||
pub struct PlayerState {
|
||||
mpv: Mutex<Option<Arc<Mpv>>>,
|
||||
|
|
@ -64,8 +60,6 @@ fn emit<R: Runtime>(app: &AppHandle<R>, payload: Value) {
|
|||
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))?;
|
||||
// libmpv's runtime may install its own crash filter as it loads; ours goes back on top.
|
||||
crate::platform::install_crash_handler();
|
||||
let surface = VideoSurface::create(window)?;
|
||||
let render_options = surface.mpv_options();
|
||||
*app.state::<PlayerState>().surface.lock() = Some(surface);
|
||||
|
|
@ -180,29 +174,13 @@ fn player<R: Runtime>(app: &AppHandle<R>) -> Result<Arc<Mpv>, String> {
|
|||
#[tauri::command]
|
||||
pub async fn player_init<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, options: Option<InitOptions>) -> Result<(), String> {
|
||||
let state = app.state::<PlayerState>();
|
||||
{
|
||||
let mut guard = state.mpv.lock();
|
||||
if guard.is_none() {
|
||||
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
|
||||
}
|
||||
let mut guard = state.mpv.lock();
|
||||
if guard.is_none() {
|
||||
*guard = Some(create_player(&app, &window, &options.unwrap_or_default())?);
|
||||
}
|
||||
// Outside the lock: creating a window waits on the UI thread.
|
||||
crate::mini::prepare(&app);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves the video into another window (the miniplayer's, mini.rs) or back to
|
||||
/// the main one. Off the UI thread only (it takes the player's locks).
|
||||
pub fn set_video_host<R: Runtime>(app: &AppHandle<R>, host: Option<isize>) -> Result<(), String> {
|
||||
let state = app.state::<PlayerState>();
|
||||
let mpv = state.mpv.lock().clone();
|
||||
let mut surface = state.surface.lock();
|
||||
match surface.as_mut() {
|
||||
Some(surface) => surface.set_host(host, mpv.as_deref()),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn player_show<R: Runtime>(app: AppHandle<R>, window: WebviewWindow<R>, visible: bool) -> Result<(), String> {
|
||||
let state = app.state::<PlayerState>();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Kaleido",
|
||||
"version": "1.0.1",
|
||||
"version": "0.1.0-beta.9",
|
||||
"identifier": "tv.kaleido.desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
|
|
|||
|
|
@ -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, isNative, win } from '../platform/native';
|
||||
import { isMac, win } from '../platform/native';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { PlayerOverlay } from '../player/PlayerOverlay';
|
||||
import { DialogHost } from '../screens/dialogs/DialogHost';
|
||||
|
|
@ -111,9 +111,7 @@ 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;
|
||||
// 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();
|
||||
useRouter.getState().back();
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'settings', mode: 'app', tab: 'general' });
|
||||
|
|
|
|||
|
|
@ -19,21 +19,13 @@ 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;
|
||||
let gone = false;
|
||||
const sync = () => {
|
||||
win.isMaximized().then((m) => !gone && setMaximized(m));
|
||||
win.isFullscreen().then((f) => !gone && setFullscreen(f));
|
||||
};
|
||||
const sync = () => win.isMaximized().then(setMaximized);
|
||||
sync();
|
||||
win.onResized(sync).then((u) => (gone ? u() : (off = u)));
|
||||
return () => {
|
||||
gone = true;
|
||||
off?.();
|
||||
};
|
||||
win.onResized(sync).then((u) => (off = u));
|
||||
return () => off?.();
|
||||
}, []);
|
||||
if (!isNative || isMac) return null;
|
||||
return (
|
||||
|
|
@ -41,15 +33,9 @@ export function WindowControls() {
|
|||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
{fullscreen ? (
|
||||
<button aria-label="Exit full screen" title="Exit full screen (Esc)" onClick={() => win.setFullscreen(false)}>
|
||||
<Icon name="collapse" size={14} strokeWidth={1.4} />
|
||||
</button>
|
||||
) : (
|
||||
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
||||
<Icon name={maximized ? 'restore' : 'maximize'} size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
)}
|
||||
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
||||
<Icon name={maximized ? 'restore' : 'maximize'} size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -36,19 +36,10 @@ export function progress(item: Item): number {
|
|||
return Math.min(1, Math.max(0, item.viewOffset / item.duration));
|
||||
}
|
||||
|
||||
/**
|
||||
* Watched once Plex has counted a full play. A rewatch left partway through keeps the
|
||||
* title watched; its position only matters for resuming (`resumable`).
|
||||
*/
|
||||
export function isWatched(item: Item, percent = 90): boolean {
|
||||
if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount;
|
||||
if (item.viewCount > 0) return true;
|
||||
return item.viewOffset > 0 && item.duration > 0 && item.viewOffset / item.duration >= percent / 100;
|
||||
}
|
||||
|
||||
/** Has a saved position worth resuming from (not one at the very end). */
|
||||
export function resumable(item: Item): boolean {
|
||||
return item.viewOffset > 0 && item.duration > 0 && item.viewOffset < item.duration * 0.97;
|
||||
if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100;
|
||||
return item.viewCount > 0;
|
||||
}
|
||||
|
||||
export function remainingEpisodes(item: Item): number {
|
||||
|
|
@ -183,24 +174,17 @@ export function plural(n: number, word: string, pluralWord = `${word}s`) {
|
|||
return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */
|
||||
export function washGradient(u: Item['ultraBlur'], strength = 1): string {
|
||||
if (!u) return '';
|
||||
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.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%)`,
|
||||
`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%)`,
|
||||
].join(', ');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
/**
|
||||
* Arrow-key movement between titles, for keyboard users. Focus moves to the
|
||||
* nearest card in the pressed direction (by on-screen geometry), so it works
|
||||
* the same across shelves, grids and people rows.
|
||||
* the same across shelves, grids, episode lists and people rows.
|
||||
*/
|
||||
const TARGETS = '.card, .person-card:not(:disabled), .shelf-title-link';
|
||||
const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link';
|
||||
|
||||
function center(r: DOMRect) {
|
||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
|
|
|
|||
|
|
@ -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, useSession } from './session';
|
||||
import { useServer } from './session';
|
||||
import { useSettings } from './settings';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
|
|
@ -15,25 +15,6 @@ export const queryClient = new QueryClient({
|
|||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Watch state changes from other Plex apps too (a TV, a phone), so the queries that show
|
||||
* it refresh when Kaleido comes back into view and, for the progress rows, every minute
|
||||
* while it is on screen. Polling pauses while the window is hidden or minimised.
|
||||
*/
|
||||
export const WATCH_STATE = { refetchOnWindowFocus: true } as const;
|
||||
export const PROGRESS = { ...WATCH_STATE, staleTime: 15_000, refetchInterval: 60_000 } as const;
|
||||
|
||||
// React Query treats a visibility change as focus. Switching back to Kaleido from another
|
||||
// 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();
|
||||
|
|
@ -56,9 +37,9 @@ export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null
|
|||
}
|
||||
|
||||
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
|
||||
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE, ...opts });
|
||||
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts });
|
||||
|
||||
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE });
|
||||
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 });
|
||||
|
||||
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });
|
||||
|
||||
|
|
|
|||
|
|
@ -19,8 +19,6 @@ export interface Preferences {
|
|||
countdownSeconds: number;
|
||||
skipIntro: SkipMode;
|
||||
skipCredits: SkipMode;
|
||||
/** Seconds a "Skip automatically" marker waits, so it can be cancelled; 0 skips at once. */
|
||||
autoSkipDelay: number;
|
||||
watchedPercent: number;
|
||||
audioLanguage: string;
|
||||
subtitleMode: SubtitleMode;
|
||||
|
|
@ -64,7 +62,6 @@ export const defaults: Preferences = {
|
|||
countdownSeconds: 8,
|
||||
skipIntro: 'button',
|
||||
skipCredits: 'button',
|
||||
autoSkipDelay: 5,
|
||||
watchedPercent: 90,
|
||||
audioLanguage: '',
|
||||
subtitleMode: 'auto',
|
||||
|
|
|
|||
|
|
@ -52,16 +52,12 @@ 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, and
|
||||
* only the version downloaded, so its streams describe the file that plays.
|
||||
*/
|
||||
function slim(raw: any, mediaIndex: number) {
|
||||
/** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */
|
||||
function slim(raw: any) {
|
||||
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;
|
||||
}
|
||||
|
||||
|
|
@ -106,12 +102,9 @@ export const useDownloads = create<DownloadsState>((set, get) => ({
|
|||
try {
|
||||
await get().init();
|
||||
const item = await api.metadata(server, input.id);
|
||||
// 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 media = 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.');
|
||||
|
|
@ -136,7 +129,7 @@ export const useDownloads = create<DownloadsState>((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, item.media.indexOf(media)) } satisfies DownloadMeta,
|
||||
meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta,
|
||||
assets,
|
||||
},
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,153 +0,0 @@
|
|||
/**
|
||||
* The miniplayer window's page (mini.html; src-tauri/src/mini.rs). The video
|
||||
* is drawn beneath this transparent page by the native side; this page draws
|
||||
* the controls, mirrors the main window's player (src/player/miniWindow.ts)
|
||||
* and sends its buttons back. Dragging moves the whole window natively.
|
||||
*/
|
||||
import { StrictMode, useEffect, useState, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { emitTo, listen } from '@tauri-apps/api/event';
|
||||
import '@fontsource-variable/inter';
|
||||
import '../styles/base.css';
|
||||
import '../styles/ui.css';
|
||||
import '../styles/player.css';
|
||||
import './mini.css';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { MINI_CORNER_KEY, type MiniAction, type MiniState } from './types';
|
||||
|
||||
const send = (type: MiniAction) => emitTo('main', 'mini:action', { type }).catch(() => {});
|
||||
|
||||
window.addEventListener('contextmenu', (e) => e.preventDefault());
|
||||
|
||||
/**
|
||||
* Drags the window: moves go to the native side one at a time, latest first
|
||||
* (each is relative to where the drag began), and letting go glides it to a
|
||||
* corner. A drag that ends over a button doesn't press it.
|
||||
*/
|
||||
function startDrag(e: ReactPointerEvent<HTMLElement>) {
|
||||
if (e.button !== 0) return;
|
||||
const el = e.currentTarget;
|
||||
const pointer = e.pointerId;
|
||||
const origin = { x: e.screenX, y: e.screenY };
|
||||
const trail: { t: number; x: number; y: number }[] = [];
|
||||
let dragging = false;
|
||||
let started: Promise<unknown> | null = null;
|
||||
let inFlight: Promise<unknown> | null = null;
|
||||
let latest: { dx: number; dy: number } | null = null;
|
||||
|
||||
const pump = () => {
|
||||
if (inFlight || !latest || !started) return;
|
||||
const next = latest;
|
||||
latest = null;
|
||||
inFlight = started
|
||||
.then(() => invoke('mini_drag', next))
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
inFlight = null;
|
||||
pump();
|
||||
});
|
||||
};
|
||||
|
||||
const move = (ev: PointerEvent) => {
|
||||
const dx = ev.screenX - origin.x;
|
||||
const dy = ev.screenY - origin.y;
|
||||
trail.push({ t: ev.timeStamp, x: ev.screenX, y: ev.screenY });
|
||||
while (trail.length > 2 && ev.timeStamp - trail[0].t > 100) trail.shift();
|
||||
if (!dragging) {
|
||||
if (Math.hypot(dx, dy) < 4) return;
|
||||
dragging = true;
|
||||
document.documentElement.classList.add('dragging');
|
||||
el.setPointerCapture(pointer);
|
||||
started = invoke('mini_drag_start').catch(() => {});
|
||||
}
|
||||
latest = { dx, dy };
|
||||
pump();
|
||||
};
|
||||
|
||||
const up = async () => {
|
||||
window.removeEventListener('pointermove', move);
|
||||
window.removeEventListener('pointerup', up);
|
||||
window.removeEventListener('pointercancel', up);
|
||||
if (!dragging) return;
|
||||
document.documentElement.classList.remove('dragging');
|
||||
const swallow = (c: MouseEvent) => {
|
||||
c.stopPropagation();
|
||||
c.preventDefault();
|
||||
};
|
||||
window.addEventListener('click', swallow, { capture: true, once: true });
|
||||
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
|
||||
|
||||
const first = trail[0];
|
||||
const last = trail[trail.length - 1];
|
||||
const dt = first && last ? Math.max(1, last.t - first.t) : 1;
|
||||
const vx = first && last ? (last.x - first.x) / dt : 0;
|
||||
const vy = first && last ? (last.y - first.y) / dt : 0;
|
||||
// The last move lands before the glide begins.
|
||||
while (inFlight || latest) await (inFlight ?? Promise.resolve(pump()));
|
||||
const corner = await invoke<string>('mini_snap', { vx, vy }).catch(() => '');
|
||||
if (corner) localStorage.setItem(MINI_CORNER_KEY, corner);
|
||||
};
|
||||
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', up);
|
||||
window.addEventListener('pointercancel', up);
|
||||
}
|
||||
|
||||
function Mini() {
|
||||
const [s, setS] = useState<MiniState | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const unlisten = listen<MiniState>('mini:state', (e) => setS(e.payload));
|
||||
unlisten.then(() => send('ready'));
|
||||
return () => void unlisten.then((f) => f());
|
||||
}, []);
|
||||
|
||||
if (!s) return <div className="mini-player loading" />;
|
||||
const pct = s.duration ? Math.min(100, (s.position / s.duration) * 100) : 0;
|
||||
return (
|
||||
<div className={`mini-player${s.loading || s.error ? ' loading' : ''}`} onPointerDown={startDrag} onDoubleClick={() => send('expand')}>
|
||||
<div className="mini-scrim" />
|
||||
<div className="mini-top">
|
||||
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => send('expand')}>
|
||||
<Icon name="expand" size={17} />
|
||||
</button>
|
||||
<button className="mini-icon" aria-label="Stop playback" title="Close" onClick={() => send('close')}>
|
||||
<Icon name="x" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="mini-center">
|
||||
{(s.loading || s.buffering) && !s.error ? (
|
||||
<span className="spinner" style={{ width: 30, height: 30 }} aria-label="Loading" />
|
||||
) : s.error ? (
|
||||
<span className="mini-error">Playback stopped</span>
|
||||
) : (
|
||||
<>
|
||||
<button className="mini-icon" aria-label="Back 10 seconds" onClick={() => send('back')}>
|
||||
<Icon name="replay10" size={22} />
|
||||
</button>
|
||||
<button className="mini-icon big" aria-label={s.paused ? 'Play' : 'Pause'} onClick={() => send('toggle')}>
|
||||
<Icon name={s.paused || s.ended ? 'play' : 'pause'} size={26} />
|
||||
</button>
|
||||
<button className="mini-icon" aria-label="Forward 10 seconds" onClick={() => send('forward')}>
|
||||
<Icon name="forward10" size={22} />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="mini-caption">
|
||||
<b>{s.title}</b>
|
||||
{s.subtitle && <span>{s.subtitle}</span>}
|
||||
</div>
|
||||
<div className="mini-progress">
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<Mini />
|
||||
</StrictMode>,
|
||||
);
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
/* The miniplayer window (mini.html): the page is transparent over the video
|
||||
and the box fills the window, whose corners Windows rounds. */
|
||||
html.mini-window,
|
||||
html.mini-window body,
|
||||
html.mini-window #root {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
background: transparent;
|
||||
}
|
||||
html.mini-window .mini-player {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: auto;
|
||||
height: auto;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
animation: none;
|
||||
cursor: default;
|
||||
}
|
||||
html.mini-window.dragging .mini-player {
|
||||
cursor: grabbing;
|
||||
}
|
||||
/* While dragged, the title stays and the buttons step back. */
|
||||
html.mini-window.dragging .mini-scrim,
|
||||
html.mini-window.dragging .mini-caption {
|
||||
opacity: 1;
|
||||
}
|
||||
html.mini-window.dragging .mini-top,
|
||||
html.mini-window.dragging .mini-center {
|
||||
opacity: 0;
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
/** What the miniplayer window shows, sent from the main window (src/player/miniWindow.ts). */
|
||||
export interface MiniState {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
paused: boolean;
|
||||
ended: boolean;
|
||||
position: number;
|
||||
duration: number;
|
||||
loading: boolean;
|
||||
buffering: boolean;
|
||||
error: boolean;
|
||||
}
|
||||
|
||||
/** Buttons and gestures in the miniplayer window, carried out by the main window's player. */
|
||||
export type MiniAction = 'ready' | 'toggle' | 'back' | 'forward' | 'expand' | 'close';
|
||||
|
||||
export const MINI_CORNER_KEY = 'kaleido.miniCorner';
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { usePlayer } from './store';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings, QUALITY_LABEL, UPSCALING, type Quality, type SubtitleBox, type Upscaling } from '../app/settings';
|
||||
|
|
@ -10,11 +10,9 @@ import { win, isNative } from '../platform/native';
|
|||
import { WindowControls } from '../app/TopBar';
|
||||
import { navigate } from '../app/router';
|
||||
import { mpv } from './engine';
|
||||
import { separateMini } from './miniWindow';
|
||||
import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance';
|
||||
import { toast } from '../ui/overlays';
|
||||
import type { Item } from '../plex/types';
|
||||
import { PostPlay } from './PostPlay';
|
||||
|
||||
const HIDE_AFTER = 3000;
|
||||
|
||||
|
|
@ -493,103 +491,69 @@ function Volume() {
|
|||
);
|
||||
}
|
||||
|
||||
/** A seek that lands inside a marker this recently means the viewer chose to be there. */
|
||||
const SEEK_GRACE_MS = 1500;
|
||||
const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock']);
|
||||
|
||||
/**
|
||||
* Skip intro / Skip credits. With "Skip automatically" the button counts down for the
|
||||
* chosen delay, filling as it goes, then skips. Pausing, seeking or pressing a key
|
||||
* before then keeps watching: the button stays as a plain skip for the rest of the marker.
|
||||
*/
|
||||
function SkipButton() {
|
||||
const item = usePlayer((s) => s.item);
|
||||
const position = usePlayer((s) => s.position);
|
||||
const seek = usePlayer((s) => s.seek);
|
||||
const nextUp = usePlayer((s) => s.nextUp);
|
||||
const countdown = usePlayer((s) => s.countdown);
|
||||
const postPlayDismissed = usePlayer((s) => s.postPlayDismissed);
|
||||
const paused = usePlayer((s) => s.paused);
|
||||
const ready = usePlayer((s) => s.firstFrame);
|
||||
const lastSeek = usePlayer((s) => s.lastSeek);
|
||||
const skipIntro = useSettings((s) => s.skipIntro);
|
||||
const skipCredits = useSettings((s) => s.skipCredits);
|
||||
const delay = useSettings((s) => s.autoSkipDelay);
|
||||
// Markers already skipped, or whose automatic skip was cancelled, don't count down again.
|
||||
const settled = useRef(new Set<string>());
|
||||
const [pending, setPending] = useState<{ key: string; from: number } | null>(null);
|
||||
const autoSkipped = useRef(new Set<string>());
|
||||
const ms = position * 1000;
|
||||
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
|
||||
const key = item && marker ? `${item.id}:${marker.type}:${marker.start}` : '';
|
||||
const episodeCredits = marker?.type === 'credits' && item?.type === 'episode';
|
||||
const mode = marker?.type === 'intro' ? skipIntro : episodeCredits ? 'button' : skipCredits;
|
||||
const auto = !!marker && !episodeCredits && mode === 'auto';
|
||||
const counting = pending && pending.key === key ? pending : null;
|
||||
|
||||
const skip = () => {
|
||||
if (!marker) return;
|
||||
settled.current.add(key);
|
||||
setPending(null);
|
||||
if (marker.type === 'credits' && item?.type === 'episode') usePlayer.getState().showPostPlay();
|
||||
else seek(marker.end / 1000);
|
||||
};
|
||||
const cancel = () => {
|
||||
if (!pending) return;
|
||||
settled.current.add(pending.key);
|
||||
setPending(null);
|
||||
};
|
||||
|
||||
// Start counting once an automatic marker is playing.
|
||||
const mode = marker?.type === 'intro' ? skipIntro : skipCredits;
|
||||
useEffect(() => {
|
||||
if (!auto || !ready || paused || settled.current.has(key) || pending?.key === key) return;
|
||||
if (Date.now() - usePlayer.getState().lastSeek < SEEK_GRACE_MS) {
|
||||
settled.current.add(key);
|
||||
return;
|
||||
if (marker && mode === 'auto' && !autoSkipped.current.has(marker.id + marker.start) && !(marker.type === 'credits' && nextUp)) {
|
||||
autoSkipped.current.add(marker.id + marker.start);
|
||||
seek(marker.end / 1000);
|
||||
}
|
||||
if (delay <= 0) return skip();
|
||||
setPending({ key, from: usePlayer.getState().position });
|
||||
}, [key, auto, ready, paused, delay]);
|
||||
|
||||
// Count playback time, so buffering doesn't eat into the delay.
|
||||
useEffect(() => {
|
||||
if (counting && position - counting.from >= delay) skip();
|
||||
else if (pending && !counting) setPending(null);
|
||||
}, [position, key]);
|
||||
|
||||
// Pausing or seeking means the viewer is watching.
|
||||
useEffect(() => {
|
||||
if (paused) cancel();
|
||||
}, [paused]);
|
||||
useEffect(cancel, [lastSeek]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!counting) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (!MODIFIER_KEYS.has(e.key)) cancel();
|
||||
};
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, [counting]);
|
||||
|
||||
if (!marker || (episodeCredits && !postPlayDismissed) || mode === 'off' || countdown !== null) return null;
|
||||
const what = marker.type === 'intro' ? 'intro' : 'credits';
|
||||
const elapsed = counting ? Math.max(0, position - counting.from) : 0;
|
||||
}, [marker?.id, marker?.start, mode]);
|
||||
if (!marker || mode === 'off' || countdown !== null) return null;
|
||||
if (marker.type === 'credits' && nextUp) return null;
|
||||
return (
|
||||
<button
|
||||
className={`skip-button${counting ? ' counting' : ''}`}
|
||||
style={counting ? { ['--p' as string]: `${Math.min(1, elapsed / delay) * 100}%` } : undefined}
|
||||
title={counting ? 'Click to skip now. Pause, seek or press any key to keep watching.' : undefined}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
skip();
|
||||
}}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<span>{counting ? `Skipping ${what}` : `Skip ${what}`}</span>
|
||||
<button className="skip-button" onClick={() => seek(marker.end / 1000)}>
|
||||
{marker.type === 'intro' ? 'Skip intro' : 'Skip credits'}
|
||||
<Icon name="skipNext" size={16} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function PostPlay() {
|
||||
const server = useSession((s) => s.server);
|
||||
const nextUp = usePlayer((s) => s.nextUp);
|
||||
const countdown = usePlayer((s) => s.countdown);
|
||||
const playNext = usePlayer((s) => s.playNext);
|
||||
const cancel = usePlayer((s) => s.cancelCountdown);
|
||||
if (!nextUp || countdown === null || !server) return null;
|
||||
return (
|
||||
<div className="post-play" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="post-play-art">
|
||||
<img src={server.image(nextUp.thumb, 360, 202)} alt="" draggable={false} />
|
||||
{countdown > 0 && (
|
||||
<svg className="post-play-ring" viewBox="0 0 40 40">
|
||||
<circle cx="20" cy="20" r="17" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-play-text">
|
||||
<span className="micro">Next episode{countdown > 0 ? ` in ${countdown}` : ''}</span>
|
||||
<b>
|
||||
{episodeLabel(nextUp)} · {nextUp.title}
|
||||
</b>
|
||||
<div className="actions">
|
||||
<Button variant="primary" size="sm" icon="play" onClick={playNext}>
|
||||
Play now
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={cancel}>
|
||||
{countdown > 0 ? 'Cancel' : 'Dismiss'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The title opens its show or movie page, with playback moving to the miniplayer. */
|
||||
function openFromPlayer(id: string | undefined) {
|
||||
if (!id) return;
|
||||
|
|
@ -619,62 +583,18 @@ function TitleBlock({ item }: { item: Item }) {
|
|||
);
|
||||
}
|
||||
|
||||
/** Where the miniplayer was dragged to: its distance from the window's right and bottom edges. */
|
||||
type MiniPos = { x: number; y: number };
|
||||
const MINI_POS_KEY = 'kaleido.miniPosition';
|
||||
const MINI_MARGIN = 8;
|
||||
let miniPos: MiniPos | null | undefined;
|
||||
|
||||
function savedMiniPos(): MiniPos | null {
|
||||
if (miniPos === undefined) {
|
||||
try {
|
||||
const p = JSON.parse(localStorage.getItem(MINI_POS_KEY) ?? 'null');
|
||||
miniPos = p && Number.isFinite(p.x) && Number.isFinite(p.y) ? p : null;
|
||||
} catch {
|
||||
miniPos = null;
|
||||
}
|
||||
}
|
||||
return miniPos ?? null;
|
||||
}
|
||||
|
||||
/** Keeps the whole box inside the window. */
|
||||
function clampMini(el: HTMLElement, pos: MiniPos): MiniPos {
|
||||
const cs = getComputedStyle(el);
|
||||
const maxX = window.innerWidth - parseFloat(cs.width) - MINI_MARGIN;
|
||||
const maxY = window.innerHeight - parseFloat(cs.height) - MINI_MARGIN;
|
||||
return { x: Math.round(Math.max(MINI_MARGIN, Math.min(maxX, pos.x))), y: Math.round(Math.max(MINI_MARGIN, Math.min(maxY, pos.y))) };
|
||||
}
|
||||
|
||||
/** The box and the page's hole for the video (base.css) both follow these. */
|
||||
function applyMiniPos(pos: MiniPos | null) {
|
||||
const root = document.documentElement.style;
|
||||
if (!pos) {
|
||||
root.removeProperty('--mini-x');
|
||||
root.removeProperty('--mini-y');
|
||||
return;
|
||||
}
|
||||
root.setProperty('--mini-x', `${pos.x}px`);
|
||||
root.setProperty('--mini-y', `${pos.y}px`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Playing in the corner while browsing, and draggable anywhere in the window.
|
||||
* The native video is drawn into this box's rectangle and the page has a
|
||||
* matching hole (see `html.player-mini`).
|
||||
* Playing in the corner while browsing. The native video is drawn into this
|
||||
* box's rectangle and the page has a matching hole (see `html.player-mini`).
|
||||
*/
|
||||
function MiniPlayer() {
|
||||
const st = usePlayer();
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const placeVideo = useRef(() => {});
|
||||
|
||||
useEffect(() => {
|
||||
const el = box.current;
|
||||
if (!el) return;
|
||||
let frame = 0;
|
||||
const fit = () => {
|
||||
const saved = savedMiniPos();
|
||||
applyMiniPos(saved && clampMini(el, saved));
|
||||
};
|
||||
const place = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
|
|
@ -690,64 +610,23 @@ function MiniPlayer() {
|
|||
if (isNative) mpv.rect({ x: x * dpr - 1, y: y * dpr - 1, width: width * dpr + 2, height: height * dpr + 2 }).catch(() => {});
|
||||
});
|
||||
};
|
||||
placeVideo.current = place;
|
||||
const onResize = () => {
|
||||
fit();
|
||||
place();
|
||||
};
|
||||
onResize();
|
||||
place();
|
||||
const ro = new ResizeObserver(place);
|
||||
ro.observe(el);
|
||||
window.addEventListener('resize', onResize);
|
||||
window.addEventListener('resize', place);
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
ro.disconnect();
|
||||
window.removeEventListener('resize', onResize);
|
||||
window.removeEventListener('resize', place);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const startDrag = (e: ReactPointerEvent) => {
|
||||
const el = box.current;
|
||||
if (e.button !== 0 || !el) return;
|
||||
const cs = getComputedStyle(el);
|
||||
const start = { px: e.clientX, py: e.clientY, x: parseFloat(cs.right), y: parseFloat(cs.bottom) };
|
||||
let dragging = false;
|
||||
const move = (ev: PointerEvent) => {
|
||||
const dx = ev.clientX - start.px;
|
||||
const dy = ev.clientY - start.py;
|
||||
if (!dragging && Math.hypot(dx, dy) < 5) return;
|
||||
dragging = true;
|
||||
el.classList.add('dragging');
|
||||
miniPos = clampMini(el, { x: start.x - dx, y: start.y - dy });
|
||||
applyMiniPos(miniPos);
|
||||
placeVideo.current();
|
||||
};
|
||||
const up = () => {
|
||||
window.removeEventListener('pointermove', move);
|
||||
window.removeEventListener('pointerup', up);
|
||||
window.removeEventListener('pointercancel', up);
|
||||
if (!dragging) return;
|
||||
el.classList.remove('dragging');
|
||||
localStorage.setItem(MINI_POS_KEY, JSON.stringify(miniPos));
|
||||
// Letting go after a drag isn't a click on the button under the pointer.
|
||||
const swallow = (c: MouseEvent) => {
|
||||
c.stopPropagation();
|
||||
c.preventDefault();
|
||||
};
|
||||
window.addEventListener('click', swallow, { capture: true, once: true });
|
||||
setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0);
|
||||
};
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', up);
|
||||
window.addEventListener('pointercancel', up);
|
||||
};
|
||||
|
||||
if (!st.item) return null;
|
||||
const item = st.item;
|
||||
const loading = !st.firstFrame && !st.error;
|
||||
const pct = st.duration ? Math.min(100, (st.position / st.duration) * 100) : 0;
|
||||
return (
|
||||
<div ref={box} className={`mini-player${loading || st.error ? ' loading' : ''}`} onPointerDown={startDrag} onDoubleClick={() => st.expand()}>
|
||||
<div ref={box} className={`mini-player${loading || st.error ? ' loading' : ''}`} onDoubleClick={() => st.expand()}>
|
||||
<div className="mini-scrim" />
|
||||
<div className="mini-top">
|
||||
<button className="mini-icon" aria-label="Back to full screen player" title="Expand" onClick={() => st.expand()}>
|
||||
|
|
@ -758,7 +637,7 @@ function MiniPlayer() {
|
|||
</button>
|
||||
</div>
|
||||
<div className="mini-center">
|
||||
{(loading || st.buffering || st.reconnecting) && !st.error ? (
|
||||
{(loading || st.buffering) && !st.error ? (
|
||||
<Spinner size={30} />
|
||||
) : st.error ? (
|
||||
<span className="mini-error">Playback stopped</span>
|
||||
|
|
@ -811,9 +690,6 @@ export function PlayerOverlay() {
|
|||
useEffect(() => {
|
||||
if (!st.open || st.mini) return;
|
||||
const onKey = async (e: KeyboardEvent) => {
|
||||
// Up Next owns Tab, Space/Enter and Escape; player shortcuts must not
|
||||
// seek or change volume while a viewer is browsing its episode rows.
|
||||
if (usePlayer.getState().postPlay) return;
|
||||
if ((e.target as HTMLElement)?.tagName === 'INPUT' && (e.target as HTMLInputElement).type !== 'range') return;
|
||||
const p = usePlayer.getState();
|
||||
let handled = true;
|
||||
|
|
@ -856,11 +732,6 @@ export function PlayerOverlay() {
|
|||
if (e.shiftKey && p.nextUp) p.playNext();
|
||||
else handled = false;
|
||||
break;
|
||||
case 'p':
|
||||
case 'P':
|
||||
if (e.shiftKey && p.prevUp) p.playPrevious();
|
||||
else handled = false;
|
||||
break;
|
||||
case 'u':
|
||||
case 'U': {
|
||||
const prefs = useSettings.getState();
|
||||
|
|
@ -911,7 +782,7 @@ export function PlayerOverlay() {
|
|||
}, [st.open, st.mini, seekStep, poke]);
|
||||
|
||||
// The macOS traffic lights fade with the rest of the player's chrome.
|
||||
const chromeHidden = st.open && !st.mini && !st.postPlay && !visible && st.firstFrame && !st.error;
|
||||
const chromeHidden = st.open && !st.mini && !visible && st.firstFrame && !st.error;
|
||||
useEffect(() => {
|
||||
if (!chromeHidden) return;
|
||||
win.setButtonsVisible(false);
|
||||
|
|
@ -919,9 +790,7 @@ export function PlayerOverlay() {
|
|||
}, [chromeHidden]);
|
||||
|
||||
if (!st.open || !st.item) return null;
|
||||
// On Windows the miniplayer is a window of its own (miniWindow.ts).
|
||||
if (st.mini) return separateMini ? null : <MiniPlayer />;
|
||||
if (st.postPlay && !st.error) return <PostPlay key={st.item.id} />;
|
||||
if (st.mini) return <MiniPlayer />;
|
||||
const item = st.item;
|
||||
const loading = !st.firstFrame && !st.error;
|
||||
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
|
||||
|
|
@ -965,12 +834,10 @@ export function PlayerOverlay() {
|
|||
{!st.fullscreen && <WindowControls />}
|
||||
</div>
|
||||
|
||||
{(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && (
|
||||
{(loading || st.buffering || st.seeking || preparing) && !st.error && (
|
||||
<div className="player-center">
|
||||
<Spinner size={44} />
|
||||
{st.reconnecting ? (
|
||||
<p className="player-preparing">Lost connection to {server?.name ?? 'the server'}</p>
|
||||
) : preparing && (
|
||||
{preparing && (
|
||||
<p className="player-preparing">
|
||||
Preparing {UPSCALING[st.enhance.active].label} upscaling
|
||||
<small>First time on this computer only</small>
|
||||
|
|
@ -1009,6 +876,7 @@ export function PlayerOverlay() {
|
|||
)}
|
||||
|
||||
<SkipButton />
|
||||
<PostPlay />
|
||||
|
||||
{!st.error && (
|
||||
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
|
|
@ -1019,49 +887,24 @@ export function PlayerOverlay() {
|
|||
<Timeline onScrub={setScrubbing} />
|
||||
<div className="player-controls">
|
||||
<div className="player-controls-left">
|
||||
<Volume />
|
||||
<span className="player-time">
|
||||
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="player-controls-center">
|
||||
{/* Balances Stop on the other side, so play/pause stays centred. */}
|
||||
<span className="player-icon-spacer" aria-hidden="true" />
|
||||
{/* Both episode buttons stay for episodes (dimmed at either end) so play/pause holds its place. */}
|
||||
{item.type === 'episode' && (
|
||||
<button
|
||||
className="player-icon"
|
||||
aria-label="Previous episode"
|
||||
title={st.prevUp ? `Previous: ${episodeLabel(st.prevUp)} ${st.prevUp.title}` : undefined}
|
||||
disabled={!st.prevUp}
|
||||
onClick={() => st.playPrevious()}
|
||||
>
|
||||
<Icon name="skipPrev" size={22} />
|
||||
</button>
|
||||
)}
|
||||
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
||||
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
|
||||
<Icon name="replay10" size={24} />
|
||||
</button>
|
||||
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
||||
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={28} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
|
||||
<Icon name="forward10" size={24} />
|
||||
</button>
|
||||
{item.type === 'episode' && (
|
||||
<button
|
||||
className="player-icon"
|
||||
aria-label="Next episode"
|
||||
title={st.nextUp ? `Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}` : undefined}
|
||||
disabled={!st.nextUp}
|
||||
onClick={() => st.playNext()}
|
||||
>
|
||||
{st.nextUp && (
|
||||
<button className="player-icon" aria-label="Next episode" title={`Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}`} onClick={() => st.playNext()}>
|
||||
<Icon name="skipNext" size={22} />
|
||||
</button>
|
||||
)}
|
||||
<button className="player-icon" aria-label="Stop playback" title="Stop" onClick={() => st.close()}>
|
||||
<Icon name="stop" size={19} />
|
||||
</button>
|
||||
<Volume />
|
||||
<span className="player-time">
|
||||
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="player-controls-right">
|
||||
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
|
||||
|
|
|
|||
|
|
@ -1,334 +0,0 @@
|
|||
import { useEffect, useLayoutEffect, useMemo, useRef } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { usePlayer } from './store';
|
||||
import { mpv } from './engine';
|
||||
import { isNative } from '../platform/native';
|
||||
import { useSession } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { art, clock, duration, episodeLabel } from '../app/format';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { Backdrop } from '../ui/Backdrop';
|
||||
import { Facts, Shelf, TitleArt } from '../ui/media';
|
||||
import { Artwork } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowControls } from '../app/TopBar';
|
||||
|
||||
/**
|
||||
* Up Next, adapted from Kaleido for Android TV: the credits keep playing in the
|
||||
* top-left corner (the native video is drawn into that rectangle, with a matching
|
||||
* hole in the page) beside the next episode, with the season and related shows
|
||||
* below. Play next episode carries the one countdown; moving the mouse, clicking,
|
||||
* scrolling or pressing a key stops it. Clicking the video, or Esc, returns to it.
|
||||
*/
|
||||
export function PostPlay() {
|
||||
const item = usePlayer((s) => s.item)!;
|
||||
const nextUp = usePlayer((s) => s.nextUp);
|
||||
const contextReady = usePlayer((s) => s.episodeContextReady);
|
||||
const fullscreen = usePlayer((s) => s.fullscreen);
|
||||
const server = useSession((s) => s.server);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const video = useRef<HTMLButtonElement>(null);
|
||||
const play = useRef<HTMLButtonElement>(null);
|
||||
|
||||
// The listed episode lacks the rating and full synopsis.
|
||||
const details = useQuery({
|
||||
queryKey: [server?.machineId, 'item', nextUp?.id],
|
||||
queryFn: () => api.metadata(server!, nextUp!.id),
|
||||
enabled: !!server && !!nextUp,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const upcoming = nextUp && details.data?.id === nextUp.id ? details.data : nextUp;
|
||||
|
||||
useVideoRect(root, video);
|
||||
|
||||
useEffect(() => {
|
||||
(play.current ?? video.current)?.focus({ preventScroll: true });
|
||||
const stop = () => {
|
||||
if (usePlayer.getState().countdown !== null) usePlayer.getState().cancelCountdown();
|
||||
};
|
||||
// Layout changes can send a mousemove without the mouse moving.
|
||||
const move = (e: MouseEvent) => (e.movementX || e.movementY) && stop();
|
||||
const key = (e: KeyboardEvent) => {
|
||||
stop();
|
||||
if (e.key === 'Escape' || e.key === 'Backspace') {
|
||||
e.preventDefault();
|
||||
usePlayer.getState().dismissPostPlay();
|
||||
} else if (e.key === 'F11' || ((e.key === 'f' || e.key === 'F') && !e.ctrlKey && !e.metaKey && !e.altKey)) {
|
||||
e.preventDefault();
|
||||
usePlayer.getState().toggleFullscreen();
|
||||
}
|
||||
};
|
||||
const opts = { capture: true, passive: true };
|
||||
window.addEventListener('keydown', key, true);
|
||||
window.addEventListener('pointerdown', stop, opts);
|
||||
window.addEventListener('mousemove', move, opts);
|
||||
window.addEventListener('wheel', stop, opts);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', key, true);
|
||||
window.removeEventListener('pointerdown', stop, opts);
|
||||
window.removeEventListener('mousemove', move, opts);
|
||||
window.removeEventListener('wheel', stop, opts);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const backToVideo = () => usePlayer.getState().dismissPostPlay();
|
||||
// As in the player: the show page opens with playback moving to the miniplayer.
|
||||
const openShow = () => {
|
||||
usePlayer.getState().minimize();
|
||||
navigate({ name: 'item', id: item.grandparentId });
|
||||
};
|
||||
// The next episode's own still, as on Android TV: darker than most show art, so the copy reads.
|
||||
const scene = upcoming ?? item;
|
||||
const sceneArt = useMemo(() => ({ ...scene, grandparentArt: scene.thumb || scene.grandparentArt }), [scene]);
|
||||
|
||||
return (
|
||||
<div className="player up-next" ref={root} role="dialog" aria-modal="true" aria-labelledby="up-next-label">
|
||||
<div className="up-next-scene">{server && <Backdrop item={sceneArt} className="up-next-backdrop" />}</div>
|
||||
<div className="player-top up-next-top" data-tauri-drag-region={isNative ? true : undefined}>
|
||||
<button className="player-back" onClick={() => usePlayer.getState().minimize()} aria-label="Back to browsing" title="Keep playing in the corner">
|
||||
<Icon name="arrowLeft" size={22} />
|
||||
</button>
|
||||
<button className="player-icon up-next-fullscreen" aria-label={fullscreen ? 'Exit full screen' : 'Full screen'} title={fullscreen ? 'Exit full screen' : 'Full screen'} onClick={() => usePlayer.getState().toggleFullscreen()}>
|
||||
<Icon name={fullscreen ? 'collapse' : 'expand'} size={21} />
|
||||
</button>
|
||||
{!fullscreen && <WindowControls />}
|
||||
</div>
|
||||
|
||||
<div className="up-next-head">
|
||||
<div className="up-next-now">
|
||||
<button ref={video} className="up-next-video" onClick={backToVideo} aria-label={`Return to ${item.title}`} />
|
||||
<NowPlaying item={item} />
|
||||
</div>
|
||||
<div className="up-next-info">
|
||||
<span className="micro" id="up-next-label">
|
||||
{upcoming || !contextReady ? 'Up next' : 'More to watch'}
|
||||
</span>
|
||||
{item.grandparentId ? (
|
||||
<button className="player-title-link up-next-logo" title={`Go to ${item.grandparentTitle}`} onClick={openShow}>
|
||||
<TitleArt item={item} maxWidth={300} maxHeight={64} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<TitleArt item={item} maxWidth={300} maxHeight={64} as="h2" className="up-next-logo" />
|
||||
)}
|
||||
{upcoming ? (
|
||||
<>
|
||||
<h1>{upcoming.title}</h1>
|
||||
<Facts item={{ ...upcoming, viewOffset: 0, originallyAvailableAt: '' }} withFormats={false} />
|
||||
{upcoming.summary && <p className="up-next-summary">{upcoming.summary}</p>}
|
||||
<PlayNext ref={play} />
|
||||
</>
|
||||
) : (
|
||||
contextReady && <p className="up-next-summary">You’ve reached the end of this series.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{server && <UpNextRows item={item} nextUp={nextUp} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the native video into the frame's rectangle and cuts the same hole in
|
||||
* the page, following window resizes and display scale changes.
|
||||
*/
|
||||
function useVideoRect(root: React.RefObject<HTMLDivElement | null>, frame: React.RefObject<HTMLElement | null>) {
|
||||
useLayoutEffect(() => {
|
||||
const el = frame.current;
|
||||
const page = root.current;
|
||||
if (!el || !page) return;
|
||||
let raf = 0;
|
||||
const place = () => {
|
||||
cancelAnimationFrame(raf);
|
||||
raf = requestAnimationFrame(() => {
|
||||
const r = el.getBoundingClientRect();
|
||||
page.style.setProperty('--up-x', `${r.x}px`);
|
||||
page.style.setProperty('--up-y', `${r.y}px`);
|
||||
page.style.setProperty('--up-w', `${r.width}px`);
|
||||
page.style.setProperty('--up-h', `${r.height}px`);
|
||||
page.classList.add('placed');
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
// A pixel of overdraw on each side keeps the hole covered at any scale.
|
||||
if (isNative) mpv.rect({ x: r.x * dpr - 1, y: r.y * dpr - 1, width: r.width * dpr + 2, height: r.height * dpr + 2 }).catch(() => {});
|
||||
});
|
||||
};
|
||||
const ro = new ResizeObserver(place);
|
||||
ro.observe(el);
|
||||
window.addEventListener('resize', place);
|
||||
place();
|
||||
return () => {
|
||||
cancelAnimationFrame(raf);
|
||||
ro.disconnect();
|
||||
window.removeEventListener('resize', place);
|
||||
if (isNative) mpv.rect(null).catch(() => {});
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** Where the playing episode is, under the video. Its own subscription: position ticks re-render only this. */
|
||||
function NowPlaying({ item }: { item: Item }) {
|
||||
const position = usePlayer((s) => s.position);
|
||||
const total = usePlayer((s) => s.duration);
|
||||
return (
|
||||
<div className="up-next-progress">
|
||||
<div className="up-next-progress-text">
|
||||
<span>
|
||||
{episodeLabel(item)} · {item.title}
|
||||
</span>
|
||||
<small>−{clock(Math.max(0, total - position))}</small>
|
||||
</div>
|
||||
<div className="up-next-progress-bar">
|
||||
<i style={{ width: `${total ? Math.min(100, (position / total) * 100) : 0}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Play next episode. While autoplay counts down, a lighter fill sweeps across it.
|
||||
* The store counts in 50 ms steps; the fill is drawn every frame between them.
|
||||
*/
|
||||
function PlayNext({ ref }: { ref: React.Ref<HTMLButtonElement> }) {
|
||||
const counting = usePlayer((s) => s.countdown !== null && s.countdownTotal > 0);
|
||||
const fill = useRef<HTMLSpanElement>(null);
|
||||
useEffect(() => {
|
||||
if (!counting) return;
|
||||
let last = { value: usePlayer.getState().countdown ?? 0, at: performance.now() };
|
||||
const unsubscribe = usePlayer.subscribe((s, prev) => {
|
||||
if (s.countdown !== prev.countdown && s.countdown !== null) last = { value: s.countdown, at: performance.now() };
|
||||
});
|
||||
let raf = 0;
|
||||
const draw = () => {
|
||||
const { countdownTotal: total } = usePlayer.getState();
|
||||
// Run on from the last step, but never more than a couple of steps ahead (a held countdown stays held).
|
||||
const remaining = Math.max(0, last.value - Math.min(performance.now() - last.at, 120) / 1000);
|
||||
if (fill.current && total) fill.current.style.transform = `scaleX(${1 - remaining / total})`;
|
||||
raf = requestAnimationFrame(draw);
|
||||
};
|
||||
draw();
|
||||
return () => {
|
||||
unsubscribe();
|
||||
cancelAnimationFrame(raf);
|
||||
};
|
||||
}, [counting]);
|
||||
return (
|
||||
<button ref={ref} className={`btn primary lg up-next-play${counting ? ' counting' : ''}`} onClick={() => usePlayer.getState().playNext()}>
|
||||
{counting && <span className="up-next-play-fill" ref={fill} aria-hidden="true" />}
|
||||
<Icon name="play" size={17} />
|
||||
<span>Play next episode</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function UpNextRows({ item, nextUp }: { item: Item; nextUp: Item | null }) {
|
||||
const server = useSession((s) => s.server)!;
|
||||
const season = useQuery({
|
||||
queryKey: [server.machineId, 'children', item.parentId],
|
||||
queryFn: () => api.children(server, item.parentId),
|
||||
enabled: !!item.parentId,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const related = useQuery({
|
||||
queryKey: [server.machineId, 'related', item.grandparentId],
|
||||
queryFn: () => api.related(server, item.grandparentId),
|
||||
enabled: !!item.grandparentId,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
const episodes = (season.data ?? []).filter((e) => e.type === 'episode');
|
||||
const seen = new Set([item.grandparentId]);
|
||||
const shows = (related.data ?? []).flatMap((h) => h.items).filter((i) => i.type === 'show' && !seen.has(i.id) && !!seen.add(i.id));
|
||||
|
||||
// The season row starts just before the playing episode.
|
||||
const seasonRow = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const row = seasonRow.current?.querySelector<HTMLElement>('.shelf');
|
||||
const current = row?.querySelector<HTMLElement>('[aria-current]');
|
||||
if (!row || !current) return;
|
||||
const start = (current.previousElementSibling as HTMLElement | null) ?? current;
|
||||
const target = row.scrollLeft + start.getBoundingClientRect().left - row.getBoundingClientRect().left - parseFloat(getComputedStyle(row).paddingLeft);
|
||||
row.scrollTo({ left: target, behavior: 'instant' });
|
||||
}, [episodes.length]);
|
||||
|
||||
const choose = (episode: Item) => {
|
||||
const st = usePlayer.getState();
|
||||
if (episode.id === item.id) st.dismissPostPlay();
|
||||
else st.play(episode, { resume: true, quality: st.quality });
|
||||
};
|
||||
const browse = async (show: Item) => {
|
||||
await usePlayer.getState().close();
|
||||
navigate({ name: 'item', id: show.id, title: show.title });
|
||||
};
|
||||
if (!episodes.length && !shows.length) return null;
|
||||
return (
|
||||
<div className="up-next-rows">
|
||||
{episodes.length > 0 && (
|
||||
<div ref={seasonRow}>
|
||||
<Shelf title={item.parentIndex ? `Season ${item.parentIndex}` : 'Episodes'} kind="landscape" className="up-next-shelf">
|
||||
{episodes.map((ep) => (
|
||||
<UpNextCard
|
||||
key={ep.id}
|
||||
item={ep}
|
||||
current={ep.id === item.id}
|
||||
caption={ep.id === item.id ? 'Now playing' : ep.id === nextUp?.id ? 'Up next' : duration(ep.duration)}
|
||||
onChoose={() => choose(ep)}
|
||||
/>
|
||||
))}
|
||||
</Shelf>
|
||||
</div>
|
||||
)}
|
||||
{shows.length > 0 && (
|
||||
<Shelf title="Related shows" kind="landscape" className="up-next-shelf">
|
||||
{shows.map((show) => (
|
||||
<UpNextCard key={show.id} item={show} caption={show.year ? String(show.year) : ''} onChoose={() => void browse(show)} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UpNextCard({ item, caption, current, onChoose }: { item: Item; caption: string; current?: boolean; onChoose: () => void }) {
|
||||
const server = useSession((s) => s.server)!;
|
||||
const episode = item.type === 'episode';
|
||||
const title = episode ? `${item.index}. ${item.title}` : item.title;
|
||||
const progress = episode && !current && item.viewOffset && item.duration ? item.viewOffset / item.duration : 0;
|
||||
return (
|
||||
<article
|
||||
className="card landscape"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={title}
|
||||
aria-current={current || undefined}
|
||||
onClick={onChoose}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||
e.preventDefault();
|
||||
onChoose();
|
||||
}}
|
||||
>
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(art.landscape(item), 400, 225)} alt="" fallback={<span className="cover-fallback">{title}</span>} />
|
||||
<div className="card-hover" />
|
||||
{episode && !current && (
|
||||
<div className="card-actions">
|
||||
<span className="card-play" aria-hidden="true">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{progress > 0 && (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${Math.max(3, progress * 100)}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="card-caption">
|
||||
<div className="card-title" title={title}>
|
||||
{title}
|
||||
</div>
|
||||
{caption && <div className="card-meta">{caption}</div>}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
/**
|
||||
* The miniplayer as a window of its own (Windows, src-tauri/src/mini.rs): the
|
||||
* video moves into it, so it drags as one piece. This side keeps its page
|
||||
* (src/mini/) up to date and carries out its buttons; macOS keeps the
|
||||
* in-page miniplayer (PlayerOverlay).
|
||||
*/
|
||||
import { hostOS, invoke, isNative, listen } from '../platform/native';
|
||||
import { episodeLabel } from '../app/format';
|
||||
import { MINI_CORNER_KEY, type MiniAction, type MiniState } from '../mini/types';
|
||||
import type { Item } from '../plex/types';
|
||||
|
||||
export const separateMini = isNative && hostOS === 'windows';
|
||||
|
||||
export async function showMiniWindow() {
|
||||
await invoke('mini_show', { corner: localStorage.getItem(MINI_CORNER_KEY) ?? 'br' });
|
||||
}
|
||||
|
||||
/** Moves the video back to the main window; harmless when already there. */
|
||||
export async function hideMiniWindow() {
|
||||
await invoke('mini_hide').catch(() => {});
|
||||
}
|
||||
|
||||
interface PlayerView {
|
||||
open: boolean;
|
||||
mini: boolean;
|
||||
item: Item | null;
|
||||
paused: boolean;
|
||||
ended: boolean;
|
||||
position: number;
|
||||
duration: number;
|
||||
firstFrame: boolean;
|
||||
buffering: boolean;
|
||||
reconnecting: boolean;
|
||||
error: string;
|
||||
}
|
||||
|
||||
interface PlayerActions {
|
||||
togglePause(): void;
|
||||
seekBy(delta: number): void;
|
||||
expand(): void;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
function view(st: PlayerView): MiniState {
|
||||
const item = st.item;
|
||||
return {
|
||||
title: item ? (item.type === 'episode' ? item.grandparentTitle : item.title) : '',
|
||||
subtitle: item?.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : '',
|
||||
paused: st.paused,
|
||||
ended: st.ended,
|
||||
position: st.position,
|
||||
duration: st.duration,
|
||||
loading: !st.firstFrame && !st.error,
|
||||
// Waiting for the server to come back shows as buffering.
|
||||
buffering: st.buffering || st.reconnecting,
|
||||
error: !!st.error,
|
||||
};
|
||||
}
|
||||
|
||||
/** Mirrors the player into the miniplayer window and listens for its buttons. */
|
||||
export function bridgeMiniWindow(store: { getState(): PlayerView & PlayerActions; subscribe(listener: (st: PlayerView, prev: PlayerView) => void): () => void }) {
|
||||
if (!separateMini) return;
|
||||
let lastSent = 0;
|
||||
let pending: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const send = async () => {
|
||||
pending = null;
|
||||
lastSent = Date.now();
|
||||
const st = store.getState();
|
||||
if (!st.open) return;
|
||||
const { emitTo } = await import('@tauri-apps/api/event');
|
||||
emitTo('mini', 'mini:state', view(st)).catch(() => {});
|
||||
};
|
||||
|
||||
store.subscribe((st, prev) => {
|
||||
if (!st.open || !st.mini) return;
|
||||
// Everything but the position goes straight away; the position a few times a second.
|
||||
const a = view(st);
|
||||
const b = view(prev);
|
||||
const only = (Object.keys(a) as (keyof MiniState)[]).every((k) => k === 'position' || a[k] === b[k]);
|
||||
if (!only || st.mini !== prev.mini) {
|
||||
if (pending) clearTimeout(pending);
|
||||
send();
|
||||
} else if (!pending) {
|
||||
pending = setTimeout(send, Math.max(0, 250 - (Date.now() - lastSent)));
|
||||
}
|
||||
});
|
||||
|
||||
listen<{ type: MiniAction }>('mini:action', ({ type }) => {
|
||||
const st = store.getState();
|
||||
if (type === 'ready') return send();
|
||||
if (!st.open) return;
|
||||
if (type === 'toggle') st.togglePause();
|
||||
else if (type === 'back') st.seekBy(-10);
|
||||
else if (type === 'forward') st.seekBy(10);
|
||||
else if (type === 'expand') st.expand();
|
||||
else if (type === 'close') st.close();
|
||||
});
|
||||
}
|
||||
|
|
@ -1,280 +0,0 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { MpvEvent } from './engine';
|
||||
|
||||
const harness = vi.hoisted(() => {
|
||||
const memory = new Map<string, string>();
|
||||
vi.stubGlobal('localStorage', { getItem: (k: string) => memory.get(k) ?? null, setItem: (k: string, v: string) => memory.set(k, v), removeItem: (k: string) => memory.delete(k) });
|
||||
vi.stubGlobal('document', Object.assign(new EventTarget(), { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } }));
|
||||
return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true, identity: vi.fn() };
|
||||
});
|
||||
|
||||
vi.mock('../platform/native', () => ({
|
||||
isNative: true, invoke: vi.fn().mockResolvedValue(undefined), keepAwake: vi.fn(),
|
||||
win: { isFullscreen: vi.fn().mockResolvedValue(false), setFullscreen: vi.fn(), onResized: vi.fn() },
|
||||
}));
|
||||
vi.mock('./engine', () => ({ mpv: {
|
||||
init: vi.fn().mockResolvedValue(undefined), set: vi.fn().mockResolvedValue(undefined),
|
||||
command: vi.fn().mockResolvedValue(undefined), show: vi.fn().mockResolvedValue(undefined),
|
||||
rect: vi.fn().mockResolvedValue(undefined),
|
||||
on: vi.fn(async (cb: typeof harness.event) => { harness.event = cb; return () => {}; }),
|
||||
} }));
|
||||
vi.mock('../app/session', async () => {
|
||||
const { create } = await import('zustand');
|
||||
return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only', name: 'Test', get: harness.identity }, connection: { local: true } })) };
|
||||
});
|
||||
vi.mock('../downloads/store', () => ({ useDownloads: { getState: () => ({ items: [] }) } }));
|
||||
vi.mock('../app/queries', () => ({ invalidateLibrary: vi.fn() }));
|
||||
vi.mock('../ui/overlays', () => ({ toast: vi.fn() }));
|
||||
vi.mock('./theme', () => ({ stopThemeMusic: vi.fn() }));
|
||||
vi.mock('./miniWindow', () => ({ bridgeMiniWindow: vi.fn(), hideMiniWindow: vi.fn(), showMiniWindow: vi.fn(), separateMini: false }));
|
||||
vi.mock('./enhance', () => ({ followVideoSize: vi.fn(), noteMpvLog: vi.fn(), requestEnhancement: vi.fn().mockResolvedValue(undefined), watchPerformance: vi.fn() }));
|
||||
vi.mock('../plex/playback', () => ({ directUrl: () => 'test://video', previewUrl: () => '', reportTimeline: vi.fn().mockResolvedValue({}), stopTranscode: vi.fn(), transcodeUrl: () => '' }));
|
||||
vi.mock('../plex/api', () => ({ allLeaves: vi.fn(async () => harness.next), metadata: vi.fn(), setWatched: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
import { usePlayer } from './store';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { parseItem } from '../plex/parse';
|
||||
import { mpv } from './engine';
|
||||
import * as api from '../plex/api';
|
||||
|
||||
const episode = (id = '1') => parseItem({ ratingKey: id, type: 'episode', title: `Episode ${id}`, grandparentRatingKey: 'show', duration: 100000,
|
||||
Marker: [{ id: 'credits', type: 'credits', startTimeOffset: 80000, endTimeOffset: 90000 }],
|
||||
Media: [{ Part: [{ key: '/video', Stream: [{ id: 'audio', streamType: 2 }] }] }],
|
||||
});
|
||||
const time = (position: number) => harness.event({ type: 'property', name: 'time-pos', value: position });
|
||||
/** The stream ending at `position` (by default the real end of the 100 s episode). */
|
||||
const eof = (position = 99.6) => {
|
||||
usePlayer.setState({ position });
|
||||
harness.event({ type: 'end-file', reason: 'eof' });
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('performance', { now: () => Date.now() });
|
||||
Object.assign(document, { hidden: false, hasFocus: () => harness.focused });
|
||||
harness.focused = true;
|
||||
useSettings.setState({ autoplayNext: true, countdownSeconds: 5, skipCredits: 'auto', watchedPercent: 95 });
|
||||
const current = episode();
|
||||
harness.next = [current, episode('2')];
|
||||
vi.mocked(api.metadata).mockResolvedValue(current);
|
||||
await usePlayer.getState().play(current, { resume: false });
|
||||
await Promise.resolve();
|
||||
usePlayer.setState({ firstFrame: true });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await usePlayer.getState().close();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('Up Next playback lifecycle', () => {
|
||||
it('opens immediately at any episode credits marker with a single countdown', () => {
|
||||
time(81);
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5, countdownTotal: 5 });
|
||||
});
|
||||
it.each(['button', 'off', 'auto'] as const)('opens at the first credits frame with movie credit skipping set to %s', (skipCredits) => {
|
||||
useSettings.setState({ skipCredits });
|
||||
time(79.9);
|
||||
expect(usePlayer.getState().postPlay).toBe(false);
|
||||
time(80);
|
||||
expect(usePlayer.getState().postPlay).toBe(true);
|
||||
});
|
||||
it('counts while the native video owns focus instead of the webview', () => {
|
||||
harness.focused = false;
|
||||
time(81);
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||
});
|
||||
it('counts elapsed time even when the webview delivers timer callbacks late', () => {
|
||||
time(81);
|
||||
vi.setSystemTime(Date.now() + 2000);
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(usePlayer.getState().countdown).toBeCloseTo(2.95);
|
||||
});
|
||||
it('opens at EOF even when automatic credit skipping is off', () => {
|
||||
useSettings.setState({ skipCredits: 'off' });
|
||||
eof();
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, ended: true, countdown: 5 });
|
||||
});
|
||||
it('plays the next episode exactly once after the configured delay', () => {
|
||||
const next = vi.fn().mockResolvedValue(undefined);
|
||||
const original = usePlayer.getState().playNext;
|
||||
usePlayer.setState({ playNext: next });
|
||||
time(81);
|
||||
vi.advanceTimersByTime(5100);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
usePlayer.setState({ playNext: original });
|
||||
});
|
||||
it('starts the next episode from the beginning, ignoring an earlier partial viewing', async () => {
|
||||
const original = usePlayer.getState().play;
|
||||
const spy = vi.fn().mockResolvedValue(undefined);
|
||||
usePlayer.setState({ play: spy, nextUp: { ...episode('2'), viewOffset: 88000 } });
|
||||
await usePlayer.getState().playNext();
|
||||
expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: '2' }), expect.objectContaining({ resume: false }));
|
||||
usePlayer.setState({ play: original });
|
||||
});
|
||||
it('cancels autoplay while keeping the screen open, including across EOF', () => {
|
||||
time(81);
|
||||
usePlayer.getState().cancelCountdown();
|
||||
eof();
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true });
|
||||
});
|
||||
it('returns to credits without reopening while they play', () => {
|
||||
time(81);
|
||||
usePlayer.getState().dismissPostPlay();
|
||||
time(82);
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: false, countdown: null });
|
||||
});
|
||||
it('reopens at the end after returning to the credits', () => {
|
||||
time(81);
|
||||
usePlayer.getState().dismissPostPlay();
|
||||
eof();
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 });
|
||||
});
|
||||
it('reopens when the credits start again after seeking back into the episode', () => {
|
||||
time(81);
|
||||
usePlayer.getState().dismissPostPlay();
|
||||
usePlayer.getState().seek(40);
|
||||
time(40);
|
||||
expect(usePlayer.getState().postPlay).toBe(false);
|
||||
time(80);
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 });
|
||||
});
|
||||
it.each(['hidden', 'mini'] as const)('holds the countdown while %s', (reason) => {
|
||||
time(81);
|
||||
if (reason === 'hidden') Object.assign(document, { hidden: true });
|
||||
if (reason === 'mini') usePlayer.setState({ mini: true });
|
||||
vi.advanceTimersByTime(20000);
|
||||
expect(usePlayer.getState().countdown).toBe(5);
|
||||
Object.assign(document, { hidden: false });
|
||||
harness.focused = true;
|
||||
usePlayer.setState({ paused: false, mini: false });
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||
});
|
||||
it('keeps counting at EOF even when mpv reports pause', () => {
|
||||
eof();
|
||||
usePlayer.setState({ paused: true });
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||
});
|
||||
it('keeps counting while credits are paused, like Android Up Next', () => {
|
||||
time(81);
|
||||
usePlayer.setState({ paused: true });
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(usePlayer.getState().countdown).toBeCloseTo(4);
|
||||
});
|
||||
it('does not spend hidden time when the app returns before another timer tick', () => {
|
||||
time(80);
|
||||
Object.assign(document, { hidden: true });
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
vi.setSystemTime(Date.now() + 60000);
|
||||
Object.assign(document, { hidden: false });
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(usePlayer.getState().countdown).toBeCloseTo(4.95);
|
||||
});
|
||||
it('shows a finale without an autoplay target', () => {
|
||||
usePlayer.setState({ nextUp: null });
|
||||
eof();
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null });
|
||||
});
|
||||
it('respects autoplay off', () => {
|
||||
useSettings.setState({ autoplayNext: false });
|
||||
time(81);
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null });
|
||||
});
|
||||
it('opens when seeking into credits instead of suppressing Up Next', () => {
|
||||
usePlayer.getState().seek(81);
|
||||
time(81);
|
||||
vi.advanceTimersByTime(2000);
|
||||
time(83);
|
||||
expect(usePlayer.getState().postPlay).toBe(true);
|
||||
expect(mpv.command).toHaveBeenCalledWith('seek', '81.000', 'absolute+exact');
|
||||
});
|
||||
it.each(['ended', 'credits'] as const)('shows Up Next immediately and loads slow episode context after %s', async (reason) => {
|
||||
let resolve!: (items: ReturnType<typeof episode>[]) => void;
|
||||
vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
||||
await usePlayer.getState().play(episode(), { resume: false });
|
||||
usePlayer.setState({ firstFrame: true });
|
||||
useSettings.setState({ skipCredits: 'button' });
|
||||
if (reason === 'ended') eof();
|
||||
else time(80);
|
||||
expect(usePlayer.getState().postPlay).toBe(true);
|
||||
expect(usePlayer.getState().countdown).toBeNull();
|
||||
resolve([episode(), episode('2')]);
|
||||
await vi.waitFor(() => expect(usePlayer.getState().episodeContextReady).toBe(true));
|
||||
expect(usePlayer.getState().nextUp?.id).toBe('2');
|
||||
expect(usePlayer.getState().countdownTotal).toBe(5);
|
||||
expect(usePlayer.getState().countdown).toBeGreaterThan(4.9);
|
||||
expect(usePlayer.getState().countdown).toBeLessThanOrEqual(5);
|
||||
});
|
||||
it('keeps autoplay cancelled when episode context arrives after interaction', async () => {
|
||||
let resolve!: (items: ReturnType<typeof episode>[]) => void;
|
||||
vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
|
||||
await usePlayer.getState().play(episode(), { resume: false });
|
||||
usePlayer.setState({ firstFrame: true });
|
||||
time(80);
|
||||
usePlayer.getState().cancelCountdown();
|
||||
resolve([episode(), episode('2')]);
|
||||
await vi.waitFor(() => expect(usePlayer.getState().episodeContextReady).toBe(true));
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true });
|
||||
});
|
||||
it('clears Up Next and its timer when playback closes', async () => {
|
||||
time(81);
|
||||
await usePlayer.getState().close();
|
||||
vi.advanceTimersByTime(10000);
|
||||
expect(usePlayer.getState()).toMatchObject({ open: false, postPlay: false, countdown: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Losing the server mid-stream', () => {
|
||||
it('waits for the server instead of ending when the stream is cut off early', () => {
|
||||
eof(42);
|
||||
expect(usePlayer.getState()).toMatchObject({ reconnecting: true, ended: false, postPlay: false });
|
||||
});
|
||||
it('resumes from where it stopped once the server answers again', async () => {
|
||||
const original = usePlayer.getState().play;
|
||||
const play = vi.fn().mockResolvedValue(undefined);
|
||||
usePlayer.setState({ play });
|
||||
harness.identity.mockRejectedValueOnce(new Error('unreachable'));
|
||||
eof(42);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(play).not.toHaveBeenCalled();
|
||||
expect(usePlayer.getState().reconnecting).toBe(true);
|
||||
harness.identity.mockResolvedValueOnce({});
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
expect(play).toHaveBeenCalledWith(expect.objectContaining({ id: '1' }), expect.objectContaining({ offsetMs: 42000, keepMini: true }));
|
||||
expect(usePlayer.getState().reconnecting).toBe(false);
|
||||
usePlayer.setState({ play: original });
|
||||
});
|
||||
it('tries straight away on Play instead of starting over', async () => {
|
||||
const original = usePlayer.getState().play;
|
||||
const play = vi.fn().mockResolvedValue(undefined);
|
||||
usePlayer.setState({ play });
|
||||
harness.identity.mockResolvedValueOnce({});
|
||||
eof(42);
|
||||
usePlayer.getState().togglePause();
|
||||
await vi.waitFor(() => expect(play).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ offsetMs: 42000 })));
|
||||
expect(mpv.command).not.toHaveBeenCalledWith('seek', '0.000', 'absolute+exact');
|
||||
usePlayer.setState({ play: original });
|
||||
});
|
||||
it('treats a second cut-off at the same place as the real end of the file', async () => {
|
||||
harness.identity.mockResolvedValueOnce({});
|
||||
eof(42);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
usePlayer.setState({ firstFrame: true });
|
||||
eof(42.5);
|
||||
expect(usePlayer.getState()).toMatchObject({ reconnecting: false, ended: true });
|
||||
});
|
||||
it('stops waiting when the player is closed', async () => {
|
||||
eof(42);
|
||||
await usePlayer.getState().close();
|
||||
harness.identity.mockClear();
|
||||
await vi.advanceTimersByTimeAsync(10000);
|
||||
expect(harness.identity).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
@ -2,18 +2,15 @@ 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 { invoke, keepAwake, isNative, win } from '../platform/native';
|
||||
import { keepAwake, isNative, win } from '../platform/native';
|
||||
import { mpv, type MpvEvent, type MpvTrack } from './engine';
|
||||
import { toast } from '../ui/overlays';
|
||||
import { stopThemeMusic } from './theme';
|
||||
import { bridgeMiniWindow, hideMiniWindow, separateMini, showMiniWindow } from './miniWindow';
|
||||
|
||||
export interface Track {
|
||||
key: string; // stable UI key
|
||||
|
|
@ -34,10 +31,6 @@ 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 };
|
||||
/** Reloading the same title in place (after an outage): stay in the miniplayer if it's there. */
|
||||
keepMini?: boolean;
|
||||
}
|
||||
|
||||
interface PlayerState {
|
||||
|
|
@ -50,16 +43,12 @@ interface PlayerState {
|
|||
error: string;
|
||||
/** The server owner stopped this stream (error holds their message). */
|
||||
terminated: boolean;
|
||||
/** The stream was cut off before the end (the server went away); waiting for it to come back. */
|
||||
reconnecting: boolean;
|
||||
position: number;
|
||||
duration: number;
|
||||
cacheTime: number;
|
||||
paused: boolean;
|
||||
buffering: boolean;
|
||||
seeking: boolean;
|
||||
/** When the last seek was asked for (Date.now()), so a pending auto-skip can step aside. */
|
||||
lastSeek: number;
|
||||
volume: number;
|
||||
muted: boolean;
|
||||
speed: number;
|
||||
|
|
@ -72,12 +61,7 @@ interface PlayerState {
|
|||
video: { width: number; height: number; hwdec: string; codec: string } | null;
|
||||
ended: boolean;
|
||||
nextUp: Item | null;
|
||||
/** The episode before this one, for the previous-episode button. */
|
||||
prevUp: Item | null;
|
||||
episodeContextReady: boolean;
|
||||
countdown: number | null;
|
||||
countdownTotal: number;
|
||||
postPlay: boolean;
|
||||
postPlayDismissed: boolean;
|
||||
fullscreen: boolean;
|
||||
/** Playing in the corner while browsing. */
|
||||
|
|
@ -105,10 +89,7 @@ interface PlayerState {
|
|||
setQuality(q: Quality): Promise<void>;
|
||||
selectVersion(index: number): Promise<void>;
|
||||
playNext(): Promise<void>;
|
||||
playPrevious(): Promise<void>;
|
||||
cancelCountdown(): void;
|
||||
showPostPlay(): void;
|
||||
dismissPostPlay(): void;
|
||||
toggleFullscreen(): Promise<void>;
|
||||
previewAt(seconds: number): string;
|
||||
}
|
||||
|
|
@ -120,23 +101,13 @@ let lastReport = 0;
|
|||
let sessionAnswered = false;
|
||||
let reportTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let countdownTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let unwatchCountdown: (() => void) | null = null;
|
||||
let scrobbled = false;
|
||||
let unlisten: (() => void) | null = null;
|
||||
let loadToken = 0;
|
||||
let wasFullscreenBeforePlay = false;
|
||||
let pendingExternal: Track | null = null;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
const server = () => useSession.getState().server;
|
||||
|
||||
/**
|
||||
* mpv applies its volume on a cubic curve, so halfway on a linear slider was
|
||||
|
|
@ -241,34 +212,8 @@ 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<boolean> {
|
||||
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);
|
||||
|
|
@ -315,11 +260,9 @@ function onTerminated(text: string) {
|
|||
function checkScrobble() {
|
||||
const { item, position, duration } = usePlayer.getState();
|
||||
const s = server();
|
||||
if (!item || scrobbled || !duration || item.type === 'clip') return;
|
||||
if (!item || !s || 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)
|
||||
|
|
@ -328,156 +271,42 @@ function checkScrobble() {
|
|||
}
|
||||
}
|
||||
|
||||
/** The episodes either side of this one in the show. */
|
||||
async function findNeighbours(item: Item): Promise<{ prevUp: Item | null; nextUp: Item | null }> {
|
||||
const none = { prevUp: null, nextUp: null };
|
||||
async function findNext(item: Item): Promise<Item | null> {
|
||||
const s = server();
|
||||
if (!s || item.type !== 'episode' || !item.grandparentId) return none;
|
||||
if (!s || item.type !== 'episode' || !item.grandparentId) return null;
|
||||
try {
|
||||
const leaves = await api.allLeaves(s, item.grandparentId);
|
||||
const i = leaves.findIndex((e) => e.id === item.id);
|
||||
return i >= 0 ? { prevUp: leaves[i - 1] ?? null, nextUp: leaves[i + 1] ?? null } : none;
|
||||
return i >= 0 ? (leaves[i + 1] ?? null) : null;
|
||||
} catch {
|
||||
return none;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function openPostPlay() {
|
||||
const st = usePlayer.getState();
|
||||
if (!st.open || st.error || st.item?.type !== 'episode' || st.postPlay || st.postPlayDismissed) return;
|
||||
usePlayer.setState({ postPlay: true });
|
||||
startCountdown();
|
||||
}
|
||||
|
||||
function startCountdown() {
|
||||
const st = usePlayer.getState();
|
||||
if (!st.open || !st.postPlay || st.error || !st.nextUp || st.postPlayDismissed || st.countdown !== null) return;
|
||||
if (!st.nextUp || st.countdown !== null || st.postPlayDismissed) return;
|
||||
const settings = useSettings.getState();
|
||||
const total = settings.autoplayNext ? settings.countdownSeconds : 0;
|
||||
if (total <= 0) return;
|
||||
stopCountdown();
|
||||
usePlayer.setState({ countdown: total, countdownTotal: total });
|
||||
let lastTick = performance.now();
|
||||
const visibilityChanged = () => { lastTick = performance.now(); };
|
||||
document.addEventListener('visibilitychange', visibilityChanged);
|
||||
unwatchCountdown = () => document.removeEventListener('visibilitychange', visibilityChanged);
|
||||
if (!settings.autoplayNext) {
|
||||
usePlayer.setState({ countdown: -1 });
|
||||
return;
|
||||
}
|
||||
usePlayer.setState({ countdown: settings.countdownSeconds });
|
||||
countdownTimer && clearInterval(countdownTimer);
|
||||
countdownTimer = setInterval(() => {
|
||||
const now = performance.now();
|
||||
const elapsed = Math.max(0, (now - lastTick) / 1000);
|
||||
lastTick = now;
|
||||
const current = usePlayer.getState();
|
||||
if (!current.open || !current.postPlay || current.error || current.countdown === null) return stopCountdown();
|
||||
// Native video can own keyboard focus while the webview is still on screen.
|
||||
if (document.hidden || current.mini) return;
|
||||
const remaining = Math.max(0, current.countdown - elapsed);
|
||||
usePlayer.setState({ countdown: remaining });
|
||||
if (remaining === 0) {
|
||||
stopCountdown();
|
||||
current.playNext();
|
||||
}
|
||||
}, 50);
|
||||
const c = usePlayer.getState().countdown;
|
||||
if (c === null || c < 0) return;
|
||||
if (c <= 1) {
|
||||
clearInterval(countdownTimer!);
|
||||
countdownTimer = null;
|
||||
usePlayer.getState().playNext();
|
||||
} else usePlayer.setState({ countdown: c - 1 });
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function stopCountdown() {
|
||||
if (countdownTimer) clearInterval(countdownTimer);
|
||||
countdownTimer = null;
|
||||
unwatchCountdown?.();
|
||||
unwatchCountdown = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 =
|
||||
(lang && audio.find((t) => t.language === lang)?.key) ||
|
||||
audio.find((t) => t.stream?.selected)?.key ||
|
||||
audio.find((t) => t.stream?.default)?.key ||
|
||||
audio[0]?.key ||
|
||||
'';
|
||||
}
|
||||
if (subKey === '__init') {
|
||||
const lang = prefs.subtitleLanguage || audio.find((t) => t.key === audioKey)?.language || '';
|
||||
const inLang = subs.filter((t) => !lang || t.language === lang);
|
||||
switch (prefs.subtitleMode) {
|
||||
case 'off':
|
||||
subKey = '';
|
||||
break;
|
||||
case 'always':
|
||||
subKey = (inLang.find((t) => !t.forced) ?? inLang[0] ?? subs[0])?.key ?? '';
|
||||
break;
|
||||
case 'forced':
|
||||
subKey = inLang.find((t) => t.forced)?.key ?? '';
|
||||
break;
|
||||
default:
|
||||
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<Item> {
|
||||
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. */
|
||||
|
|
@ -497,7 +326,36 @@ async function applyInitialTracks(tracks: MpvTrack[]) {
|
|||
if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel);
|
||||
}
|
||||
|
||||
const { audioKey, subKey } = preferredTracks(audio, subs, prefs, st.audioKey, st.subKey);
|
||||
// Audio: preferred language, else Plex's selection, else the file default.
|
||||
let audioKey = st.audioKey;
|
||||
if (!audioKey) {
|
||||
const lang = prefs.audioLanguage;
|
||||
audioKey =
|
||||
(lang && audio.find((t) => t.language === lang)?.key) ||
|
||||
audio.find((t) => t.stream?.selected)?.key ||
|
||||
audio.find((t) => t.stream?.default)?.key ||
|
||||
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);
|
||||
switch (prefs.subtitleMode) {
|
||||
case 'off':
|
||||
subKey = '';
|
||||
break;
|
||||
case 'always':
|
||||
subKey = (inLang.find((t) => !t.forced) ?? inLang[0] ?? subs[0])?.key ?? '';
|
||||
break;
|
||||
case 'forced':
|
||||
subKey = inLang.find((t) => t.forced)?.key ?? '';
|
||||
break;
|
||||
default:
|
||||
subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? '';
|
||||
}
|
||||
}
|
||||
usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey });
|
||||
if (direct) {
|
||||
const a = audio.find((t) => t.key === audioKey);
|
||||
|
|
@ -601,7 +459,7 @@ function onEvent(e: MpvEvent) {
|
|||
}
|
||||
break;
|
||||
case 'eof-reached':
|
||||
if (v === true) onStreamEnd();
|
||||
if (v === true) onEnded();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
|
|
@ -622,14 +480,11 @@ function onEvent(e: MpvEvent) {
|
|||
// (Briefly: an unreachable server shouldn't hold up the error.)
|
||||
const failed = session;
|
||||
Promise.race([report('buffering'), new Promise<boolean>((r) => setTimeout(() => r(false), 3000))]).then((terminated) => {
|
||||
const now = usePlayer.getState();
|
||||
if (terminated || !now.open || session !== failed) return;
|
||||
// Partway through a stream that was playing, it's the connection that failed.
|
||||
if (cutShort(now)) return onStreamEnd();
|
||||
if (terminated || !usePlayer.getState().open || session !== failed) return;
|
||||
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
|
||||
fallbackAfterError();
|
||||
});
|
||||
} else if (e.reason === 'eof') onStreamEnd();
|
||||
} else if (e.reason === 'eof') onEnded();
|
||||
break;
|
||||
case 'log':
|
||||
noteMpvLog(e.level, e.prefix, e.text);
|
||||
|
|
@ -638,9 +493,6 @@ 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() {
|
||||
|
|
@ -649,74 +501,14 @@ 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', tracks: currentTracks(st) });
|
||||
st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080' });
|
||||
}
|
||||
|
||||
function maybeCredits(pos: number) {
|
||||
const st = usePlayer.getState();
|
||||
if (st.item?.type !== 'episode' || !st.firstFrame) return;
|
||||
const inCredits = st.item.markers.some((m) => m.type === 'credits' && pos * 1000 >= m.start && pos * 1000 < m.end);
|
||||
// Leaving the credits (seeking back into the episode) re-arms Up Next for the next time they start.
|
||||
if (!inCredits) {
|
||||
if (st.postPlayDismissed && !st.postPlay && !st.ended) usePlayer.setState({ postPlayDismissed: false });
|
||||
} else if (!st.postPlayDismissed) openPostPlay();
|
||||
}
|
||||
|
||||
/**
|
||||
* A streamed title stopping well short of its end means the connection went
|
||||
* (mpv plays out its buffer, then sees the cut-off stream as the end of the file).
|
||||
*/
|
||||
const CUT_SHORT_MARGIN = 15;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
/** Where the last cut-off happened, so a file that really does end early isn't retried forever. */
|
||||
let lastCutAt: number | null = null;
|
||||
|
||||
function cutShort(st: PlayerState) {
|
||||
return st.delivery?.mode !== 'local' && st.firstFrame && st.duration > 0 && st.position < st.duration - CUT_SHORT_MARGIN;
|
||||
}
|
||||
|
||||
/** The stream ran out: a real ending, or a lost connection to wait out. */
|
||||
function onStreamEnd() {
|
||||
const st = usePlayer.getState();
|
||||
if (!cutShort(st)) return onEnded();
|
||||
if (st.reconnecting || st.ended) return;
|
||||
// Cut off at the same place again once the server answered: the file itself ends there.
|
||||
if (lastCutAt !== null && Math.abs(st.position - lastCutAt) < 5) return onEnded();
|
||||
lastCutAt = st.position;
|
||||
usePlayer.setState({ reconnecting: true, buffering: false });
|
||||
keepAwake(false);
|
||||
scheduleReconnect(2000);
|
||||
}
|
||||
|
||||
function stopReconnecting() {
|
||||
if (reconnectTimer) clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
|
||||
function scheduleReconnect(delay: number) {
|
||||
stopReconnecting();
|
||||
reconnectTimer = setTimeout(() => void tryReconnect(), delay);
|
||||
}
|
||||
|
||||
/** Resumes where the stream was cut off if the server answers; otherwise checks again shortly. */
|
||||
async function tryReconnect(): Promise<boolean> {
|
||||
stopReconnecting();
|
||||
const st = usePlayer.getState();
|
||||
const s = server();
|
||||
if (!st.open || !st.reconnecting || !st.item || !s) return false;
|
||||
const reachable = await s.get('/identity', undefined, { timeout: 4000 }).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
const now = usePlayer.getState();
|
||||
if (!now.open || !now.reconnecting || now.item?.id !== st.item.id) return false;
|
||||
if (!reachable) {
|
||||
scheduleReconnect(3000);
|
||||
return false;
|
||||
}
|
||||
usePlayer.setState({ reconnecting: false });
|
||||
await now.play(now.item, { offsetMs: now.position * 1000, mediaIndex: now.mediaIndex, quality: now.quality, tracks: currentTracks(now), keepMini: true });
|
||||
return true;
|
||||
if (st.item?.type !== 'episode' || !st.nextUp || st.countdown !== null) return;
|
||||
const credits = st.item.markers.find((m) => m.type === 'credits' && (m.final || m.end >= st.item!.duration - 5000));
|
||||
if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits !== 'off') startCountdown();
|
||||
}
|
||||
|
||||
function onEnded() {
|
||||
|
|
@ -725,11 +517,7 @@ function onEnded() {
|
|||
usePlayer.setState({ ended: true });
|
||||
report('stopped');
|
||||
checkScrobble();
|
||||
// Reaching the end always offers Up Next, as on Android, even after watching the credits.
|
||||
if (st.item?.type === 'episode' && !st.postPlay) {
|
||||
usePlayer.setState({ postPlayDismissed: false });
|
||||
openPostPlay();
|
||||
}
|
||||
if (st.nextUp) startCountdown();
|
||||
}
|
||||
|
||||
export const usePlayer = create<PlayerState>((set, get) => ({
|
||||
|
|
@ -741,14 +529,12 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
firstFrame: false,
|
||||
error: '',
|
||||
terminated: false,
|
||||
reconnecting: false,
|
||||
position: 0,
|
||||
duration: 0,
|
||||
cacheTime: 0,
|
||||
paused: false,
|
||||
buffering: false,
|
||||
seeking: false,
|
||||
lastSeek: 0,
|
||||
volume: 100,
|
||||
muted: false,
|
||||
speed: 1,
|
||||
|
|
@ -761,11 +547,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
video: null,
|
||||
ended: false,
|
||||
nextUp: null,
|
||||
prevUp: null,
|
||||
episodeContextReady: false,
|
||||
countdown: null,
|
||||
countdownTotal: 0,
|
||||
postPlay: false,
|
||||
postPlayDismissed: false,
|
||||
fullscreen: false,
|
||||
mini: false,
|
||||
|
|
@ -775,8 +557,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
|
||||
async play(input, opts = {}) {
|
||||
const token = ++loadToken;
|
||||
// Closing or starting something else while this one is still setting up wins.
|
||||
const stale = () => token !== loadToken;
|
||||
const s = server();
|
||||
const prefs = useSettings.getState();
|
||||
stopThemeMusic();
|
||||
stopCountdown();
|
||||
|
|
@ -785,29 +566,13 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
return;
|
||||
}
|
||||
const previous = get();
|
||||
stopReconnecting();
|
||||
if (previous.item?.id !== input.id) lastCutAt = null;
|
||||
// The previous title's reporting ends here, against its own server.
|
||||
if (reportTimer) clearInterval(reportTimer);
|
||||
reportTimer = null;
|
||||
if (previous.open && previous.item) {
|
||||
report('stopped');
|
||||
const ps = server();
|
||||
if (previous.delivery?.session && ps) stopTranscode(ps, previous.delivery.session);
|
||||
if (previous.delivery?.session && s) stopTranscode(s, 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;
|
||||
// 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 = fullscreenNow;
|
||||
wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false);
|
||||
}
|
||||
set({
|
||||
open: true,
|
||||
|
|
@ -815,29 +580,23 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
firstFrame: false,
|
||||
error: '',
|
||||
terminated: false,
|
||||
reconnecting: false,
|
||||
position: (opts.offsetMs ?? 0) / 1000,
|
||||
lastSeek: 0,
|
||||
duration: input.duration / 1000,
|
||||
cacheTime: 0,
|
||||
paused: false,
|
||||
buffering: true,
|
||||
ended: false,
|
||||
nextUp: null,
|
||||
prevUp: null,
|
||||
episodeContextReady: false,
|
||||
countdown: null,
|
||||
countdownTotal: 0,
|
||||
postPlay: false,
|
||||
postPlayDismissed: false,
|
||||
chapters: [],
|
||||
audioTracks: [],
|
||||
subTracks: [],
|
||||
audioKey: opts.tracks?.audioKey ?? '',
|
||||
subKey: opts.tracks?.subKey ?? '__init',
|
||||
audioKey: '',
|
||||
subKey: '__init',
|
||||
video: null,
|
||||
fullscreen: fullscreenNow,
|
||||
mini: opts.keepMini ? previous.open && previous.mini : false,
|
||||
fullscreen: wasFullscreenBeforePlay,
|
||||
mini: false,
|
||||
videoGamma: '',
|
||||
enhance: { ...previous.enhance, bypass: false, preparing: false },
|
||||
});
|
||||
|
|
@ -848,16 +607,16 @@ export const usePlayer = create<PlayerState>((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 (stale()) return;
|
||||
if (token !== loadToken) return;
|
||||
const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1));
|
||||
let media = item.media[mediaIndex];
|
||||
const 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);
|
||||
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;
|
||||
session = crypto.randomUUID();
|
||||
sessionAnswered = false;
|
||||
scrobbled = false;
|
||||
|
||||
let delivery: Delivery;
|
||||
if (opts.localFile) {
|
||||
|
|
@ -867,52 +626,30 @@ export const usePlayer = create<PlayerState>((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, audioStreamID, subtitleStreamID: subtitleStreamID || undefined }),
|
||||
url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local }),
|
||||
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,
|
||||
subTracks,
|
||||
...(tracks ?? {}),
|
||||
});
|
||||
|
||||
findNeighbours(item).then((n) => {
|
||||
if (token !== loadToken) return;
|
||||
set({ ...n, episodeContextReady: true });
|
||||
const current = get();
|
||||
if (current.postPlay) startCountdown();
|
||||
else if (current.ended) openPostPlay();
|
||||
else maybeCredits(current.position);
|
||||
audioTracks: streams.filter((x) => x.streamType === 2).map(audioTrackFromStream),
|
||||
subTracks: streams.filter((x) => x.streamType === 3).map(subTrackFromStream),
|
||||
});
|
||||
|
||||
await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough });
|
||||
if (!unlisten) unlisten = await mpv.on(onEvent);
|
||||
if (stale()) return;
|
||||
if (token !== loadToken) return;
|
||||
// mpv keeps pause across files: a title paused and closed would start paused.
|
||||
await mpv.set('pause', false);
|
||||
await mpv.set('mute', false);
|
||||
|
|
@ -920,24 +657,16 @@ export const usePlayer = create<PlayerState>((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);
|
||||
// A file left paused at its end (keep-open) re-pauses as soon as it's unpaused
|
||||
// above, so a reload in place (after an outage) would open paused: unpause again.
|
||||
await mpv.set('pause', false);
|
||||
if (stale()) return;
|
||||
keepAwake(true);
|
||||
report('buffering');
|
||||
reportTimer && clearInterval(reportTimer);
|
||||
|
|
@ -945,6 +674,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
const st = get();
|
||||
if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing');
|
||||
}, 10000);
|
||||
findNext(item).then((next) => token === loadToken && set({ nextUp: next }));
|
||||
} catch (e: any) {
|
||||
if (token !== loadToken) return;
|
||||
set({ error: e?.message ?? String(e), buffering: false });
|
||||
|
|
@ -955,44 +685,25 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
loadToken++;
|
||||
const st = get();
|
||||
stopCountdown();
|
||||
stopReconnecting();
|
||||
lastCutAt = null;
|
||||
if (reportTimer) clearInterval(reportTimer);
|
||||
reportTimer = null;
|
||||
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) {
|
||||
// From the miniplayer window, the video goes home first (and stays hidden).
|
||||
if (separateMini && st.mini) await hideMiniWindow();
|
||||
await mpv.command('stop').catch(() => {});
|
||||
await mpv.show(false).catch(() => {});
|
||||
}
|
||||
set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, reconnecting: false, countdown: null, nextUp: null, prevUp: null, firstFrame: 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);
|
||||
}
|
||||
set({ open: false, mini: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, firstFrame: false });
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false);
|
||||
if (st.item) invalidateLibrary();
|
||||
},
|
||||
|
||||
togglePause() {
|
||||
const st = get();
|
||||
// Play while the server is away: try it now rather than at the next check.
|
||||
if (st.reconnecting) {
|
||||
tryReconnect().then((resumed) => {
|
||||
if (!resumed && get().reconnecting) toast(`Still can’t reach ${server()?.name ?? 'the server'}.`);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (st.ended) {
|
||||
st.seek(0);
|
||||
set({ ended: false });
|
||||
|
|
@ -1003,8 +714,11 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
seek(seconds) {
|
||||
const st = get();
|
||||
const target = Math.max(0, Math.min(seconds, (st.duration || seconds) - 0.5));
|
||||
set({ position: target, ended: false, lastSeek: Date.now() });
|
||||
if (st.postPlay) st.dismissPostPlay();
|
||||
set({ position: target, ended: false });
|
||||
if (st.countdown !== null) {
|
||||
stopCountdown();
|
||||
set({ countdown: null });
|
||||
}
|
||||
mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {});
|
||||
},
|
||||
|
||||
|
|
@ -1040,22 +754,16 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
async minimize() {
|
||||
const st = get();
|
||||
if (!st.open || st.mini) return;
|
||||
if (st.postPlay) st.dismissPostPlay();
|
||||
// Full screen stays for browsing; Esc or the window controls leave it.
|
||||
set({ mini: true });
|
||||
if (separateMini) {
|
||||
// Once the page is opaque again (no video in it), the video moves into
|
||||
// the miniplayer's own window (miniWindow.ts).
|
||||
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
|
||||
if (get().open && get().mini) await showMiniWindow().catch((e) => console.warn('[mini]', e));
|
||||
// Full screen was for the video; browsing goes back to the window.
|
||||
if (st.fullscreen && !wasFullscreenBeforePlay) {
|
||||
await win.setFullscreen(false).catch(() => {});
|
||||
set({ fullscreen: false });
|
||||
}
|
||||
},
|
||||
|
||||
expand() {
|
||||
if (!get().mini) return;
|
||||
// The video comes back behind the still-opaque page before it turns transparent.
|
||||
if (separateMini) hideMiniWindow().finally(() => set({ mini: false }));
|
||||
else set({ mini: false });
|
||||
if (get().mini) set({ mini: false });
|
||||
},
|
||||
|
||||
async selectAudio(key) {
|
||||
|
|
@ -1063,30 +771,35 @@ export const usePlayer = create<PlayerState>((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) {
|
||||
// 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 } });
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality });
|
||||
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, tracks: { ...currentTracks(st), subKey: key } });
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality });
|
||||
usePlayer.setState({ 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, tracks: currentTracks(st) });
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q });
|
||||
},
|
||||
|
||||
async selectVersion(index) {
|
||||
|
|
@ -1099,15 +812,7 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
const st = get();
|
||||
stopCountdown();
|
||||
if (!st.nextUp) return;
|
||||
// Watching on through a season starts each episode from the top, never at a
|
||||
// stale position left by an earlier, unfinished viewing.
|
||||
await st.play(st.nextUp, { resume: false, quality: st.quality });
|
||||
},
|
||||
|
||||
async playPrevious() {
|
||||
const st = get();
|
||||
if (!st.prevUp) return;
|
||||
await st.play(st.prevUp, { resume: false, quality: st.quality });
|
||||
await st.play(st.nextUp, { resume: true, quality: st.quality });
|
||||
},
|
||||
|
||||
cancelCountdown() {
|
||||
|
|
@ -1115,17 +820,6 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
set({ countdown: null, postPlayDismissed: true });
|
||||
},
|
||||
|
||||
showPostPlay() {
|
||||
// A deliberate Skip credits can reopen a screen previously dismissed.
|
||||
set({ postPlayDismissed: false });
|
||||
openPostPlay();
|
||||
},
|
||||
|
||||
dismissPostPlay() {
|
||||
stopCountdown();
|
||||
set({ countdown: null, postPlay: false, postPlayDismissed: true });
|
||||
},
|
||||
|
||||
async toggleFullscreen() {
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
await win.setFullscreen(!fs);
|
||||
|
|
@ -1147,44 +841,13 @@ export const usePlayer = create<PlayerState>((set, get) => ({
|
|||
usePlayer.subscribe((st, prev) => {
|
||||
if (st.firstFrame !== prev.firstFrame || st.open !== prev.open || st.error !== prev.error || st.mini !== prev.mini) {
|
||||
const html = document.documentElement.classList;
|
||||
// With a miniplayer window, the video has left this page entirely.
|
||||
html.toggle('video-active', st.open && st.firstFrame && !st.error && !(st.mini && separateMini));
|
||||
html.toggle('video-active', st.open && st.firstFrame && !st.error);
|
||||
html.toggle('player-open', st.open && !st.mini);
|
||||
html.toggle('player-mini', st.open && st.mini);
|
||||
}
|
||||
// However the miniplayer is left (expanding, playing another title, closing),
|
||||
// the video returns to the whole window.
|
||||
if (prev.mini && !st.mini && isNative) {
|
||||
if (separateMini) hideMiniWindow();
|
||||
else mpv.rect(null).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
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.
|
||||
* 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;
|
||||
if (prev.mini && !st.mini && isNative) mpv.rect(null).catch(() => {});
|
||||
});
|
||||
|
||||
/** Subtitle look changes apply to the playing video straight away. */
|
||||
|
|
|
|||
|
|
@ -121,41 +121,23 @@ export async function plexRequest<T = any>(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<never>((_, 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 {
|
||||
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);
|
||||
}
|
||||
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);
|
||||
} 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 {
|
||||
|
|
|
|||
|
|
@ -39,10 +39,6 @@ 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),
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { parseItem, parseScores } from './parse';
|
|||
import { isLocalAddress } from './account';
|
||||
import { partAt } from './playback';
|
||||
import { headerSafe } from './client';
|
||||
import { duration, formatBadges, isWatched, remaining, resumable, washGradient } from '../app/format';
|
||||
import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format';
|
||||
import { buildFeatures } from '../screens/discover';
|
||||
import type { Hub } from './types';
|
||||
|
||||
|
|
@ -65,16 +65,10 @@ describe('parsing', () => {
|
|||
});
|
||||
|
||||
describe('watched rules', () => {
|
||||
it('keeps a title watched while it is being rewatched', () => {
|
||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(true);
|
||||
it('treats a resumed title as watched only past the threshold', () => {
|
||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false);
|
||||
expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 90)).toBe(true);
|
||||
expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true);
|
||||
expect(resumable(movie({ viewCount: 1, viewOffset: 3000000 }))).toBe(true);
|
||||
});
|
||||
|
||||
it('counts an unplayed title as watched only past the threshold', () => {
|
||||
expect(isWatched(movie({ viewOffset: 3000000 }), 90)).toBe(false);
|
||||
expect(isWatched(movie({ viewOffset: 5700000 }), 90)).toBe(true);
|
||||
expect(isWatched(movie({}), 90)).toBe(false);
|
||||
});
|
||||
|
||||
it('uses episode counts for shows', () => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import * as api from '../plex/api';
|
||||
import { PROGRESS, WATCH_STATE, useSections, useServerQuery } from '../app/queries';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { Hero } from '../ui/Hero';
|
||||
|
|
@ -14,8 +14,8 @@ export function Home() {
|
|||
const sections = useSections();
|
||||
const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden);
|
||||
|
||||
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), WATCH_STATE);
|
||||
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), PROGRESS);
|
||||
const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s));
|
||||
const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), { staleTime: 15_000 });
|
||||
// Section hubs feed the hero and the release shelves; shared with Discover.
|
||||
const sectionHubs = useQuery({
|
||||
queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')],
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
||||
import { useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { goBack, navigate } from '../app/router';
|
||||
import { canManage, itemMenu, openDialog, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
|
||||
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, remainingEpisodes, resolutionLabel, resumable, technicalLine } from '../app/format';
|
||||
import { goBack, navigate, useRouter } from '../app/router';
|
||||
import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions';
|
||||
import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format';
|
||||
import { Backdrop } from '../ui/Backdrop';
|
||||
import { EpisodeCard, Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
|
||||
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader } from '../ui/primitives';
|
||||
import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media';
|
||||
import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { openMenu } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
|
|
@ -255,12 +255,11 @@ function AboutPanel({ item }: { item: Item }) {
|
|||
// —— Movie ——————————————————————————————————————————————————————————
|
||||
|
||||
function MovieDetail({ item }: { item: Item }) {
|
||||
const resume = resumable(item);
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
return (
|
||||
<div className="detail movie">
|
||||
<DetailHero item={item}>
|
||||
{/* The Resume button carries the time left; the facts give the runtime. */}
|
||||
<Facts item={{ ...item, viewOffset: 0 }} />
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
|
|
@ -299,75 +298,115 @@ function MovieDetail({ item }: { item: Item }) {
|
|||
|
||||
// —— Shows and seasons ————————————————————————————————————————————
|
||||
|
||||
function EpisodeGrid({ episodes, upNextId }: { episodes: Item[] | undefined; upNextId?: string }) {
|
||||
if (!episodes) return <PageLoader />;
|
||||
if (!episodes.length) return <EmptyState icon="tv" title="No episodes" />;
|
||||
function EpisodeRow({ ep }: { ep: Item }) {
|
||||
const server = useServer();
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(ep, percent);
|
||||
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
|
||||
return (
|
||||
<div className="episode-grid">
|
||||
{episodes.map((ep) => (
|
||||
<EpisodeCard key={ep.id} item={ep} upNext={ep.id === upNextId} />
|
||||
))}
|
||||
<div
|
||||
className="episode-row"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => openItem(ep)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && openItem(ep)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY });
|
||||
}}
|
||||
>
|
||||
<div className="episode-index">{ep.index || '–'}</div>
|
||||
<div className="episode-pic">
|
||||
<Artwork src={server.image(ep.thumb, 320, 180)} />
|
||||
<button
|
||||
className="episode-play"
|
||||
aria-label={`Play ${ep.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
playWithVersion(ep);
|
||||
}}
|
||||
>
|
||||
<Icon name="play" size={18} />
|
||||
</button>
|
||||
{p > 0 && !watched && (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${p * 100}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="episode-text">
|
||||
<h3>
|
||||
{ep.title}
|
||||
{watched && <Icon name="check" size={15} className="episode-watched" />}
|
||||
</h3>
|
||||
<div className="episode-meta">
|
||||
{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
{ep.summary && <p>{ep.summary}</p>}
|
||||
</div>
|
||||
<button
|
||||
className="icon-btn episode-more"
|
||||
aria-label="More"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openMenu(itemMenu(ep), e.currentTarget);
|
||||
}}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EpisodesSection({ episodes, subtitle, upNextId }: { episodes: Item[] | undefined; subtitle?: string; upNextId?: string }) {
|
||||
function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) {
|
||||
const saved = useRouter((s) => s.current.state.season as string | undefined);
|
||||
const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id);
|
||||
useEffect(() => {
|
||||
if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id);
|
||||
}, [seasons, initialSeason]);
|
||||
const episodes = useChildren(seasonId);
|
||||
const season = seasons.find((s) => s.id === seasonId);
|
||||
if (!seasons.length) return null;
|
||||
return (
|
||||
<section className="episodes">
|
||||
<div className="shelf-head">
|
||||
<h2>
|
||||
Episodes
|
||||
{subtitle && <small>{subtitle}</small>}
|
||||
</h2>
|
||||
<div className="episodes-head">
|
||||
<h2>Episodes</h2>
|
||||
{showPicker && seasons.length > 1 && (
|
||||
<Select
|
||||
value={seasonId!}
|
||||
label="Season"
|
||||
options={seasons.map((s) => ({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
|
||||
onChange={(v) => {
|
||||
setSeasonId(v);
|
||||
useRouter.getState().setState({ season: v });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{season && (
|
||||
<span className="episodes-sub">
|
||||
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{season?.summary && <p className="season-summary">{season.summary}</p>}
|
||||
<div className="episode-list">
|
||||
{episodes.isLoading && <PageLoader />}
|
||||
{episodes.data?.map((ep) => <EpisodeRow key={ep.id} ep={ep} />)}
|
||||
{episodes.data && !episodes.data.length && <EmptyState icon="tv" title="No episodes" />}
|
||||
</div>
|
||||
<EpisodeGrid episodes={episodes} upNextId={upNextId} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** The season's name, which opens a menu of the show's other seasons. */
|
||||
function SeasonSwitcher({ season, seasons }: { season: Item; seasons: Item[] }) {
|
||||
if (seasons.length < 2) return <h1 className="detail-subtitle">{season.title}</h1>;
|
||||
const choose = (e: React.MouseEvent<HTMLButtonElement>) =>
|
||||
openMenu(
|
||||
seasons.map((s) => ({
|
||||
label: s.title,
|
||||
hint: s.leafCount ? `${s.leafCount} episodes` : undefined,
|
||||
checked: s.id === season.id,
|
||||
// Replace, so Back still returns to the show rather than through each season.
|
||||
onSelect: () => s.id !== season.id && navigate({ name: 'item', id: s.id, title: s.title }, { replace: true }),
|
||||
})),
|
||||
e.currentTarget,
|
||||
{ minWidth: 240 },
|
||||
);
|
||||
return (
|
||||
<h1 className="detail-subtitle">
|
||||
<button className="season-switch" aria-haspopup="menu" title="Choose a season" onClick={choose}>
|
||||
{season.title}
|
||||
<Icon name="chevronDown" size={20} strokeWidth={2.4} />
|
||||
</button>
|
||||
</h1>
|
||||
);
|
||||
}
|
||||
|
||||
/** "24 episodes · 8 unwatched", by Plex's own counts so it agrees with the Watched button. */
|
||||
function seasonSubtitle(season: Item) {
|
||||
const count = season.leafCount;
|
||||
if (!count) return '';
|
||||
const left = remainingEpisodes(season);
|
||||
return [`${count} episode${count === 1 ? '' : 's'}`, left > 0 && left < count ? `${left} unwatched` : ''].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
function ShowDetail({ item }: { item: Item }) {
|
||||
const seasons = useChildren(item.id);
|
||||
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), PROGRESS);
|
||||
const server = useServer();
|
||||
const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), { staleTime: 15_000 });
|
||||
const nextEp = next.data;
|
||||
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
|
||||
// A single-season show lists its episodes here instead of one lonely poster.
|
||||
const only = seasonList.length === 1 ? seasonList[0] : undefined;
|
||||
const onlyEpisodes = useChildren(only?.id);
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const playLabel = nextEp ? (resumable(nextEp) ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
||||
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
||||
void server;
|
||||
return (
|
||||
<div className="detail show">
|
||||
<DetailHero item={item}>
|
||||
|
|
@ -385,16 +424,14 @@ function ShowDetail({ item }: { item: Item }) {
|
|||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{/* The button names the episode number; this adds its title, and the time left when resuming. */}
|
||||
{nextEp && (
|
||||
<div className="detail-tech">
|
||||
Up next: {[nextEp.title, resumable(nextEp) ? remaining(nextEp) : ''].filter(Boolean).join(' · ')}
|
||||
Up next: {episodeLabel(nextEp)} · {nextEp.title}
|
||||
</div>
|
||||
)}
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{seasons.isLoading && <PageLoader />}
|
||||
{seasonList.length > 1 && (
|
||||
<Shelf title="Seasons">
|
||||
{seasonList.map((s) => (
|
||||
|
|
@ -402,7 +439,7 @@ function ShowDetail({ item }: { item: Item }) {
|
|||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{only && <EpisodesSection episodes={onlyEpisodes.data} subtitle={seasonSubtitle(only)} upNextId={nextEp?.id} />}
|
||||
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
|
|
@ -415,21 +452,12 @@ function ShowDetail({ item }: { item: Item }) {
|
|||
|
||||
function SeasonDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.parentId);
|
||||
const showItem = show.data;
|
||||
const episodes = useChildren(item.id);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
|
||||
const deck = useServerQuery(['onDeck', item.parentId], (s) => (showItem ? api.onDeckFor(s, showItem) : Promise.resolve(null)), { ...PROGRESS, enabled: !!showItem });
|
||||
const episodes = useChildren(item.id);
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const list = episodes.data ?? [];
|
||||
// The show's up-next episode when it is in this season (so the season page and the
|
||||
// show page agree), else the first one started but never finished, else the first
|
||||
// unwatched, else the start of the season. Positions left by rewatches don't count.
|
||||
const deckHere = deck.data?.parentId === item.id ? list.find((e) => e.id === deck.data!.id) : undefined;
|
||||
const next = deckHere ?? list.find((e) => resumable(e) && !isWatched(e, percent)) ?? list.find((e) => !isWatched(e, percent)) ?? list[0];
|
||||
const resumeNext = !!next && resumable(next) && (next === deckHere || !isWatched(next, percent));
|
||||
const aired = list.find((e) => e.originallyAvailableAt)?.originallyAvailableAt;
|
||||
const year = aired ? new Date(aired).getFullYear() : item.year;
|
||||
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
|
||||
const showItem = show.data;
|
||||
return (
|
||||
<div className="detail season">
|
||||
<DetailHero
|
||||
|
|
@ -444,15 +472,15 @@ function SeasonDetail({ item }: { item: Item }) {
|
|||
) : (
|
||||
<h2 className="title-text small">{item.parentTitle}</h2>
|
||||
)}
|
||||
<SeasonSwitcher season={item} seasons={seasonList} />
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, year, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
||||
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
||||
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next, resumeNext ? {} : { offsetMs: 0, resume: false })}>
|
||||
{next ? `${resumeNext ? 'Resume' : 'Play'} ${episodeLabel(next)}` : 'Play'}
|
||||
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
|
||||
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
|
||||
</Button>
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
|
|
@ -461,7 +489,7 @@ function SeasonDetail({ item }: { item: Item }) {
|
|||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
<EpisodesSection episodes={episodes.data} subtitle={seasonSubtitle(item)} upNextId={resumeNext ? next?.id : undefined} />
|
||||
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
|
||||
{showItem && <CastRow item={showItem} />}
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -472,7 +500,7 @@ function SeasonDetail({ item }: { item: Item }) {
|
|||
function EpisodeDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.grandparentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const resume = resumable(item);
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
const showItem = show.data;
|
||||
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
|
||||
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
|
||||
|
|
@ -495,7 +523,7 @@ function EpisodeDetail({ item }: { item: Item }) {
|
|||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, viewOffset: 0, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
||||
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
|
|
|
|||
|
|
@ -236,33 +236,6 @@ 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<number>();
|
||||
let timer: ReturnType<typeof setTimeout> | 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)));
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { useMemo } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { PROGRESS, useSectionFor, useServerQuery } from '../app/queries';
|
||||
import { useSectionFor, useServerQuery } from '../app/queries';
|
||||
import { navigate, useRouter, type SectionKind, type SectionTab } from '../app/router';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { Section } from '../plex/types';
|
||||
|
|
@ -46,7 +46,7 @@ function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind
|
|||
|
||||
function Discover({ kind, section }: { kind: SectionKind; section: Section }) {
|
||||
const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id));
|
||||
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), PROGRESS);
|
||||
const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), { staleTime: 15_000 });
|
||||
const seasons = useServerQuery(['recentSeasons', section.id], (s) => recentSeasons(s, section.id), { enabled: kind === 'show', staleTime: 120_000 });
|
||||
const features = useMemo(() => buildFeatures(hubs.data ?? [], 7, kind === 'movie' ? 1 : 2), [hubs.data, kind]);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,11 +2,11 @@ import { useEffect, useRef } from 'react';
|
|||
import { useSettings } from '../app/settings';
|
||||
|
||||
/**
|
||||
* The cold-start brand sequence, kept short because desktop startup is quick:
|
||||
* the mark's six facets spin in from a loose ring and snap together with a
|
||||
* ring pulse. If startup is still going, small shards circle the mark. Once
|
||||
* startup is ready the camera flies through the mark's open centre, revealing
|
||||
* the app drawn beneath (which settles from a slight zoom, `html.splash-arrival`).
|
||||
* The cold-start brand sequence: a kaleidoscope. A mirrored field of shards
|
||||
* turns and gathers into the mark's six facets; if startup is still going,
|
||||
* small shards keep circling the mark. Once startup is ready the camera flies
|
||||
* through the mark's open centre, revealing the app drawn beneath (which
|
||||
* settles from a slight zoom, `html.splash-arrival`).
|
||||
*/
|
||||
|
||||
type Point = { x: number; y: number };
|
||||
|
|
@ -51,7 +51,7 @@ const rad = (deg: number) => (deg * Math.PI) / 180;
|
|||
const PALETTE = ['#C3E8D3', '#71B9B0', '#3D7C7B', '#D0A977', '#E9D8AE', '#EEF2DD'];
|
||||
|
||||
// The brand mark's facets, centred on its 64-unit viewport, each with the
|
||||
// outward normal of its hexagon edge and its centroid.
|
||||
// angle of its hexagon edge's outward normal and its centroid.
|
||||
const FACETS = [
|
||||
[33, 4, 55.5, 17, 42.5, 24.5, 33, 19],
|
||||
[56.5, 19, 56.5, 45, 43.5, 37.5, 43.5, 26.5],
|
||||
|
|
@ -63,46 +63,48 @@ const FACETS = [
|
|||
const points: Point[] = [];
|
||||
for (let k = 0; k < pts.length; k += 2) points.push({ x: pts[k] - 32, y: pts[k + 1] - 32 });
|
||||
const centroid = { x: points.reduce((s, p) => s + p.x, 0) / 4, y: points.reduce((s, p) => s + p.y, 0) / 4 };
|
||||
const angle = rad(-60 + 60 * i);
|
||||
return { points, centroid, color: PALETTE[i], normal: { x: Math.cos(angle), y: Math.sin(angle) } };
|
||||
return { points, centroid, color: PALETTE[i], angle: rad(-60 + 60 * i) };
|
||||
});
|
||||
type Facet = (typeof FACETS)[number];
|
||||
|
||||
// Loose shards around each facet: angle offset from the facet's normal, starting
|
||||
// radius (px), size, palette offset and how far they tumble on the way in.
|
||||
const SHARDS = [
|
||||
{ angle: 20, radius: 170, scale: 0.42, color: 2, spin: 1.2 },
|
||||
{ angle: -20, radius: 170, scale: 0.42, color: 4, spin: -1.2 },
|
||||
{ angle: 36, radius: 320, scale: 0.3, color: 3, spin: 2.1 },
|
||||
{ angle: -36, radius: 320, scale: 0.3, color: 1, spin: -2.1 },
|
||||
{ angle: 8, radius: 420, scale: 0.2, color: 5, spin: 3 },
|
||||
{ angle: -8, radius: 420, scale: 0.2, color: 5, spin: -3 },
|
||||
];
|
||||
|
||||
// The inner hexagon traced by the facets' inner edges: the aperture the exit flies through.
|
||||
const INNER_RADIUS = 13.6;
|
||||
const MARK_BOX = 140;
|
||||
// Timeline (ms): the last facet locks at INTRO_END; the sequence then idles until startup is ready.
|
||||
const FACET_STAGGER = 18;
|
||||
const FACET_MS = 350;
|
||||
const INTRO_END = FACET_STAGGER * 5 + FACET_MS;
|
||||
// Still waiting at this point: shards start circling and a sheen crosses the mark.
|
||||
const IDLE_START = 1100;
|
||||
// Keep in step with the `splash-arrival` animation in app.css.
|
||||
const EXIT_MS = 540;
|
||||
// Timeline (ms): the mark has formed at INTRO_END; the sequence then idles until startup is ready.
|
||||
const INTRO_END = 1700;
|
||||
const EXIT_MS = 640;
|
||||
// The mark is larger than the old lockup, so it zooms less to end the flight at the same size.
|
||||
const FLIGHT_ZOOM = 30;
|
||||
|
||||
const INK = '#090a0c';
|
||||
const SEA_GLASS = [113, 185, 176];
|
||||
const LIGHT = [238, 242, 221];
|
||||
const rgba = (c: number[], a: number) => `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${Math.max(0, a)})`;
|
||||
|
||||
/**
|
||||
* Facet `f` around mark centre `o`, `unit` px per grid unit: pushed `out` along its
|
||||
* normal, shrunk and spun about its own centroid, then turned `rot` about the mark centre.
|
||||
*/
|
||||
function facetPath(ctx: CanvasRenderingContext2D, f: Facet, o: Point, unit: number, out = 0, scale = 1, spin = 0, rot = 0) {
|
||||
/** A facet turned `rot` about the mark centre, shrunk and spun about its own centroid, then offset. */
|
||||
function facetPath(ctx: CanvasRenderingContext2D, f: Facet, o: Point, unit: number, rot: number, scale: number, spin: number, offset: Point) {
|
||||
const cr = Math.cos(rot);
|
||||
const sr = Math.sin(rot);
|
||||
const cs = Math.cos(spin);
|
||||
const ss = Math.sin(spin);
|
||||
const cx = f.centroid.x + f.normal.x * out;
|
||||
const cy = f.centroid.y + f.normal.y * out;
|
||||
f.points.forEach((p, i) => {
|
||||
const rx = p.x + f.normal.x * out - cx;
|
||||
const ry = p.y + f.normal.y * out - cy;
|
||||
const x = cx + (rx * cs - ry * ss) * scale;
|
||||
const y = cy + (rx * ss + ry * cs) * scale;
|
||||
const px = o.x + (x * cr - y * sr) * unit;
|
||||
const py = o.y + (x * sr + y * cr) * unit;
|
||||
const rx = p.x - f.centroid.x;
|
||||
const ry = p.y - f.centroid.y;
|
||||
const x = f.centroid.x + (rx * cs - ry * ss) * scale;
|
||||
const y = f.centroid.y + (rx * ss + ry * cs) * scale;
|
||||
const px = o.x + (x * cr - y * sr) * unit + offset.x;
|
||||
const py = o.y + (x * sr + y * cr) * unit + offset.y;
|
||||
if (i === 0) ctx.moveTo(px, py);
|
||||
else ctx.lineTo(px, py);
|
||||
});
|
||||
|
|
@ -140,6 +142,9 @@ function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number,
|
|||
ctx.clearRect(0, 0, w, h);
|
||||
const zoom = q > 0 ? Math.exp(Math.log(FLIGHT_ZOOM) * Flight(q)) : 1;
|
||||
const unit = (MARK_BOX / 64) * zoom;
|
||||
const gather = Emphasized(phase(time, 0, 1450));
|
||||
// The whole field turns a little less than half a revolution as it gathers.
|
||||
const field = rad(-150) * (1 - Emphasized(phase(time, 0, 1550)));
|
||||
|
||||
// The surface: ink everywhere, with the aperture's centre cut away on exit.
|
||||
const hole = InOut(phase(q, 0.12, 0.5));
|
||||
|
|
@ -158,7 +163,25 @@ function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number,
|
|||
ctx.globalAlpha = 1;
|
||||
}
|
||||
|
||||
const bloom = 0.09 * InOut(phase(time, 0, 260)) * (1 - Standard(phase(time, 420, 1100)));
|
||||
// The kaleidoscope's mirror lines, turning with the field.
|
||||
const lines = InOut(phase(time, 0, 450)) * (1 - Standard(phase(time, 1100, 1700)));
|
||||
if (lines > 0) {
|
||||
ctx.lineWidth = 1;
|
||||
for (let s = 0; s < 6; s++) {
|
||||
const a = field + rad(-90 + 60 * s);
|
||||
const end = { x: o.x + Math.cos(a) * 640, y: o.y + Math.sin(a) * 640 };
|
||||
const g = ctx.createLinearGradient(o.x, o.y, end.x, end.y);
|
||||
g.addColorStop(0, rgba(LIGHT, 0.2 * lines));
|
||||
g.addColorStop(1, rgba(LIGHT, 0));
|
||||
ctx.strokeStyle = g;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(o.x, o.y);
|
||||
ctx.lineTo(end.x, end.y);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
const bloom = 0.09 * InOut(phase(time, 200, 1000)) * (1 - Standard(phase(time, 1500, 2600)));
|
||||
if (bloom > 0.001) {
|
||||
ctx.globalCompositeOperation = 'lighter';
|
||||
const g = ctx.createRadialGradient(o.x, o.y, 0, o.x, o.y, 300);
|
||||
|
|
@ -172,36 +195,56 @@ function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number,
|
|||
ctx.globalCompositeOperation = 'source-over';
|
||||
}
|
||||
|
||||
// The six facets spin in from a loose ring and lock into the mark.
|
||||
// Shards spiral inward, faster than the field turns, and vanish into the centre.
|
||||
ctx.globalCompositeOperation = 'screen';
|
||||
const inward = Emphasized(phase(time, 0, 1350));
|
||||
FACETS.forEach((f, s) => {
|
||||
const start = s * FACET_STAGGER;
|
||||
const p = Emphasized(phase(time, start, start + FACET_MS));
|
||||
ctx.globalAlpha = Standard(phase(time, start, start + 160));
|
||||
SHARDS.forEach((d, j) => {
|
||||
const appear = Standard(phase(time, j * 50 + s * 25, j * 50 + s * 25 + 420));
|
||||
const vanish = Standard(phase(time, 750 + j * 45, 1350 + j * 45));
|
||||
if (appear <= 0 || vanish >= 1) return;
|
||||
const a = f.angle + rad(d.angle) + field * 1.5;
|
||||
const r = d.radius * (1 - 0.88 * inward);
|
||||
ctx.globalAlpha = appear * (1 - vanish) * 0.9;
|
||||
ctx.fillStyle = PALETTE[(s + d.color) % 6];
|
||||
ctx.beginPath();
|
||||
shardPath(ctx, f, { x: o.x + Math.cos(a) * r, y: o.y + Math.sin(a) * r }, unit * d.scale * (1 - 0.6 * vanish), field * 2 + d.spin * (1 - gather));
|
||||
ctx.fill();
|
||||
});
|
||||
});
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.globalCompositeOperation = 'source-over';
|
||||
|
||||
// The six facets ride in from the field and lock into the mark.
|
||||
FACETS.forEach((f, s) => {
|
||||
const r = 240 * (1 - gather);
|
||||
const a = f.angle + field;
|
||||
ctx.globalAlpha = Standard(phase(time, s * 25, s * 25 + 420));
|
||||
ctx.fillStyle = f.color;
|
||||
ctx.beginPath();
|
||||
facetPath(ctx, f, o, unit, 7 * (1 - p), mix(0.5, 1, p), rad(-45) * (1 - p), rad(-60) * (1 - p));
|
||||
facetPath(ctx, f, o, unit, field, mix(0.55, 1, gather), rad(-60) * (1 - gather), { x: Math.cos(a) * r, y: Math.sin(a) * r });
|
||||
ctx.fill();
|
||||
});
|
||||
ctx.globalAlpha = 1;
|
||||
|
||||
// A ring pulses out as the facets lock.
|
||||
const pulse = phase(time, 340, 900);
|
||||
const pulse = phase(time, 1380, 2050);
|
||||
if (pulse > 0 && pulse < 1) {
|
||||
ctx.strokeStyle = rgba(SEA_GLASS, 0.45 * (1 - pulse) * (1 - phase(q, 0, 0.3)));
|
||||
ctx.strokeStyle = rgba(SEA_GLASS, 0.45 * (1 - pulse));
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.beginPath();
|
||||
hexagon(ctx, o, (30 + 22 * EmphasizedDecelerate(pulse)) * unit);
|
||||
hexagon(ctx, o, (30 + 24 * EmphasizedDecelerate(pulse)) * unit);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Still starting: small shards circle the mark.
|
||||
const idle = Standard(phase(time, IDLE_START, IDLE_START + 600)) * (1 - phase(q, 0, 0.25));
|
||||
// Still starting: small shards keep circling the mark.
|
||||
const idle = Standard(phase(time, 2300, 2900)) * (1 - phase(q, 0, 0.25));
|
||||
if (idle > 0) {
|
||||
ctx.globalCompositeOperation = 'screen';
|
||||
ctx.globalAlpha = 0.4 * idle;
|
||||
for (let s = 0; s < 6; s++) {
|
||||
for (const side of [-1, 1]) {
|
||||
const a = rad(-60 + 60 * s) + side * rad(11) + (time - IDLE_START) * 0.00032;
|
||||
const a = rad(-60 + 60 * s) + side * rad(11) + (time - 2300) * 0.00032;
|
||||
ctx.fillStyle = PALETTE[(s + (side > 0 ? 2 : 4)) % 6];
|
||||
ctx.beginPath();
|
||||
shardPath(ctx, FACETS[s], { x: o.x + Math.cos(a) * 50 * unit, y: o.y + Math.sin(a) * 50 * unit }, unit * 0.16, a * 2);
|
||||
|
|
@ -212,12 +255,12 @@ function draw(ctx: CanvasRenderingContext2D, w: number, h: number, time: number,
|
|||
ctx.globalCompositeOperation = 'source-over';
|
||||
}
|
||||
|
||||
// While it waits, a band of light crosses the mark every few seconds.
|
||||
const sheen = time < IDLE_START ? 0 : ((time - IDLE_START) % 3600) / 900;
|
||||
// A band of light crosses the settled mark, then again every few seconds while it waits.
|
||||
const sheen = time < 1500 ? 0 : ((time - 1500) % 3600) / 900;
|
||||
if (q === 0 && sheen > 0 && sheen < 1) {
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
FACETS.forEach((f) => facetPath(ctx, f, o, unit));
|
||||
FACETS.forEach((f) => facetPath(ctx, f, o, unit, 0, 1, 0, { x: 0, y: 0 }));
|
||||
ctx.clip();
|
||||
const reach = 40 * unit;
|
||||
const a = rad(36);
|
||||
|
|
@ -291,7 +334,7 @@ export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }
|
|||
cancelAnimationFrame(raf);
|
||||
window.removeEventListener('resize', size);
|
||||
// Let the arrival settle finish after the splash is gone.
|
||||
setTimeout(() => document.documentElement.classList.remove('splash-arrival'), EXIT_MS + 60);
|
||||
setTimeout(() => document.documentElement.classList.remove('splash-arrival'), 700);
|
||||
};
|
||||
}, [reduced]);
|
||||
|
||||
|
|
|
|||
|
|
@ -16,21 +16,26 @@ function shuffled<T>(list: T[], salt = 0): T[] {
|
|||
return out;
|
||||
}
|
||||
|
||||
/** Recently released, highly rated, recently added, start watching, recommended. */
|
||||
const FEATURE_SOURCES: RegExp[] = [/recentlyreleased|recentlyaired/, /topunwatched|toprated/, /recentlyadded/, /startwatching/, /curated|genre|by\.actor|moreingenre/];
|
||||
const FEATURE_SOURCES: [RegExp, string][] = [
|
||||
[/recentlyreleased|recentlyaired/, 'Recently released'],
|
||||
[/topunwatched|toprated/, 'Highly rated'],
|
||||
[/recentlyadded/, 'Recently added'],
|
||||
[/startwatching/, 'Start watching'],
|
||||
[/curated|genre|by\.actor|moreingenre/, 'Recommended'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Features interleave recently released, highly rated unwatched and
|
||||
* Plex-recommended titles; they need artwork and skip in-progress titles.
|
||||
*/
|
||||
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
|
||||
const pools: Feature[][] = FEATURE_SOURCES.map((re) =>
|
||||
const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) =>
|
||||
shuffled(
|
||||
hubs
|
||||
.filter((h) => re.test(h.id))
|
||||
.flatMap((h) => h.items)
|
||||
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
|
||||
.map((item) => ({ item })),
|
||||
.map((item) => ({ item, eyebrow })),
|
||||
salt,
|
||||
),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ const SHORTCUTS: [string, string][][] = [
|
|||
['C', 'Next subtitle track'],
|
||||
['U', 'Cycle upscaling'],
|
||||
['B', 'Compare with enhancement off'],
|
||||
['Shift + P / N', 'Previous / next episode'],
|
||||
['Shift + N', 'Next episode'],
|
||||
['0–9', 'Jump to 0–90%'],
|
||||
['Esc or Backspace', 'Exit full screen, then keep playing in the corner'],
|
||||
],
|
||||
|
|
@ -192,27 +192,14 @@ export function AppSettings({ tab }: { tab: string }) {
|
|||
<Pref label="Skip intros">
|
||||
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Skip movie credits" description="Episodes open Up Next when their credits begin.">
|
||||
<Pref label="Skip credits">
|
||||
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Automatic skip delay" description="How long the button counts down before skipping automatically. Pause, seek or press any key to keep watching instead.">
|
||||
<Select
|
||||
value={s.autoSkipDelay}
|
||||
disabled={s.skipIntro !== 'auto' && s.skipCredits !== 'auto'}
|
||||
onChange={(v) => set('autoSkipDelay', v)}
|
||||
options={[0, 3, 5, 10].map((v) => ({ value: v, label: v ? `${v} seconds` : 'Skip straight away' }))}
|
||||
/>
|
||||
<Pref label="Play the next episode automatically">
|
||||
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
|
||||
</Pref>
|
||||
<Pref label="Autoplay next episode">
|
||||
<Select
|
||||
label="Autoplay next episode"
|
||||
value={s.autoplayNext ? s.countdownSeconds : 0}
|
||||
onChange={(seconds) => {
|
||||
set('autoplayNext', seconds > 0);
|
||||
if (seconds > 0) set('countdownSeconds', seconds);
|
||||
}}
|
||||
options={[{ value: 0, label: 'Off' }, ...[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `After ${v} seconds` }))]}
|
||||
/>
|
||||
<Pref label="Countdown" description="Seconds before the next episode starts.">
|
||||
<Select value={s.countdownSeconds} disabled={!s.autoplayNext} onChange={(v) => set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
<Pref label="Arrow-key seek">
|
||||
<Select value={s.seekStep} onChange={(v) => set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
|
|
|
|||
|
|
@ -270,11 +270,10 @@ html.os-macos:not(.window-fullscreen) .topbar {
|
|||
pointer-events: none;
|
||||
}
|
||||
/* The app beneath settles from a slight zoom as the camera flies through the
|
||||
aperture (held for the first quarter of the exit, then decelerating).
|
||||
The duration matches EXIT_MS in Splash.tsx. */
|
||||
aperture (held for the first quarter of the exit, then decelerating). */
|
||||
html.splash-arrival .app-shell,
|
||||
html.splash-arrival .auth-screen {
|
||||
animation: splash-arrival 540ms linear both;
|
||||
animation: splash-arrival 640ms linear both;
|
||||
}
|
||||
@keyframes splash-arrival {
|
||||
0% {
|
||||
|
|
@ -516,12 +515,6 @@ 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 {
|
||||
|
|
@ -535,42 +528,14 @@ 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: '<color>';
|
||||
inherits: false;
|
||||
initial-value: transparent;
|
||||
}
|
||||
@property --wash-tl {
|
||||
syntax: '<color>';
|
||||
inherits: false;
|
||||
initial-value: transparent;
|
||||
}
|
||||
@property --wash-br {
|
||||
syntax: '<color>';
|
||||
inherits: false;
|
||||
initial-value: transparent;
|
||||
}
|
||||
@property --wash-bl {
|
||||
syntax: '<color>';
|
||||
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;
|
||||
|
|
@ -647,9 +612,11 @@ html.splash-arrival .auth-screen {
|
|||
transform: none;
|
||||
}
|
||||
}
|
||||
/* Scoped so the later `.title-art { margin: 0 }` can't cancel the gap above the facts. */
|
||||
.hero-content .hero-title {
|
||||
margin: 0 0 22px;
|
||||
.hero-eyebrow {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.hero-title {
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
.hero-episode {
|
||||
font-size: 14px;
|
||||
|
|
@ -854,7 +821,6 @@ html.splash-arrival .auth-screen {
|
|||
overflow-y: hidden;
|
||||
scroll-snap-type: x proximity;
|
||||
scroll-padding: 0 var(--gutter);
|
||||
overflow-anchor: none;
|
||||
padding: 4px var(--gutter) 10px;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
|
@ -1093,23 +1059,6 @@ html.splash-arrival .auth-screen {
|
|||
.card.landscape .card-title {
|
||||
font-size: 13px;
|
||||
}
|
||||
.card-title-link {
|
||||
max-width: 100%;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
text-underline-offset: 3px;
|
||||
transition: text-decoration-color var(--t-fast);
|
||||
}
|
||||
.card-title-link:hover {
|
||||
color: #fff;
|
||||
text-decoration-color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
.card-meta {
|
||||
font-size: 11.5px;
|
||||
color: #8a9196;
|
||||
|
|
|
|||
|
|
@ -86,7 +86,7 @@ html.player-mini.video-active .app-shell {
|
|||
visibility: visible;
|
||||
-webkit-mask-image: linear-gradient(#000 0 0), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 90'%3E%3Crect width='160' height='90' rx='3.6'/%3E%3C/svg%3E");
|
||||
-webkit-mask-size: 100% 100%, var(--mini-w) var(--mini-h);
|
||||
-webkit-mask-position: 0 0, right var(--mini-x, var(--mini-gap)) bottom var(--mini-y, var(--mini-gap));
|
||||
-webkit-mask-position: 0 0, right var(--mini-gap) bottom var(--mini-gap);
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
|
|
|
|||
|
|
@ -328,35 +328,17 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
}
|
||||
|
||||
/* Controls */
|
||||
/* Volume and time | playback, centred under the timeline | tracks and window. */
|
||||
.player-controls {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto 1fr;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
justify-content: space-between;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.player-controls-left,
|
||||
.player-controls-center,
|
||||
.player-controls-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
.player-controls-right {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.player-controls-center {
|
||||
gap: 10px;
|
||||
}
|
||||
.player-icon-spacer {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
}
|
||||
.player-icon:disabled {
|
||||
opacity: 0.32;
|
||||
pointer-events: none;
|
||||
}
|
||||
.player-icon {
|
||||
width: 44px;
|
||||
|
|
@ -382,12 +364,11 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
color: var(--accent-strong);
|
||||
}
|
||||
.player-icon.big {
|
||||
width: 54px;
|
||||
height: 54px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
.player-time {
|
||||
margin-left: 8px;
|
||||
white-space: nowrap;
|
||||
margin-left: 12px;
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #f0f2f2;
|
||||
|
|
@ -429,8 +410,6 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
/* Panels */
|
||||
.player-panel {
|
||||
position: absolute;
|
||||
/* Above the skip and post-play cards. */
|
||||
z-index: 2;
|
||||
right: clamp(24px, 3.5vw, 56px);
|
||||
bottom: 84px;
|
||||
min-width: 300px;
|
||||
|
|
@ -659,10 +638,7 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
min-width: 340px;
|
||||
}
|
||||
|
||||
/* The skip button sits above the bottom chrome. */
|
||||
.skip-button {
|
||||
z-index: 1;
|
||||
}
|
||||
/* Skip & post-play */
|
||||
.skip-button {
|
||||
position: absolute;
|
||||
right: clamp(24px, 3.5vw, 56px);
|
||||
|
|
@ -690,272 +666,74 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
background: #f3f5f4;
|
||||
color: #111;
|
||||
}
|
||||
/* An automatic skip fills the button as it counts down. */
|
||||
.skip-button.counting {
|
||||
overflow: hidden;
|
||||
}
|
||||
.skip-button.counting::before {
|
||||
content: '';
|
||||
.post-play {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
width: var(--p, 0%);
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
transition: width 260ms linear;
|
||||
}
|
||||
.skip-button.counting:hover::before {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
.skip-button > * {
|
||||
position: relative;
|
||||
}
|
||||
/* —— Up Next ————————————————————————————————————————————————————————
|
||||
The credits keep playing in the top-left frame: the native video is drawn
|
||||
into its rectangle and the scene has a matching hole (PostPlay.tsx). Only
|
||||
the rows scroll, so the frame never moves. */
|
||||
.up-next {
|
||||
right: clamp(24px, 3.5vw, 56px);
|
||||
bottom: 150px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
--up-top: 64px;
|
||||
--up-video-w: clamp(320px, 34vw, 640px);
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
width: min(520px, calc(100vw - 48px));
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
background: rgba(20, 22, 24, 0.88);
|
||||
backdrop-filter: blur(20px);
|
||||
box-shadow:
|
||||
0 24px 70px rgba(0, 0, 0, 0.6),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.12);
|
||||
animation: rise-in 360ms var(--ease-out);
|
||||
}
|
||||
.up-next-scene {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
isolation: isolate;
|
||||
background: var(--bg);
|
||||
pointer-events: none;
|
||||
}
|
||||
.up-next.placed .up-next-scene {
|
||||
-webkit-mask-image: linear-gradient(#000 0 0), url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 160 90'%3E%3Crect width='160' height='90' rx='2.4'/%3E%3C/svg%3E");
|
||||
-webkit-mask-size: 100% 100%, var(--up-w) var(--up-h);
|
||||
-webkit-mask-position: 0 0, var(--up-x) var(--up-y);
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
-webkit-mask-composite: xor;
|
||||
mask-composite: exclude;
|
||||
}
|
||||
.up-next-backdrop {
|
||||
height: min(78vh, 860px);
|
||||
bottom: auto;
|
||||
}
|
||||
.backdrop-tint.up-next-backdrop {
|
||||
height: 100%;
|
||||
}
|
||||
/* The next episode's details sit over the artwork, so it stays dimmer here
|
||||
than on a title page, with or without the colour wash. */
|
||||
.up-next-backdrop .backdrop-scrim,
|
||||
.up-next-backdrop.washed .backdrop-scrim {
|
||||
background:
|
||||
linear-gradient(90deg, rgba(9, 10, 12, 0.96) 0%, rgba(9, 10, 12, 0.9) 38%, rgba(9, 10, 12, 0.74) 62%, rgba(9, 10, 12, 0.55) 100%),
|
||||
linear-gradient(0deg, var(--bg) 0%, rgba(9, 10, 12, 0.6) 22%, transparent 55%);
|
||||
}
|
||||
.up-next-top {
|
||||
height: 60px;
|
||||
z-index: 3;
|
||||
}
|
||||
.up-next-fullscreen {
|
||||
margin-left: auto;
|
||||
}
|
||||
/* Beside the window's own buttons (Windows, outside full screen), it takes
|
||||
their size and line so the four read as one group. */
|
||||
.up-next-top:has(> .window-controls) .up-next-fullscreen {
|
||||
align-self: flex-start;
|
||||
width: 46px;
|
||||
height: 34px;
|
||||
margin-right: 110px;
|
||||
border-radius: 0;
|
||||
color: #e4e8e9;
|
||||
}
|
||||
.up-next-top:has(> .window-controls) .up-next-fullscreen svg {
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
}
|
||||
.up-next-head {
|
||||
.post-play-art {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: clamp(28px, 3vw, 48px);
|
||||
padding: var(--up-top) var(--gutter) 30px;
|
||||
animation: fade-in 320ms var(--ease);
|
||||
}
|
||||
.up-next-now {
|
||||
flex: none;
|
||||
width: var(--up-video-w);
|
||||
}
|
||||
.up-next-video {
|
||||
display: block;
|
||||
width: 100%;
|
||||
width: 180px;
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.16);
|
||||
transition: box-shadow var(--t-fast);
|
||||
}
|
||||
.up-next-video:hover,
|
||||
.up-next-video:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px #fff;
|
||||
}
|
||||
.up-next-progress {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.up-next-progress-text {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.up-next-progress-text span {
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.up-next-progress-text small {
|
||||
flex: none;
|
||||
font-size: inherit;
|
||||
color: var(--dim);
|
||||
font-variant-numeric: tabular-nums;
|
||||
background: #000;
|
||||
}
|
||||
.up-next-video:hover + .up-next-progress .up-next-progress-text span {
|
||||
color: #fff;
|
||||
}
|
||||
.up-next-progress-bar {
|
||||
height: 3px;
|
||||
margin-top: 8px;
|
||||
border-radius: 3px;
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
overflow: hidden;
|
||||
}
|
||||
.up-next-progress-bar i {
|
||||
display: block;
|
||||
.post-play-art img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
object-fit: cover;
|
||||
}
|
||||
.up-next-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: 680px;
|
||||
padding-top: 6px;
|
||||
text-shadow: 0 1px 12px rgba(0, 0, 0, 0.5);
|
||||
}
|
||||
.up-next-info .micro {
|
||||
display: block;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.up-next-info .up-next-logo {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.up-next-info .title-text {
|
||||
font-size: clamp(26px, 2.4vw, 36px);
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.up-next-info h1 {
|
||||
margin: 0 0 10px;
|
||||
font-size: clamp(20px, 1.7vw, 26px);
|
||||
line-height: 1.2;
|
||||
letter-spacing: -0.025em;
|
||||
font-weight: 680;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.up-next-summary {
|
||||
margin: 14px 0 0;
|
||||
color: #e3e7e9;
|
||||
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6), 0 1px 14px rgba(0, 0, 0, 0.55);
|
||||
font-size: 14px;
|
||||
line-height: 1.62;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
/* The countdown: a lighter fill sweeps across the button, without numbers. */
|
||||
.up-next-play {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
isolation: isolate;
|
||||
margin-top: 22px;
|
||||
text-shadow: none;
|
||||
}
|
||||
.up-next-play.counting,
|
||||
.up-next-play.counting:hover:not(:disabled) {
|
||||
background: #a3a8a9;
|
||||
}
|
||||
.up-next-play-fill {
|
||||
.post-play-ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: -1;
|
||||
background: #f6f7f7;
|
||||
transform: scaleX(0);
|
||||
transform-origin: left;
|
||||
will-change: transform;
|
||||
margin: auto;
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
.up-next-play:focus-visible {
|
||||
outline: 2px solid #fff;
|
||||
outline-offset: 3px;
|
||||
.post-play-ring circle {
|
||||
fill: rgba(0, 0, 0, 0.45);
|
||||
stroke: #fff;
|
||||
stroke-width: 3;
|
||||
stroke-dasharray: 107;
|
||||
animation: ring 8s linear forwards;
|
||||
}
|
||||
.up-next-rows {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
padding-bottom: 12px;
|
||||
animation: fade-in 420ms var(--ease);
|
||||
}
|
||||
.up-next-shelf {
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
/* Cards are sized from the space below the header, so the season and related
|
||||
rows fill it (--up-row: a row's height besides its artwork). In a short,
|
||||
wide window they keep a sensible size and the related row runs off the
|
||||
bottom, as on Android TV. */
|
||||
.up-next-rows {
|
||||
container-type: size;
|
||||
--up-row: 128px;
|
||||
}
|
||||
.up-next-shelf .shelf .card.landscape {
|
||||
width: clamp(15vw, calc((50cqh - var(--up-row)) * 16 / 9), 26vw);
|
||||
}
|
||||
@media (max-width: 1333px) {
|
||||
.up-next-shelf .shelf .card.landscape {
|
||||
width: clamp(200px, calc((50cqh - var(--up-row)) * 16 / 9), 26vw);
|
||||
@keyframes ring {
|
||||
from {
|
||||
stroke-dashoffset: 107;
|
||||
}
|
||||
to {
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
}
|
||||
.up-next-shelf .card {
|
||||
scroll-margin-left: 0;
|
||||
.post-play-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
@media (max-height: 760px) {
|
||||
.up-next-head {
|
||||
padding-bottom: 20px;
|
||||
}
|
||||
.up-next-info .micro {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.up-next-info .up-next-logo {
|
||||
height: 44px !important;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.up-next-info .up-next-logo img {
|
||||
max-height: 44px !important;
|
||||
}
|
||||
.up-next-summary {
|
||||
-webkit-line-clamp: 2;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.up-next-play {
|
||||
margin-top: 16px;
|
||||
}
|
||||
.up-next-shelf {
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.post-play-text b {
|
||||
font-size: 14px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.up-next .card:focus-visible {
|
||||
outline: none;
|
||||
.post-play-text .actions {
|
||||
margin-top: 6px;
|
||||
}
|
||||
.player-error {
|
||||
position: absolute;
|
||||
|
|
@ -987,11 +765,10 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
--mini-h: calc(var(--mini-w) * 9 / 16);
|
||||
--mini-gap: 24px;
|
||||
}
|
||||
/* --mini-x/-y: where it was dragged to, from the right and bottom (PlayerOverlay). */
|
||||
.mini-player {
|
||||
position: fixed;
|
||||
right: var(--mini-x, var(--mini-gap));
|
||||
bottom: var(--mini-y, var(--mini-gap));
|
||||
right: var(--mini-gap);
|
||||
bottom: var(--mini-gap);
|
||||
z-index: 600;
|
||||
width: var(--mini-w);
|
||||
height: var(--mini-h);
|
||||
|
|
@ -1004,9 +781,6 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
.mini-player.loading {
|
||||
background: #000;
|
||||
}
|
||||
.mini-player.dragging {
|
||||
cursor: grabbing;
|
||||
}
|
||||
/* Opacity only: the video beneath can't follow a transform. */
|
||||
@keyframes mini-in {
|
||||
from {
|
||||
|
|
@ -1030,8 +804,6 @@ html.os-macos:not(.window-fullscreen) .player-top {
|
|||
.mini-player:hover .mini-top,
|
||||
.mini-player:hover .mini-center,
|
||||
.mini-player:hover .mini-caption,
|
||||
.mini-player.dragging .mini-scrim,
|
||||
.mini-player.dragging .mini-caption,
|
||||
.mini-player.loading .mini-center,
|
||||
.mini-player:focus-within .mini-top,
|
||||
.mini-player:focus-within .mini-center {
|
||||
|
|
|
|||
|
|
@ -430,30 +430,6 @@ button.chip:hover {
|
|||
letter-spacing: -0.035em;
|
||||
font-weight: 700;
|
||||
}
|
||||
.season-switch {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-left: -8px;
|
||||
padding: 2px 6px 2px 8px;
|
||||
border-radius: 8px;
|
||||
font: inherit;
|
||||
letter-spacing: inherit;
|
||||
transition: background var(--t-fast);
|
||||
}
|
||||
.season-switch svg {
|
||||
color: #aeb5b8;
|
||||
transition:
|
||||
color var(--t-fast),
|
||||
transform var(--t-fast);
|
||||
}
|
||||
.season-switch:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.season-switch:hover svg {
|
||||
color: #fff;
|
||||
transform: translateY(1px);
|
||||
}
|
||||
.synopsis-wrap {
|
||||
max-width: 640px;
|
||||
}
|
||||
|
|
@ -604,29 +580,122 @@ button.chip:hover {
|
|||
}
|
||||
/* Episodes */
|
||||
.episodes {
|
||||
margin-bottom: 34px;
|
||||
margin-bottom: 36px;
|
||||
}
|
||||
.episodes .shelf-head {
|
||||
padding: 0;
|
||||
.episodes-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.episode-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(clamp(240px, 19vw, 320px), 1fr));
|
||||
gap: 30px 16px;
|
||||
.episodes-head h2 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
letter-spacing: -0.028em;
|
||||
}
|
||||
.episode-grid .card {
|
||||
.episodes-sub {
|
||||
color: var(--dim);
|
||||
font-size: 12px;
|
||||
}
|
||||
.season-summary {
|
||||
color: #aeb5b8;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
max-width: 760px;
|
||||
margin: 4px 0 8px;
|
||||
}
|
||||
.episode-row {
|
||||
scroll-margin: 96px 0 48px;
|
||||
display: grid;
|
||||
grid-template-columns: 34px 220px minmax(0, 1fr) 40px;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
padding: 16px 12px 16px 6px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: background var(--t-fast);
|
||||
}
|
||||
.episode-card-summary {
|
||||
margin: 7px 0 0;
|
||||
.episode-row:hover,
|
||||
.episode-row:focus-visible {
|
||||
background: rgba(255, 255, 255, 0.045);
|
||||
}
|
||||
.episode-row:focus-visible {
|
||||
outline: 2px solid #f2f5f4;
|
||||
outline-offset: 0;
|
||||
}
|
||||
.episode-index {
|
||||
font-size: 22px;
|
||||
font-weight: 650;
|
||||
color: #8a9196;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.episode-pic {
|
||||
position: relative;
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background: #1c2024;
|
||||
}
|
||||
.episode-pic .artwork {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
.episode-play {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
margin: -21px 0 0 -21px;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(255, 255, 255, 0.92);
|
||||
color: #121314;
|
||||
opacity: 0;
|
||||
transform: scale(0.9);
|
||||
transition:
|
||||
opacity var(--t),
|
||||
transform var(--t) var(--ease-out);
|
||||
}
|
||||
.episode-row:hover .episode-play {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
.episode-text h3 {
|
||||
font-size: 14px;
|
||||
margin: 0 0 4px;
|
||||
font-weight: 640;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.episode-watched {
|
||||
color: #9fd6bb;
|
||||
}
|
||||
.episode-meta {
|
||||
font-size: 11.5px;
|
||||
color: #8a9196;
|
||||
margin-bottom: 7px;
|
||||
}
|
||||
.episode-text p {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
color: #a1a8ac;
|
||||
color: #a8afb3;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 3;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.episode-more {
|
||||
opacity: 0;
|
||||
}
|
||||
.episode-row:hover .episode-more {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* —— Search ————————————————————————————————————————————————— */
|
||||
.search-hero {
|
||||
|
|
@ -1976,6 +2045,10 @@ button.chip:hover {
|
|||
.download-intro {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.episode-row {
|
||||
grid-template-columns: 26px 160px minmax(0, 1fr) 36px;
|
||||
gap: 14px;
|
||||
}
|
||||
.history-row {
|
||||
grid-template-columns: 36px minmax(0, 1fr) 120px 90px;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,21 @@
|
|||
import { useEffect, useRef, useState, type CSSProperties } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { Item } from '../plex/types';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { art, washColors } from '../app/format';
|
||||
import { art, washGradient } from '../app/format';
|
||||
|
||||
interface Layer {
|
||||
key: number;
|
||||
src: string;
|
||||
blur: Item['ultraBlur'];
|
||||
wash: string;
|
||||
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. 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).
|
||||
* page beneath it and carries on down behind the rows. Changes crossfade; the
|
||||
* outgoing layer stays until the new image has decoded.
|
||||
*/
|
||||
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();
|
||||
|
|
@ -29,50 +25,39 @@ 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 blurKey = blur ? `${blur.topLeft}${blur.topRight}${blur.bottomRight}${blur.bottomLeft}` : '';
|
||||
const wash = colorWash && blur ? washGradient(blur) : '';
|
||||
|
||||
useEffect(() => {
|
||||
if (!src && !blur) return;
|
||||
if (!src && !wash) return;
|
||||
setLayers((prev) => {
|
||||
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 }];
|
||||
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 }];
|
||||
});
|
||||
}, [src, blurKey]);
|
||||
}, [src, wash]);
|
||||
|
||||
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;
|
||||
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;
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
{colorWash && (
|
||||
<div className={`backdrop-tint ${className}`} aria-hidden="true">
|
||||
<div className="backdrop-wash" style={washStyle} />
|
||||
{layers.map((l) => l.wash && <div key={l.key} className={`backdrop-wash${l.ready ? ' ready' : ''}`} style={{ background: l.wash }} />)}
|
||||
</div>
|
||||
)}
|
||||
<div className={`backdrop ${className}${colorWash ? ' washed' : ''}`} aria-hidden="true">
|
||||
{layers.map((l, i) => (
|
||||
<div key={l.key} className={`backdrop-layer${l.ready ? ' ready' : ''}${i < top ? ' leaving' : ''}`}>
|
||||
{layers.map((l) => (
|
||||
<div key={l.key} className={`backdrop-layer${l.ready ? ' ready' : ''}`}>
|
||||
{l.src && <img className="backdrop-art" src={l.src} alt="" draggable={false} decoding="async" onLoad={() => onReady(l.key)} onError={() => onReady(l.key)} />}
|
||||
</div>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ const ROTATE_MS = 8000;
|
|||
|
||||
export interface Feature {
|
||||
item: Item;
|
||||
eyebrow: string;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -43,14 +44,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 || !visible) return;
|
||||
if (!rotate || reduced || count < 2 || hover) return;
|
||||
const t = setTimeout(() => go(index + 1), ROTATE_MS);
|
||||
return () => clearTimeout(t);
|
||||
}, [index, rotate, reduced, count, hover, visible]);
|
||||
}, [index, rotate, reduced, count, hover]);
|
||||
|
||||
// Pause rotation when the hero is scrolled away.
|
||||
const [visible, setVisible] = useState(true);
|
||||
useEffect(() => {
|
||||
const el = root.current;
|
||||
if (!el) return;
|
||||
|
|
@ -60,6 +61,7 @@ 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);
|
||||
};
|
||||
|
|
@ -73,6 +75,7 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari
|
|||
<section ref={root} className={`hero ${variant}`} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
|
||||
<Backdrop item={item} className="hero-backdrop" />
|
||||
<div className="hero-content" key={copyKey}>
|
||||
<div className="micro hero-eyebrow">{feature.eyebrow}</div>
|
||||
<TitleArt item={item} className="hero-title" maxWidth={variant === 'home' ? 420 : 380} maxHeight={variant === 'home' ? 128 : 108} />
|
||||
{item.type === 'episode' && (
|
||||
<div className="hero-episode">
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ const PATHS: Record<string, string> = {
|
|||
arrowLeft: '<path d="M19 12H5m6-6-6 6 6 6"/>',
|
||||
play: '<path d="M7 4.8v14.4a.8.8 0 0 0 1.2.7l11.6-7.2a.8.8 0 0 0 0-1.4L8.2 4.1a.8.8 0 0 0-1.2.7Z" fill="currentColor" stroke="none"/>',
|
||||
pause: '<rect x="6" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/><rect x="14" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/>',
|
||||
stop: '<rect x="5.5" y="5.5" width="13" height="13" rx="1.6" fill="currentColor" stroke="none"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
minus: '<path d="M5 12h14"/>',
|
||||
check: '<path d="m5 12.5 4.2 4.2L19 7"/>',
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
import { memo, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { memo, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { Item } from '../plex/types';
|
||||
import { useServer, useSession } from '../app/session';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { art, date, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format';
|
||||
import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format';
|
||||
import { itemMenu, openItem, playWithVersion } from '../app/actions';
|
||||
import { navigate } from '../app/router';
|
||||
import { Artwork } from './primitives';
|
||||
import { Icon } from './Icon';
|
||||
import { openMenu } from './overlays';
|
||||
|
|
@ -91,8 +90,7 @@ 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' }) {
|
||||
// The player shows this offline too, where there is no server to draw the logo from.
|
||||
const server = useSession((s) => s.server);
|
||||
const server = useServer();
|
||||
const path = logo ?? item.logo;
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
|
|
@ -101,7 +99,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 || !server)
|
||||
if (!path || failed)
|
||||
return (
|
||||
<As className={`title-text ${className}`} style={{ maxWidth: maxWidth * 1.4 }}>
|
||||
{title}
|
||||
|
|
@ -142,14 +140,9 @@ function WatchBadge({ item }: { item: Item }) {
|
|||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A watched title's leftover position (from an unfinished rewatch) only shows where it's
|
||||
* what you're resuming: Continue Watching, or the season's up-next episode.
|
||||
*/
|
||||
function ProgressLine({ item, always = false }: { item: Item; always?: boolean }) {
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
function ProgressLine({ item }: { item: Item }) {
|
||||
const p = progress(item);
|
||||
if (!p || p > 0.995 || (!always && isWatched(item, percent))) return null;
|
||||
if (!p || p > 0.995) return null;
|
||||
return (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${Math.max(3, p * 100)}%` }} />
|
||||
|
|
@ -210,15 +203,12 @@ export const PosterCard = memo(function PosterCard({ item, caption = 'year', cla
|
|||
const server = useServer();
|
||||
const handlers = useCardHandlers(item);
|
||||
const path = art.poster(item);
|
||||
// On its show's page a season is just "Season 2"; anywhere else it needs the show's name.
|
||||
const seasonAlone = item.type === 'season' && caption !== 'episodes' && !!item.parentTitle;
|
||||
const title = item.type === 'season' && !seasonAlone ? item.title : displayTitle(item);
|
||||
let meta: ReactNode = null;
|
||||
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? item.title : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
|
||||
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? (item.leafCount ? `${item.leafCount} episodes` : '') : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
|
||||
if (caption === 'episodes') meta = item.leafCount ? `${item.leafCount} episodes` : '';
|
||||
if (caption === 'role') meta = (item as any).roleName ?? item.year;
|
||||
return (
|
||||
<article className={`card poster ${className}`} role="button" tabIndex={0} aria-label={seasonAlone ? `${title}, ${item.title}` : title} {...handlers} {...previewHandlers(item)}>
|
||||
<article className={`card poster ${className}`} role="button" tabIndex={0} aria-label={item.title} {...handlers} {...previewHandlers(item)}>
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(path, 240, 360)} alt="" fallback={<span className="cover-fallback">{displayTitle(item)}</span>} />
|
||||
<div className="card-hover" />
|
||||
|
|
@ -228,8 +218,8 @@ export const PosterCard = memo(function PosterCard({ item, caption = 'year', cla
|
|||
</div>
|
||||
{caption !== 'none' && (
|
||||
<div className="card-caption">
|
||||
<div className="card-title" title={title}>
|
||||
{title}
|
||||
<div className="card-title" title={item.type === 'season' ? item.title : displayTitle(item)}>
|
||||
{item.type === 'season' ? item.title : displayTitle(item)}
|
||||
</div>
|
||||
{meta ? <div className="card-meta">{meta}</div> : null}
|
||||
</div>
|
||||
|
|
@ -241,16 +231,14 @@ export const PosterCard = memo(function PosterCard({ item, caption = 'year', cla
|
|||
export const LandscapeCard = memo(function LandscapeCard({ item, continueWatching, showTitle = true, episodeStyle = false }: { item: Item; continueWatching?: boolean; showTitle?: boolean; episodeStyle?: boolean }) {
|
||||
const server = useServer();
|
||||
const handlers = useCardHandlers(item, { continueWatching });
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const inProgress = !!item.viewOffset && (continueWatching || !isWatched(item, percent));
|
||||
const isEp = item.type === 'episode';
|
||||
const path = isEp ? item.thumb || item.grandparentArt : art.landscape(item);
|
||||
const title = episodeStyle && isEp ? `${item.index}. ${item.title}` : displayTitle(item);
|
||||
const meta = isEp
|
||||
? episodeStyle
|
||||
? [duration(item.duration), inProgress ? remaining(item) : ''].filter(Boolean).join(' · ')
|
||||
? [duration(item.duration), item.viewOffset ? remaining(item) : ''].filter(Boolean).join(' · ')
|
||||
: `${episodeLabel(item)} ${item.title}`
|
||||
: inProgress
|
||||
: item.viewOffset
|
||||
? remaining(item)
|
||||
: [item.year, duration(item.duration)].filter(Boolean).join(' · ');
|
||||
return (
|
||||
|
|
@ -265,25 +253,12 @@ export const LandscapeCard = memo(function LandscapeCard({ item, continueWatchin
|
|||
<div className="card-hover" />
|
||||
<CardActions item={item} ctx={{ continueWatching }} />
|
||||
{episodeStyle && <WatchBadge item={item} />}
|
||||
<ProgressLine item={item} always={continueWatching} />
|
||||
<ProgressLine item={item} />
|
||||
</div>
|
||||
{showTitle && (
|
||||
<div className="card-caption">
|
||||
<div className="card-title" title={title}>
|
||||
{isEp && !episodeStyle && item.grandparentId ? (
|
||||
<button
|
||||
className="card-title-link"
|
||||
tabIndex={-1}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
navigate({ name: 'item', id: item.grandparentId, title: item.grandparentTitle });
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</button>
|
||||
) : (
|
||||
title
|
||||
)}
|
||||
{title}
|
||||
</div>
|
||||
<div className="card-meta">{meta}</div>
|
||||
</div>
|
||||
|
|
@ -292,34 +267,6 @@ export const LandscapeCard = memo(function LandscapeCard({ item, continueWatchin
|
|||
);
|
||||
});
|
||||
|
||||
/** An episode with its synopsis, for a season's episode grid. `upNext` shows its resume point even when watched. */
|
||||
export const EpisodeCard = memo(function EpisodeCard({ item, upNext = false }: { item: Item; upNext?: boolean }) {
|
||||
const server = useServer();
|
||||
const handlers = useCardHandlers(item);
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const inProgress = !!item.viewOffset && (upNext || !isWatched(item, percent));
|
||||
const title = item.index ? `${item.index}. ${item.title}` : item.title;
|
||||
const meta = [duration(item.duration), inProgress ? remaining(item) : date(item.originallyAvailableAt)].filter(Boolean).join(' · ');
|
||||
return (
|
||||
<article className="card landscape episode-card" role="button" tabIndex={0} aria-label={title} {...handlers}>
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(item.thumb || item.grandparentArt, 400, 225)} alt="" fallback={<span className="cover-fallback">{title}</span>} />
|
||||
<div className="card-hover" />
|
||||
<CardActions item={item} />
|
||||
<WatchBadge item={item} />
|
||||
<ProgressLine item={item} always={upNext} />
|
||||
</div>
|
||||
<div className="card-caption">
|
||||
<div className="card-title" title={title}>
|
||||
{title}
|
||||
</div>
|
||||
<div className="card-meta">{meta}</div>
|
||||
{item.summary && <p className="episode-card-summary">{item.summary}</p>}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
});
|
||||
|
||||
export function PersonCard({ name, role, thumb, onClick }: { name: string; role?: string; thumb?: string; onClick?: () => void }) {
|
||||
const server = useServer();
|
||||
const initials = name
|
||||
|
|
@ -342,22 +289,15 @@ export function PersonCard({ name, role, thumb, onClick }: { name: string; role?
|
|||
|
||||
export function Shelf({ title, subtitle, onViewAll, children, className = '', kind = 'poster' }: { title: ReactNode; subtitle?: ReactNode; onViewAll?: () => void; children: ReactNode; className?: string; kind?: 'poster' | 'landscape' | 'people' | 'wide' }) {
|
||||
const row = useRef<HTMLDivElement>(null);
|
||||
const atStart = useRef(true);
|
||||
const [edges, setEdges] = useState({ start: true, end: false });
|
||||
const update = () => {
|
||||
const el = row.current;
|
||||
if (!el) return;
|
||||
const start = el.scrollLeft < 8;
|
||||
const end = el.scrollLeft + el.clientWidth >= el.scrollWidth - 8;
|
||||
atStart.current = start;
|
||||
// Runs on every scroll event; re-render only when an edge changes.
|
||||
setEdges((prev) => (prev.start === start && prev.end === end ? prev : { start, end }));
|
||||
};
|
||||
// A row the viewer hasn't scrolled stays at its start when items are added
|
||||
// in front (Continue Watching), rather than holding on to the old first card.
|
||||
useLayoutEffect(() => {
|
||||
if (atStart.current && row.current) row.current.scrollLeft = 0;
|
||||
}, [children]);
|
||||
useEffect(() => {
|
||||
update();
|
||||
const el = row.current;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
{
|
||||
"version": "1.0.1",
|
||||
"notes": "A quicker start, a Stop button, and recovery when the server drops out mid-video.\r\n\r\n- Kaleido starts faster: the opening animation is shorter, so you reach your library in about a second.\r\n- The player has a Stop button, next to the forward controls, which closes the player completely instead of moving it to the miniplayer.\r\n- If your Plex server goes down while you're watching, the player waits for it once the buffered video runs out, then carries on from the same spot when the server is back. Before, it treated the video as finished and Play started it again from the beginning. Pressing Play while it waits tries to reconnect straight away.",
|
||||
"pub_date": "2026-11-17T17:47:20.996Z",
|
||||
"version": "0.1.0-beta.8",
|
||||
"notes": "Kaleido for Mac.\n\n- Kaleido now runs on Macs with Apple silicon (macOS 26 or later), with the same interface and features as on Windows: browsing, playback with hardware decoding, the miniplayer, downloads, server management and in-app updates. The window uses the Mac's own close, minimize and zoom buttons, which fade with the player's controls, and shortcuts use ⌘ (⌘K to search, ⌘[ to go back, ⌃⌘F for full screen).\n- HDR passthrough works on Mac too: HDR titles play in the display's extended dynamic range instead of being converted to SDR.\n- Each release now includes both the Windows and Mac versions.\n- Updates are signed with a new key, so the Windows version needs to be reinstalled once from this release; later updates install in the app as before.",
|
||||
"pub_date": "2026-11-02T22:24:31.764Z",
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFZMQVRPVll0SHZPQWJWUlIyQnZEME10bldKUnYxSkhHWEJSWWxOT3FoVHp6NlNsU0dwdlg1UmUweGlEdzNoQnduSnora0dZempZS2ZWdFZLa3BIRkFJPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzk0OTM3NjI5CWZpbGU6S2FsZWlkb18xLjAuMV94NjQtc2V0dXAuZXhlCXZlcnNpb246MS4wLjEKeUI5aUJ4d3hONmVlNlBBWDFxQkFkYTV4WXU0eHIzb1ZKaVZjaDhpODhpbXdvL2RWRlhTRTBwQXJGV3hJYlg2RERnMDBhSFBRWHZDekxCRTVNNCtIRFE9PQo=",
|
||||
"url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v1.0.1/Kaleido_1.0.1_x64-setup.exe"
|
||||
"darwin-aarch64": {
|
||||
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFE4NFdjWGFlNEZCRTExTTVVdkgrRTUvTXRmbVBsNE9ZVW11NXkwME1ZNkt1UzdGb3FzdW9oTWdLLzU3UWhyMSs3TTVjYXBoSTJnRysyVmR5SE4xVVFZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjU4MTgyCWZpbGU6S2FsZWlkby5hcHAudGFyLmd6CXZlcnNpb246MC4xLjAtYmV0YS44CmxXOHA2NDVPL3JDMWtuQmdhTGNDNHRZOHBwdjFmSGg5V3o1V2tRMUdDRFp4cVg2M1dFUXVIMmdNWm5VMHBaT2xZSDh6RFdSUkpUcjZQbEp4bk5PZUNnPT0K",
|
||||
"url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.8/Kaleido_0.1.0-beta.8_aarch64.app.tar.gz"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,10 +34,5 @@ export default defineConfig({
|
|||
plugins: [react(), devSession()],
|
||||
clearScreen: false,
|
||||
server: { port: 1420, strictPort: true, watch: { ignored: ['**/src-tauri/**'] } },
|
||||
build: {
|
||||
target: 'es2022',
|
||||
chunkSizeWarningLimit: 1500,
|
||||
// The miniplayer window has a page of its own (src/mini/).
|
||||
rollupOptions: { input: { main: path.resolve(import.meta.dirname, 'index.html'), mini: path.resolve(import.meta.dirname, 'mini.html') } },
|
||||
},
|
||||
build: { target: 'es2022', chunkSizeWarningLimit: 1500 },
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue