//! Terminal YouTube and AniList browsing with playback handed to Terebi. //! //! Startup offers YouTube, AniList and the explicitly separate Miruro legacy catalog. //! `--anilist` opens AniList directly; `--miruro` retains legacy catalog access. //! AniList episode numbers are catalog metadata; visible episodes receive background source checks. //! Unknown counts allow explicit positive episode selection; Terebi resolves sub on demand. //! Stable provider-scoped identities persist, never resolved sources or subtitle URLs. //! AniList and Miruro show libraries remain separate; existing Miruro IDs are never mapped. //! `--default-config` prints complete TOML without starting the terminal. //! Key instructions below describe defaults; live hints reflect `[keys]` overrides. //! Category and combined-category queries search their channels' full histories; other views search YouTube. //! Insert: Enter submits a trimmed changed query; clearing a category query restores uploads. //! Esc keeps the draft without submitting; Search and each category retain independent drafts and pages. //! 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. //! Bracketed paste inserts into the active text field at once, without submitting or triggering shortcuts. //! Pasted line breaks/tabs become spaces; other controls are removed. Non-input contexts ignore paste. //! Terminal bracketed-paste mode is disabled on exit, including unwinding after an error. //! Normal: j/k selects, Space checks, Esc discards checks; Enter plays checks in check order or the hovered video. //! Ctrl+Enter appends the same selection to Terebi's queue without interrupting playback. //! Checks are per view and survive pagination/reordering; replacement queries/refresh clear, collection filters prune. //! Previews share their view's checks. Saves/removes/status remain hovered-only; i edits, / searches and F opens Feed. //! 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 search handles use a saved mapping or an asynchronous canonical-channel lookup. //! Lookup cancellation, missing ID/handle metadata, or conflicting mappings never save a guessed identity. //! 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. //! YouTube 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, Space checks, Enter browses, p pins. //! 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. //! Checks survive filtering: Enter browses checked categories, or the hovered match when none are checked. //! Pinned categories stay visible; browsing another category replaces the single temporary tab. //! Multiple checked categories form a newest-first deduplicated temporary feed; c rechecks its members. //! Category rows show checkboxes independently of the dim p pin suffix; Esc cancels staged choices. //! P saves a combined feed's current channel union as a new flat, unpinned category; Esc cancels the name. //! Saving a group or renaming a category preserves its query drafts, submitted query, and matching cached pages. //! Changed channel membership resets pages and cursors without discarding the view's queries. //! 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 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, combined feeds and unpinned categories share one temporary tab; hidden views retain history. //! Channel views use the same pagination but extract only their stored channel identity; S stays category-only. //! Unfiltered channel/feed/tag catalogs traverse uploads, then flatten Releases album tracks. //! Release tracks share the raw-row budget; absent Releases tabs are normal, other failures are page errors. //! 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 60 results; Feed/tag pages share a total budget of 60 catalog rows or query matches. //! Upload/search ranges are batched; release discovery/albums also stay within four concurrent extractors. //! Invalid individual video entries are discarded; raw entry counts still determine pagination. //! Invalid JSON, playlist-level metadata, and extractor failures remain page errors. //! Forward video navigation authorizes prefetch within 20 rows of the loaded end in unobstructed normal mode. //! Each accepted page clears that intent, so short or invalid batches never auto-chain on startup. //! 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, including undated rows, are globally newest-first among loaded catalog entries; selection follows video ID. //! Switching views cancels in-flight extraction; returning retains the unaccepted request and per-channel offsets. //! 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 entries show the title above channel · YYYY-MM-DD; ~ marks estimated UTC dates, Unknown missing metadata. //! Prefer exact upload dates and cache date labels during extraction, not on every redraw. //! One item uses `--new-instance --url URL --progress-file PATH`; a batch uses `--new-instance --queue-file ABS_PATH`. //! Private version-1 manifests preserve canonical URLs, order, and an independent reporting session for each item. //! Checks clear after launcher spawn succeeds and remain checked on failure; each submission opens 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. //! w/v save to watch later/saved videos; W/V choose combined or category scopes in searchable selectors. //! Alt-w/Alt-v browse the current explicit category's collection, including from collection previews. //! C opens combined currently watching; m/M mark the selected video watching/watched, including previews. //! Collection views allow x/X selected/bulk removal, including previews; removal never marks watched. //! All three collections store offline metadata beside config.toml; channel tags determine category lists. //! Saved titles are green before watch-later magenta; ✓ marks watched status, set manually or by eligible playback reaching 95%. //! In watch-later, f cycles All/Unwatched/Watched. X confirms removal of the current filtered/category subset. //! In saved-video views, X confirms removal of the current category/list subset; other collections and watched state stay unchanged. //! Configure view.collection.remove.selected and view.collection.remove.bulk; y/Enter confirms bulk, n/Esc cancels. mod config; mod keys; mod miruro_browser; mod miruro_ui; mod thumbnail; mod titles; mod ui; mod video_state; 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, DisableBracketedPaste, EnableBracketedPaste, 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 video_state::{CollectionKind, WatchStatus}; use youtube::{Job, PAGE_SIZE, Page, PlayerLaunch, Video}; #[derive(Clone, Parser)] #[command( version, about = "Browse YouTube or AniList 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.\nAniList browsing uses native GraphQL with no Miruro dependency. Episode numbers are catalog metadata; visible episodes are checked separately for ZokoAnime sub sources, and playback resolves fresh. Unknown-count series accept an explicit positive episode using i. --anilist opens this catalog directly; --miruro is explicitly legacy. Show libraries and episode identities remain provider-isolated. YouTube browsing requires yt-dlp; thumbnails/cover art use curl. Legacy Miruro browsing uses the native catalog client; Terebi must support Miruro episode URLs and version-2 progress. Playback requires Terebi and its own streaming dependencies.\nDefaults to terebi on PATH; --player overrides the CLI path.\nMiruro Enter opens catalog episodes, then plays checked episodes in check order, or the hovered episode. One episode uses --new-instance --url URL --progress-file PATH; multiple episodes use --new-instance --queue-file PATH. Terebi resolves each current episode on demand, including sources, subtitles and playback metadata. Episodes use stable catalog/episode identity for collections and progress; channel tags remain YouTube-only.\nFor one YouTube video, Terebi receives --new-instance --url followed by the canonical YouTube video URL plus --progress-file. Multiple videos use --new-instance --queue-file with an absolute private version-1 JSON manifest containing ordered canonical URLs and independent private progress_file paths. Terebi resolves only the current item on demand; plain Enter opens one independent player without replacing existing playback. Ctrl+Enter (video.enqueue) sends either one video or checked videos using --enqueue --queue-file with the same private manifest format, appending to a running player without interrupting playback, or launching the queue if none is running.\nStartup selects independent YouTube, AniList or Miruro legacy interfaces through a centered provider chooser using configured selector keys; Esc/q quits. --anilist or --miruro skips the chooser. The chosen browser starts in NORMAL and searches any CLI query 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 the trimmed query if changed and returns to NORMAL; Esc keeps the draft without submitting. In category and combined-category views, queries search only those channels' full histories, not just loaded rows; clearing the query restores uploads. Each category keeps its own draft, submitted query and pagination, independent of general Search. In the independent anime interfaces, input searches the selected catalog (or selects an explicit episode for unknown AniList counts); YouTube views submit to general YouTube Search. Repeating a submitted query reuses its cache or pending request.\nTEXT EDITING (search, category/channel filters, new tag, and category name prompts): 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.\nYOUTUBE NORMAL: j/k or arrows select; Space toggles a playback check; Esc discards checks (Ctrl-Space also clears); Enter plays checked videos in check order, or the hovered video when none are checked. These controls also work in collection views and previews. Configure video.select.toggle, video.select.clear and video.enqueue. Checks belong to each view, survive pagination and reordering by video ID, clear on replacement refresh/query and successful launcher spawn, and are pruned when filters or collections hide/remove rows. Failed launches retain checks. Saves, removals and status actions still affect only the hovered video; i edits the query; / jumps to Search; F jumps to Feed; 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; R renames the current explicit category; P saves the active combined category feed as a new category; q quits.\nWATCH LATER: w saves the selected video once (also in previews); W opens a searchable watch-later collection selector; Alt-w opens the current explicit category's watch-later list. Both work in previews. Moving between watch-later scopes preserves the watched filter. Lists follow current channel category memberships and use persisted metadata offline. Only in watch-later views and their previews, x removes the selected video and X (Shift-X) prompts to remove the current filtered/category subset. Configure view.collection.remove.selected and view.collection.remove.bulk. In watch-later views f cycles All/Unwatched/Watched; y confirms bulk, n/Esc cancels, and Enter never confirms. The other collection and watched status are unchanged. Watch-later titles are magenta; a checkmark marks watched videos in every table. Eligible acknowledged progress reaching 95% of a known duration marks watched; seeking near the end counts, launcher exit does not. Separate watch-later.toml and watch-state.toml sit beside config.toml. Private playback-sessions survive Tubular exit for next-launch recovery.\nSAVED VIDEOS: v saves the selected video once (also in previews); V opens a searchable saved-video collection selector; Alt-v opens the current explicit category's saved-video list, including from a category watch-later list. Both work in previews. Alt-w/Alt-v require a category view or category-scoped collection; Search, Feed, combined category feeds, channel views and all-categories collections do not infer a category. Lists derive from current channel memberships and use offline metadata in saved-videos.toml beside config.toml. Only in saved-video views and their previews, x removes the selected video and X prompts to remove the current category/list subset, without changing watch later or watched state. Search, Feed, category and channel views and their previews never remove collection membership. Saved titles are green, taking precedence over watch-later magenta. Saved lists have no watched filter; bulk removal snapshots the current list. Both collections share the temporary tab and cached back/forward history.\nCURRENTLY WATCHING: C (Shift-C) directly opens the provider-local combined offline list of acknowledged started, unfinished videos. Positive playback progress admits a video, not launcher success; watched videos leave automatically. x removes selected and X confirms removing the list, without marking watched. Removal persists and old session reports never re-add it; a new playback session can. currently-watching.toml sits beside config.toml. This view shares collection previews, temporary tabs and navigation history; it has no category selector or watched filter.\nCOLLECTION SELECTORS (W / V): All categories (combined) is the first entry, followed by configured categories. Start in NORMAL; j/k or arrows move; i enters INSERT to filter by a case-insensitive substring. Arrows or Ctrl-J/K move while typing; Enter opens the selected scope, or does nothing with no matches. Esc returns to NORMAL then closes without navigating; reopening clears the filter. Collection selectors do not change category pins.\nYouTube Search 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; - 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; Space checks categories; Enter browses checked categories, or the hovered match if none are checked; p immediately saves pin/unpin; R renames the hovered category; Esc cancels checks and closes. Checkboxes are separate from the dim p pin marker. One checked category opens its ordinary view; multiple checked categories open their combined newest-first, deduplicated feed. Configure selector.toggle to change Space. 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 checked categories, or the selected match if none are checked; Esc returns to NORMAL with the filter retained. Space remains text while filtering. Hidden checked categories stay checked. With no checks and no matches, Enter/p do nothing. Reopening clears the filter and prechecks the active combined feed members.\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, combined category feeds 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, combined category and channel views retain loaded rows, selection, and pagination for this session. Combined feeds retain their cache when member assignments change but the resolved channel union stays equal; deleting a member invalidates the combined view rather than widening it. 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 60 results per page; Feed, categories, and channel views share a 60-row budget across up to four concurrent extractors. Category queries request matching channel-history results instead of uploads.\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 sort all loaded rows newest-first using approximate upload dates, including undated rows. Selection follows video identity when later pages reorder rows.\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; R renames the selected tag; Esc cancels staged memberships without undoing committed renames.\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.\nSAVE COMBINED CATEGORY (P / Shift-P): only an active combined category feed can be saved, including from its previews. The floating name prompt uses shared input editing controls; Enter saves a new flat category containing the currently viewed channel union, using mapped handles where available; Esc cancels without writes. Invalid or duplicate names keep the prompt open and current view unchanged. Saving copies memberships, not dynamic source-category definitions; later source-category edits do not affect the saved category. The new category becomes the active unpinned temporary tab, preserving matching cached rows, selection, pending pages, query draft and submitted query, and pagination without refetching. Source categories and existing pins stay unchanged. Configure category.save; P remains text in inputs.\nCATEGORY RENAME (R / Shift-R): rename the current category or category-scoped collection, the hovered category in category/collection selectors, or a selected tag in single/bulk tagging. Combined and channel rows cannot be renamed. The prefilled floating input uses shared editing controls; Enter commits, Esc cancels. Existing category identity is saved immediately, with memberships, pins, comments, cached selection/pages/watch filters and navigation history preserved. Tag membership changes remain staged until the main tag-list Enter; an unstored new tag rename also stays staged. Invalid, duplicate, or externally changed source categories keep the prompt open without writes; close dialogs and reload config with r before retrying external changes. Configure category.rename; R remains literal in filter/search inputs.\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.\nPlain Enter opens a new Terebi player, leaving existing playback untouched; Ctrl+Enter appends to the running queue instead. Quitting Tubular cancels only pending metadata/CLI work; Terebi continues playing independently.\nExample: tubular \"rust programming\"" )] struct Options { /// Terebi CLI executable with URL, queue-file and per-item progress support. #[arg(long, default_value = "terebi")] player: OsString, /// Print the complete default TOML configuration and exit. #[arg(long, conflicts_with = "query")] default_config: bool, /// Skip the provider chooser and open the dedicated Miruro catalog interface. #[arg(long)] miruro: bool, /// Open AniList with visible-episode source checks and fresh sub resolution on play. #[arg(long, conflicts_with = "miruro")] anilist: bool, /// Optional initial search for the selected provider. 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), CategoryGroup(Vec), Channel(String), WatchLater(Option), SavedVideos(Option), Watching, } impl ViewSource { fn channels<'a>( &'a self, config: &'a config::Config, feed: &'a [String], group: &'a [String], ) -> &'a [String] { match self { Self::Search | Self::WatchLater(_) | Self::SavedVideos(_) | Self::Watching => &[], Self::Feed => feed, Self::Category(name) => &config.categories[name], Self::CategoryGroup(_) => group, Self::Channel(identity) => std::slice::from_ref(identity), } } fn category(&self) -> Option<&str> { match self { Self::Category(name) | Self::WatchLater(Some(name)) | Self::SavedVideos(Some(name)) => { Some(name) } _ => None, } } fn rename_category(&mut self, old: &str, new: &str) -> bool { match self { Self::Category(name) | Self::WatchLater(Some(name)) | Self::SavedVideos(Some(name)) if name.as_str() == old => { *name = new.to_owned(); true } Self::CategoryGroup(names) if names.iter().any(|name| name == old) => { for name in names.iter_mut() { if name == old { *name = new.to_owned(); } } names.sort_unstable(); names.dedup(); true } _ => false, } } } fn category_union(names: &[String], config: &config::Config) -> Option> { let mut channels = Vec::new(); for name in names { channels.extend(config.categories.get(name)?.iter().cloned()); } channels.sort_unstable(); channels.dedup(); Some(channels) } fn group_name(names: &[String]) -> String { format!("Combined · {}", names.join(" + ")) } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] enum WatchFilter { #[default] All, Unwatched, Watched, } impl WatchFilter { fn label(self) -> &'static str { match self { Self::All => "All", Self::Unwatched => "Unwatched", Self::Watched => "Watched", } } fn next(self) -> Self { match self { Self::All => Self::Unwatched, Self::Unwatched => Self::Watched, Self::Watched => Self::All, } } fn includes(self, watched: bool) -> bool { self == Self::All || watched == (self == Self::Watched) } } fn video_in_channels(video: &Video, channels: &[String], config: &config::Config) -> bool { channels.iter().any(|identity| { video.channel_id.as_deref().is_some_and(|id| { identity == id || identity.strip_prefix("https://www.youtube.com/channel/") == Some(id) }) || video.uploader_id.as_deref().is_some_and(|handle| { identity.strip_prefix("https://www.youtube.com/") == Some(handle) || (video.channel_id.is_none() && config.channels.get(handle) == Some(identity)) }) }) } struct CollectionRemoval { kind: CollectionKind, ids: Vec, category: Option, filter: Option, text: String, } struct View { source: ViewSource, name: String, group_channels: Vec, query: String, submitted_query: String, title: String, videos: Vec