Skip to content

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

test(tui): grid/scroll/clamp unit coverage, boundary matrix, help keys

Samir Hossainscdfc4fce6e09
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b3d098d..5901f89 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,35 @@
## [Unreleased]
+### Added
+- **Terminal-aware rendering overhaul**:
+ - Theme autodetection now actually runs when no explicit theme is configured:
+ `NO_COLOR` forces monochrome, truecolor terminals get full RGB palettes,
+ strict 256-color terminals get quantized indexed palettes, ANSI-only
+ terminals get the fallback palette, and an OSC 11 background query picks
+ light/dark variants by measured luminance instead of `COLORFGBG` guesswork.
+ - Graphics salvage: terminals that answer kitty/sixel capability probes but
+ no cell size (Windows Terminal sixel, iTerm2 over SSH) keep posters via
+ default cell metrics instead of falling back to "No Poster".
+ - `MOVIEBOX_IMAGE_PROTOCOL=kitty|sixel|iterm2|none` and
+ `MOVIEBOX_CELL_SIZE=WxH` overrides, documented in `--help`.
+ - Automatic re-probe on focus regain when the initial probe found nothing
+ (covers tmux attach after startup), plus a `/probe` slash command.
+ - Kitty keyboard protocol (`DISAMBIGUATE_ESCAPE_CODES | REPORT_EVENT_TYPES`)
+ for faster unambiguous keys on Ghostty/kitty/foot/WezTerm/Alacritty.
+- **Responsive result grid**: results render in two columns at ≥110 columns
+ and three at ≥160, with row-based `↑`/`↓`, item-step `←`/`→`, grid-aware
+ click mapping, pagination, prefetching, and scroll clamping. Narrow
+ terminals keep the classic single-column behavior.
+- **Status strip**: transient status messages (previously computed but never
+ rendered) now appear as a slim centered line on the bottom row.
+- **Scrollable help overlay**: overflowing help content switches to a scrolled
+ single column with position indicator; keyboard and wheel scrolling with
+ key-swallowing so shortcuts no longer act behind the overlay.
+- **Viewport-adaptive caps**: picker popup rows grow with terminal height
+ (4–14), details selector height becomes viewport-proportional, and non-
+ graphics terminals get a compact filmstrip poster placeholder.
+
### Fixed
- **DNS resolution on Android/Termux and minimal containers**: Replaced the reqwest
`hickory-dns` feature flag with a custom resolver (`src/net.rs`) that reads the OS
@@ -33,6 +62,15 @@
- **Mouse click accuracy**: Search-result hit testing uses the real scroll offset
instead of deriving it from the selection, fixing clicks selecting or opening the
wrong title after sorting or scrolling partway.
+- **Popup geometry parity**: Picker, TV-config, addon-manager, and download-confirm
+ popups share one layout function between renderer and mouse handler, fixing
+ off-by-one-row TV clicks, missed confirmation buttons on short summaries, skewed
+ picker widths, and scroll-blind hit-testing on lists longer than eight rows.
+- **Text layout safety**: Details stream rows budget by display width rather than
+ byte length (CJK uploaders/languages no longer overflow); suggestion descriptions,
+ addon names, download gauge status, and playlist URLs truncate to their containers;
+ notification card width no longer panics below 40 columns; addon URL input edits by
+ grapheme clusters so CJK/emoji cursors stay aligned.
- **Poster memory footprint**: Decoded posters are downscaled to ≤512px before
caching, decoded/encoded cache sizes were right-sized (roughly 10× less RAM on
low-end devices), failed posters retry after 10 minutes instead of being negatively
@@ -42,7 +80,7 @@
runs off the UI thread (previously up to 2s of blank screen at startup); resize
performs a single deferred clear instead of two flashes; grid poster width derives
from real terminal cell metrics; the input caret blink keeps animating while
- typing; the mouse wheel scrolls one result row per notch; `NO_COLOR` now overrides
+ typing; the mouse wheel scrolls contextually; `NO_COLOR` now overrides
`MOVIEBOX_THEME`; strict 256-color terminals receive quantized indexed palettes
rather than RGB sequences.
diff --git a/docs/config.md b/docs/config.md
index eaabf3a..5fb3ee1 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -39,8 +39,10 @@ macOS `~/Library/Application Support/moviebox-tui`, Linux `~/.config/moviebox-tu
| `MOVIEBOX_VLC_PATH` | Custom VLC executable. |
| `MOVIEBOX_IINA_PATH` | Custom IINA/iina-cli executable. |
| `MOVIEBOX_FOURKHDHUB_URL` | Override the 4KHDHub base URL. |
-| `MOVIEBOX_THEME` | Force a theme (e.g. `Dracula`, `Gruvbox`, `Nord`, `Mocha`, `RosePine`, etc.). |
+| `MOVIEBOX_THEME` | Force a theme (e.g. `Dracula`, `Gruvbox`, `Nord`, `Mocha`, `RosePine`, etc.). When unset and no saved theme exists, the app auto-detects: `NO_COLOR` wins, truecolor terminals get full palettes, 256-color terminals get quantized palettes, and the OSC 11 background query picks light/dark variants. |
| `MOVIEBOX_NO_IMAGE` | Disable poster image queries (set to `1` or `true`). |
+| `MOVIEBOX_IMAGE_PROTOCOL` | Force poster graphics protocol: `kitty`, `sixel`, `iterm2`, or `none`. |
+| `MOVIEBOX_CELL_SIZE` | Override terminal cell size as `WxH` (e.g. `10x20`) for poster scaling. |
## CLI
diff --git a/docs/controls.md b/docs/controls.md
index bb4f903..0f0ad29 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -79,6 +79,20 @@ Type these commands directly into the search bar:
| `/disable-tv` | All | Disable TV Mode navigation |
| `/enable-addons` | All | Enable Addon Mode navigation in bottom dock |
| `/disable-addons` | All | Disable Addon Mode navigation |
+| `/probe` | All | Re-run terminal graphics detection and report the result |
+
+## Help Overlay
+
+- Open with `?`; close with `?`, `Esc`, or `q`.
+- `↑`/`↓`, `PageUp`/`PageDown`, and the mouse wheel scroll long content.
+- Other keys are ignored while help is open.
+
+## Wide-Terminal Grid
+
+On terminals at least 110 columns wide, search results render in two
+columns (three at 160+). `↑`/`↓` move one visual row, `←`/`→` move one
+item, and clicks map through column bounds. Narrower terminals keep the
+classic single-column list where `←`/`→` jump a full page.
| `/download-dir` | All | View, change, or reset the download directory |
| `/theme` | All | Open theme picker (Mocha, Latte, Macchiato, Frappe, Nord, TokyoNight, Dracula, Gruvbox, RosePine) |
| `/clear-cache` | All | Clear temporary cache files |
diff --git a/docs/cross-platform.md b/docs/cross-platform.md
index e339540..5d3b77d 100644
--- a/docs/cross-platform.md
+++ b/docs/cross-platform.md
@@ -19,11 +19,27 @@ the release checks in [`release-checklist.md`](release-checklist.md).
## Terminal capabilities
-The app probes the terminal at startup via `ratatui_image`:
-
-- **Poster rendering**: High-resolution graphics via Sixel, Kitty, and iTerm2 protocols when supported by the terminal. Non-graphics terminals (for example Apple Terminal.app or basic xterm) display a clean, centered `No Poster` label. Image queries can be disabled via `MOVIEBOX_NO_IMAGE=1`.
+The app probes the terminal at startup via `ratatui_image` (400ms cap,
+off the UI thread; retried on focus regain if the first probe found
+nothing, and on demand via `/probe`):
+
+- **Poster rendering**: Sixel, Kitty, and iTerm2 protocols where the probe
+ detects them. Terminals that report kitty/sixel capability but no cell
+ size (Windows Terminal sixel, iTerm2 over SSH) are salvaged with default
+ cell metrics. True Halfblocks-only terminals show a compact filmstrip
+ placeholder instead. `MOVIEBOX_NO_IMAGE=1` disables queries;
+ `MOVIEBOX_IMAGE_PROTOCOL` forces a protocol; `MOVIEBOX_CELL_SIZE=WxH`
+ overrides metrics.
+- **Colors**: With no explicit theme, `NO_COLOR` wins, then truecolor RGB,
+ quantized 256-color palettes for strict terminals, ANSI fallback
+ otherwise; an OSC 11 background query picks light/dark variants. An
+ explicit `MOVIEBOX_THEME` or saved theme always wins over autodetection.
+- **Keyboard**: The kitty keyboard protocol (disambiguated escapes, event
+ types) is requested at start and popped on exit; unsupported terminals
+ ignore it.
- **Terminal classification**: `TERM=dumb`/`linux` fall back to a basic UI.
-- Focus events (focus loss/gain) are used to re-render in place without clearing.
+- Focus events re-render in place without clearing; results render in two
+ columns from 110 columns wide (three from 160).
## Network & TLS portability
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 7a215f6..b23cf3d 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -479,23 +479,26 @@ impl AppState {
.unwrap_or(0)
.min(total - 1);
self.search_list_state.select(Some(selected));
- let (columns, visible_items) = match self.last_result_metrics {
- Some(metrics) => (metrics.columns as usize, metrics.visible_items),
- None => (1, 8),
+ let columns = match self.last_result_metrics {
+ Some(metrics) => metrics.columns as usize,
+ None => 1,
};
- let mut scroll = self.result_scroll;
- if selected < scroll {
- scroll = selected;
- } else if selected >= scroll + visible_items.max(1) {
- scroll = (selected + 1).saturating_sub(visible_items.max(1));
- }
- scroll -= scroll % columns.max(1);
- let max_scroll = total.saturating_sub(visible_items);
- if scroll > max_scroll {
- scroll = max_scroll;
+ let visible_items = match self.last_result_metrics {
+ Some(metrics) => metrics.visible_items,
+ None => 8,
+ };
+ let cols = columns.max(1);
+ let rows_visible = (visible_items / cols).max(1);
+ let selected_row = selected / cols;
+ let mut base_row = self.result_scroll / cols;
+ if selected_row < base_row {
+ base_row = selected_row;
+ } else if selected_row >= base_row + rows_visible {
+ base_row = selected_row.saturating_sub(rows_visible - 1);
}
- scroll -= scroll % columns.max(1);
- self.result_scroll = scroll;
+ let max_base = total.saturating_sub(rows_visible * cols) / cols;
+ let base_row = base_row.min(max_base);
+ self.result_scroll = base_row * cols;
}
pub fn effective_visible_items(&self) -> usize {
@@ -661,3 +664,79 @@ impl AppState {
rows
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn state_with(results: usize) -> AppState {
+ let mut state = AppState::default();
+ for i in 0..results {
+ state.search_results.push(crate::models::SearchResult {
+ id: i.to_string(),
+ title: format!("T{i}"),
+ stype: 1,
+ release_year: "2020".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: crate::providers::models::ProviderKind::MovieBox,
+ });
+ }
+ state
+ }
+
+ #[test]
+ fn columns_follow_width_tiers() {
+ assert_eq!(result_columns_for(80), 1);
+ assert_eq!(result_columns_for(110), 2);
+ assert_eq!(result_columns_for(160), 3);
+ assert_eq!(result_columns_for(60), 1);
+ }
+
+ #[test]
+ fn poster_rows_clamp_to_viewport() {
+ let state = AppState {
+ poster_rows: 12,
+ ..Default::default()
+ };
+ let metrics = state.result_metrics(10, 100);
+ assert!(metrics.poster_rows_eff <= 9, "rows must fit viewport");
+ assert!(metrics.visible_items >= 1);
+ }
+
+ #[test]
+ fn normalize_clamps_selection_and_aligns_scroll() {
+ let mut state = state_with(20);
+ state.last_result_metrics = Some(ResultMetrics {
+ poster_rows_eff: 3,
+ row_height: 4,
+ visible_items: 9,
+ columns: 3,
+ col_width: 60,
+ });
+ state.search_list_state.select(Some(25));
+ state.result_scroll = 50;
+ state.normalize_result_view();
+ assert_eq!(state.search_list_state.selected(), Some(19));
+ assert!(state.result_scroll <= 11);
+ assert_eq!(state.result_scroll % 3, 0);
+ }
+
+ #[test]
+ fn normalize_keeps_selection_visible_when_scrolling_down() {
+ let mut state = state_with(30);
+ state.last_result_metrics = Some(ResultMetrics {
+ poster_rows_eff: 3,
+ row_height: 4,
+ visible_items: 6,
+ columns: 3,
+ col_width: 40,
+ });
+ state.search_list_state.select(Some(10));
+ state.result_scroll = 0;
+ state.normalize_result_view();
+ assert_eq!(state.result_scroll, 6);
+ assert!(state.search_list_state.selected().unwrap() < state.result_scroll + 6);
+ }
+}
diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rs
index 6642138..1a2b5c8 100644
--- a/tests/tui_acceptance.rs
+++ b/tests/tui_acceptance.rs
@@ -67,12 +67,16 @@ async fn test_tui_all_theme_rendering() {
async fn test_tui_terminal_resizing_matrix_no_panics() {
let sizes = [
(40, 15),
+ (49, 13),
+ (50, 14),
+ (55, 18),
(80, 24),
(100, 30),
(120, 40),
(160, 50),
(200, 60),
(25, 8),
+ (60, 100),
(300, 80),
];
@@ -86,6 +90,77 @@ async fn test_tui_terminal_resizing_matrix_no_panics() {
}
}
+#[tokio::test]
+async fn test_grid_metrics_and_visibility_at_tier_boundaries() {
+ let mut app = App::new();
+ app.state_mut().active_screen = Screen::Home;
+ for i in 0..30 {
+ app.state_mut().search_results.push(SearchResult {
+ id: i.to_string(),
+ title: format!("Title {i}"),
+ stype: 1,
+ release_year: "2020".to_string(),
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ provider: ProviderKind::MovieBox,
+ });
+ }
+
+ app.state_mut().last_result_metrics = Some(app.state().result_metrics(20, 180));
+ let wide = app.state().last_result_metrics.unwrap();
+ assert_eq!(wide.columns, 3);
+ assert!(wide.visible_items >= 3);
+
+ app.state_mut().last_result_metrics = Some(app.state().result_metrics(20, 100));
+ let narrow = app.state().last_result_metrics.unwrap();
+ assert_eq!(narrow.columns, 1);
+ assert!(narrow.visible_items >= 1);
+
+ app.state_mut().poster_rows = 12;
+ let cramped = app.state().result_metrics(10, 100);
+ assert_eq!(cramped.visible_items, 1);
+
+ app.state_mut().poster_rows = 3;
+ app.state_mut().last_result_metrics = Some(app.state().result_metrics(20, 180));
+ app.state_mut().search_list_state.select(Some(29));
+ app.state_mut().result_scroll = 0;
+ app.state_mut().normalize_result_view();
+ let selected = app.state().search_list_state.selected().unwrap();
+ let scroll = app.state().result_scroll;
+ let visible = app.state().effective_visible_items();
+ assert!(selected >= scroll && selected < scroll + visible);
+}
+
+#[tokio::test]
+async fn test_help_overlay_scrolls_with_keys() {
+ let mut app = App::new();
+ let state = app.state_mut();
+ state.show_help = true;
+ state.help_scroll = 0;
+
+ app.handle_action(Action::Key(crossterm::event::KeyEvent::new(
+ crossterm::event::KeyCode::Down,
+ crossterm::event::KeyModifiers::empty(),
+ )))
+ .await;
+ assert_eq!(app.state().help_scroll, 1);
+
+ app.handle_action(Action::Key(crossterm::event::KeyEvent::new(
+ crossterm::event::KeyCode::Up,
+ crossterm::event::KeyModifiers::empty(),
+ )))
+ .await;
+ assert_eq!(app.state().help_scroll, 0);
+
+ app.handle_action(Action::Key(crossterm::event::KeyEvent::new(
+ crossterm::event::KeyCode::Char('x'),
+ crossterm::event::KeyModifiers::empty(),
+ )))
+ .await;
+ assert!(app.state().show_help, "unrelated keys are swallowed");
+}
+
#[tokio::test]
async fn test_mouse_click_help_overlay_dismisses() {
let mut app = App::new();