Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

fix(tui): downgrade named themes on basic terminals and parallelize sidecar launch

Samir Hossainsf16521add6e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5a49f2c..0d10903 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,28 +4,30 @@
### Fixed
- **Media Playback & Subtitle Engine**:
- - Preserved native Windows `\` path separators for `--sub-file` in VLC (`C:\...`) and passed `--no-one-instance` on Windows/Linux so open VLC windows do not strip subtitle, header, or resume flags.
- - Stripped query strings and fragments before parsing subtitle extensions (`.srt`, `.vtt`, `.ass`, `.ssa`, `.sub`), preventing signed CloudFront/OSS URLs from saving as `.srt` or injecting mismatched DASH MIME types.
- - Pre-downloaded subtitles locally for `mpv` with remote URL fallback, appended an 8-char URL hash to subtitle filenames to prevent cross-language overwrites, and sanitized commas in `--script-opts`.
- - Mounted `xdg-cache/moviebox-tui:ro`, `xdg-data/moviebox-tui`, and `/tmp:ro` in `flatpak run` while preserving custom user Flatpak flags so sandboxed `mpv` and `VLC` can read subtitles and write watch progress.
- - Served Termux private-storage subtitles over the local `StreamRelay` `/sub/` loopback endpoint when Android shared storage is unavailable, and restricted startup subtitle cleanup to internal cache/temp folders.
- - Parsed player `stderr` and exit diagnostics to surface exact failure reasons (`HTTP 403`, `HTTP 404`, `HTTP 410`, timeout, connection refused) instead of vague guesses.
+ - Preserved native Windows `\` path separators for `--sub-file` in VLC (`C:\...`) and passed `--no-one-instance` on Windows and Linux so running VLC windows keep subtitle, header, and resume flags.
+ - Stripped query strings and fragments before parsing subtitle extensions (`.srt`, `.vtt`, `.ass`, `.ssa`, `.sub`) so signed CloudFront and OSS URLs keep their true format and DASH MIME type.
+ - Pre-downloaded subtitles locally for `mpv` with remote URL fallback, parallelized subtitle downloads with `StreamRelay` sidecar startup, appended an 8-char URL hash to subtitle filenames, and sanitized commas in `--script-opts`.
+ - Mounted `xdg-cache/moviebox-tui:ro`, `xdg-data/moviebox-tui`, and `/tmp:ro` in `flatpak run` while keeping custom user Flatpak flags so sandboxed `mpv` and `VLC` can read subtitles and write watch progress.
+ - Served Termux private-storage subtitles over the local `StreamRelay` `/sub/` loopback endpoint when Android shared storage is unavailable, and restricted startup subtitle cleanup to internal cache and temp folders.
+ - Parsed player `stderr` and exit codes to report specific failure reasons (`HTTP 403`, `HTTP 404`, `HTTP 410`, timeout, connection refused).
- **StreamRelay Proxy & Downloader**:
- - Forwarded `User-Agent` and `Referer` while isolating stream cookies (`Cookie: Edge-Cache-Cookie=...`) to same-host requests across `StreamRelay`, subtitle pre-downloads, and media downloads, preventing HTTP 403 CDN rejections.
- - Capped `.m4s` segment chunk fetching in `StreamRelay` to batches of 16 concurrent `Range` requests and enforced `http://` / `https://` scheme validation on `/proxy?url=` routes.
- - Reported exact subtitle and DASH download errors (HTTP status, timeout, missing `yt-dlp` vs `ffmpeg`) and guarded `yt-dlp` progress parsing against out-of-order status tokens.
+ - Forwarded `User-Agent` and `Referer` while isolating stream cookies (`Cookie: Edge-Cache-Cookie=...`) to same-host requests across `StreamRelay`, subtitle pre-downloads, and media downloads.
+ - Capped `.m4s` segment chunk fetching in `StreamRelay` to batches of 16 concurrent `Range` requests, registered in-flight segment wait futures under lock, and required `http://` or `https://` schemes on `/proxy?url=` routes.
+ - Reported specific subtitle and DASH download errors (HTTP status, timeout, missing `yt-dlp` vs `ffmpeg`) and matched `"at"` after `"of"` in `yt-dlp` progress lines.
- **Providers & Disk Cache**:
- - Removed the broad `"notice"` substring filter in MovieBox stream adaptation while keeping `/notice.mp4` and known deprecation hashes, restoring streams for titles like *Red Notice* and *Burn Notice*.
- - Required a leading `'S'` prefix in 4KHDHub season count parsing so release years after `"Score"` are not parsed as thousands of seasons.
- - Improved Dramachi episode number extraction across Unicode boundaries and quality suffixes, and inserted `/manifest.json` before query parameters in Stremio addon URLs.
- - Evicted cached poster images only when file age exceeds the 30-day TTL, preserving valid cache files across minor clock skew.
-- **TUI Navigation, Modals & Mouse**:
- - Validated `Details` and stream responses against each item's own provider, fixing infinite `"Loading details..."` hangs when opening cross-provider items from Continue Watching, Favorites, `/history`, or `/favorites`.
- - Aborted in-flight caption and 4KHDHub mirror resolution tasks on `Esc` / `GoBack`, preventing stale subtitle popups or player launches after leaving `Details`.
+ - Removed the broad `"notice"` substring filter in MovieBox stream adaptation while keeping `/notice.mp4` and known deprecation hashes, which restores streams for titles like *Red Notice* and *Burn Notice*.
+ - Required a leading `'S'` prefix in 4KHDHub season count parsing so release years after `"Score"` do not parse as season counts, and cached static HTML selectors in 4KHDHub parsers.
+ - Matched Dramachi episode numbers across Unicode boundaries and quality suffixes, and inserted `/manifest.json` before query parameters in Stremio addon URLs.
+ - Evicted cached poster images only when file age exceeds the 30-day TTL so valid cache files survive minor clock skew.
+ - Replaced synchronous `fsync` barriers on ephemeral cache writes with atomic temp-file renames, cached default directory paths via `LazyLock`, reused a static HTTP client in `probe_url`, and shared `Arc<[u8]>` poster buffers across disk caching and decoding.
+- **TUI Navigation, Themes, Modals & Mouse**:
+ - Validated `Details` and stream responses against each item's own provider so cross-provider items opened from Continue Watching, Favorites, `/history`, or `/favorites` load without hanging.
+ - Aborted in-flight caption and 4KHDHub mirror resolution tasks on `Esc` or `GoBack` so stale subtitle popups or players do not launch after leaving `Details`.
- Processed active Picker and Subtitle popups before the background loading guard on `Enter`, cleared queued season downloads when cancelling the download subtitle prompt or on stream failure, and reset TV input focus on overlay dismissal.
- - Enabled `/browse` for Stremio Addons, skipped search pagination on active addon catalogs, and clamped initial cursor selection in empty TV and Addon manager modals.
+ - Enabled `/browse` for Stremio Addons, reused in-memory addon state during stream resolution, skipped search pagination on active addon catalogs, and clamped initial cursor selection in empty TV and Addon manager modals.
- Synchronized `Home` and `Details` mouse hitboxes with the 3-row download gauge, narrow `< 85` col selector panes, compact `< 76` col bottom bar buttons, non-Stream footer `[Enter] Select` actions, and outside-click theme preview revert.
- - Shortened toast notifications to show filenames instead of full paths and removed duplicate status-bar/toast alerts on compact terminals.
+ - Downgraded named themes in `Theme::from_kind` on 16-color (`Basic`) and `NO_COLOR` terminals, improved `Latte` light-mode contrast on selected badges and modal rows, and added `ALACRITTY_SOCKET`, `KONSOLE_VERSION`, `TERMUX_VERSION`, `WT_SESSION`, and `TERM_PROGRAM` graphics/TrueColor detection.
+ - Shortened toast notifications to show filenames instead of full paths and removed duplicate status-bar and toast alerts on compact terminals.
## [0.1.25] - 2026-09-27
diff --git a/README.md b/README.md
index 3b2a4c7..51d68db 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@
- **Streaming:** Movies, TV series, anime, Asian dramas, and community Stremio addons across multiple native providers.
- **Live TV:** M3U playlist import with channel categories, EPG support, and search.
- **Resolution Picker:** Direct stream quality selection (`4K`, `1080p`, `720p`, `480p`, `Auto`) before playback.
-- **Hardware Players:** Seamless launch in `mpv`, `VLC`, or `IINA` with custom auth header and cookie forwarding.
+- **Hardware Players:** Direct launch in `mpv`, `VLC`, or `IINA` with custom auth header and cookie forwarding.
- **Batch Downloader:** Multi-segment concurrent downloader with HTTP range pause and resume for episodes and full seasons.
- **Subtitle Picker:** Multi-language subtitle tracks extracted and selectable via an interactive picker before playback or download.
- **Terminal UI:** Vim navigation, mouse interaction, slash command palette (`/help`, `/settings`), and 9 built-in themes.
diff --git a/docs/architecture.md b/docs/architecture.md
index f728cd3..65c000c 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -132,7 +132,7 @@ interval, forwarding them into the action channel (capacity 128).
- Background tasks send `Action` messages back (e.g. `SearchSuccess`,
`EpisodeStreamsReady`, `DownloadCompleted`), which `handle_action` consumes.
-## Data flow — a typical search
+## Data flow: a typical search
1. User types a query; the `Key` handler updates `search_query` and sends `Action::Search`.
2. `handle_action` resolves the active provider, dispatches to the provider client
@@ -154,13 +154,13 @@ interval, forwarding them into the action channel (capacity 128).
## Configuration and persistence
-- `config.json` — settings (mode persistence, mode toggles, theme, provider, auto-update, `default_player`, download directory, BDIX) in the config dir.
-- `addons_config.json` — installed HTTP community addons in the config dir.
-- `tv_config.json` — user M3U playlist sources (URLs or file paths) in the config dir.
-- `history.json` — watch history in the system data dir.
+- `config.json`: settings (mode persistence, mode toggles, theme, provider, auto-update, `default_player`, download directory, BDIX) in the config dir.
+- `addons_config.json`: installed HTTP community addons in the config dir.
+- `tv_config.json`: user M3U playlist sources (URLs or file paths) in the config dir.
+- `history.json`: watch history in the system data dir.
- `favorites.json`: starred titles in the system data dir, independent of `history.json`.
-- `playback/` — temporary playback states for session crash/kill reconciliation in the system data dir.
-- `scripts/` — bundled player scripts (`moviebox_tracker.lua`) in the system data dir.
+- `playback/`: temporary playback states for session crash/kill reconciliation in the system data dir.
+- `scripts/`: bundled player scripts (`moviebox_tracker.lua`) in the system data dir.
- Cache lives under the system cache dir, keyed per provider.
- Logs live under the system data dir with rotation.
diff --git a/docs/cache.md b/docs/cache.md
index 83b47d4..767b476 100644
--- a/docs/cache.md
+++ b/docs/cache.md
@@ -33,6 +33,6 @@ The envelope stores the expiration timestamp (`expires_at: u64`) alongside the s
## Durability & Safety
-- **Atomic File Writes**: All cache entries are written to a temporary sidecar file (`.tmp.<pid>.<salt>`) and renamed atomically to destination, preventing corruption if interrupted.
+- **Atomic File Writes**: All cache entries write to a temporary sidecar file (`.tmp-<pid>-<stamp>`) and rename atomically to the destination so interrupted writes never corrupt cache files.
- **Automatic Purging**: Stale cache entries older than 7 days are automatically removed by a background worker at startup.
- **Manual Purge**: Enter `/settings` → **Maintenance** → **Clear Disk Cache** to immediately wipe all cached files, images, and playlist snapshots.
diff --git a/docs/debugging.md b/docs/debugging.md
index 56de52b..beb2450 100644
--- a/docs/debugging.md
+++ b/docs/debugging.md
@@ -21,7 +21,7 @@ only shows a short status line. See [logging.md](logging.md) for location and se
- Operating system and terminal (e.g. macOS + iTerm2, Windows + Windows Terminal,
Termux).
- The player used, if the issue is playback.
-- The log file (sanitized — safe to share; URLs and paths are redacted).
+- The log file (sanitized and safe to share; URLs and paths are redacted).
## Reading the log
diff --git a/docs/downloads.md b/docs/downloads.md
index af14078..72ed197 100644
--- a/docs/downloads.md
+++ b/docs/downloads.md
@@ -24,20 +24,21 @@ Upon completion, temporary sidecars are verified and renamed atomically to the t
- Press **`d`** on any stream in the Details screen to start downloading immediately.
- Press **`x`** or **`X`** during an active download to cancel or pause the transfer. Partial `.part` data is preserved on disk for resumption.
-- Downloads run cooperatively in the background, allowing you to browse or search without interrupting transfers.
+- Downloads run cooperatively in the background so you can browse or search while transfers finish.
## Header Forwarding
-Authenticated streams (such as MovieBox DASH manifests or 4KHDHub mirrors) automatically forward required headers (`User-Agent`, `Referer`, signed CloudFront cookies) to download workers, ensuring CDN transfers complete without `403 Forbidden` errors.
+Authenticated streams (such as MovieBox DASH manifests or 4KHDHub mirrors) forward required headers (`User-Agent`, `Referer`, signed CloudFront cookies) to download workers so CDN transfers complete without `403 Forbidden` errors.
## DASH Streams (`yt-dlp`)
-MovieBox DASH streams require `yt-dlp` and `ffmpeg` to download and mux adaptive video/audio representations:
+MovieBox DASH streams require `yt-dlp` and `ffmpeg` to download and mux adaptive video and audio representations:
- **Windows**: `winget install yt-dlp.yt-dlp Gyan.FFmpeg`
- **macOS**: `brew install yt-dlp ffmpeg`
- **Android (Termux)**: `pkg install yt-dlp ffmpeg`
- **Linux**: Install `yt-dlp` and `ffmpeg` via system package manager.
-The downloader preflights both binaries before launching the transfer, failing fast with platform-specific installation commands if either is absent. Transferred fragments are pulled with `--concurrent-fragments 8` and `--http-chunk-size 95K` (keeping individual range sub-requests under Tengine's `limit_rate_after 96k` throttle boundary) alongside resilient retry bounds (`--fragment-retries 10`, `--retries 5`, `--socket-timeout 30`). Any subprocess errors during transfer capture and display the underlying `yt-dlp` error diagnostics directly in the failure notification.
-All other providers (4KHDHub, Dramachi, BDIX, DhakaFlix, CircleFTP, Stremio Addons, TV mode) download directly through the internal multi-segment HTTP engine (4–12 concurrent workers writing in-place to the pre-allocated `.part` file).
+The downloader checks both binaries before starting the transfer and reports which binary is missing if either is absent. Fragments are pulled with `--concurrent-fragments 8` and `--http-chunk-size 95K` (keeping individual range sub-requests under Tengine's `limit_rate_after 96k` throttle boundary) alongside retry bounds (`--fragment-retries 10`, `--retries 5`, `--socket-timeout 30`). Subprocess errors during transfer report the underlying `yt-dlp` diagnostic in the failure notification.
+
+All other providers (4KHDHub, Dramachi, BDIX, DhakaFlix, CircleFTP, Stremio Addons, TV mode) download directly through the internal multi-segment HTTP engine (4 to 12 concurrent workers writing in-place to the pre-allocated `.part` file).
diff --git a/docs/logging.md b/docs/logging.md
index e5bfe40..71a17d9 100644
--- a/docs/logging.md
+++ b/docs/logging.md
@@ -17,7 +17,7 @@ The active file is `moviebox-tui_rCURRENT.log`; rotated files are
- **Level** is controlled by `MOVIEBOX_LOG` (`off|error|warn|info|debug|trace`). Default is
`info` across all builds (`warn` and `error` lines are always included).
- **Rotation**: rotates at 5MB and keeps 3 files.
-- **Terminal output**: normal log lines go only to the file without writing to stdout or stderr, preventing screen bleed before entering alternate screen mode. Setup errors (if any) are reported on `stderr`.
+- **Terminal output**: normal log lines write only to the log file and never touch stdout or stderr, which keeps the screen clean before entering alternate screen mode. Setup errors (if any) are reported on `stderr`.
- **Session header**: version, OS, and the log path are written on startup.
- **Panics**: the panic hook captures stack backtraces, logs the payload and backtrace to the file, flushes log buffers, and then restores the terminal.
- `--version` and `--help` never create a log file.
@@ -35,8 +35,8 @@ The active file is `moviebox-tui_rCURRENT.log`; rotated files are
Logs are sanitized so they can be pasted into a GitHub issue:
-- URLs are reduced to `scheme://host` — file tokens, filenames, and query params are
- removed.
+- URLs are reduced to `scheme://host` (file tokens, filenames, and query params are
+ removed).
- Absolute paths are rewritten to `~` so your username does not appear.
- Headers, `Authorization`, search queries, and watch history are never
logged.
diff --git a/docs/players.md b/docs/players.md
index ec1e72b..c86d1c5 100644
--- a/docs/players.md
+++ b/docs/players.md
@@ -24,11 +24,11 @@ You can set a default player via `/settings` (Media Player), or override it with
```bash
mpv --autofit=WxH --geometry=50%:50% --hwdec=auto-safe --stream-buffer-size=4M --idle=no --keep-open=no [OPTIONS] <url>
```
-- **Tracking**: Injects `moviebox_tracker.lua` to track playback progress, total duration, and chosen stream filename, auto-restoring the exact stream mirror upon re-opening multi-stream titles (such as 4KHDHub releases).
-- **Hardware Decoding & Direct Streams**: Enables `--hwdec=auto-safe` for hardware-accelerated 4K 10-bit HEVC HDR decoding and passes `--ytdl=no` on non-DASH direct streams (`.mkv`, `.mp4`, `.m3u8`) for immediate native `ffmpeg` demuxer startup.
-- **Headers**: Custom stream headers (`User-Agent`, `Referer`) are passed via `--http-header-fields`.
-- **DASH Manifests & Loopback Acceleration**: DASH `.mpd` streams route through the local `StreamRelay` proxy (`127.0.0.1:<port>`), which caches rewritten manifests in RAM, warm-prefetches initialization and opening fragments on sidecar startup, fetches `.m4s` segments via parallel `95 KB` HTTP `Range` sub-requests, and prefetches both the next 3 video segments (`N+1..N+3`) and matching audio segments (`chunk-stream3-N..N+1`).
-- **Subtitles**: Remote subtitles are pre-downloaded to temporary storage and passed via `--sub-file=<path>`, falling back to the remote URL if local download fails.
+- **Tracking**: Injects `moviebox_tracker.lua` to record playback progress, total duration, and chosen stream filename, then restores that stream mirror when re-opening multi-stream titles.
+- **Hardware Decoding & Direct Streams**: Enables `--hwdec=auto-safe` for hardware-accelerated 4K 10-bit HEVC HDR decoding and passes `--ytdl=no` on non-DASH direct streams (`.mkv`, `.mp4`, `.m3u8`) for direct `ffmpeg` demuxer startup.
+- **Headers**: Passes custom stream headers (`User-Agent`, `Referer`) via `--http-header-fields`.
+- **DASH Manifests & Loopback Acceleration**: Routes DASH `.mpd` streams through the local `StreamRelay` proxy (`127.0.0.1:<port>`), which caches rewritten manifests in RAM, warm-prefetches initialization and opening fragments on sidecar startup, fetches `.m4s` segments via parallel `95 KB` HTTP `Range` sub-requests, and prefetches the next 3 video segments (`N+1..N+3`) and matching audio segments (`chunk-stream3-N..N+1`).
+- **Subtitles**: Pre-downloads remote subtitles to temporary storage in parallel with sidecar startup and passes `--sub-file=<path>`, with fallback to the remote URL if local download fails.
### VLC
```bash
@@ -55,11 +55,11 @@ termux-open --chooser --content-type video/* <url>
## Watch History & Resume
- **Position Resumption**: In-progress items launch with `--start=<seconds>` (`mpv`/`IINA`) or `--start-time=<seconds>` (`VLC`).
-- **Completion Detection**: Reaching ≥ 90% or stream EOF marks media as completed.
-- **State Reconciliation**: `mpv` and `IINA` sync playback progress via background IPC state files, preventing wall-clock drift during pauses or seeks.
+- **Completion Detection**: Reaching 90% or stream EOF marks media as completed.
+- **State Reconciliation**: `mpv` and `IINA` sync playback progress via background IPC state files so pauses or seeks do not cause wall-clock drift.
## Spawning & Process Safety
-- Players and the `StreamRelay` sidecar launch in fully detached OS sessions (`libc::setsid()` with `SIGHUP` ignored on Unix/macOS/Linux/Android, and `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` on Windows) so closing the terminal window or quitting `moviebox-tui` never terminates active video playback.
-- Player `stderr` is directed to a temporary log file rather than a parent pipe, preventing `SIGPIPE` / broken-pipe crashes when `moviebox-tui` exits while preserving full crash diagnostics when the TUI remains open.
-- Clean exits (VLC exit code `1` with empty stderr, or Unix `SIGTERM`) are recognized as normal exits and update watch history without false crash popups.
+- Players and the `StreamRelay` sidecar launch in detached OS sessions (`libc::setsid()` with `SIGHUP` ignored on Unix/macOS/Linux/Android, and `DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP` on Windows) so closing the terminal or quitting `moviebox-tui` does not stop active video playback.
+- Player `stderr` writes to a temporary log file so `moviebox-tui` can exit without triggering `SIGPIPE` crashes while still capturing crash diagnostics when the TUI stays open.
+- Clean exits (VLC exit code `1` with empty stderr, or Unix `SIGTERM`) count as normal exits and update watch history without false crash popups.
diff --git a/docs/testing.md b/docs/testing.md
index cfa41c5..f8e98b9 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -4,7 +4,7 @@ This document describes the testing architecture, quality assurance procedures,
## 1. Test Architecture
-The test suite runs in an isolated process sandbox (`TEST_SANDBOX_DIR` in `src/config.rs`) that redirects `config_dir()`, `data_dir()`, and `cache_dir()` to temporary directories and guards external browser launches (`open_external_url` in `src/net.rs`), ensuring tests never read, mutate, or delete host user files (`~/.config`, `~/.local/share`, `~/.cache`).
+The test suite runs in an isolated process sandbox (`TEST_SANDBOX_DIR` in `src/config.rs`) that redirects `config_dir()`, `data_dir()`, and `cache_dir()` to temporary directories and guards external browser launches (`open_external_url` in `src/net.rs`) so tests never read, mutate, or delete host user files (`~/.config`, `~/.local/share`, `~/.cache`).
The MovieBox-TUI test architecture follows a strict separation of concerns:
```text
diff --git a/src/cache.rs b/src/cache.rs
index c85a9e5..fb2857b 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -77,7 +77,7 @@ pub fn set_typed_cache<T: Serialize + ?Sized>(path: &Path, expiry_secs: u64, dat
let mut file_bytes = Vec::with_capacity(512);
file_bytes.extend_from_slice(&CACHE_MAGIC);
if rmp_serde::encode::write(&mut file_bytes, &envelope).is_ok() {
- if let Err(error) = atomic_write_file(path, &file_bytes) {
+ if let Err(error) = atomic_write_cache_file(path, &file_bytes) {
log::warn!(
"failed to write cache file {}: {error}",
crate::logging::sanitize_path(path)
@@ -124,6 +124,29 @@ pub fn atomic_write_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Resul
}
}
+pub fn atomic_write_cache_file(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).ok();
+ }
+ let stamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ let temporary = path.with_extension(format!("tmp-{}-{stamp}", std::process::id()));
+ fs::write(&temporary, bytes)?;
+ if fs::rename(&temporary, path).is_ok() {
+ return Ok(());
+ }
+ let _ = fs::remove_file(path);
+ match fs::rename(&temporary, path) {
+ Ok(()) => Ok(()),
+ Err(error) => {
+ let _ = fs::remove_file(&temporary);
+ Err(error)
+ }
+ }
+}
+
fn write_durable(target: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut file = fs::File::create(target)?;
@@ -498,7 +521,7 @@ pub fn get_namespaced_image_cache(namespace: &str, id: &str) -> Option<Vec<u8>>
pub fn set_namespaced_image_cache(namespace: &str, id: &str, bytes: &[u8]) {
let path = get_namespaced_image_path(namespace, id);
- if let Err(error) = atomic_write_file(&path, bytes) {
+ if let Err(error) = atomic_write_cache_file(&path, bytes) {
log::warn!(
"failed to commit image cache to {}: {error}",
crate::logging::sanitize_path(&path)
diff --git a/src/config.rs b/src/config.rs
index 3e9d546..c58d6a0 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -83,33 +83,33 @@ pub fn config_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("MOVIEBOX_CONFIG_DIR") {
return Some(PathBuf::from(dir));
}
- if let Some(sandbox) = TEST_SANDBOX_DIR.as_ref() {
- return Some(sandbox.join("config").join(APP_NAME));
- }
- if let Some(dir) = dirs::config_dir() {
- return Some(dir.join(APP_NAME));
- }
- if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
- let p = PathBuf::from(xdg);
- if !p.as_os_str().is_empty() {
- return Some(p.join(APP_NAME));
+ static DEFAULT_CONFIG_DIR: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
+ if let Some(dir) = dirs::config_dir() {
+ return dir.join(APP_NAME);
}
- }
- if let Ok(prefix) = std::env::var("PREFIX") {
- let p = PathBuf::from(prefix).join("etc").join(APP_NAME);
- if p.exists() {
- return Some(p);
+ if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
+ let p = PathBuf::from(xdg);
+ if !p.as_os_str().is_empty() {
+ return p.join(APP_NAME);
+ }
}
- }
- if let Some(dir) = dirs::home_dir().map(|h| h.join(".config").join(APP_NAME)) {
- return Some(dir);
- }
- let fallback = std::env::temp_dir().join(APP_NAME).join("config");
- log::warn!(
- "unable to locate user config directory, falling back to {}",
- fallback.display()
- );
- Some(fallback)
+ if let Ok(prefix) = std::env::var("PREFIX") {
+ let p = PathBuf::from(prefix).join("etc").join(APP_NAME);
+ if p.exists() {
+ return p;
+ }
+ }
+ if let Some(dir) = dirs::home_dir().map(|h| h.join(".config").join(APP_NAME)) {
+ return dir;
+ }
+ let fallback = std::env::temp_dir().join(APP_NAME).join("config");
+ log::warn!(
+ "unable to locate user config directory, falling back to {}",
+ fallback.display()
+ );
+ fallback
+ });
+ Some(DEFAULT_CONFIG_DIR.clone())
}
pub fn data_dir() -> Option<PathBuf> {
@@ -119,33 +119,33 @@ pub fn data_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("MOVIEBOX_DATA_DIR") {
return Some(PathBuf::from(dir));
}
- if let Some(sandbox) = TEST_SANDBOX_DIR.as_ref() {
- return Some(sandbox.join("data").join(APP_NAME));
- }
- if let Some(dir) = dirs::data_dir() {
- return Some(dir.join(APP_NAME));
- }
- if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
- let p = PathBuf::from(xdg);
- if !p.as_os_str().is_empty() {
- return Some(p.join(APP_NAME));
+ static DEFAULT_DATA_DIR: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
+ if let Some(dir) = dirs::data_dir() {
+ return dir.join(APP_NAME);
}
- }
- if let Ok(prefix) = std::env::var("PREFIX") {
- let p = PathBuf::from(prefix).join("var").join("lib").join(APP_NAME);
- if p.exists() {
- return Some(p);
+ if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
+ let p = PathBuf::from(xdg);
+ if !p.as_os_str().is_empty() {
+ return p.join(APP_NAME);
+ }
}
- }
- if let Some(dir) = dirs::home_dir().map(|h| h.join(".local").join("share").join(APP_NAME)) {
- return Some(dir);
- }
- let fallback = std::env::temp_dir().join(APP_NAME).join("data");
- log::warn!(
- "unable to locate user data directory, falling back to {}",
- fallback.display()
- );
- Some(fallback)
+ if let Ok(prefix) = std::env::var("PREFIX") {
+ let p = PathBuf::from(prefix).join("var").join("lib").join(APP_NAME);
+ if p.exists() {
+ return p;
+ }
+ }
+ if let Some(dir) = dirs::home_dir().map(|h| h.join(".local").join("share").join(APP_NAME)) {
+ return dir;
+ }
+ let fallback = std::env::temp_dir().join(APP_NAME).join("data");
+ log::warn!(
+ "unable to locate user data directory, falling back to {}",
+ fallback.display()
+ );
+ fallback
+ });
+ Some(DEFAULT_DATA_DIR.clone())
}
pub fn cache_dir() -> PathBuf {
@@ -155,30 +155,30 @@ pub fn cache_dir() -> PathBuf {
if let Ok(dir) = std::env::var("MOVIEBOX_CACHE_DIR") {
return PathBuf::from(dir);
}
- if let Some(sandbox) = TEST_SANDBOX_DIR.as_ref() {
- return sandbox.join("cache").join(APP_NAME);
- }
- if let Some(dir) = dirs::cache_dir() {
- return dir.join(APP_NAME);
- }
- if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
- let p = PathBuf::from(xdg);
- if !p.as_os_str().is_empty() {
- return p.join(APP_NAME);
+ static DEFAULT_CACHE_DIR: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
+ if let Some(dir) = dirs::cache_dir() {
+ return dir.join(APP_NAME);
}
- }
- if let Ok(prefix) = std::env::var("PREFIX") {
- let p = PathBuf::from(prefix)
- .join("var")
- .join("cache")
- .join(APP_NAME);
- if p.exists() {
- return p;
+ if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
+ let p = PathBuf::from(xdg);
+ if !p.as_os_str().is_empty() {
+ return p.join(APP_NAME);
+ }
}
- }
- dirs::home_dir()
- .map(|h| h.join(".cache").join(APP_NAME))
- .unwrap_or_else(|| std::env::temp_dir().join(APP_NAME))
+ if let Ok(prefix) = std::env::var("PREFIX") {
+ let p = PathBuf::from(prefix)
+ .join("var")
+ .join("cache")
+ .join(APP_NAME);
+ if p.exists() {
+ return p;
+ }
+ }
+ dirs::home_dir()
+ .map(|h| h.join(".cache").join(APP_NAME))
+ .unwrap_or_else(|| std::env::temp_dir().join(APP_NAME))
+ });
+ DEFAULT_CACHE_DIR.clone()
}
pub fn logs_dir() -> PathBuf {
diff --git a/src/net.rs b/src/net.rs
index 6e40ef2..82bbe5c 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -87,43 +87,53 @@ pub fn http_client_builder() -> reqwest::ClientBuilder {
}
pub async fn probe_url(url: &str, timeout: std::time::Duration) -> bool {
- let Ok(client) = http_client_builder_base()
- .timeout(timeout)
- .connect_timeout(timeout)
- .build()
- else {
- return false;
- };
- match client.head(url).send().await {
- Ok(resp) if resp.status().is_success() || resp.status().is_redirection() => return true,
- Ok(resp) => {
+ static PROBE_CLIENT: std::sync::LazyLock<reqwest::Client> = std::sync::LazyLock::new(|| {
+ http_client_builder_base()
+ .build()
+ .unwrap_or_else(|_| reqwest::Client::new())
+ });
+ match tokio::time::timeout(timeout, PROBE_CLIENT.head(url).send()).await {
+ Ok(Ok(resp)) if resp.status().is_success() || resp.status().is_redirection() => {
+ return true;
+ }
+ Ok(Ok(resp)) => {
log::debug!(
"probe HEAD non-success for {}: {}",
crate::logging::sanitize_url(url),
resp.status()
);
}
- Err(e) => {
+ Ok(Err(e)) => {
log::debug!(
"probe HEAD error for {}: {e}",
crate::logging::sanitize_url(url)
);
}
+ Err(_) => {
+ log::debug!(
+ "probe HEAD timed out for {}",
+ crate::logging::sanitize_url(url)
+ );
+ }
}
- match client
- .get(url)
- .header(reqwest::header::RANGE, "bytes=0-0")
- .send()
- .await
+ match tokio::time::timeout(
+ timeout,
+ PROBE_CLIENT
+ .get(url)
+ .header(reqwest::header::RANGE, "bytes=0-0")
+ .send(),
+ )
+ .await
{
- Ok(resp) => resp.status().is_success() || resp.status().is_redirection(),
- Err(e) => {
+ Ok(Ok(resp)) => resp.status().is_success() || resp.status().is_redirection(),
+ Ok(Err(e)) => {
log::debug!(
"probe GET error for {}: {e}",
crate::logging::sanitize_url(url)
);
false
}
+ Err(_) => false,
}
}
diff --git a/src/providers/addons/mod.rs b/src/providers/addons/mod.rs
index 5ca3790..8e66a6b 100644
--- a/src/providers/addons/mod.rs
+++ b/src/providers/addons/mod.rs
@@ -30,7 +30,9 @@ impl Provider for AddonClient {
}
async fn search(&self, query: &str, _page: usize) -> Result<Vec<CatalogItem>, ProviderError> {
- let addons = crate::config::load_addons();
+ let addons = tokio::task::spawn_blocking(crate::config::load_addons)
+ .await
+ .unwrap_or_default();
let catalog_addons: Vec<_> = addons
.iter()
.filter(|a| a.enabled && (a.provides_meta || a.provides_catalog))
@@ -81,7 +83,9 @@ impl Provider for AddonClient {
_ => (None, id),
};
- let addons = crate::config::load_addons();
+ let addons = tokio::task::spawn_blocking(crate::config::load_addons)
+ .await
+ .unwrap_or_default();
let mut target_addons: Vec<_> = addons
.iter()
.filter(|a| a.enabled && a.provides_meta)
diff --git a/src/providers/fourkhdhub/hubcloud.rs b/src/providers/fourkhdhub/hubcloud.rs
index 3a8a769..f1a30af 100644
--- a/src/providers/fourkhdhub/hubcloud.rs
+++ b/src/providers/fourkhdhub/hubcloud.rs
@@ -213,8 +213,7 @@ fn decode_greenmotors_payload(payload: &str) -> Option<String> {
fn extract_hubcloud_drive_url(html: &str) -> Option<String> {
let document = Html::parse_document(html);
- let links = Selector::parse("a[href]").ok()?;
- document.select(&links).find_map(|node| {
+ document.select(&SEL_LINKS).find_map(|node| {
let raw = node.value().attr("href")?;
let url = Url::parse(raw).ok()?;
let host = url.host_str()?;
diff --git a/src/providers/fourkhdhub/parser.rs b/src/providers/fourkhdhub/parser.rs
index 0297870..8e12a39 100644
--- a/src/providers/fourkhdhub/parser.rs
+++ b/src/providers/fourkhdhub/parser.rs
@@ -39,6 +39,12 @@ static SEL_FILE_TITLE: LazyLock<Selector> =
static SEL_LINK_HREF: LazyLock<Selector> = LazyLock::new(|| Selector::parse("a[href]").unwrap());
static SEL_BADGE_SIZE: LazyLock<Selector> =
LazyLock::new(|| Selector::parse(".badge-size, .badge").unwrap());
+static SEL_OG_IMAGE: LazyLock<Selector> =
+ LazyLock::new(|| Selector::parse("meta[property=\"og:image\"]").unwrap());
+static SEL_OG_TITLE: LazyLock<Selector> =
+ LazyLock::new(|| Selector::parse("meta[property=\"og:title\"]").unwrap());
+static SEL_META_DESC: LazyLock<Selector> =
+ LazyLock::new(|| Selector::parse("meta[name=\"description\"]").unwrap());
pub fn parse_search(base: &Url, html: &str) -> Result<Vec<CatalogItem>, FourKHdHubError> {
let document = Html::parse_document(html);
@@ -89,7 +95,7 @@ pub fn parse_details(id: &str, html: &str) -> Result<MediaDetails, FourKHdHubErr
.select(&SEL_H1)
.find_map(|node| text_of(Some(node)))
.filter(|text| !text.is_empty())
- .or_else(|| meta_content(&document, "meta[property=\"og:title\"]"))
+ .or_else(|| meta_content(&document, &SEL_OG_TITLE))
.ok_or_else(|| FourKHdHubError::Parse("title missing".into()))?;
let title = strip_trailing_year(&raw_title);
let media_type = if id.contains("-series-") {
@@ -100,14 +106,14 @@ pub fn parse_details(id: &str, html: &str) -> Result<MediaDetails, FourKHdHubErr
let description = document
.select(&SEL_CONTENT_DESC)
.find_map(|node| text_of(Some(node)))
- .or_else(|| meta_content(&document, "meta[name=\"description\"]"));
+ .or_else(|| meta_content(&document, &SEL_META_DESC));
let tagline = document
.select(&SEL_TAGLINE)
.find_map(|node| text_of(Some(node)));
let imdb_rating = document
.select(&SEL_IMDB)
.find_map(|node| text_of(Some(node)));
- let poster_url = meta_content(&document, "meta[property=\"og:image\"]");
+ let poster_url = meta_content(&document, &SEL_OG_IMAGE);
let year = find_metadata(&document, "Release:")
.and_then(|value| first_four_digit_year(&value))
.or_else(|| {
@@ -271,10 +277,9 @@ fn text_of(node: Option<ElementRef<'_>>) -> Option<String> {
.filter(|text| !text.is_empty())
}
-fn meta_content(document: &Html, query: &str) -> Option<String> {
- let selector = Selector::parse(query).ok()?;
+fn meta_content(document: &Html, selector: &Selector) -> Option<String> {
document
- .select(&selector)
+ .select(selector)
.next()
.and_then(|node| node.value().attr("content"))
.map(str::to_string)
diff --git a/src/proxy.rs b/src/proxy.rs
index 55528ce..adb0248 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -772,19 +772,22 @@ async fn fetch_or_get_segment(
return Ok((reqwest::StatusCode::OK, ct, data));
}
- let (is_owner, notify) = {
- let mut lock = cache.in_flight.lock().unwrap();
- if let Some(existing) = lock.get(url) {
- (false, Arc::clone(existing))
- } else {
- let n = Arc::new(tokio::sync::Notify::new());
- lock.insert(url.to_string(), Arc::clone(&n));
- (true, n)
+ let (is_owner, notify, notified_fut) = match cache.in_flight.lock() {
+ Ok(mut lock) => {
+ if let Some(existing) = lock.get(url) {
+ let n = Arc::clone(existing);
+ (false, Arc::clone(&n), Some(n.notified_owned()))
+ } else {
+ let n = Arc::new(tokio::sync::Notify::new());
+ lock.insert(url.to_string(), Arc::clone(&n));
+ (true, n, None)
+ }
}
+ Err(_) => (true, Arc::new(tokio::sync::Notify::new()), None),
};
- if !is_owner {
- let _ = tokio::time::timeout(Duration::from_secs(15), notify.notified()).await;
+ if let Some(fut) = notified_fut {
+ let _ = tokio::time::timeout(Duration::from_secs(15), fut).await;
if let Some((ct, data)) = cache.get(url) {
return Ok((reqwest::StatusCode::OK, ct, data));
}
diff --git a/src/service.rs b/src/service.rs
index 82bfd4a..12c1228 100644
--- a/src/service.rs
+++ b/src/service.rs
@@ -360,15 +360,14 @@ impl MovieBoxService {
{
return Some(img);
}
- let bytes = self.fetch_poster_bytes(url).await?;
+ let bytes = Arc::<[u8]>::from(self.fetch_poster_bytes(url).await?);
let ns = namespace.to_string();
let id_owned = id.to_string();
- let bytes_clone = bytes.clone();
- let _ = tokio::task::spawn_blocking(move || {
- crate::cache::set_namespaced_image_cache(&ns, &id_owned, &bytes_clone);
- })
- .await;
- decode_poster(bytes).await
+ let bytes_for_cache = Arc::clone(&bytes);
+ tokio::task::spawn_blocking(move || {
+ crate::cache::set_namespaced_image_cache(&ns, &id_owned, &bytes_for_cache);
+ });
+ decode_poster_arc(bytes).await
}
pub async fn download_subtitle_file(
@@ -452,6 +451,21 @@ pub async fn decode_poster(bytes: Vec<u8>) -> Option<Arc<image::DynamicImage>> {
.ok()?
}
+async fn decode_poster_arc(bytes: Arc<[u8]>) -> Option<Arc<image::DynamicImage>> {
+ tokio::task::spawn_blocking(move || {
+ let img = image::load_from_memory(&bytes).ok()?;
+ const MAX_DIM: u32 = 512;
+ let downscaled = if img.width().max(img.height()) <= MAX_DIM {
+ img
+ } else {
+ img.resize(MAX_DIM, MAX_DIM, image::imageops::FilterType::Triangle)
+ };
+ Some(Arc::new(downscaled))
+ })
+ .await
+ .ok()?
+}
+
pub fn metric_value(item: &serde_json::Value, keys: &[&str]) -> Option<f64> {
let mut containers = vec![item];
if let Some(metadata) = item.get("metadata") {
diff --git a/src/tui/app/addons.rs b/src/tui/app/addons.rs
index 3829403..bdc9e22 100644
--- a/src/tui/app/addons.rs
+++ b/src/tui/app/addons.rs
@@ -51,11 +51,15 @@ impl App {
installed.version.as_deref().unwrap_or("1.0.0")
)))
.ok();
- let mut addons = crate::config::load_addons();
- addons
- .retain(|existing| existing.manifest_url != installed.manifest_url);
- addons.push(installed);
- crate::config::save_addons(&addons);
+ let _ = tokio::task::spawn_blocking(move || {
+ let mut addons = crate::config::load_addons();
+ addons.retain(|existing| {
+ existing.manifest_url != installed.manifest_url
+ });
+ addons.push(installed);
+ crate::config::save_addons(&addons);
+ })
+ .await;
sender.send(Action::ShowAddonManager).ok();
}
Err(err) => {
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index f6d54f2..1ac5da1 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -321,12 +321,59 @@ impl App {
let service = self.service.clone();
tokio::spawn(async move {
let is_android = matches!(kind, crate::tui::state::PlayerKind::AndroidIntent);
+ let is_dash = crate::player::is_dash_url(&link);
+ let has_extra_headers = headers.iter().any(|(name, _)| {
+ !name.eq_ignore_ascii_case("referer") && !name.eq_ignore_ascii_case("user-agent")
+ });
+ let eager_proxy = is_dash
+ || (matches!(
+ kind,
+ crate::tui::state::PlayerKind::Vlc
+ | crate::tui::state::PlayerKind::AndroidIntent
+ ) && has_extra_headers);
+ let sidecar_sub = if is_android {
+ subtitle.as_deref()
+ } else {
+ None
+ };
+
+ let eager_sidecar_fut = async {
+ if eager_proxy {
+ let link_c = link.clone();
+ let headers_c = headers.clone();
+ let sub_c = sidecar_sub.map(str::to_string);
+ tokio::task::spawn_blocking(move || {
+ crate::proxy::spawn_sidecar(
+ &link_c,
+ &headers_c,
+ sub_c.as_deref(),
+ max_height,
+ )
+ })
+ .await
+ .ok()
+ } else {
+ None
+ }
+ };
+
+ let sub_fut = async {
+ if let Some(url) = &subtitle {
+ Some(
+ service
+ .download_subtitle_file(url, &headers, preferred_sub_name.as_deref())
+ .await,
+ )
+ } else {
+ None
+ }
+ };
+
+ let (eager_sidecar_res, sub_res) = tokio::join!(eager_sidecar_fut, sub_fut);
+
let mut local_subtitle = subtitle.clone();
let mut temporary_subtitle = None;
- if let Some(url) = &subtitle {
- let download_res = service
- .download_subtitle_file(url, &headers, preferred_sub_name.as_deref())
- .await;
+ if let (Some(url), Some(download_res)) = (&subtitle, sub_res) {
match download_res {
Ok(path) => {
local_subtitle = Some(path.to_string_lossy().into_owned());
@@ -358,28 +405,32 @@ impl App {
&& local_subtitle
.as_deref()
.is_some_and(|p| p.starts_with("/data/data/com.termux/"));
- let is_dash = crate::player::is_dash_url(&link);
- let has_extra_headers = headers.iter().any(|(name, _)| {
- !name.eq_ignore_ascii_case("referer") && !name.eq_ignore_ascii_case("user-agent")
- });
- let needs_proxy = is_dash
- || (matches!(
- kind,
- crate::tui::state::PlayerKind::Vlc
- | crate::tui::state::PlayerKind::AndroidIntent
- ) && has_extra_headers)
+ let needs_proxy = eager_proxy
|| (is_android
&& subtitle.is_some()
&& (local_subtitle.is_none() || android_sub_is_private));
- let sidecar_sub = if is_android {
- subtitle.as_deref()
- } else {
- None
- };
let mut sidecar_child = None;
let (effective_link, effective_subtitle) = if needs_proxy {
- match crate::proxy::spawn_sidecar(&link, &headers, sidecar_sub, max_height) {
+ let sidecar_outcome = match eager_sidecar_res {
+ Some(res) => res,
+ None => {
+ let link_c = link.clone();
+ let headers_c = headers.clone();
+ let sub_c = sidecar_sub.map(str::to_string);
+ tokio::task::spawn_blocking(move || {
+ crate::proxy::spawn_sidecar(
+ &link_c,
+ &headers_c,
+ sub_c.as_deref(),
+ max_height,
+ )
+ })
+ .await
+ .unwrap_or_else(|e| Err(format!("join error: {e}")))
+ }
+ };
+ match sidecar_outcome {
Ok((local_url, sc_child)) => {
sidecar_child = Some(sc_child);
let sub_url = if is_android {
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 8334774..acd5ae4 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -1287,7 +1287,7 @@ impl App {
if context.provider == ProviderKind::Addons {
let sender = self.action_sender.clone();
let client = self.service.addon_client.clone();
- let addons = crate::config::load_addons();
+ let addons = self.state.installed_addons.clone();
let id = subject_id.clone();
let is_series = self
.state
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index 85154b6..09039ff 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -695,6 +695,10 @@ pub(crate) fn selection_style(theme: &Theme, basic_terminal: bool) -> Style {
Style::default()
.fg(theme.highlight.fg.unwrap_or(theme.base))
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED)
+ } else if theme.is_light {
+ let bg = theme.surface0_color();
+ let fg = theme.text.fg.unwrap_or(theme.base);
+ Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD)
} else {
let bg = theme.surface1_color();
let fg = theme
diff --git a/src/tui/terminal.rs b/src/tui/terminal.rs
index acc7085..9a89852 100644
--- a/src/tui/terminal.rs
+++ b/src/tui/terminal.rs
@@ -14,26 +14,31 @@ fn is_inside_tmux() -> bool {
}
fn outer_terminal_supports_graphics() -> bool {
- if std::env::var("GHOSTTY_RESOURCES_DIR").is_ok() {
- return true;
- }
- if std::env::var("KITTY_WINDOW_ID").is_ok() {
- return true;
- }
- if std::env::var("WEZTERM_EXECUTABLE").is_ok() {
- return true;
- }
- if std::env::var("ITERM_SESSION_ID").is_ok() {
- return true;
- }
- if std::env::var("ALACRITTY_LOG").is_ok() || std::env::var("ALACRITTY_WINDOW_ID").is_ok() {
+ if std::env::var("GHOSTTY_RESOURCES_DIR").is_ok()
+ || std::env::var("KITTY_WINDOW_ID").is_ok()
+ || std::env::var("WEZTERM_EXECUTABLE").is_ok()
+ || std::env::var("ITERM_SESSION_ID").is_ok()
+ || std::env::var("ALACRITTY_LOG").is_ok()
+ || std::env::var("ALACRITTY_WINDOW_ID").is_ok()
+ || std::env::var("ALACRITTY_SOCKET").is_ok()
+ || std::env::var("KONSOLE_VERSION").is_ok()
+ || std::env::var("WT_SESSION").is_ok()
+ {
return true;
}
- let term = env("TERM");
- if term.starts_with("foot") {
+ let term = env("TERM").to_ascii_lowercase();
+ if term.starts_with("foot")
+ || term.contains("kitty")
+ || term.contains("ghostty")
+ || term.contains("alacritty")
+ {
return true;
}
- false
+ let term_program = env("TERM_PROGRAM").to_ascii_lowercase();
+ matches!(
+ term_program.as_str(),
+ "ghostty" | "wezterm" | "iterm.app" | "vscode" | "rio"
+ )
}
pub fn should_query_images() -> bool {
@@ -76,8 +81,12 @@ pub fn should_query_images() -> bool {
let is_modern_terminal = std::env::var("WT_SESSION").is_ok()
|| std::env::var("TERM_PROGRAM").is_ok()
|| std::env::var("ALACRITTY_LOG").is_ok()
+ || std::env::var("ALACRITTY_SOCKET").is_ok()
|| std::env::var("WEZTERM_EXECUTABLE").is_ok()
- || std::env::var("GHOSTTY_RESOURCES_DIR").is_ok();
+ || std::env::var("GHOSTTY_RESOURCES_DIR").is_ok()
+ || term.contains("alacritty")
+ || term.contains("kitty")
+ || term.contains("ghostty");
if !is_modern_terminal {
return false;
}
@@ -128,19 +137,23 @@ mod tests {
std::env::set_var("MOVIEBOX_IMAGE_PROTOCOL", "kitty");
assert!(should_query_images());
std::env::remove_var("MOVIEBOX_IMAGE_PROTOCOL");
- let saved_ghostty = std::env::var("GHOSTTY_RESOURCES_DIR").ok();
- let saved_kitty = std::env::var("KITTY_WINDOW_ID").ok();
- let saved_wezterm = std::env::var("WEZTERM_EXECUTABLE").ok();
- let saved_iterm = std::env::var("ITERM_SESSION_ID").ok();
- let saved_alacritty_log = std::env::var("ALACRITTY_LOG").ok();
- let saved_alacritty_win = std::env::var("ALACRITTY_WINDOW_ID").ok();
+ let saved_vars = [
+ "GHOSTTY_RESOURCES_DIR",
+ "KITTY_WINDOW_ID",
+ "WEZTERM_EXECUTABLE",
+ "ITERM_SESSION_ID",
+ "ALACRITTY_LOG",
+ "ALACRITTY_WINDOW_ID",
+ "ALACRITTY_SOCKET",
+ "KONSOLE_VERSION",
+ "WT_SESSION",
+ "TERM_PROGRAM",
+ ]
+ .map(|k| (k, std::env::var(k).ok()));
- std::env::remove_var("GHOSTTY_RESOURCES_DIR");
- std::env::remove_var("KITTY_WINDOW_ID");
- std::env::remove_var("WEZTERM_EXECUTABLE");
- std::env::remove_var("ITERM_SESSION_ID");
- std::env::remove_var("ALACRITTY_LOG");
- std::env::remove_var("ALACRITTY_WINDOW_ID");
+ for (k, _) in &saved_vars {
+ std::env::remove_var(k);
+ }
std::env::set_var("TMUX", "/tmp/tmux-1000/default,12345,0");
assert!(!should_query_images());
@@ -154,23 +167,10 @@ mod tests {
std::env::remove_var("MOVIEBOX_IMAGE_PROTOCOL");
std::env::remove_var("TMUX");
- if let Some(v) = saved_ghostty {
- std::env::set_var("GHOSTTY_RESOURCES_DIR", v);
- }
- if let Some(v) = saved_kitty {
- std::env::set_var("KITTY_WINDOW_ID", v);
- }
- if let Some(v) = saved_wezterm {
- std::env::set_var("WEZTERM_EXECUTABLE", v);
- }
- if let Some(v) = saved_iterm {
- std::env::set_var("ITERM_SESSION_ID", v);
- }
- if let Some(v) = saved_alacritty_log {
- std::env::set_var("ALACRITTY_LOG", v);
- }
- if let Some(v) = saved_alacritty_win {
- std::env::set_var("ALACRITTY_WINDOW_ID", v);
+ for (k, val) in saved_vars {
+ if let Some(v) = val {
+ std::env::set_var(k, v);
+ }
}
}
}
diff --git a/src/tui/theme.rs b/src/tui/theme.rs
index 2204d36..cde27cb 100644
--- a/src/tui/theme.rs
+++ b/src/tui/theme.rs
@@ -128,7 +128,10 @@ impl ColorSupport {
if std::env::var("WT_SESSION").is_ok()
|| std::env::var("WEZTERM_EXECUTABLE").is_ok()
|| std::env::var("ALACRITTY_WINDOW_ID").is_ok()
+ || std::env::var("ALACRITTY_SOCKET").is_ok()
|| std::env::var("TILIX_ID").is_ok()
+ || std::env::var("TERMUX_VERSION").is_ok()
+ || std::env::var("KONSOLE_VERSION").is_ok()
|| std::env::var("VTE_VERSION")
.ok()
.is_some_and(|v| is_vte_version_truecolor(&v))
@@ -297,8 +300,10 @@ impl Theme {
ThemeKind::Mocha => Self::mocha(),
};
match ColorSupport::current() {
+ ColorSupport::NoColor => Self::monochrome(base.is_light),
+ ColorSupport::Basic => Self::fallback(base.is_light),
ColorSupport::Color256 => base.quantized_to_256(),
- _ => base,
+ ColorSupport::Truecolor => base,
}
}
pub fn palette_swatch_spans(theme_name: &str, basic_terminal: bool) -> Vec<Span<'static>> {
@@ -309,12 +314,16 @@ impl Theme {
return vec![Span::styled("* * *", sample.text_dim)];
}
- let accent_color = sample.accent.fg.unwrap_or(Color::Cyan);
+ let accent_color = sample
+ .accent
+ .fg
+ .or(sample.highlight.fg)
+ .unwrap_or(sample.base);
let surface_color = sample
.surface0
.fg
.or(sample.surface1.fg)
- .unwrap_or(Color::DarkGray);
+ .unwrap_or(sample.base);
let base_color = sample.base;
vec![
@@ -395,6 +404,7 @@ impl Theme {
pub fn monochrome(is_light: bool) -> Self {
let foreground = if is_light { Color::Black } else { Color::White };
+ let inverse = if is_light { Color::White } else { Color::Black };
let dim = if is_light {
Color::DarkGray
} else {
@@ -429,8 +439,8 @@ impl Theme {
overlay0: Style::default().fg(Color::DarkGray),
overlay1: Style::default().fg(dim),
overlay2: Style::default().fg(dim),
- mantle: Style::default().fg(foreground),
- crust: Style::default().fg(foreground),
+ mantle: Style::default().fg(inverse),
+ crust: Style::default().fg(inverse),
is_light,
}
}
@@ -472,7 +482,7 @@ impl Theme {
maroon: Style::default().fg(Color::Red),
surface0: Style::default().fg(Color::DarkGray),
surface1: Style::default().fg(Color::DarkGray),
- surface2: Style::default().fg(Color::Black),
+ surface2: Style::default().fg(Color::Gray),
overlay0: Style::default().fg(Color::DarkGray),
overlay1: Style::default().fg(Color::DarkGray),
overlay2: Style::default().fg(Color::Black),
diff --git a/src/tui/widgets/badge.rs b/src/tui/widgets/badge.rs
index 167f822..ae49c7c 100644
--- a/src/tui/widgets/badge.rs
+++ b/src/tui/widgets/badge.rs
@@ -1,5 +1,5 @@
use ratatui::{
- style::{Color, Modifier, Style},
+ style::{Modifier, Style},
text::Span,
};
@@ -78,19 +78,12 @@ pub fn resolution_badge_spans<'a>(
}
let is_light = theme.is_light;
+ let selected_fg = theme.crust_color();
let (badge_bg, contrast_fg, label) = match resolution {
-1 => {
let accent_color = theme.lavender.fg.unwrap_or(theme.base);
if is_selected {
- (
- accent_color,
- if is_light {
- Color::White
- } else {
- theme.crust_color()
- },
- " Multi ",
- )
+ (accent_color, selected_fg, " Multi ")
} else if is_light {
(theme.surface2_color(), accent_color, " Multi ")
} else {
@@ -100,15 +93,7 @@ pub fn resolution_badge_spans<'a>(
2160 | 4320 => {
let accent_color = theme.rating.fg.unwrap_or(theme.base);
if is_selected {
- (
- accent_color,
- if is_light {
- Color::White
- } else {
- theme.crust_color()
- },
- " 4K ",
- )
+ (accent_color, selected_fg, " 4K ")
} else if is_light {
(theme.surface2_color(), accent_color, " 4K ")
} else {
@@ -118,15 +103,7 @@ pub fn resolution_badge_spans<'a>(
1080 => {
let accent_color = theme.sapphire.fg.unwrap_or(theme.base);
if is_selected {
- (
- accent_color,
- if is_light {
- Color::White
- } else {
- theme.crust_color()
- },
- " 1080p ",
- )
+ (accent_color, selected_fg, " 1080p ")
} else if is_light {
(theme.surface2_color(), accent_color, " 1080p ")
} else {
@@ -136,15 +113,7 @@ pub fn resolution_badge_spans<'a>(
720 => {
let accent_color = theme.teal.fg.unwrap_or(theme.base);
if is_selected {
- (
- accent_color,
- if is_light {
- Color::White
- } else {
- theme.crust_color()
- },
- " 720p ",
- )
+ (accent_color, selected_fg, " 720p ")
} else if is_light {
(theme.surface2_color(), accent_color, " 720p ")
} else {