//! A Ratatui YouTube browser backed by yt-dlp, with playback handed to Terebi. //! //! Run `cargo run -- "rust programming"`; default to the installed Terebi CLI on PATH. //! Key instructions below describe defaults. `[keys]` configures all actions; live hints use overrides. //! `--default-config` prints complete TOML without loading config or starting the terminal. //! Always start in normal mode; a CLI query searches automatically. Press i to edit the query. //! Insert: Enter submits a changed query and returns to normal; Esc returns without searching. //! Search and new-tag text: Option/Alt+Backspace or Ctrl-W deletes the previous whitespace word. //! Cmd/Super+Backspace or Ctrl-U clears the line; plain Backspace removes one character. //! The terminal must transmit modified Backspace; otherwise map it to Ctrl-W or Ctrl-U. //! Active text fields show a steady block cursor at the scrolled end; other views hide it. //! The terminal's configured default cursor shape is restored when the app exits. //! Normal: j/k selects, Enter opens the video in Terebi, and i edits the query. //! View tabs wrap whole labels into rows using terminal-cell widths and reflow on resize. //! Short terminals keep the selected tab row visible while reserving space for the other panes. //! A single label wider than the terminal is clipped rather than split across rows. //! Normal-mode d opens video info; d expands the full description in place, then returns to info. //! Both modes share one centered popup, up to 70% width and 60% height, capped at 96 by 20 cells. //! Full descriptions scroll with Up/Down, Ctrl-J/K, and PgUp/PgDn; plain j/k selects videos. //! Esc closes the popup; i returns to editing. Mode toggles retain cached content and pending work. //! Images use native terminal graphics when supported, otherwise colored half-block characters. //! HQ thumbnails reserve their proportional 4:3 footprint before loading, avoiding metadata reflow. //! Thumbnails have one column of left padding and two columns before the left-aligned text. //! A blank row separates the bold title from the dimmed author · publication date. //! Full descriptions scroll metadata and paragraphs together, with a leading blank row and one-column side padding. //! Description excerpts use normal brightness and retain a two-column right gutter. //! Overflowing excerpts end with … without splitting wide glyphs; full descriptions preserve paragraphs. //! Both modes share an in-memory LRU of 64 full descriptions, keyed by video ID across views. //! Thumbnails retain eight recently used inactive decoded images plus the selected image. //! Reopening or revisiting cached videos skips extraction/download/decoding; resize work stays off-thread. //! Title, author, and publication metadata remain in loaded view rows; preview caches survive view/query changes. //! Caches last for this session without a timer. A successful r refresh clears both preview buffers. //! curl fetches JPEGs lazily into memory; decoding and image resizing/encoding run off-thread. //! Channel tags live in `$XDG_CONFIG_HOME/tubular/config.toml`, or `~/.config/tubular/config.toml`. //! `[categories]` stores flat, overlapping tags: one channel can appear in several arrays. //! Checked tags save the creator's @handle; `[channels]` retains its canonical URL. //! Mapped handles resolve to stable channel IDs; unmapped handles still work directly. //! Deselecting removes the channel from that tag, preserving other creators and empty tags. //! Missing handle/ID metadata or a conflicting mapping prevents saving rather than guessing. //! Normal-mode s edits memberships: j/k moves, Space toggles, Enter commits, Esc cancels. //! i filters tags case-insensitively; arrows or Ctrl-J/K move through matches while typing. //! Enter/Esc leaves filter editing without saving; hidden staged memberships remain unchanged. //! n prompts for a new tag; Enter stages it checked, clears the filter, and selects it. Esc abandons the name. //! Normal-mode S in a category view edits every saved channel, even with no videos loaded. //! Shared tags start checked; Enter atomically replaces every target's tags with the checked set. //! Unchecked tags lose only target channels; other creators, registrations, pins, and empty categories remain. //! n stages a new shared tag; Esc cancels the whole edit. Changed source membership requires reopening. //! Clearing all tags is refused for category-only channels, avoiding accidental unsubscription. //! Search and Feed are permanent tabs. Normal-mode c opens the saved-category browser. //! The category browser starts NORMAL: j/k or arrows move, i filters, Enter browses, p pins, Esc closes. //! INSERT filters live with case-insensitive substring matching; arrows or Ctrl-J/K move, Enter browses. //! Esc returns to NORMAL without clearing the filter; another Esc closes. Search input editing shortcuts apply. //! Matching selections survive filter edits; no matches leaves Enter/p without an action. //! Pinned categories stay visible; browsing another category replaces the single temporary tab. //! Pinned category tab titles use a dimmed `p` suffix; Search, Feed, and temporary tabs do not. //! The suffix stays dimmed when selected and counts toward whole-label wrapping without changing category names. //! Browsing a pinned category focuses its existing tab and removes the temporary tab. //! `[settings].pinned_categories = ["Favorites"]` persists pins; missing category names are ignored. //! Settings, channels, categories and keys tables can appear in any order. Move legacy root pins into settings. //! Tab/Shift-Tab cycle only visible tabs; hidden views retain cached rows and selection. //! In normal mode Esc or minus goes back through visited views, restoring cached rows and selection. //! Plus goes forward after going back; a new view navigation discards the old forward branch. //! Esc closes popups or leaves insert mode first; missing historical views are skipped. //! Normal-mode ? overlays a scrollable keybinding reference without changing the view or dialog. //! Help scrolls with j/k, arrows, Ctrl-J/K and page keys; ? or Esc closes it. Text inputs keep literal ?. //! Normal-mode u opens a searchable saved-channel selector with the category browser's modal controls. //! Normal-mode U opens the selected video's creator directly, without saving a subscription. //! Choices include untagged registrations and category-only channels, deduplicated with readable handle labels. //! Channels and unpinned categories share one temporary tab; hidden views retain caches and back history. //! Channel views use the same pagination but extract only their stored channel identity; S stays category-only. //! Config changes preserve unsaved browsing, relabel saved identities, and drop explicitly removed subscriptions. //! r reloads config and refreshes the current view. //! Feed includes saved `[channels]` entries, even untagged, plus direct tag entries, without duplicates. //! Untagging is not unsubscribing: remove mappings and tag references from the file to unsubscribe. //! Search pages contain 20 results; Feed/tag pages request 20 uploads per channel's /videos tab. //! Invalid individual video entries are discarded; raw entry counts still determine pagination. //! Invalid JSON, playlist-level metadata, and extractor failures remain page errors. //! In normal mode, approaching the loaded end fetches the next page without replacing rows/selection. //! Loading result/preview panes animate a spinner after their title, including additional pages. //! Info spinners cover image download/decode/resize and description fetching; errors stop them. //! Feed rows use approximate upload dates; older rows wait until newer channel pages catch up. //! Undated feed rows appear at exhaustion. Cached views retain their page position across switches. //! Switching views cancels in-flight extraction; returning resumes the same pending range. //! Errors keep loaded rows and stop automatic retries; r reloads config and restarts the current view. //! Deep pages may slow down because yt-dlp offsets re-traverse earlier continuation pages. //! Video tables show Published as YYYY-MM-DD; ~ marks estimated UTC dates, Unknown missing metadata. //! Prefer exact upload dates and cache date labels during extraction, not on every redraw. //! Terebi receives `--new-instance --url` and the canonical YouTube URL; each selection gets its own player. //! `--player` overrides its CLI path; otherwise `terebi` is resolved through PATH. //! The CLI exits after handoff, not playback completion. Later playback errors appear in Terebi. //! Quitting cancels pending metadata/launch processes, not the separately running player. mod config; mod keys; mod thumbnail; mod youtube; use std::{ collections::{BTreeMap, HashSet}, ffi::OsString, io, path::PathBuf, time::{Duration, Instant}, }; use clap::Parser; use keys::{Action, Context}; use ratatui::{ DefaultTerminal, Frame, crossterm::{ cursor::SetCursorStyle, event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}, execute, }, layout::{Constraint, Layout, Rect}, style::{Color, Style, Stylize}, text::{Line, Span, Text}, widgets::{Block, Cell, Clear, List, ListState, Paragraph, Row, Table, TableState, Wrap}, }; use youtube::{Job, PAGE_SIZE, Page, PlayerLaunch, Video}; #[derive(Parser)] #[command( version, about = "Browse YouTube and open selected videos in Terebi", after_help = "Key names below describe default bindings. [keys] overrides named actions with a string or array; omitted actions keep defaults and [] disables an action. Live hints and help reflect overrides.\n--default-config prints complete default TOML to stdout and exits without loading config or starting a terminal.\nRequires yt-dlp for browsing; thumbnails also use curl. Playback requires Terebi and its own streaming dependencies.\nDefaults to terebi on PATH; --player overrides the CLI path.\nTerebi receives --new-instance --url followed by the canonical YouTube video URL and handles extraction, decoding, and playback itself; each selection opens an independent player instance without replacing existing playback.\nAlways start in NORMAL. A CLI query is searched automatically; otherwise press i to enter a query.\nNORMAL ? opens a scrollable keybinding reference over the current view or dialog. The bottom bar shows only essential actions. Scroll help with j/k, arrows, Ctrl-J/K or PageUp/PageDown; ? or Esc closes it. Question mark remains literal text in input fields.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nTEXT EDITING (search, category/channel filters, and new tag): Option/Alt+Backspace or Ctrl-W deletes the previous whitespace-delimited word, including trailing whitespace; Cmd/Super+Backspace or Ctrl-U clears the entire line. Plain Backspace removes one character.\nThe terminal must transmit modified Backspace. If it intercepts Option/Cmd, map those shortcuts to Ctrl-W/Ctrl-U respectively.\nNORMAL: j/k or arrows select; Enter opens the video in Terebi; i edits the query; d opens video info (again for full description); c browses saved categories; u browses saved channels; U opens the selected video's channel; s edits channel tags; S edits all channels in the current category; q quits.\nSearch and Feed are permanent tabs. Pinned categories also stay visible; one temporary category tab is replaced by each new unpinned selection.\nTab/Shift-Tab cycle only visible tabs; Esc or - in NORMAL goes back through view history; + goes forward. Both restore cached rows, selection, and pagination, including replaced temporary tabs. New view navigation clears the forward branch. Removed views are skipped and empty history does nothing. Esc first closes popups or leaves INSERT without navigating; minus and plus type normally in input fields. r reloads config and refreshes the current view from its first page.\nCATEGORY BROWSER (c): starts NORMAL; j/k or arrows move; i enters INSERT to filter; Enter browses; p immediately saves pin/unpin; Esc closes. Choosing a pinned category focuses its existing tab and clears the temporary tab.\nCATEGORY FILTER INSERT: type a case-insensitive substring to filter live; arrows or Ctrl-J/K move; Enter browses the selected match; Esc returns to NORMAL with the filter retained. In NORMAL, j/k and pinning operate on the filtered list. No matches makes Enter/p a no-op. Reopening the selector clears the filter.\nCHANNEL BROWSER (u): starts NORMAL; j/k or arrows move; i enters INSERT to filter; Enter opens only the selected channel's videos; Esc closes. INSERT uses case-insensitive filtering, arrows or Ctrl-J/K to move, Enter to browse, and Esc to return to NORMAL. Empty matches do nothing.\nSaved choices include registered channels (even untagged) and category-only subscriptions, deduplicated by resolved identity; mapped handles label aliases. Channel selection never changes subscriptions or pins.\nChannels and unpinned categories share one temporary browsing tab. Choosing either replaces the previous temporary view while pinned category tabs remain visible. Revisiting or navigating back restores cached rows, selection, and page position. Channel views use the same infinite scrolling but extract only their chosen channel; S remains category-only.\nVIDEO CHANNEL (U / Shift-U): opens the selected video's creator in the same temporary channel tab, reusing cached rows and pagination without subscribing. A canonical channel ID or valid @handle is required; unavailable metadata leaves the current view unchanged. Saved mappings resolve handle-only rows. Unsaved channels do not appear in the saved selector unless you save them.\nReloading config relabels stable saved identities and removes explicitly unsubscribed channels; removing the active saved channel falls back to Search. Unsaved channels opened with U remain browseable for the session.\nHidden category and channel views retain loaded rows, selection, and pagination for this session. Temporary tabs do not survive restarting; pins do.\nPUBLISHED: Every video view shows YYYY-MM-DD. Exact upload dates take precedence; ~ marks an estimated UTC date from flat metadata, and Unknown means unavailable. Dates are cached without fetching full metadata for every video.\nLOADING: Result/feed and preview titles show an animated spinner while content loads, including further pages and thumbnail decoding/resizing; it disappears when ready or on error.\nFeed sits immediately right of Search and combines every saved [channels] registration, including untagged channels, plus channels entered directly in tags.\nChannel URLs and videos are deduplicated; Feed keeps its cached selection and page position when only tag assignments change.\nSubscriptions: $XDG_CONFIG_HOME/tubular/config.toml, or ~/.config/tubular/config.toml when XDG_CONFIG_HOME is unset/empty/relative.\nExample TOML:\n[settings]\npinned_categories = [\"Favorites\"]\n[categories]\nCreators = [\"@jawed\"]\nFavorites = [\"@jawed\"]\n[channels]\n\"@jawed\" = \"https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A\"\n[settings].pinned_categories is an array of category names; pins referencing removed categories are ignored. Settings, channels, categories and keys tables can appear in any order. Add [settings] above pinned_categories in older configs; root-level pins are no longer accepted.\n[categories] defines flat, overlapping tags, each with its own feed; there is no hierarchy or inheritance.\nEntries accept @handles, HTTPS YouTube channel URLs, or canonical UC channel IDs.\n[channels] registers saved handles with canonical channel URLs/IDs; feeds use these stable identities.\nChecked tags save the handle plus its mapping; existing URLs/aliases are replaced with the handle, preserving comments.\nUnchecked tags remove only that channel's tag assignment; other creators, omitted tags, empty tag arrays, saved registrations, and pins are retained.\nUntagging does not unsubscribe from Feed. To unsubscribe, remove all of that channel's [channels] mappings and tag entries, then press r.\nUnmapped handles work directly. Existing URL entries still load.\nSaving a single channel requires a handle and canonical ID; unavailable metadata or conflicting mappings are reported without changing the file.\nPAGINATION: Search loads 20 results per page; Feed and tags request 20 uploads per channel's /videos tab per page.\nMoving near the loaded end in NORMAL fetches more asynchronously, preserving existing rows, selection, and previews. Insert mode and open popups pause automatic prefetch.\nFeed views merge newest-first using approximate upload dates. Older uploads wait while newer channel pages catch up; undated uploads appear when the feed is exhausted.\nStatus shows the page and whether more is available or the end is reached. Switching views cancels pending extraction; returning resumes the same range with cached rows intact.\nPage errors retain loaded rows and stop automatic retries; r reloads config and restarts the current view from page one.\nDeep pages may take longer because yt-dlp offsets re-traverse earlier continuation pages.\nTAGS (s): existing assignments are checked; j/k or arrows move; Space toggles; Enter saves all staged memberships; n prompts for a new tag; Esc cancels without writing.\nTAG FILTER (s/S): i edits a case-insensitive substring filter; arrows or Ctrl-J/K move through matches while typing. Enter or Esc returns to NORMAL without saving or clearing the filter. Hidden staged memberships are retained; no matches makes navigation/toggling a no-op. Reopening clears the filter.\nBULK TAGS (S, category views only): edits all saved channels in the current category, not just channels with loaded videos. Tags shared by every target start checked; mixed memberships start unchecked. Enter atomically applies the exact checked tag set to every target, removing targets from all unchecked categories while leaving other channels untouched. Empty categories, registrations, pins, and comments remain. n stages a new category for all targets; Esc cancels without saving. If source channels changed while editing, close and reopen. Clearing all tags is refused if any target lacks a [channels] registration, so category-only subscriptions are not accidentally lost.\nNEW TAG: type a name; Enter stages it checked, clears the filter, selects the new tag, and returns to the list; Esc abandons the name; Ctrl-U clears.\nNew tags and membership changes reach disk only on Enter in the main tag list.\nVIDEO INFO: d opens thumbnail and details; d again expands the full description inside the same popup; another d returns to info. Esc closes.\nThe popup uses up to 70% width and 60% height, capped at 96 by 20 cells.\nFull descriptions have one-column left/right padding and an empty line above the bold title and dimmed author/publication row. Title, metadata, and description scroll together as one document; paragraphs are preserved. Up/Down or Ctrl-J/K scroll lines and PgUp/PgDn scroll pages. Plain j/k selects videos in either mode.\nThumbnails have one column of left padding and two columns before the text. Image space is reserved before loading so metadata does not shift when decoding finishes.\nThe title is bold, only author/publication metadata is dimmed, and readable excerpts end with an ellipsis when clipped.\nImages fit proportionally on resize. Terminal graphics are detected at startup, falling back to colored half-blocks.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\nSwitching info/description retains in-flight work and cached content. Full descriptions have a session LRU of 64; thumbnails retain eight inactive images plus the selected image.\ni, c, s, S, view changes, and refresh dismiss the preview; successful refresh clears its caches. Typing d or t in INSERT edits text.\nCtrl-C quits in any mode or popup.\nThe player CLI exits once macOS accepts the handoff; Tubular reports launcher errors, while later extraction/playback errors appear in Terebi.\nSelecting another video opens a new Terebi player, leaving existing playback untouched. Quitting Tubular cancels only pending metadata/CLI work; Terebi continues playing independently.\nExample: tubular \"rust programming\"" )] struct Options { /// Terebi CLI executable; accepts --new-instance --url followed by a YouTube video URL. #[arg(long, default_value = "terebi")] player: OsString, /// Print the complete default TOML configuration and exit. #[arg(long, conflicts_with = "query")] default_config: bool, /// Optional initial YouTube search. query: Option, } const DESCRIPTION_CACHE_SIZE: usize = 64; fn cached_description<'a>( cache: &'a std::collections::VecDeque<(String, String)>, id: &str, ) -> Option<&'a str> { cache .iter() .find(|(cached, _)| cached == id) .map(|(_, text)| text.as_str()) } #[derive(Debug, PartialEq, Eq)] enum Mode { Insert, Normal, } #[derive(Clone, Debug, PartialEq, Eq)] enum ViewSource { Search, Feed, Category(String), Channel(String), } impl ViewSource { fn channels<'a>(&'a self, config: &'a config::Config, feed: &'a [String]) -> &'a [String] { match self { Self::Search => &[], Self::Feed => feed, Self::Category(name) => &config.categories[name], Self::Channel(identity) => std::slice::from_ref(identity), } } } struct View { source: ViewSource, name: String, title: String, videos: Vec