//! A Ratatui YouTube browser backed by yt-dlp and FFmpeg, with no API key. //! //! Run `cargo run -- "rust programming"`; macOS defaults to IINA, other platforms to mpv. //! Without a CLI query, start in insert mode; otherwise search and start in normal mode. //! 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 streams, and i returns to insert mode to edit the query. //! Normal-mode d opens the full description; Up/Down scrolls lines and PgUp/PgDn scrolls pages. //! The centered popup uses up to 70% width and 60% height, capped at 96 by 20 cells. //! Esc closes the popup; j/k loads the selected video's description and i returns to editing. //! Normal-mode t toggles a thumbnail in the same-sized popup; j/k follows selection, Esc closes. //! Images use native terminal graphics when supported, otherwise colored half-block characters. //! Thumbnails scale up or down proportionally to fill the popup without cropping. //! 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 c edits memberships: j/k moves, Space toggles, Enter commits, Esc cancels. //! n prompts for a new tag; Enter stages it checked, Esc returns. Only list Enter writes the file. //! Tab/Shift-Tab switch Search, the combined Feed, then independent tag views; r reloads/refreshes. //! 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. //! Feeds merge up to 20 videos per channel's /videos tab, ordered by approximate upload dates. //! IINA receives `--stdin`; other players must read standard input when passed `-`. //! Audio and video are streamed through a pipe, never saved to a video file. //! See `--help` for controls; replacing playback or quitting cancels its processes. mod config; mod thumbnail; mod youtube; use std::{collections::BTreeMap, ffi::OsString, io, path::PathBuf, time::Duration}; use clap::Parser; 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, widgets::{Block, Clear, List, ListState, Paragraph, Row, Table, TableState, Tabs, Wrap}, }; use youtube::{Job, Playback, Video}; #[derive(Parser)] #[command( version, about = "Search YouTube and stream videos to your chosen player", after_help = "Requires yt-dlp, FFmpeg, and a player on PATH; thumbnails also use curl.\nDefaults to IINA on macOS and mpv elsewhere; --player overrides the default.\nIINA receives '--stdin'; other players receive '-' to read audio/video from standard input.\nWithout a CLI query, start in INSERT; a CLI query is searched automatically in NORMAL.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nTEXT EDITING (search 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 streams; i edits the query; d toggles description; t toggles thumbnail; c edits channel tags; q quits.\nTab/Shift-Tab switch Search, Feed, then tag views; r reloads config and refreshes the current view.\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 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[categories]\nCreators = [\"@jawed\"]\nFavorites = [\"@jawed\"]\n[channels]\n\"@jawed\" = \"https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A\"\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, and saved registrations 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 requires a handle and canonical ID; unavailable metadata or conflicting mappings are reported without changing the file.\nAll feed views combine up to 20 videos per channel's /videos tab, newest-first using approximate upload dates.\nTAGS: 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.\nNEW TAG: type a name; Enter stages it checked 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.\nOpening the description fetches full video metadata, preserving paragraphs and caching it for these results.\nPreview windows use up to 70% width and 60% height, capped at 96 by 20 cells.\nIn descriptions, Up/Down scroll lines and PgUp/PgDn scroll pages; j/k still selects videos.\nEsc closes the description; i closes it to edit the query. Scrolling stays within the text.\nTHUMBNAIL: t or Esc closes; j/k or arrows load the selected video's image; d switches to description.\nThumbnails are fetched lazily into memory and fit proportionally inside the popup on resize.\nTerminal graphics are detected at startup, with colored half-block rendering when image protocols are unavailable.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\ni, c, view changes, and refresh dismiss the thumbnail; typing t in INSERT or a tag name edits text.\nCtrl-C quits in any mode or popup.\nSelecting another video replaces playback. Quitting stops playback.\nExample: tubular --player mpv --player-arg=--volume=50 \"rust programming\"" )] struct Options { /// Player executable (IINA or a player supporting '-' for standard input). #[arg(long, default_value = if cfg!(target_os = "macos") { "iina" } else { "mpv" })] player: OsString, /// Argument passed to the player before its standard-input flag; repeat as needed. #[arg(long, allow_hyphen_values = true)] player_arg: Vec, /// Optional initial YouTube search. query: Option, } #[derive(Debug, PartialEq, Eq)] enum Mode { Insert, Normal, } struct View { name: String, title: String, videos: Vec