Commit 4a3947397f

4a3947397fe2de2cda4a6bfbd5365015546ebdb9

parent: 947b90ad9b

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-06-23 18:11 UTC

Changed nothing btw

Layout: unified · split

README.md +57 −132
@@ -1,144 +1,69 @@
1## Warning: 1![](https://img.shields.io/github/languages/top/siriusmart/youtube-tui?label=rust)
2* This app is only for *\*nix* systems 2![](https://shields.io/github/license/siriusmart/youtube-tui)
3[![](https://img.shields.io/crates/d/youtube-tui?label=crates.io%20downloads)](https://crates.io/crates/youtube-tui)
4[![](https://img.shields.io/crates/v/youtube-tui?label=crates.io%20version)](https://crates.io/crates/youtube-tui)
5![](https://shields.io/github/stars/siriusmart/youtube-tui?style=social)
3 6
4## Changes made in this commit 7# YouTube TUI
5* Channel support 8
9An aesthetically pleasing pleasing YouTube TUI written in Rust.
10
11## Overview
12
13YouTube TUI is a text user interface that provides a clean UI for browsing YouTube content. It can perform searches and view channels in the terminal, play videos and playlists with external programs like MPV. Rust is used in writing this program for its better performance and ease of maintaining.
14
15This program is being actively developed and there will be new features coming up every commit.
16
17> ### What's new in this commit
18>
19> * Code is being cleaned up but still unreadable
20> * Haven't touched this project for a week because of exams, so I'm just trying to figure out how stuff works again
21> * Just a little save stat before I overhaul the configs and how it's handled
6 22
7## Installation 23## Installation
8Requirements: Git, Cargo and the Rust Compiler
9 24
10Executable size: ~12.5MB 25### Install from crates.io
11 26
12```bash 27```bash
13# Install from crates.io (might not be as up-to-date as the one on GitHub)
14cargo install youtube-tui 28cargo install youtube-tui
15``` 29```
30### Clone from GitHub and build
31
32```bash
33git clone https://github.com/sirusmart/youtube-tui && cd youtube-tui && cargo build --release
34```
35
36The binary is located at `./target/release/youtube-tui`, go move it to other locations so that you can launch the program with `youtube-tui` command.
37
38## Usage
39
40### To launch
16 41
17```bash 42```bash
18# Install from GitHub with cargo install (The binary will be placed in ~/.cargo/bin, and can be called with `youtube-tui`) 43youtube-tui # or path to the binary
19git clone https://github.com/siriusmart/youtube-tui && cd youtube-tui && cargo install --path . && cd .. && rm -rf youtube-tui
20``` 44```
21 45
22## Features 46### Movement
23* View the Trending and Popular tab of YouTube 47
24* View your Watch history 48|Key|What does it do|
25* Download videos and audio 49|---|---|
26* Watch videos and audio 50|Arrow keys|Move in corresponding direction|
27* Video and playlist support 51|Right arrow|Move cursor right
28 52|Enter|Select/Launch|
29## Movement 53|Q|Quit the program|
30* Use the arrow keys to move around the screen 54
31* Press enter to select an item 55> ### Note
32* When item is selected all your keys will be passed into it 56>
33* Press escape to exit the item 57> These keys only work when nothing is selected. When something is selected, your key presses are passed directly to the "object" you've selected. Press escape (Esc) if you want to deselect.
34* Press q to quit the program 58
35 59## Credits
36## Layout 60
37* Each divided area is one item 61* [ytfzf](https://github.com/pystardust/ytfzf) by [pystardust](https://github.com/pystardust) - The TUI I used to watch YouTube, gave me an idea how this program is going to work
38* Red shows the item your currently on 62* [Terminal Typeracer](https://gitlab.com/ttyperacer/terminal-typeracer) by [Darrien Glasser](https://gitlab.com/DarrienG) - A very clean looking TUI for typing speed test, gave me idea on how this program should look like
39* Blue shows the selected item 63* [Invidious](https://invidious.io) - For having a nice API for doing YouTube searches and stuff. (I made a wrapper for the API you can check it [here](https://crates.io/crates/invidious) out if you want to)
40* Yellow shows an item in a special state 64
41 65
42## Storage 66... and of course, credits to myself for not having the ability to read the docs for ytfzf and decided to make my own instead.
43* Cache is stored in `~/.cache/youtube-tui`, it is cleared when you quit the program 67## Bug reports
44* Storage is stored in `~/.local/share/youtube-tui` 68
45* Config files are stored in `~/.config/youtube-tui` 69If there is an issue with this program, please open an issue on GitHub, thank you :D
46
47## Config files
48The config files are located in `~/.config/youtube-tui`, run the program once to create the config files. The following are the default config files:
49
50> ### `main.yml`
51> ```yaml
52> # The program's main config file
53> ---
54> yt_dl: # Donwload location for your downloaded videos
55> video_path: ~/Downloads/%(title)s.%(ext)s
56> audio_path: ~/Downloads/%(title)s.%(ext)s
57> max_watch_history: 50 # Maximum length of watch history
58> ```
59
60> ### `commands.yml`
61> ```yaml
62> # Command arguments to use when launching applications
63> ---
64> video_player:
65> command: mpv
66> open_in_console: false
67> args:
68> - "--no-terminal"
69> - "{url}"
70> audio_player:
71> command: mpv
72> open_in_console: true
73> args:
74> - "--no-video"
75> - "{url}"
76> image_viewer:
77> command: mpv
78> open_in_console: false
79> args:
80> - "{url}"
81> - "--no-terminal"
82> video_downloader:
83> command: yt-dlp
84> open_in_console: true
85> args:
86> - "{url}"
87> - "-o"
88> - "{video_save_location}"
89> audio_downloader:
90> command: yt-dlp
91> open_in_console: true
92> args:
93> - "{url}"
94> - "-o"
95> - "{audio_save_location}"
96> - "-x"
97> terminal:
98> command: konsole
99> open_in_console: false
100> args:
101> - "-e"
102> - "{command}"
103> playlist_audio_all:
104> command: mpv
105> open_in_console: true
106> args:
107> - "--no-video"
108> - "{url}"
109> playlist_video_all:
110> command: mpv
111> open_in_console: false
112> args:
113> - "{url}"
114> - "--no-terminal"
115> playlist_shuffle_audio_all:
116> command: mpv
117> open_in_console: true
118> args:
119> - "--no-video"
120> - "{url}"
121> - "--shuffle"
122> download_all_audio:
123> command: yt-dlp
124> open_in_console: true
125> args:
126> - "{url}"
127> - "-o"
128> - "{audio_save_location}"
129> - "-x"
130> download_all_video:
131> command: yt-dlp
132> open_in_console: true
133> args:
134> - "{url}"
135> - "-o"
136> - "{video_save_location}"
137> ```
138## To Do
139* Update notice (e.g. when a new version is released on GitHub or crates.io, can be disabled in the config file)
140* Keybind options (e.g. change the keybinds in the config file)
141* Channel search + item sorting
142
143## Bugs
144* If there is a bug please open a GitHub issue thx :)\ No newline at end of file
src/app/app.rs +40 −138
@@ -6,7 +6,7 @@ use std::{
6use crate::{ 6use crate::{
7 app::pages::main_menu::*, 7 app::pages::main_menu::*,
8 structs::{AppHistory, Item, Page, Row, SearchSettings, WatchHistory}, 8 structs::{AppHistory, Item, Page, Row, SearchSettings, WatchHistory},
9 traits::{KeyInput, SelectItem}, 9 traits::{ItemTrait, PageTrait},
10}; 10};
11use crossterm::event::KeyCode; 11use crossterm::event::KeyCode;
12use invidious::blocking::Client; 12use invidious::blocking::Client;
@@ -23,7 +23,7 @@ use super::{
23 pages::{channel::Channel, item_info::ItemInfo, search::Search}, 23 pages::{channel::Channel, item_info::ItemInfo, search::Search},
24}; 24};
25 25
26#[derive(Debug)] 26#[derive(Debug, Clone)]
27pub struct App { 27pub struct App {
28 pub config: Config, 28 pub config: Config,
29 pub page: Page, 29 pub page: Page,
@@ -96,47 +96,11 @@ impl App {
96 pub fn key_input(mut self, key: KeyCode) -> App { 96 pub fn key_input(mut self, key: KeyCode) -> App {
97 if let Some((x, y)) = self.selected { 97 if let Some((x, y)) = self.selected {
98 if key != KeyCode::Esc { 98 if key != KeyCode::Esc {
99 match &mut self.state[y].items[x].item { 99 let mut item = self.state[y].items[x].item.clone();
100 Item::Global(item) => { 100 let updated;
101 let mut item = item.clone(); 101 (updated, self) = item.key_input(key, self);
102 let hold = item.key_input(key, self); 102 if updated {
103 self = hold.1; 103 self.state[y].items[x].item = item;
104 if hold.0 {
105 self.state[y].items[x].item = Item::Global(item);
106 }
107 }
108 Item::MainMenu(item) => {
109 let mut item = item.clone();
110 let hold = item.key_input(key, self);
111 self = hold.1;
112 if hold.0 {
113 self.state[y].items[x].item = Item::MainMenu(item);
114 }
115 }
116 Item::ItemInfo(item) => {
117 let mut item = item.clone();
118 let hold = item.key_input(key, self);
119 self = hold.1;
120 if hold.0 {
121 self.state[y].items[x].item = Item::ItemInfo(item);
122 }
123 }
124 Item::Search(item) => {
125 let mut item = item.clone();
126 let hold = item.key_input(key, self);
127 self = hold.1;
128 if hold.0 {
129 self.state[y].items[x].item = Item::Search(item);
130 }
131 }
132 Item::Channel(item) => {
133 let mut item = item.clone();
134 let hold = item.key_input(key, self);
135 self = hold.1;
136 if hold.0 {
137 self.state[y].items[x].item = Item::Channel(item);
138 }
139 }
140 } 104 }
141 105
142 return self; 106 return self;
@@ -148,7 +112,9 @@ impl App {
148 if self.hover.is_some() && self.selected.is_none() { 112 if self.hover.is_some() && self.selected.is_none() {
149 let (mut x, mut y) = self.hover.unwrap(); 113 let (mut x, mut y) = self.hover.unwrap();
150 (x, y) = self.selectable[y][x]; 114 (x, y) = self.selectable[y][x];
151 match self.state[y] 115
116 let select;
117 (self, select) = self.state[y]
152 .items 118 .items
153 .iter() 119 .iter()
154 .nth(x) 120 .nth(x)
@@ -156,42 +122,9 @@ impl App {
156 .unwrap() 122 .unwrap()
157 .item 123 .item
158 .clone() 124 .clone()
159 { 125 .select(self);
160 Item::Global(mut item) => { 126 if select {
161 let held = item.select(self); 127 self.selected = Some((x, y));
162 self = held.0;
163 if held.1 {
164 self.selected = Some((x, y));
165 }
166 }
167 Item::MainMenu(mut item) => {
168 let held = item.select(self);
169 self = held.0;
170 if held.1 {
171 self.selected = Some((x, y));
172 }
173 }
174 Item::ItemInfo(mut item) => {
175 let held = item.select(self);
176 self = held.0;
177 if held.1 {
178 self.selected = Some((x, y));
179 }
180 }
181 Item::Search(mut item) => {
182 let held = item.select(self);
183 self = held.0;
184 if held.1 {
185 self.selected = Some((x, y));
186 }
187 }
188 Item::Channel(mut item) => {
189 let held = item.select(self);
190 self = held.0;
191 if held.1 {
192 self.selected = Some((x, y));
193 }
194 }
195 } 128 }
196 129
197 return self; 130 return self;
@@ -268,9 +201,10 @@ impl App {
268 self 201 self
269 } 202 }
270 203
271 pub fn render<B: Backend>(&mut self, frame: &mut Frame<B>) { 204 pub fn render<B: Backend>(mut self, frame: &mut Frame<B>) -> Self {
272 let size = frame.size(); 205 let size = frame.size();
273 let mut popups = Vec::new(); 206 let mut popups = Vec::new();
207 let mut modified = Vec::new();
274 208
275 let min = match self.page { 209 let min = match self.page {
276 Page::MainMenu(_) => MainMenu::min(), 210 Page::MainMenu(_) => MainMenu::min(),
@@ -288,7 +222,7 @@ impl App {
288 .style(Style::default().fg(Color::Red)) 222 .style(Style::default().fg(Color::Red))
289 .wrap(Wrap { trim: true }); 223 .wrap(Wrap { trim: true });
290 frame.render_widget(paragraph, size); 224 frame.render_widget(paragraph, size);
291 return; 225 return self;
292 } 226 }
293 227
294 let hover_selected = if let Some((x, y)) = self.hover { 228 let hover_selected = if let Some((x, y)) = self.hover {
@@ -307,9 +241,10 @@ impl App {
307 ) 241 )
308 .split(size); 242 .split(size);
309 243
310 for (y, (row, row_chunk)) in self 244 let state = self.state.clone();
311 .state 245
312 .iter_mut() 246 for (y, (row, row_chunk)) in state
247 .iter()
313 .zip(vertical_chunks.clone().into_iter()) 248 .zip(vertical_chunks.clone().into_iter())
314 .enumerate() 249 .enumerate()
315 { 250 {
@@ -348,73 +283,40 @@ impl App {
348 283
349 frame.render_widget(Block::default(), chunks.next().unwrap()); 284 frame.render_widget(Block::default(), chunks.next().unwrap());
350 285
351 for (x, (chunk, item)) in chunks 286 for (x, (chunk, item)) in chunks.zip(row.items.iter().map(|i| &i.item)).enumerate() {
352 .zip(row.items.iter_mut().map(|i| &mut i.item))
353 .enumerate()
354 {
355 let selected = self.selected == Some((x, y)); 287 let selected = self.selected == Some((x, y));
356 288
357 let hover = hover_selected == Some((x, y)); 289 let hover = hover_selected == Some((x, y));
290 let popup_focus = self.popup_focus;
358 291
359 if match item { 292 let hold =
360 Item::Global(i) => i.render_item( 293 item.render_item(frame, chunk, self, selected, hover, popup_focus, false);
361 frame,
362 chunk,
363 selected,
364 hover,
365 false,
366 &*self.message.lock().unwrap(),
367 &mut self.search_settings,
368 &self.search_text,
369 ),
370 Item::MainMenu(i) => {
371 i.render_item(frame, chunk, selected, hover, self.popup_focus, &self.page);
372 false
373 }
374 294
375 Item::ItemInfo(i) => { 295 self = hold.2;
376 i.render_item(frame, chunk, selected, hover, self.popup_focus);
377 false
378 }
379 296
380 Item::Search(i) => { 297 if let Some(item) = hold.1 {
381 i.render_item(frame, chunk, selected, hover, self.popup_focus); 298 modified.push((x, y, item));
382 false 299 }
383 }
384 300
385 Item::Channel(i) => { 301 if hold.0 {
386 i.render_item(frame, chunk, selected, hover, self.popup_focus, &self.page); 302 popups.push((item, selected, hover, chunk, x, y));
387 false
388 }
389 } {
390 popups.push((item, selected, hover, chunk));
391 } 303 }
392 } 304 }
393 } 305 }
394 306
395 for (item, selected, hover, chunk) in popups { 307 for (item, selected, hover, chunk, x, y) in popups {
396 match item { 308 let hold = item.render_item(frame, chunk, self, selected, hover, true, true);
397 Item::Global(i) => { 309 self = hold.2;
398 i.render_item(
399 frame,
400 chunk,
401 selected,
402 hover,
403 true,
404 &*self.message.lock().unwrap(),
405 &mut self.search_settings,
406 &self.search_text,
407 );
408 }
409 _ => {} // Item::MainMenu(i) => {
410 // i.render_item(frame, chunk, selected, hover, &self.page);
411 // }
412 310
413 // Item::ItemInfo(i) => { 311 if let Some(item) = hold.1 {
414 // i.render_item(frame, chunk, selected, hover); 312 modified.push((x, y, item));
415 // }
416 } 313 }
417 } 314 }
315
316 for (x, y, item) in modified {
317 self.state[y].items[x].item = item;
318 }
319 self
418 } 320 }
419 321
420 pub fn pop(mut self) -> (App, bool) { 322 pub fn pop(mut self) -> (App, bool) {
src/app/pages/channel.rs +55 −20
@@ -12,8 +12,10 @@ use tui::{
12use crate::{ 12use crate::{
13 app::app::App, 13 app::app::App,
14 functions::download_all_thumbnails, 14 functions::download_all_thumbnails,
15 structs::{FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem}, 15 structs::{
16 traits::{KeyInput, SelectItem}, 16 FullChannel, Item, ListItem, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
17 },
18 traits::{ItemTrait, PageTrait},
17 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 19 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
18}; 20};
19 21
@@ -43,8 +45,8 @@ pub enum ChannelDisplayItem {
43 Unknown, 45 Unknown,
44} 46}
45 47
46impl ChannelItem { 48impl ItemTrait for ChannelItem {
47 pub fn load_item(&self, app: &App) -> Result<Self, Box<dyn Error>> { 49 fn load_item(&self, app: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn Error>> {
48 let mut this = self.clone(); 50 let mut this = self.clone();
49 51
50 if let Page::Channel(channel_page, id) = &app.page { 52 if let Page::Channel(channel_page, id) = &app.page {
@@ -112,18 +114,28 @@ impl ChannelItem {
112 } 114 }
113 } 115 }
114 116
115 Ok(this) 117 Ok(Item::Channel(this))
116 } 118 }
117 119
118 pub fn render_item<B: Backend>( 120 fn render_item<B: Backend>(
119 &mut self, 121 // &mut self,
122 // frame: &mut Frame<B>,
123 // rect: Rect,
124 // selected: bool,
125 // hover: bool,
126 // popup_focus: bool,
127 // page: &Page,
128 &self,
120 frame: &mut Frame<B>, 129 frame: &mut Frame<B>,
121 rect: Rect, 130 rect: Rect,
131 app: App,
122 selected: bool, 132 selected: bool,
123 hover: bool, 133 hover: bool,
124 popup_focus: bool, 134 popup_focus: bool,
125 page: &Page, 135 _: bool,
126 ) { 136 ) -> (bool, Option<Item>, App) {
137 let mut out = (false, None, app);
138
127 let mut style = Style::default().fg(if selected { 139 let mut style = Style::default().fg(if selected {
128 Color::LightBlue 140 Color::LightBlue
129 } else if hover { 141 } else if hover {
@@ -172,9 +184,16 @@ impl ChannelItem {
172 184
173 frame.render_widget(split, rect); 185 frame.render_widget(split, rect);
174 186
175 textlist.area(chunks[0]);
176 let mut textlist = textlist.clone(); 187 let mut textlist = textlist.clone();
177 188
189 textlist.area(chunks[0]);
190
191 let hold_textlist = if textlist.area == textlist.prev_area {
192 None
193 } else {
194 Some(textlist.clone())
195 };
196
178 if selected { 197 if selected {
179 textlist.selected_style(Style::default().fg(Color::LightRed)); 198 textlist.selected_style(Style::default().fg(Color::LightRed));
180 } else { 199 } else {
@@ -193,6 +212,12 @@ impl ChannelItem {
193 } 212 }
194 213
195 frame.render_widget(textlist, chunks[0]); 214 frame.render_widget(textlist, chunks[0]);
215
216 if let Some(textlist) = hold_textlist {
217 out.1 = Some(Item::Channel(ChannelItem::InfoDisplay(
218 ChannelDisplayItem::Videos(videos.clone(), textlist),
219 )));
220 }
196 } 221 }
197 ChannelDisplayItem::Playlists(playlists, textlist) => { 222 ChannelDisplayItem::Playlists(playlists, textlist) => {
198 let split = HorizontalSplit::default() 223 let split = HorizontalSplit::default()
@@ -209,9 +234,16 @@ impl ChannelItem {
209 234
210 frame.render_widget(split, rect); 235 frame.render_widget(split, rect);
211 236
212 textlist.area(chunks[0]);
213 let mut textlist = textlist.clone(); 237 let mut textlist = textlist.clone();
214 238
239 textlist.area(chunks[0]);
240
241 let hold_textlist = if textlist.area == textlist.prev_area {
242 None
243 } else {
244 Some(textlist.clone())
245 };
246
215 if selected { 247 if selected {
216 textlist.selected_style(Style::default().fg(Color::LightRed)); 248 textlist.selected_style(Style::default().fg(Color::LightRed));
217 } else { 249 } else {
@@ -230,11 +262,17 @@ impl ChannelItem {
230 } 262 }
231 263
232 frame.render_widget(textlist, chunks[0]); 264 frame.render_widget(textlist, chunks[0]);
265
266 if let Some(textlist) = hold_textlist {
267 out.1 = Some(Item::Channel(ChannelItem::InfoDisplay(
268 ChannelDisplayItem::Playlists(playlists.clone(), textlist),
269 )));
270 }
233 } 271 }
234 }, 272 },
235 ChannelItem::SelectItems(selected_page) => { 273 ChannelItem::SelectItems(selected_page) => {
236 if !hover { 274 if !hover {
237 if let Page::Channel(channel_page, _) = page { 275 if let Page::Channel(channel_page, _) = &out.2.page {
238 if *selected_page == *channel_page { 276 if *selected_page == *channel_page {
239 style = style.fg(Color::LightYellow); 277 style = style.fg(Color::LightYellow);
240 } 278 }
@@ -252,10 +290,9 @@ impl ChannelItem {
252 frame.render_widget(paragraph, rect); 290 frame.render_widget(paragraph, rect);
253 } 291 }
254 } 292 }
293 out
255 } 294 }
256}
257 295
258impl KeyInput for ChannelItem {
259 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 296 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
260 match self { 297 match self {
261 ChannelItem::InfoDisplay(displayitem) => match displayitem { 298 ChannelItem::InfoDisplay(displayitem) => match displayitem {
@@ -336,9 +373,7 @@ impl KeyInput for ChannelItem {
336 373
337 (true, app) 374 (true, app)
338 } 375 }
339}
340 376
341impl SelectItem for ChannelItem {
342 fn select(&mut self, app: App) -> (App, bool) { 377 fn select(&mut self, app: App) -> (App, bool) {
343 let cloned = self.clone(); 378 let cloned = self.clone();
344 match &cloned { 379 match &cloned {
@@ -377,16 +412,16 @@ impl SelectItem for ChannelItem {
377 412
378pub struct Channel; 413pub struct Channel;
379 414
380impl Channel { 415impl PageTrait for Channel {
381 pub fn message() -> String { 416 fn message() -> String {
382 String::from("Loading channel info...") 417 String::from("Loading channel info...")
383 } 418 }
384 419
385 pub fn min() -> (u16, u16) { 420 fn min() -> (u16, u16) {
386 (45, 15) 421 (45, 15)
387 } 422 }
388 423
389 pub fn default() -> Vec<Row> { 424 fn default() -> Vec<Row> {
390 vec![ 425 vec![
391 Row { 426 Row {
392 items: vec![ 427 items: vec![
src/app/pages/global.rs +47 −24
@@ -12,8 +12,8 @@ use tui::{
12use crate::{ 12use crate::{
13 app::app::App, 13 app::app::App,
14 functions::center_rect, 14 functions::center_rect,
15 structs::{Page, SearchSettings}, 15 structs::{Item, Page, WatchHistory},
16 traits::{KeyInput, SelectItem}, 16 traits::{ItemTrait, PageTrait},
17 widgets::{force_clear::ForceClear, horizontal_split::HorizontalSplit}, 17 widgets::{force_clear::ForceClear, horizontal_split::HorizontalSplit},
18}; 18};
19 19
@@ -50,7 +50,7 @@ impl Mode {
50 } 50 }
51} 51}
52 52
53impl SelectItem for GlobalItem { 53impl ItemTrait for GlobalItem {
54 fn select(&mut self, mut app: App) -> (App, bool) { 54 fn select(&mut self, mut app: App) -> (App, bool) {
55 let selected = match self { 55 let selected = match self {
56 GlobalItem::SearchBar => true, 56 GlobalItem::SearchBar => true,
@@ -70,9 +70,7 @@ impl SelectItem for GlobalItem {
70 _ => false, 70 _ => false,
71 } 71 }
72 } 72 }
73}
74 73
75impl KeyInput for GlobalItem {
76 fn key_input(&mut self, key: KeyCode, mut app: App) -> (bool, App) { 74 fn key_input(&mut self, key: KeyCode, mut app: App) -> (bool, App) {
77 match self { 75 match self {
78 GlobalItem::SearchBar => match key { 76 GlobalItem::SearchBar => match key {
@@ -118,21 +116,28 @@ impl KeyInput for GlobalItem {
118 116
119 (true, app) 117 (true, app)
120 } 118 }
121}
122 119
123impl GlobalItem { 120 fn render_item<B: Backend>(
124 pub fn render_item<B: Backend>( 121 // &self,
122 // frame: &mut Frame<B>,
123 // rect: Rect,
124 // selected: bool,
125 // hover: bool,
126 // popup_render: bool,
127 // message: &Option<String>,
128 // search_settings: &mut SearchSettings,
129 // search_text: &String,
125 &self, 130 &self,
126 frame: &mut Frame<B>, 131 frame: &mut Frame<B>,
127 rect: Rect, 132 rect: Rect,
133 app: App,
128 selected: bool, 134 selected: bool,
129 hover: bool, 135 hover: bool,
136 _: bool,
130 popup_render: bool, 137 popup_render: bool,
131 message: &Option<String>, 138 ) -> (bool, Option<Item>, App) {
132 search_settings: &mut SearchSettings,
133 search_text: &String,
134 ) -> bool {
135 let area = frame.size(); 139 let area = frame.size();
140 let mut out = (false, None, app);
136 match self { 141 match self {
137 GlobalItem::SearchBar => { 142 GlobalItem::SearchBar => {
138 let block = Block::default() 143 let block = Block::default()
@@ -147,10 +152,15 @@ impl GlobalItem {
147 })) 152 }))
148 .title("Search YouTube") 153 .title("Search YouTube")
149 .title_alignment(Alignment::Center); 154 .title_alignment(Alignment::Center);
150 let paragraph = Paragraph::new(search_text.clone()).block(block); 155 let mut text = out.2.search_text.clone();
156 if selected {
157 text.push('█');
158 }
159 let paragraph = Paragraph::new(text).block(block);
151 frame.render_widget(paragraph, rect); 160 frame.render_widget(paragraph, rect);
152 } 161 }
153 GlobalItem::MessageBar => { 162 GlobalItem::MessageBar => {
163 let message = out.2.message.lock().unwrap();
154 // let color = Color::LightYellow; 164 // let color = Color::LightYellow;
155 let block = Block::default() 165 let block = Block::default()
156 .border_type(BorderType::Rounded) 166 .border_type(BorderType::Rounded)
@@ -196,32 +206,39 @@ impl GlobalItem {
196 206
197 frame.render_widget(split, rect); 207 frame.render_widget(split, rect);
198 208
199 search_settings.text_list.area(chunks[0]); 209 out.2.search_settings.text_list.area(chunks[0]);
200 210
201 if search_settings.row { 211 if out.2.search_settings.row {
202 search_settings 212 out.2
213 .search_settings
203 .text_list 214 .text_list
204 .selected_style(Style::default().fg(Color::LightRed)); 215 .selected_style(Style::default().fg(Color::LightRed));
205 216
206 search_settings 217 out.2
218 .search_settings
207 .select_text_list 219 .select_text_list
208 .selected_style(Style::default().fg(Color::LightYellow)); 220 .selected_style(Style::default().fg(Color::LightYellow));
209 } else { 221 } else {
210 search_settings 222 out.2
223 .search_settings
211 .text_list 224 .text_list
212 .selected_style(Style::default().fg(Color::LightYellow)); 225 .selected_style(Style::default().fg(Color::LightYellow));
213 226
214 search_settings 227 out.2
228 .search_settings
215 .select_text_list 229 .select_text_list
216 .selected_style(Style::default().fg(Color::LightRed)); 230 .selected_style(Style::default().fg(Color::LightRed));
217 } 231 }
218 232
219 frame.render_widget(search_settings.text_list.clone(), chunks[0]); 233 frame.render_widget(
234 out.2.search_settings.text_list.clone(),
235 chunks[0],
236 );
220 237
221 search_settings.select_text_list.area(chunks[1]); 238 out.2.search_settings.select_text_list.area(chunks[1]);
222 239
223 frame.render_widget( 240 frame.render_widget(
224 search_settings.select_text_list.clone(), 241 out.2.search_settings.select_text_list.clone(),
225 chunks[1], 242 chunks[1],
226 ); 243 );
227 244
@@ -235,12 +252,18 @@ impl GlobalItem {
235 } 252 }
236 //panic!("{:?}", rect); 253 //panic!("{:?}", rect);
237 } else { 254 } else {
238 return true; 255 out.0 = true;
239 } 256 }
240 } 257 }
241 } 258 }
242 } 259 }
243 260
244 false 261 out
262 }
263
264 fn load_item(&self, _: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn std::error::Error>> {
265 Ok(Item::Global(self.clone()))
245 } 266 }
246} 267}
268
269impl GlobalItem {}
src/app/pages/item_info.rs +28 −23
@@ -10,7 +10,7 @@ use crate::{
10 app::{app::App, config::EnvVar, pages::global::*}, 10 app::{app::App, config::EnvVar, pages::global::*},
11 functions::download_all_thumbnails, 11 functions::download_all_thumbnails,
12 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory}, 12 structs::{FullPlayList, FullVideo, Item, ListItem, Page, Row, RowItem, WatchHistory},
13 traits::{KeyInput, SelectItem}, 13 traits::{ItemTrait, PageTrait},
14 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 14 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
15}; 15};
16use crossterm::event::KeyCode; 16use crossterm::event::KeyCode;
@@ -64,7 +64,7 @@ impl PlayListDisplayView {
64 } 64 }
65} 65}
66 66
67impl SelectItem for ItemInfoItem { 67impl ItemTrait for ItemInfoItem {
68 fn select(&mut self, app: App) -> (App, bool) { 68 fn select(&mut self, app: App) -> (App, bool) {
69 let selected = true; 69 let selected = true;
70 70
@@ -74,9 +74,7 @@ impl SelectItem for ItemInfoItem {
74 fn selectable(&self) -> bool { 74 fn selectable(&self) -> bool {
75 true 75 true
76 } 76 }
77}
78 77
79impl KeyInput for ItemInfoItem {
80 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 78 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
81 match self { 79 match self {
82 ItemInfoItem::Video(videoinfo) => match key { 80 ItemInfoItem::Video(videoinfo) => match key {
@@ -587,14 +585,12 @@ impl KeyInput for ItemInfoItem {
587 585
588 (true, app) 586 (true, app)
589 } 587 }
590}
591 588
592impl ItemInfoItem { 589 fn load_item(
593 pub fn load_item(
594 &self, 590 &self,
595 app: &App, 591 app: &App,
596 watch_history: &mut WatchHistory, 592 watch_history: &mut WatchHistory,
597 ) -> Result<Self, Box<dyn Error>> { 593 ) -> Result<Item, Box<dyn Error>> {
598 let mut this = self.clone(); 594 let mut this = self.clone();
599 595
600 if let ItemInfoItem::Unknown = this { 596 if let ItemInfoItem::Unknown = this {
@@ -682,22 +678,30 @@ impl ItemInfoItem {
682 _ => {} 678 _ => {}
683 } 679 }
684 } 680 }
685 Ok(this) 681 Ok(Item::ItemInfo(this))
686 } 682 }
687 683
688 pub fn render_item<B: Backend>( 684 fn render_item<B: Backend>(
689 &mut self, 685 // &mut self,
686 // frame: &mut Frame<B>,
687 // rect: Rect,
688 // selected: bool,
689 // hover: bool,
690 // popup_focus: bool,
691 &self,
690 frame: &mut Frame<B>, 692 frame: &mut Frame<B>,
691 rect: Rect, 693 rect: Rect,
694 app: App,
692 selected: bool, 695 selected: bool,
693 hover: bool, 696 hover: bool,
694 popup_focus: bool, 697 popup_focus: bool,
695 ) { 698 _: bool,
699 ) -> (bool, Option<Item>, App) {
700 let out = (false, None, app);
696 match self { 701 match self {
697 ItemInfoItem::Video(videoinfo) => { 702 ItemInfoItem::Video(videoinfo) => {
698 let index = videoinfo.list.items.len() - 1; 703 let mut list = videoinfo.list.clone();
699 videoinfo.list.items[index] = format!("Mode: {}", videoinfo.mode); 704 list.items[videoinfo.list.items.len() - 1] = format!("Mode: {}", videoinfo.mode);
700 drop(index);
701 705
702 let split = HorizontalSplit::default() 706 let split = HorizontalSplit::default()
703 .percentages(vec![40, 60]) 707 .percentages(vec![40, 60])
@@ -710,7 +714,6 @@ impl ItemInfoItem {
710 })); 714 }));
711 715
712 let chunks = split.inner(rect); 716 let chunks = split.inner(rect);
713 let mut list = videoinfo.list.clone();
714 717
715 list.area(chunks[1]); 718 list.area(chunks[1]);
716 if selected { 719 if selected {
@@ -768,10 +771,9 @@ impl ItemInfoItem {
768 frame.render_widget(list, chunks[1]); 771 frame.render_widget(list, chunks[1]);
769 } 772 }
770 PlayListDisplayView::PlayListView => { 773 PlayListDisplayView::PlayListView => {
771 let index = playlistinfo.playlist_view_list.items.len() - 1; 774 let mut playlist_view_list = playlistinfo.playlist_view_list.clone();
772 playlistinfo.playlist_view_list.items[index] = 775 playlist_view_list.items[playlistinfo.playlist_view_list.items.len() - 1] =
773 format!("Mode: {}", playlistinfo.mode); 776 format!("Mode: {}", playlistinfo.mode);
774 drop(index);
775 777
776 let mut list = playlistinfo.playlist_view_list.clone(); 778 let mut list = playlistinfo.playlist_view_list.clone();
777 list.area(chunks[1]); 779 list.area(chunks[1]);
@@ -800,6 +802,7 @@ impl ItemInfoItem {
800 frame.render_widget(split, rect); 802 frame.render_widget(split, rect);
801 } 803 }
802 } 804 }
805 out
803 } 806 }
804} 807}
805 808
@@ -811,16 +814,16 @@ pub enum DisplayItem {
811 814
812pub struct ItemInfo; 815pub struct ItemInfo;
813 816
814impl ItemInfo { 817impl PageTrait for ItemInfo {
815 pub fn message() -> String { 818 fn message() -> String {
816 String::from("Loading item info...") 819 String::from("Loading item info...")
817 } 820 }
818 821
819 pub fn min() -> (u16, u16) { 822 fn min() -> (u16, u16) {
820 (21, 12) 823 (21, 12)
821 } 824 }
822 825
823 pub fn default() -> Vec<Row> { 826 fn default() -> Vec<Row> {
824 vec![ 827 vec![
825 Row { 828 Row {
826 items: vec![ 829 items: vec![
@@ -856,6 +859,8 @@ impl ItemInfo {
856 } 859 }
857} 860}
858 861
862impl ItemInfoItem {}
863
859fn run_command(args: Vec<String>, message: Arc<Mutex<Option<String>>>) { 864fn run_command(args: Vec<String>, message: Arc<Mutex<Option<String>>>) {
860 thread::spawn(move || { 865 thread::spawn(move || {
861 let mut args = args.into_iter(); 866 let mut args = args.into_iter();
src/app/pages/main_menu.rs +110 −88
@@ -6,8 +6,8 @@ use crate::{
6 pages::{global::*, item_info::*}, 6 pages::{global::*, item_info::*},
7 }, 7 },
8 functions::download_all_thumbnails, 8 functions::download_all_thumbnails,
9 structs::{Item, ListItem, Page, Row, RowItem}, 9 structs::{Item, ListItem, Page, Row, RowItem, WatchHistory},
10 traits::{KeyInput, SelectItem}, 10 traits::{ItemTrait, PageTrait},
11 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 11 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
12}; 12};
13use crossterm::event::KeyCode; 13use crossterm::event::KeyCode;
@@ -26,80 +26,8 @@ pub enum MainMenuItem {
26 26
27// app.client.trending(None) 27// app.client.trending(None)
28 28
29impl SelectItem for MainMenuItem { 29impl ItemTrait for MainMenuItem {
30 fn select(&mut self, mut app: App) -> (App, bool) { 30 fn load_item(&self, app: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn Error>> {
31 let selected = match self {
32 MainMenuItem::SeletorTab(selector) => {
33 if app.page == (Page::MainMenu(*selector)) {
34 return (app, false);
35 }
36 app.page = Page::MainMenu(*selector);
37 app.load = true;
38 false
39 }
40
41 _ => true,
42 };
43
44 (app, selected)
45 }
46
47 fn selectable(&self) -> bool {
48 true
49 }
50}
51
52impl KeyInput for MainMenuItem {
53 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
54 match self {
55 MainMenuItem::VideoList(Some((list, textlist, _))) => match key {
56 KeyCode::Up => textlist.up(),
57 KeyCode::Down => textlist.down(),
58 KeyCode::PageUp => textlist.selected = 0,
59 KeyCode::PageDown => textlist.selected = textlist.items.len() - 1,
60 KeyCode::Enter => {
61 let state = ItemInfo::default();
62 let mut history = app.history.clone();
63 history.push(app.into());
64
65 return (
66 false,
67 App {
68 history,
69 page: Page::ItemDisplay(
70 match list.iter().nth(textlist.selected).unwrap() {
71 ListItem::FullVideo(item) => {
72 DisplayItem::Video(item.video_id.clone())
73 }
74 ListItem::FullPlayList(item) => {
75 DisplayItem::PlayList(item.playlist_id.clone())
76 }
77 ListItem::MiniPlayList(item) => {
78 DisplayItem::PlayList(item.playlist_id.clone())
79 }
80 ListItem::MiniVideo(item) => {
81 DisplayItem::Video(item.video_id.clone())
82 }
83 _ => unreachable!(),
84 },
85 ),
86 selectable: App::selectable(&state),
87 state,
88 ..Default::default()
89 },
90 );
91 }
92 _ => {}
93 },
94 _ => {}
95 }
96
97 (true, app)
98 }
99}
100
101impl MainMenuItem {
102 pub fn load_item(&self, app: &App) -> Result<Self, Box<dyn Error>> {
103 let mut this = self.clone(); 31 let mut this = self.clone();
104 32
105 match &mut this { 33 match &mut this {
@@ -201,18 +129,27 @@ impl MainMenuItem {
201 _ => {} 129 _ => {}
202 } 130 }
203 131
204 Ok(this) 132 Ok(Item::MainMenu(this))
205 } 133 }
206 134
207 pub fn render_item<B: Backend>( 135 fn render_item<B: Backend>(
208 &mut self, 136 // &mut self,
137 // frame: &mut Frame<B>,
138 // rect: Rect,
139 // selected: bool,
140 // hover: bool,
141 // popup_focus: bool,
142 // page: &Page,
143 &self,
209 frame: &mut Frame<B>, 144 frame: &mut Frame<B>,
210 rect: Rect, 145 rect: Rect,
146 app: App,
211 selected: bool, 147 selected: bool,
212 hover: bool, 148 hover: bool,
213 popup_focus: bool, 149 popup_focus: bool,
214 page: &Page, 150 _: bool,
215 ) { 151 ) -> (bool, Option<Item>, App) {
152 let mut out = (false, None, app);
216 let mut style = Style::default().fg(if selected { 153 let mut style = Style::default().fg(if selected {
217 Color::LightBlue 154 Color::LightBlue
218 } else if hover { 155 } else if hover {
@@ -223,7 +160,7 @@ impl MainMenuItem {
223 160
224 match self { 161 match self {
225 MainMenuItem::SeletorTab(selector) => { 162 MainMenuItem::SeletorTab(selector) => {
226 if !hover && page == &(Page::MainMenu(*selector)) { 163 if !hover && &out.2.page == &(Page::MainMenu(*selector)) {
227 style = style.fg(Color::LightYellow); 164 style = style.fg(Color::LightYellow);
228 } 165 }
229 let text = match selector { 166 let text = match selector {
@@ -257,10 +194,17 @@ impl MainMenuItem {
257 194
258 frame.render_widget(split, rect); 195 frame.render_widget(split, rect);
259 196
260 if let Some((videos, list, _)) = data { 197 if let Some((videos, list, index)) = data {
261 list.area(chunks[0]);
262 let mut list = list.clone(); 198 let mut list = list.clone();
263 199
200 list.area(chunks[0]);
201
202 let hold_textlist = if list.area == list.prev_area {
203 None
204 } else {
205 Some(list.clone())
206 };
207
264 if selected { 208 if selected {
265 list.selected_style(Style::default().fg(Color::LightRed)); 209 list.selected_style(Style::default().fg(Color::LightRed));
266 } else { 210 } else {
@@ -274,12 +218,90 @@ impl MainMenuItem {
274 } 218 }
275 219
276 frame.render_widget(list, chunks[0]); 220 frame.render_widget(list, chunks[0]);
221
222 if let Some(textlist) = hold_textlist {
223 out.1 = Some(Item::MainMenu(MainMenuItem::VideoList(Some((
224 videos.clone(),
225 textlist,
226 *index,
227 )))));
228 }
229 }
230 }
231 }
232 out
233 }
234 fn select(&mut self, mut app: App) -> (App, bool) {
235 let selected = match self {
236 MainMenuItem::SeletorTab(selector) => {
237 if app.page == (Page::MainMenu(*selector)) {
238 return (app, false);
277 } 239 }
240 app.page = Page::MainMenu(*selector);
241 app.load = true;
242 false
278 } 243 }
244
245 _ => true,
246 };
247
248 (app, selected)
249 }
250
251 fn selectable(&self) -> bool {
252 true
253 }
254
255 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
256 match self {
257 MainMenuItem::VideoList(Some((list, textlist, _))) => match key {
258 KeyCode::Up => textlist.up(),
259 KeyCode::Down => textlist.down(),
260 KeyCode::PageUp => textlist.selected = 0,
261 KeyCode::PageDown => textlist.selected = textlist.items.len() - 1,
262 KeyCode::Enter => {
263 let state = ItemInfo::default();
264 let mut history = app.history.clone();
265 history.push(app.into());
266
267 return (
268 false,
269 App {
270 history,
271 page: Page::ItemDisplay(
272 match list.iter().nth(textlist.selected).unwrap() {
273 ListItem::FullVideo(item) => {
274 DisplayItem::Video(item.video_id.clone())
275 }
276 ListItem::FullPlayList(item) => {
277 DisplayItem::PlayList(item.playlist_id.clone())
278 }
279 ListItem::MiniPlayList(item) => {
280 DisplayItem::PlayList(item.playlist_id.clone())
281 }
282 ListItem::MiniVideo(item) => {
283 DisplayItem::Video(item.video_id.clone())
284 }
285 _ => unreachable!(),
286 },
287 ),
288 selectable: App::selectable(&state),
289 state,
290 ..Default::default()
291 },
292 );
293 }
294 _ => {}
295 },
296 _ => {}
279 } 297 }
298
299 (true, app)
280 } 300 }
281} 301}
282 302
303impl MainMenuItem {}
304
283pub fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> { 305pub fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> {
284 original.iter().map(|item| item.to_string()).collect() 306 original.iter().map(|item| item.to_string()).collect()
285} 307}
@@ -299,16 +321,16 @@ impl Default for MainMenuSelector {
299 321
300pub struct MainMenu; 322pub struct MainMenu;
301 323
302impl MainMenu { 324impl PageTrait for MainMenu {
303 pub fn message() -> String { 325 fn message() -> String {
304 String::from("Loading home page...") 326 String::from("Loading home page...")
305 } 327 }
306 328
307 pub fn min() -> (u16, u16) { 329 fn min() -> (u16, u16) {
308 (45, 15) 330 (45, 15)
309 } 331 }
310 332
311 pub fn default() -> Vec<Row> { 333 fn default() -> Vec<Row> {
312 vec![ 334 vec![
313 Row { 335 Row {
314 items: vec![ 336 items: vec![
src/app/pages/search.rs +20 −17
@@ -12,8 +12,10 @@ use tui::{
12use crate::{ 12use crate::{
13 app::app::App, 13 app::app::App,
14 functions::download_all_thumbnails, 14 functions::download_all_thumbnails,
15 structs::{Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem}, 15 structs::{
16 traits::{KeyInput, SelectItem}, 16 Item, ListItem, MiniChannel, MiniPlayList, MiniVideo, Page, Row, RowItem, WatchHistory,
17 },
18 traits::{ItemTrait, PageTrait},
17 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList}, 19 widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
18}; 20};
19 21
@@ -32,7 +34,7 @@ pub enum SearchItem {
32 }, 34 },
33} 35}
34 36
35impl SelectItem for SearchItem { 37impl ItemTrait for SearchItem {
36 fn select(&mut self, app: App) -> (App, bool) { 38 fn select(&mut self, app: App) -> (App, bool) {
37 (app, true) 39 (app, true)
38 } 40 }
@@ -40,9 +42,7 @@ impl SelectItem for SearchItem {
40 fn selectable(&self) -> bool { 42 fn selectable(&self) -> bool {
41 true 43 true
42 } 44 }
43}
44 45
45impl KeyInput for SearchItem {
46 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) { 46 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
47 match self { 47 match self {
48 SearchItem::Search { results, text_list } => match key { 48 SearchItem::Search { results, text_list } => match key {
@@ -154,10 +154,8 @@ impl KeyInput for SearchItem {
154 154
155 (true, app) 155 (true, app)
156 } 156 }
157}
158 157
159impl SearchItem { 158 fn load_item(&self, app: &App, _: &mut WatchHistory) -> Result<Item, Box<dyn Error>> {
160 pub fn load_item(&self, app: &App) -> Result<Self, Box<dyn Error>> {
161 let mut this = self.clone(); 159 let mut this = self.clone();
162 160
163 match &mut this { 161 match &mut this {
@@ -279,17 +277,20 @@ impl SearchItem {
279 } 277 }
280 } 278 }
281 279
282 Ok(this) 280 Ok(Item::Search(this))
283 } 281 }
284 282
285 pub fn render_item<B: Backend>( 283 fn render_item<B: Backend>(
286 &mut self, 284 &self,
287 frame: &mut Frame<B>, 285 frame: &mut Frame<B>,
288 rect: Rect, 286 rect: Rect,
287 app: App,
289 selected: bool, 288 selected: bool,
290 hover: bool, 289 hover: bool,
291 popup_focus: bool, 290 popup_focus: bool,
292 ) { 291 _: bool,
292 ) -> (bool, Option<Item>, App) {
293 let out = (false, None, app);
293 match self { 294 match self {
294 SearchItem::Search { results, text_list } => { 295 SearchItem::Search { results, text_list } => {
295 let split = HorizontalSplit::default() 296 let split = HorizontalSplit::default()
@@ -306,8 +307,8 @@ impl SearchItem {
306 307
307 frame.render_widget(split, rect); 308 frame.render_widget(split, rect);
308 309
309 text_list.area(chunks[0]);
310 let mut text_list = text_list.clone(); 310 let mut text_list = text_list.clone();
311 text_list.area(chunks[0]);
311 312
312 if let Some(result) = results { 313 if let Some(result) = results {
313 if let Some(item) = result.iter().nth(text_list.selected) { 314 if let Some(item) = result.iter().nth(text_list.selected) {
@@ -326,21 +327,23 @@ impl SearchItem {
326 frame.render_widget(text_list, chunks[0]); 327 frame.render_widget(text_list, chunks[0]);
327 } 328 }
328 } 329 }
330
331 out
329 } 332 }
330} 333}
331 334
332pub struct Search; 335pub struct Search;
333 336
334impl Search { 337impl PageTrait for Search {
335 pub fn message() -> String { 338 fn message() -> String {
336 String::from("Loading search results...") 339 String::from("Loading search results...")
337 } 340 }
338 341
339 pub fn min() -> (u16, u16) { 342 fn min() -> (u16, u16) {
340 (45, 12) 343 (45, 12)
341 } 344 }
342 345
343 pub fn default() -> Vec<Row> { 346 fn default() -> Vec<Row> {
344 vec![ 347 vec![
345 Row { 348 Row {
346 items: vec![ 349 items: vec![
src/main.rs +33 −82
@@ -3,7 +3,7 @@ use crossterm::{
3 execute, 3 execute,
4 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen}, 4 terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
5}; 5};
6use std::{error::Error, fs, io}; 6use std::{error::Error, fs, io, sync::mpsc::channel};
7use tui::{ 7use tui::{
8 backend::{Backend, CrosstermBackend}, 8 backend::{Backend, CrosstermBackend},
9 Terminal, 9 Terminal,
@@ -11,9 +11,8 @@ use tui::{
11use youtube_tui::{ 11use youtube_tui::{
12 app::{ 12 app::{
13 app::App, 13 app::App,
14 pages::{channel::Channel, item_info::ItemInfo, main_menu::MainMenu, search::Search},
15 }, 14 },
16 structs::{Item, Page, Row, RowItem}, 15 structs::{Row, RowItem},
17}; 16};
18 17
19fn main() -> Result<(), Box<dyn Error>> { 18fn main() -> Result<(), Box<dyn Error>> {
@@ -45,92 +44,35 @@ fn main() -> Result<(), Box<dyn Error>> {
45fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> { 44fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> {
46 loop { 45 loop {
47 if app.render { 46 if app.render {
48 ui(&mut terminal, &mut app)?; 47 let hold = ui(&mut terminal, app);
48 app = hold.0;
49 hold.1?;
49 } 50 }
50 51
51 if app.load { 52 if app.load {
52 *app.message.lock().unwrap() = Some(match app.page { 53 *app.message.lock().unwrap() = Some(app.page.message());
53 Page::MainMenu(_) => MainMenu::message(), 54 let mut watch_history = app.watch_history.clone();
54 Page::ItemDisplay(_) => ItemInfo::message(),
55 Page::Search => Search::message(),
56 Page::Channel(_, _) => Channel::message(),
57 });
58 terminal.clear()?; 55 terminal.clear()?;
59 ui(&mut terminal, &mut app)?; 56 let hold = ui(&mut terminal, app);
57 app = hold.0;
58 hold.1?;
60 let mut new_state = Vec::new(); 59 let mut new_state = Vec::new();
61 for row in app.state.iter() { 60 for row in app.state.iter() {
62 let mut row_vec = Vec::new(); 61 let mut row_vec = Vec::new();
63 for row_item in row.items.iter() { 62 for row_item in row.items.iter() {
64 match &row_item.item { 63 match row_item.item.load_item(&app, &mut watch_history) {
65 Item::MainMenu(item) => match item.load_item(&app) { 64 Ok(new) => {
66 Ok(new) => { 65 row_vec.push(RowItem {
67 row_vec.push(RowItem { 66 item: new,
68 item: Item::MainMenu(new), 67 ..*row_item
69 ..*row_item 68 });
70 });
71 }
72 Err(e) => {
73 row_vec.push(RowItem {
74 item: Item::MainMenu(item.clone()),
75 ..*row_item
76 });
77 *app.message.lock().unwrap() = Some(e.to_string());
78 }
79 },
80 Item::ItemInfo(item) => {
81 let mut watch_history = app.watch_history.clone();
82 match item.load_item(&app, &mut watch_history) {
83 Ok(new) => {
84 row_vec.push(RowItem {
85 item: Item::ItemInfo(new),
86 ..*row_item
87 });
88 }
89 Err(e) => {
90 row_vec.push(RowItem {
91 item: Item::ItemInfo(item.clone()),
92 ..*row_item
93 });
94 *app.message.lock().unwrap() = Some(e.to_string());
95 }
96 }
97 app.watch_history = watch_history;
98 } 69 }
99 Item::Search(item) => match item.load_item(&app) { 70 Err(e) => {
100 Ok(new) => {
101 row_vec.push(RowItem {
102 item: Item::Search(new),
103 ..*row_item
104 });
105 }
106 Err(e) => {
107 row_vec.push(RowItem {
108 item: Item::Search(item.clone()),
109 ..*row_item
110 });
111 *app.message.lock().unwrap() = Some(e.to_string());
112 }
113 },
114 Item::Channel(item) => match item.load_item(&app) {
115 Ok(new) => {
116 row_vec.push(RowItem {
117 item: Item::Channel(new),
118 ..*row_item
119 });
120 }
121 Err(e) => {
122 row_vec.push(RowItem {
123 item: Item::Channel(item.clone()),
124 ..*row_item
125 });
126 *app.message.lock().unwrap() = Some(e.to_string());
127 }
128 },
129 _ => {
130 row_vec.push(RowItem { 71 row_vec.push(RowItem {
131 item: row_item.item.clone(), 72 item: row_item.item.clone(),
132 ..*row_item 73 ..*row_item
133 }); 74 });
75 *app.message.lock().unwrap() = Some(e.to_string());
134 } 76 }
135 } 77 }
136 } 78 }
@@ -141,11 +83,13 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
141 }); 83 });
142 } 84 }
143 85
86 app.watch_history = watch_history;
144 app.state = new_state; 87 app.state = new_state;
145 88
146 app.load = false; 89 app.load = false;
147 terminal.clear()?; 90 terminal.clear()?;
148 ui(&mut terminal, &mut app)?; 91 let hold = ui(&mut terminal, app);
92 app = hold.0;
149 } else { 93 } else {
150 match event::read()? { 94 match event::read()? {
151 event::Event::Key(key) => { 95 event::Event::Key(key) => {
@@ -188,15 +132,22 @@ fn run_app<B: Backend>(mut terminal: &mut Terminal<B>, mut app: App) -> Result<(
188 } 132 }
189} 133}
190 134
191fn ui<B: Backend>(terminal: &mut Terminal<B>, app: &mut App) -> Result<(), Box<dyn Error>> { 135fn ui<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> (App, Result<(), Box<dyn Error>>) {
192 terminal.draw(|mut frame| { 136 let (send, recv) = channel();
193 app.render(&mut frame); 137 let res = terminal.draw(|mut frame| {
194 })?; 138 let app = app.render(&mut frame);
139 send.send(app).unwrap();
140 });
141
142 app = recv.recv().unwrap();
195 143
196 *app.message.lock().unwrap() = None; 144 *app.message.lock().unwrap() = None;
197 app.render = false; 145 app.render = false;
198 146
199 Ok(()) 147 match res {
148 Ok(_) => (app, Ok(())),
149 Err(e) => (app, Err(Box::new(e))),
150 }
200} 151}
201 152
202fn init() -> Result<(), Box<dyn Error>> { 153fn init() -> Result<(), Box<dyn Error>> {
src/structs/page.rs +19 −2
@@ -1,5 +1,11 @@
1use crate::app::pages::{ 1use crate::{
2 channel::ChannelPage, item_info::DisplayItem, main_menu::MainMenuSelector, 2 app::pages::{
3 channel::{Channel, ChannelPage},
4 item_info::{DisplayItem, ItemInfo},
5 main_menu::{MainMenu, MainMenuSelector},
6 search::Search,
7 },
8 traits::PageTrait,
3}; 9};
4 10
5#[derive(Debug, PartialEq, Clone)] 11#[derive(Debug, PartialEq, Clone)]
@@ -15,3 +21,14 @@ impl Default for Page {
15 Self::MainMenu(MainMenuSelector::default()) 21 Self::MainMenu(MainMenuSelector::default())
16 } 22 }
17} 23}
24
25impl Page {
26 pub fn message(&self) -> String {
27 match self {
28 Self::MainMenu(_) => MainMenu::message(),
29 Self::ItemDisplay(_) => ItemInfo::message(),
30 Self::Channel(_, _) => Channel::message(),
31 Self::Search => Search::message(),
32 }
33 }
34}
src/structs/states.rs +84 −4
@@ -1,10 +1,25 @@
1use tui::layout::Constraint; 1use std::error::Error;
2 2
3use crate::app::pages::{ 3use crossterm::event::KeyCode;
4 channel::ChannelItem, global::GlobalItem, item_info::ItemInfoItem, main_menu::MainMenuItem, 4use tui::{
5 search::SearchItem, 5 backend::Backend,
6 layout::{Constraint, Rect},
7 Frame,
6}; 8};
7 9
10use crate::{
11 app::{
12 app::App,
13 pages::{
14 channel::ChannelItem, global::GlobalItem, item_info::ItemInfoItem,
15 main_menu::MainMenuItem, search::SearchItem,
16 },
17 },
18 traits::ItemTrait,
19};
20
21use super::WatchHistory;
22
8#[derive(Debug, Clone)] 23#[derive(Debug, Clone)]
9pub enum Item { 24pub enum Item {
10 Global(GlobalItem), 25 Global(GlobalItem),
@@ -14,6 +29,71 @@ pub enum Item {
14 Channel(ChannelItem), 29 Channel(ChannelItem),
15} 30}
16 31
32impl Item {
33 pub fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
34 match self {
35 Item::Global(item) => item.key_input(key, app),
36 Item::MainMenu(item) => item.key_input(key, app),
37 Item::ItemInfo(item) => item.key_input(key, app),
38 Item::Search(item) => item.key_input(key, app),
39 Item::Channel(item) => item.key_input(key, app),
40 }
41 }
42
43 pub fn render_item<B: Backend>(
44 &self,
45 frame: &mut Frame<B>,
46 rect: Rect,
47 app: App,
48 selected: bool,
49 hover: bool,
50 popup_focus: bool,
51 popup_render: bool,
52 ) -> (bool, Option<Item>, App) {
53 match self {
54 Item::Global(item) => {
55 item.render_item(frame, rect, app, selected, hover, popup_focus, popup_render)
56 }
57 Item::MainMenu(item) => {
58 item.render_item(frame, rect, app, selected, hover, popup_focus, popup_render)
59 }
60 Item::ItemInfo(item) => {
61 item.render_item(frame, rect, app, selected, hover, popup_focus, popup_render)
62 }
63 Item::Search(item) => {
64 item.render_item(frame, rect, app, selected, hover, popup_focus, popup_render)
65 }
66 Item::Channel(item) => {
67 item.render_item(frame, rect, app, selected, hover, popup_focus, popup_render)
68 }
69 }
70 }
71
72 pub fn select(&mut self, app: App) -> (App, bool) {
73 match self {
74 Item::Global(item) => item.select(app),
75 Item::MainMenu(item) => item.select(app),
76 Item::ItemInfo(item) => item.select(app),
77 Item::Search(item) => item.select(app),
78 Item::Channel(item) => item.select(app),
79 }
80 }
81
82 pub fn load_item(
83 &self,
84 app: &App,
85 watchhistory: &mut WatchHistory,
86 ) -> Result<Self, Box<dyn Error>> {
87 match self {
88 Item::Global(item) => item.load_item(app, watchhistory),
89 Item::MainMenu(item) => item.load_item(app, watchhistory),
90 Item::ItemInfo(item) => item.load_item(app, watchhistory),
91 Item::Search(item) => item.load_item(app, watchhistory),
92 Item::Channel(item) => item.load_item(app, watchhistory),
93 }
94 }
95}
96
17#[derive(Debug, Clone)] 97#[derive(Debug, Clone)]
18pub struct Row { 98pub struct Row {
19 pub items: Vec<RowItem>, 99 pub items: Vec<RowItem>,
src/traits/item.rs added +29
@@ -0,0 +1,29 @@
1use std::error::Error;
2
3use crate::{
4 app::app::App,
5 structs::{Item, WatchHistory},
6};
7use crossterm::event::KeyCode;
8use tui::{backend::Backend, layout::Rect, Frame};
9
10pub trait ItemTrait {
11 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App);
12 fn render_item<B: Backend>(
13 &self,
14 frame: &mut Frame<B>,
15 rect: Rect,
16 app: App,
17 selected: bool,
18 hover: bool,
19 popup_focus: bool,
20 popup_render: bool,
21 ) -> (bool, Option<Item>, App);
22 fn select(&mut self, app: App) -> (App, bool);
23 fn selectable(&self) -> bool;
24 fn load_item(
25 &self,
26 app: &App,
27 watch_history: &mut WatchHistory,
28 ) -> Result<Item, Box<dyn Error>>;
29}
src/traits/key_input.rs deleted −6
@@ -1,6 +0,0 @@
1use crate::app::app::App;
2use crossterm::event::KeyCode;
3
4pub trait KeyInput {
5 fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App);
6}
src/traits/mod.rs +4 −4
@@ -1,5 +1,5 @@
1mod select_item; 1mod item;
2pub use select_item::*; 2pub use item::*;
3 3
4mod key_input; 4mod page;
5pub use key_input::*; 5pub use page::*;
src/traits/page.rs added +11
@@ -0,0 +1,11 @@
1use crate::structs::Row;
2
3pub trait PageTrait {
4 fn message() -> String {
5 String::from("Loading page...")
6 }
7
8 fn min() -> (u16, u16);
9
10 fn default() -> Vec<Row>;
11}
src/traits/render_item.rs deleted −7
@@ -1,7 +0,0 @@
1use tui::{backend::Backend, layout::Rect, Frame};
2
3use crate::app::app::App;
4
5pub trait RenderItem {
6 fn render_item<B: Backend>(&mut self, frame: &mut Frame<B>, rect: Rect, selected: bool, hover: bool);
7}\ No newline at end of file
src/traits/select_item.rs deleted −6
@@ -1,6 +0,0 @@
1use crate::app::app::App;
2
3pub trait SelectItem {
4 fn select(&mut self, app: App) -> (App, bool);
5 fn selectable(&self) -> bool;
6}
src/widgets/text_list.rs +3
@@ -15,6 +15,7 @@ pub struct TextList {
15 pub selected: usize, 15 pub selected: usize,
16 pub scroll: usize, 16 pub scroll: usize,
17 pub area: Option<Rect>, 17 pub area: Option<Rect>,
18 pub prev_area: Option<Rect>,
18 pub style: Style, 19 pub style: Style,
19 pub selected_style: Style, 20 pub selected_style: Style,
20} 21}
@@ -119,6 +120,7 @@ impl Default for TextList {
119 selected: 0, 120 selected: 0,
120 scroll: 0, 121 scroll: 0,
121 area: None, 122 area: None,
123 prev_area: None,
122 style: Style::default(), 124 style: Style::default(),
123 selected_style: Style::default().fg(Color::Yellow), 125 selected_style: Style::default().fg(Color::Yellow),
124 } 126 }
@@ -127,6 +129,7 @@ impl Default for TextList {
127 129
128impl TextList { 130impl TextList {
129 pub fn area(&mut self, area: Rect) { 131 pub fn area(&mut self, area: Rect) {
132 self.prev_area = self.area;
130 self.area = Some(area); 133 self.area = Some(area);
131 } 134 }
132 135