//! Independent Ratatui YouTube and Miruro browsers 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. //! Startup offers a centered YouTube/Miruro chooser; --miruro starts directly. Browsers start in normal mode. //! A CLI query searches the selected provider after confirmation. Press i to edit. //! `--miruro apothecary` opens the dedicated Catalog → series → episodes interface. //! Miruro autocomplete returns at most eight catalog titles, without pagination; s saves shows with overlapping tags. //! Playback resolves fresh direct ssub/sun sources off-thread and passes a private source file to Terebi. //! Miruro episode collections retain stable catalog/episode keys, never stream URLs; c browses saved shows by category. //! Route titles follow Miruro's Unicode NFD slug helper; unrepresentable titles report an explicit error. //! 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, Enter opens the video in Terebi, i edits; / jumps to Search and F to 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 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, 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. //! 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 request budget of 60 uploads or query matches. //! Search uses one extractor; feeds batch matching channel ranges across up to 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 uploads; 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 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 a private `--progress-file`; 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. //! 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 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(Parser)] #[command( version, about = "Browse YouTube or Miruro 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.\nYouTube browsing requires yt-dlp; YouTube thumbnails also use curl. Miruro uses the native client and requires Terebi --source-file support. Playback requires Terebi and its own streaming dependencies.\nDefaults to terebi on PATH; --player overrides the CLI path.\nMiruro Enter opens catalog episodes, then resolves fresh direct ssub/sun HLS/VTT into a private source document; the player receives --new-instance --source-file PATH --progress-file PATH. Episodes use stable catalog/episode identity for collections and progress; channel tags remain YouTube-only.\nFor YouTube, Terebi receives --new-instance --url followed by the canonical YouTube video URL plus --progress-file for an independent private reporting stream and handles extraction, decoding, and playback itself; each selection opens an independent player instance without replacing existing playback.\nStartup selects independent YouTube or Miruro interfaces through a centered provider chooser using configured selector keys; Esc/q quits. --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 Miruro interface, input searches its catalog; 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; Enter opens the video in Terebi; 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; 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; 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.\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; Miruro also requires --source-file 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, /// 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