diff --git a/src/main.rs b/src/main.rs index 8dd1047..a3ab80a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ //! 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. +//! 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. @@ -73,7 +73,7 @@ use youtube::{Job, PAGE_SIZE, Page, Playback, Video}; #[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 from its first page.\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[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.\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: 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\"" + 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.\nAlways start in NORMAL. A CLI query is searched automatically; otherwise press i to enter a query.\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 from its first page.\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[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.\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: 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). @@ -228,18 +228,13 @@ struct App { impl App { fn new(options: Options, config_path: PathBuf, config: config::Config) -> Self { let query = options.query.clone().unwrap_or_default(); - let mode = if query.trim().is_empty() { - Mode::Insert - } else { - Mode::Normal - }; let feed_channels = config.subscriptions(); let mut views = vec![View::new("Search".into()), View::new("Feed".into())]; views.extend(config.categories.keys().cloned().map(View::new)); Self { options, query, - mode, + mode: Mode::Normal, submitted_query: String::new(), config_path, config, @@ -257,14 +252,14 @@ impl App { description_viewport: None, job: None, playback: None, - status: "Type a query, then press Enter.".into(), + status: "Press i to enter a query, then Enter to search.".into(), } } fn search(&mut self) { let query = self.query.trim(); if query.is_empty() { - self.status = "Enter a search first.".into(); + self.status = "Press i to enter a query, then Enter to search.".into(); return; } if query != self.submitted_query { @@ -310,7 +305,7 @@ impl App { let page = (view.next_start - 1) / PAGE_SIZE + 1; let result = if self.view_index == 0 { if self.submitted_query.is_empty() { - self.status = "Type a query, then press Enter.".into(); + self.status = "Press i to enter a query, then Enter to search.".into(); return; } self.status = format!("Searching for {} (page {page})...", self.submitted_query); @@ -1429,6 +1424,7 @@ mod tests { #[test] fn prefetch_only_runs_near_the_end_in_an_unobstructed_normal_view() { let mut app = app(&["tubular"]); + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); let mut page = youtube::search_results(r#"{"entries":[{"id":"jNQXAC9IVRw","title":"Result"}]}"#) .unwrap(); @@ -1489,6 +1485,7 @@ mod tests { use ratatui::{Terminal, backend::TestBackend}; let mut app = app(&["tubular"]); + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); let mut terminal = Terminal::new(TestBackend::new(24, 20)).unwrap(); for (text, x) in [ ("", 1), @@ -1573,6 +1570,7 @@ mod tests { error: None, }); } else { + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); app.query = input.into(); } app.key(KeyEvent::new(code, modifiers)); @@ -1612,7 +1610,7 @@ mod tests { #[test] fn modal_keys_edit_or_navigate_without_submitting_on_escape() { let mut app = app(&["tubular"]); - assert_eq!(app.mode, Mode::Insert); + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); app.views[0].videos = vec![ Video { id: "jNQXAC9IVRw".into(), @@ -1659,9 +1657,6 @@ mod tests { assert_eq!(app.mode, Mode::Normal); assert!(app.query.is_empty()); assert!(app.job.is_none()); - - assert_eq!(self::app(&["tubular", "rust"]).mode, Mode::Normal); - assert_eq!(self::app(&["tubular", " "]).mode, Mode::Insert); } #[test] @@ -1984,19 +1979,11 @@ mod tests { fn empty_feed_is_informative_and_navigation_wraps_without_extraction() { let mut app = app(&["tubular"]); assert_eq!(app.views.len(), 2); - app.key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); - assert_eq!(app.view_index, 0); - assert_eq!(app.mode, Mode::Insert); - app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); app.key(KeyEvent::new(KeyCode::Tab, KeyModifiers::CONTROL)); assert_eq!(app.view_index, 1); assert!(app.views[1].loaded); assert!(app.views[1].videos.is_empty()); assert_eq!(app.views[1].selection.selected(), None); - assert_eq!( - app.status, - "Feed has no channels. Press c on a search result to add one." - ); assert!(app.job.is_none()); app.key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); assert_eq!(app.view_index, 0); @@ -2104,6 +2091,7 @@ mod tests { #[test] fn thumbnails_are_normal_mode_only_and_other_popups_dismiss_them() { let mut app = app(&["tubular"]); + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); app.key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::NONE)); assert_eq!(app.query, "t"); assert!(!app.thumbnail_open);