Commit 8b4931ead5

8b4931ead5f384d586b7ce1b1bffca9edcd8533a

parent: a49e41106a

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-11-21 20:29 UTC

page turners improved image display + config files

Layout: unified · split

Cargo.lock +11 −11
@@ -70,9 +70,9 @@ checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
7070
7171[[package]]
7272name = "bytes"
73version = "1.2.1"
73version = "1.3.0"
7474source = "registry+https://github.com/rust-lang/crates.io-index"
75checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db"
75checksum = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c"
7676
7777[[package]]
7878name = "cassowary"
@@ -82,9 +82,9 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
8282
8383[[package]]
8484name = "cc"
85version = "1.0.76"
85version = "1.0.77"
8686source = "registry+https://github.com/rust-lang/crates.io-index"
87checksum = "76a284da2e6fe2092f2353e51713435363112dfd60030e22add80be333fb928f"
87checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4"
8888
8989[[package]]
9090name = "cfg-if"
@@ -181,9 +181,9 @@ dependencies = [
181181
182182[[package]]
183183name = "crossbeam-epoch"
184version = "0.9.11"
184version = "0.9.12"
185185source = "registry+https://github.com/rust-lang/crates.io-index"
186checksum = "f916dfc5d356b0ed9dae65f1db9fc9770aa2851d2662b988ccf4fe3516e86348"
186checksum = "96bf8df95e795db1a4aca2957ad884a2df35413b24bbeb3114422f3cc21498e8"
187187dependencies = [
188188 "autocfg",
189189 "cfg-if",
@@ -194,9 +194,9 @@ dependencies = [
194194
195195[[package]]
196196name = "crossbeam-utils"
197version = "0.8.12"
197version = "0.8.13"
198198source = "registry+https://github.com/rust-lang/crates.io-index"
199checksum = "edbafec5fa1f196ca66527c1b12c2ec4745ca14b50f1ad8f9f6f720b55d11fac"
199checksum = "422f23e724af1240ec469ea1e834d87a4b59ce2efe2c6a96256b0c47e2fd86aa"
200200dependencies = [
201201 "cfg-if",
202202]
@@ -811,9 +811,9 @@ checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
811811
812812[[package]]
813813name = "memoffset"
814version = "0.6.5"
814version = "0.7.1"
815815source = "registry+https://github.com/rust-lang/crates.io-index"
816checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
816checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4"
817817dependencies = [
818818 "autocfg",
819819]
@@ -1879,7 +1879,7 @@ dependencies = [
18791879
18801880[[package]]
18811881name = "youtube-tui"
1882version = "0.5.1"
1882version = "0.5.2"
18831883dependencies = [
18841884 "chrono",
18851885 "crossterm",
Cargo.toml +1 −1
@@ -1,6 +1,6 @@
11[package]
22name = "youtube-tui"
3version = "0.5.1"
3version = "0.5.2"
44authors = ["Siriusmart <siriusmart@tuta.io>"]
55edition = "2021"
66description = "An aesthetically pleasing YouTube TUI written in Rust"
README.md +5 −3
@@ -4,13 +4,13 @@
44[![](https://img.shields.io/crates/v/youtube-tui?label=crates.io%20version)](https://crates.io/crates/youtube-tui)
55![](https://shields.io/github/stars/siriusmart/youtube-tui?style=social)
66
7*Read more in the [user manual](https://siriusmart.github.io/youtube-tui) (including installation gude and documentation).*
7***Read more in the [user manual](https://siriusmart.github.io/youtube-tui) (including installation gude and documentation).***
88
99# Overview
1010
1111Written in Rust, the **YouTube TUI** is a lightweight and user friendly TUI for browsing YouTube content from the terminal.
1212
13![](./docs/src/images/search-showcase.png)
13![](./images/search-showcase.png)
1414
1515It is like an *app launcher*, it launches other programs to do the heavy lifting (for example, `mpv` for playing videos).
1616
@@ -43,7 +43,7 @@ The YouTube TUI does not work on its own, it is instead like a *TUI frontend* fo
4343
4444However, the programs to launch can be changed, and therefore the YouTube TUI <u>does not rely on any specific dependencies</u> to run.
4545
46![](./docs/src/images/custom-dependencies-showcase.png)
46![](./images/custom-dependencies-showcase.png)
4747
4848## Powerful
4949
@@ -57,6 +57,8 @@ The YouTube TUI allows you to browse YouTube with (almost) all of it's features,
5757### What it doesn't have
5858
5959- Vim-like commands (first priority)
60- Command line args (first priority)
61- Bootleg Vimscript? (will implement)
6062- Channel search (will implement)
6163- Channel videos sorting (will implement)
6264- Subscriptions (will implement)
docs/src/README.md +3 −3
@@ -48,9 +48,9 @@ The YouTube TUI allows you to browse YouTube with (almost) all of it's features,
4848
4949### What it doesn't have
5050
51- Next page button in pages (first priority)
52- Lazy image loading (first priority)
53- Vim-like commands (will implement)
51- Vim-like commands (first priority)
52- Command line args (first priority)
53- Bootleg Vimscript? (will implement)
5454- Channel search (will implement)
5555- Channel videos sorting (will implement)
5656- Subscriptions (will implement)
docs/src/changelogs.md +14 −1
@@ -1,6 +1,17 @@
11# Changelogs
22
3## v0.5.1
3## v0.5.2
4
5#### Added
6
7- Improved config files (including hex colour support)
8- Page turners (next/prev page in search)
9
10### Fixed
11
12- Where the image and text are displaying in the same place, and the image is displayed over the text
13
14### v0.5.1
415
516#### Added
617
@@ -15,6 +26,8 @@
1526- Sixels image support
1627- Improved config files
1728
29<hr>
30
1831## v0.4.4
1932
2033#### Added
docs/src/config/appearance.md +10 −24
@@ -15,10 +15,7 @@ colors:
1515 outline_selected: LightBlue
1616 outline_hover: LightRed
1717 outline_secondary: LightYellow
18 message_outline: !Rgb # todo: represent colours with hex values or `rgb(r,g,b)`
19 - 255
20 - 127
21 - 0
18 message_outline: '#FF7F00'
2219 message_error_outline: LightRed
2320 message_success_outline: LightGreen
2421 item_info:
@@ -29,22 +26,11 @@ colors:
2926 viewcount: LightYellow
3027 length: LightCyan
3128 published: LightMagenta
32 video_count: !Rgb
33 - 131
34 - 141
35 - 255
36 sub_count: !Rgb
37 - 101
38 - 255
39 - 186
40 likes: !Rgb
41 - 200
42 - 255
43 - 129
44 genre: !Rgb
45 - 255
46 - 121
47 - 215
29 video_count: '#838DFF'
30 sub_count: '#65FFBA'
31 likes: '#C8FF81'
32 genre: '#FF75D7'
33 page_turner: Gray
4834```
4935
5036<hr>
@@ -63,10 +49,10 @@ Any colours, here are the 2 main represenations of colours, for more check out t
6349
6450#### Terminal colour
6551
66This can be modified by the themes of your terminal.
52This can be modified by the themes of your terminal (e.g. white, green, etc).
6753
68#### RGB
54#### Hex
6955
70RGB colour values, requires TrueColour support in terminal (for instance Windows CMD cannot display RBG colours).
56Hex should be a string that starts with the `#` character, and can be from `000000` (black) to `FFFFFF` (white).
7157
72> Hex colour values to be implemented.
58> RGB color values has been deprecated
docs/src/config/keybindings.md +30 −8
@@ -5,26 +5,48 @@ The keybindings config binds each key to an action, or multiple keys for the sam
55## Example keybindings config
66
77```yaml
8'q':
9 0: Exit
10Down:
11 0: MoveDown
12'r':
13 2: Reload
14Enter:
15 0: Select
16'l':
17 0: MoveRight
818Up:
919 0: MoveUp
10Down:
20'j':
1121 0: MoveDown
22End:
23 0: ClearHistory
1224Right:
1325 0: MoveRight
14Left:
26Backspace:
27 0: Back
28'h':
1529 0: MoveLeft
16 4: Back
30F5:
31 0: Reload
32'k':
33 0: MoveUp
1734Esc:
1835 0: Deselect
19Backspace:
20 0: Back
21Enter:
22 0: Select
36Home:
37 0: FirstHistory
38Left:
39 0: MoveLeft
40 4: Back
2341```
2442
2543## Keys
2644
27Keys are the name of the keys that are pressed in the keyboard, all keys are avaliable <a href="https://docs.rs/crossterm/latest/crossterm/event/enum.KeyCode.html" target=_blank>*here*</a>.
45Keys can be:
46
47- A single character (e.g. `'q'`)
48- Named keys (e.g. `Up`, `Down`)
49- Function keys (e.g. `F5`)
2850
2951## Key modifiers
3052
docs/src/config/pages.md +8 −4
@@ -7,16 +7,20 @@ The layout config determins the position of where each item is placed, mainly th
77```yaml
88main_menu:
99 layout:
10 - !NonCenteredRow
10 - type: NonCenteredRow
11 items:
1112 - SearchBar
1213 - SearchFilters
13 - !CenteredRow
14 - type: CenteredRow
15 items:
1416 - Popular
1517 - Trending
1618 - History
17 - !NonCenteredRow
19 - type: NonCenteredRow
20 items:
1821 - ItemList
19 - !NonCenteredRow
22 - type: NonCenteredRow
23 items:
2024 - MessageBar
2125 message: Loading main menu...
2226
src/config/appearance.rs +217 −80
@@ -1,5 +1,12 @@
1use super::serde::BorderTypeSerde;
2use crate::global::traits::ConfigTrait;
1use std::{
2 error::Error,
3 fs::{self, OpenOptions},
4 io::Write,
5};
6
7use super::serde::{BorderTypeSerde, ColorSerde, ColorVariantSerde};
8use crate::global::traits::{ConfigTrait, EXTENSION};
9use home::home_dir;
310use serde::{Deserialize, Serialize};
411use tui::{style::Color, widgets::BorderType};
512use typemap::Key;
@@ -10,7 +17,7 @@ pub struct AppearanceConfigSerde {
1017 #[serde(default)]
1118 pub borders: BorderTypeSerde,
1219 #[serde(default)]
13 pub colors: ColorsConfig,
20 pub colors: ColorsConfigSerde,
1421}
1522
1623/// `appearance.yml`, this struct is stored in `data.global`
@@ -20,63 +27,188 @@ pub struct AppearanceConfig {
2027 pub colors: ColorsConfig,
2128}
2229
30impl AppearanceConfig {
31 /// generates a new file if the original one is invalid
32 pub fn load() -> Result<Self, Box<dyn Error>> {
33 let serde = *AppearanceConfigSerde::load()?;
34 let try_into = Self::from(serde);
35
36 // check if it be converted from `AppearanceConfigSerde` to `AppearanceConfig`
37 if let Some(appearance) = try_into {
38 return Ok(appearance);
39 }
40
41 let config_path = home_dir().unwrap().join(format!(
42 ".config/youtube-tui/{}.{}",
43 AppearanceConfigSerde::LABEL,
44 EXTENSION
45 ));
46
47 // if it cannot, back it up and regenerate it
48 let mut new_path = config_path.clone();
49 new_path.pop();
50 new_path.push(format!(
51 "{}-{}.{}",
52 AppearanceConfigSerde::LABEL,
53 chrono::offset::Local::now(),
54 EXTENSION
55 ));
56 fs::rename(&config_path, &new_path)?;
57
58 // here generates a default and write it to the file
59 let default = AppearanceConfigSerde::default();
60
61 let mut file = OpenOptions::new()
62 .write(true)
63 .create(true)
64 .truncate(true)
65 .open(&config_path)?;
66
67 file.write_all(serde_yaml::to_string(&default)?.as_bytes())?;
68
69 match Self::from(default) {
70 Some(appearance) => Ok(appearance),
71 // if the default still cannot be converted, panic and exit the program
72 None => panic!(
73 "the default for {}.{} is invalid",
74 AppearanceConfigSerde::LABEL,
75 EXTENSION
76 ),
77 }
78 }
79}
80
2381/// Includes all configurable colors
24#[derive(Clone, Copy, Serialize, Deserialize)]
82#[derive(Clone, Copy)]
2583pub struct ColorsConfig {
26 #[serde(default = "text_default")]
2784 pub text: Color,
28 #[serde(default = "text_special_default")]
2985 pub text_special: Color,
30 #[serde(default = "text_secondary_default")]
3186 pub text_secondary: Color,
32 #[serde(default = "text_error_default")]
3387 pub text_error: Color,
34 #[serde(default = "outline_default")]
3588 pub outline: Color,
36 #[serde(default = "outline_selected_default")]
3789 pub outline_selected: Color,
38 #[serde(default = "outline_hover_default")]
3990 pub outline_hover: Color,
40 #[serde(default = "outline_secondary_default")]
4191 pub outline_secondary: Color,
42 #[serde(default = "message_outline_default")]
4392 pub message_outline: Color,
44 #[serde(default = "message_error_outline_default")]
4593 pub message_error_outline: Color,
46 #[serde(default = "message_success_outline_default")]
4794 pub message_success_outline: Color,
48 #[serde(default)]
4995 pub item_info: ItemInfoColors,
5096}
5197
5298/// Colors used by ItemInfo
53#[derive(Clone, Copy, Serialize, Deserialize)]
99#[derive(Clone, Copy)]
54100pub struct ItemInfoColors {
55 #[serde(default = "tag_default")]
56101 pub tag: Color,
57 #[serde(default = "title_default")]
58102 pub title: Color,
59 #[serde(default = "description_default")]
60103 pub description: Color,
61 #[serde(default = "author_default")]
62104 pub author: Color,
63 #[serde(default = "viewcount_default")]
64105 pub viewcount: Color,
65 #[serde(default = "length_default")]
66106 pub length: Color,
67 #[serde(default = "published_default")]
68107 pub published: Color,
69 #[serde(default = "video_count_default")]
70108 pub video_count: Color,
71 #[serde(default = "sub_count_default")]
72109 pub sub_count: Color,
73 #[serde(default = "likes_default")]
74110 pub likes: Color,
75 #[serde(default = "genre_default")]
76111 pub genre: Color,
112 pub page_turner: Color,
113}
114
115#[derive(Clone, Serialize, Deserialize)]
116pub struct ColorsConfigSerde {
117 #[serde(default = "text_default")]
118 pub text: ColorSerde,
119 #[serde(default = "text_special_default")]
120 pub text_special: ColorSerde,
121 #[serde(default = "text_secondary_default")]
122 pub text_secondary: ColorSerde,
123 #[serde(default = "text_error_default")]
124 pub text_error: ColorSerde,
125 #[serde(default = "outline_default")]
126 pub outline: ColorSerde,
127 #[serde(default = "outline_selected_default")]
128 pub outline_selected: ColorSerde,
129 #[serde(default = "outline_hover_default")]
130 pub outline_hover: ColorSerde,
131 #[serde(default = "outline_secondary_default")]
132 pub outline_secondary: ColorSerde,
133 #[serde(default = "message_outline_default")]
134 pub message_outline: ColorSerde,
135 #[serde(default = "message_error_outline_default")]
136 pub message_error_outline: ColorSerde,
137 #[serde(default = "message_success_outline_default")]
138 pub message_success_outline: ColorSerde,
139 #[serde(default)]
140 pub item_info: ItemInfoColorsSerde,
141}
142
143#[derive(Clone, Serialize, Deserialize)]
144pub struct ItemInfoColorsSerde {
145 #[serde(default = "tag_default")]
146 pub tag: ColorSerde,
147 #[serde(default = "title_default")]
148 pub title: ColorSerde,
149 #[serde(default = "description_default")]
150 pub description: ColorSerde,
151 #[serde(default = "author_default")]
152 pub author: ColorSerde,
153 #[serde(default = "viewcount_default")]
154 pub viewcount: ColorSerde,
155 #[serde(default = "length_default")]
156 pub length: ColorSerde,
157 #[serde(default = "published_default")]
158 pub published: ColorSerde,
159 #[serde(default = "video_count_default")]
160 pub video_count: ColorSerde,
161 #[serde(default = "sub_count_default")]
162 pub sub_count: ColorSerde,
163 #[serde(default = "likes_default")]
164 pub likes: ColorSerde,
165 #[serde(default = "genre_default")]
166 pub genre: ColorSerde,
167 #[serde(default = "page_turner_default")]
168 pub page_turner: ColorSerde,
77169}
78170
79impl Default for ColorsConfig {
171// uses a custom `into` for Option<T> instead of T so that we can know that the config is invalid
172// without panicking
173impl ColorsConfigSerde {
174 pub fn into(self) -> Option<ColorsConfig> {
175 Some(ColorsConfig {
176 text: self.text.to_color()?,
177 text_special: self.text_special.to_color()?,
178 text_secondary: self.text_secondary.to_color()?,
179 text_error: self.text_error.to_color()?,
180 outline: self.outline.to_color()?,
181 outline_selected: self.outline_selected.to_color()?,
182 outline_hover: self.outline_hover.to_color()?,
183 outline_secondary: self.outline_secondary.to_color()?,
184 message_outline: self.message_outline.to_color()?,
185 message_error_outline: self.message_error_outline.to_color()?,
186 message_success_outline: self.message_success_outline.to_color()?,
187 item_info: self.item_info.into()?,
188 })
189 }
190}
191
192impl ItemInfoColorsSerde {
193 pub fn into(self) -> Option<ItemInfoColors> {
194 Some(ItemInfoColors {
195 tag: self.tag.to_color()?,
196 title: self.title.to_color()?,
197 description: self.description.to_color()?,
198 author: self.author.to_color()?,
199 viewcount: self.viewcount.to_color()?,
200 length: self.length.to_color()?,
201 published: self.published.to_color()?,
202 video_count: self.video_count.to_color()?,
203 sub_count: self.sub_count.to_color()?,
204 likes: self.likes.to_color()?,
205 genre: self.genre.to_color()?,
206 page_turner: self.page_turner.to_color()?,
207 })
208 }
209}
210
211impl Default for ColorsConfigSerde {
80212 fn default() -> Self {
81213 Self {
82214 text: text_default(),
@@ -90,12 +222,12 @@ impl Default for ColorsConfig {
90222 message_error_outline: message_error_outline_default(),
91223 message_success_outline: message_success_outline_default(),
92224 text_error: text_error_default(),
93 item_info: ItemInfoColors::default(),
225 item_info: ItemInfoColorsSerde::default(),
94226 }
95227 }
96228}
97229
98impl Default for ItemInfoColors {
230impl Default for ItemInfoColorsSerde {
99231 fn default() -> Self {
100232 Self {
101233 tag: tag_default(),
@@ -109,16 +241,17 @@ impl Default for ItemInfoColors {
109241 sub_count: sub_count_default(),
110242 likes: likes_default(),
111243 genre: genre_default(),
244 page_turner: page_turner_default(),
112245 }
113246 }
114247}
115248
116impl From<AppearanceConfigSerde> for AppearanceConfig {
117 fn from(original: AppearanceConfigSerde) -> Self {
118 Self {
249impl AppearanceConfig {
250 fn from(original: AppearanceConfigSerde) -> Option<Self> {
251 Some(Self {
119252 borders: original.borders.into(),
120 colors: original.colors,
121 }
253 colors: original.colors.into()?,
254 })
122255 }
123256}
124257
@@ -132,90 +265,94 @@ impl Key for AppearanceConfig {
132265
133266// defaults
134267
135fn text_default() -> Color {
136 Color::Reset
268fn text_default() -> ColorSerde {
269 ColorSerde::ColorVariant(ColorVariantSerde::Reset)
270}
271
272fn text_special_default() -> ColorSerde {
273 ColorSerde::ColorVariant(ColorVariantSerde::Reset)
137274}
138275
139fn text_special_default() -> Color {
140 Color::Reset
276fn text_secondary_default() -> ColorSerde {
277 ColorSerde::ColorVariant(ColorVariantSerde::Reset)
141278}
142279
143fn text_secondary_default() -> Color {
144 Color::Reset
280fn outline_default() -> ColorSerde {
281 ColorSerde::ColorVariant(ColorVariantSerde::Reset)
145282}
146283
147fn outline_default() -> Color {
148 Color::Reset
284fn outline_selected_default() -> ColorSerde {
285 ColorSerde::ColorVariant(ColorVariantSerde::LightBlue)
149286}
150287
151fn outline_selected_default() -> Color {
152 Color::LightBlue
288fn outline_hover_default() -> ColorSerde {
289 ColorSerde::ColorVariant(ColorVariantSerde::LightRed)
153290}
154291
155fn outline_hover_default() -> Color {
156 Color::LightRed
292fn outline_secondary_default() -> ColorSerde {
293 ColorSerde::ColorVariant(ColorVariantSerde::LightYellow)
157294}
158295
159fn outline_secondary_default() -> Color {
160 Color::LightYellow
296fn message_outline_default() -> ColorSerde {
297 ColorSerde::Hex(String::from("#FF7F00"))
161298}
162299
163fn message_outline_default() -> Color {
164 Color::Rgb(255, 127, 0)
300fn message_error_outline_default() -> ColorSerde {
301 ColorSerde::ColorVariant(ColorVariantSerde::LightRed)
165302}
166303
167fn message_error_outline_default() -> Color {
168 Color::LightRed
304fn message_success_outline_default() -> ColorSerde {
305 ColorSerde::ColorVariant(ColorVariantSerde::LightGreen)
169306}
170307
171fn message_success_outline_default() -> Color {
172 Color::LightGreen
308fn text_error_default() -> ColorSerde {
309 ColorSerde::ColorVariant(ColorVariantSerde::LightRed)
173310}
174311
175fn text_error_default() -> Color {
176 Color::LightRed
312fn tag_default() -> ColorSerde {
313 ColorSerde::ColorVariant(ColorVariantSerde::Gray)
177314}
178315
179fn tag_default() -> Color {
180 Color::Gray
316fn title_default() -> ColorSerde {
317 ColorSerde::ColorVariant(ColorVariantSerde::LightBlue)
181318}
182319
183fn title_default() -> Color {
184 Color::LightBlue
320fn description_default() -> ColorSerde {
321 ColorSerde::ColorVariant(ColorVariantSerde::Gray)
185322}
186323
187fn description_default() -> Color {
188 Color::Gray
324fn author_default() -> ColorSerde {
325 ColorSerde::ColorVariant(ColorVariantSerde::LightGreen)
189326}
190327
191fn author_default() -> Color {
192 Color::LightGreen
328fn viewcount_default() -> ColorSerde {
329 ColorSerde::ColorVariant(ColorVariantSerde::LightYellow)
193330}
194331
195fn viewcount_default() -> Color {
196 Color::LightYellow
332fn length_default() -> ColorSerde {
333 ColorSerde::ColorVariant(ColorVariantSerde::LightCyan)
197334}
198335
199fn length_default() -> Color {
200 Color::LightCyan
336fn published_default() -> ColorSerde {
337 ColorSerde::ColorVariant(ColorVariantSerde::LightMagenta)
201338}
202339
203fn published_default() -> Color {
204 Color::LightMagenta
340fn video_count_default() -> ColorSerde {
341 ColorSerde::Hex(String::from("#838DFF"))
205342}
206343
207fn video_count_default() -> Color {
208 Color::Rgb(131, 141, 255)
344fn sub_count_default() -> ColorSerde {
345 ColorSerde::Hex(String::from("#65FFBA"))
209346}
210347
211fn sub_count_default() -> Color {
212 Color::Rgb(101, 255, 186)
348fn likes_default() -> ColorSerde {
349 ColorSerde::Hex(String::from("#C8FF81"))
213350}
214351
215fn likes_default() -> Color {
216 Color::Rgb(200, 255, 129)
352fn genre_default() -> ColorSerde {
353 ColorSerde::Hex(String::from("#FF75D7"))
217354}
218355
219fn genre_default() -> Color {
220 Color::Rgb(255, 121, 215)
356fn page_turner_default() -> ColorSerde {
357 ColorSerde::ColorVariant(ColorVariantSerde::Gray)
221358}
src/config/keybindings.rs +138 −23
@@ -1,7 +1,17 @@
1use crate::global::{structs::KeyAction, traits::ConfigTrait};
1use super::serde::{KeyCodeSerde, KeyVariantsSerde};
2use crate::global::{
3 structs::KeyAction,
4 traits::{ConfigTrait, EXTENSION},
5};
26use crossterm::event::KeyCode;
7use home::home_dir;
38use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
9use std::{
10 collections::HashMap,
11 error::Error,
12 fs::{self, OpenOptions},
13 io::Write,
14};
515use typemap::Key;
616
717// The outer HashMap<KeyCode, T> gets a value for whatever code is being pressed
@@ -9,51 +19,156 @@ use typemap::Key;
919// The u8 for each modifier key can be found in https://docs.rs/crossterm/latest/src/crossterm/event.rs.html#587-603
1020// The sum of u8 for each key modifier would mean having all of those modifiers at the same time
1121/// `keybindings.yml`, contains a hashmap of key + key modifier to action pair
12#[derive(Serialize, Deserialize, Clone)]
22#[derive(Clone)]
1323pub struct KeyBindingsConfig(pub HashMap<KeyCode, HashMap<u8, KeyAction>>);
1424
15impl ConfigTrait for KeyBindingsConfig {
16 const LABEL: &'static str = "keybindings";
17}
18
1925impl Key for KeyBindingsConfig {
2026 type Value = Self;
2127}
2228
23impl Default for KeyBindingsConfig {
29#[derive(Serialize, Deserialize, Clone)]
30pub struct KeyBindingsConfigSerde(pub HashMap<KeyCodeSerde, HashMap<u8, KeyAction>>);
31
32impl ConfigTrait for KeyBindingsConfigSerde {
33 const LABEL: &'static str = "keybindings";
34}
35
36impl Default for KeyBindingsConfigSerde {
2437 fn default() -> Self {
2538 Self(HashMap::from([
2639 // movement keys // Alt left should be back
2740 (
28 KeyCode::Left,
41 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Left),
2942 HashMap::from([(0, KeyAction::MoveLeft), (4, KeyAction::Back)]),
3043 ),
31 (KeyCode::Right, HashMap::from([(0, KeyAction::MoveRight)])),
32 (KeyCode::Up, HashMap::from([(0, KeyAction::MoveUp)])),
33 (KeyCode::Down, HashMap::from([(0, KeyAction::MoveDown)])),
44 (
45 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Right),
46 HashMap::from([(0, KeyAction::MoveRight)]),
47 ),
48 (
49 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Up),
50 HashMap::from([(0, KeyAction::MoveUp)]),
51 ),
52 (
53 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Down),
54 HashMap::from([(0, KeyAction::MoveDown)]),
55 ),
3456 // vim keybindings
3557 (
36 KeyCode::Char('h'),
58 KeyCodeSerde::Char('h'),
3759 HashMap::from([(0, KeyAction::MoveLeft)]),
3860 ),
3961 (
40 KeyCode::Char('j'),
62 KeyCodeSerde::Char('j'),
4163 HashMap::from([(0, KeyAction::MoveDown)]),
4264 ),
43 (KeyCode::Char('k'), HashMap::from([(0, KeyAction::MoveUp)])),
4465 (
45 KeyCode::Char('l'),
66 KeyCodeSerde::Char('k'),
67 HashMap::from([(0, KeyAction::MoveUp)]),
68 ),
69 (
70 KeyCodeSerde::Char('l'),
4671 HashMap::from([(0, KeyAction::MoveRight)]),
4772 ),
4873 // functional keys
49 (KeyCode::Enter, HashMap::from([(0, KeyAction::Select)])),
50 (KeyCode::Esc, HashMap::from([(0, KeyAction::Deselect)])),
51 (KeyCode::Char('q'), HashMap::from([(0, KeyAction::Exit)])),
52 (KeyCode::Char('r'), HashMap::from([(2, KeyAction::Reload)])),
74 (
75 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Enter),
76 HashMap::from([(0, KeyAction::Select)]),
77 ),
78 (
79 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Esc),
80 HashMap::from([(0, KeyAction::Deselect)]),
81 ),
82 (
83 KeyCodeSerde::F(String::from("F5")),
84 HashMap::from([(0, KeyAction::Reload)]),
85 ),
86 (
87 KeyCodeSerde::Char('q'),
88 HashMap::from([(0, KeyAction::Exit)]),
89 ),
90 (
91 KeyCodeSerde::Char('r'),
92 HashMap::from([(2, KeyAction::Reload)]),
93 ),
5394 // history
54 (KeyCode::Backspace, HashMap::from([(0, KeyAction::Back)])),
55 (KeyCode::End, HashMap::from([(0, KeyAction::ClearHistory)])),
56 (KeyCode::Home, HashMap::from([(0, KeyAction::FirstHistory)])),
95 (
96 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace),
97 HashMap::from([(0, KeyAction::Back)]),
98 ),
99 (
100 KeyCodeSerde::KeyVariants(KeyVariantsSerde::End),
101 HashMap::from([(0, KeyAction::ClearHistory)]),
102 ),
103 (
104 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home),
105 HashMap::from([(0, KeyAction::FirstHistory)]),
106 ),
57107 ]))
58108 }
59109}
110
111impl KeyBindingsConfigSerde {
112 /// converts KeyBindingsConfigSerde into KeyBindingsConfig
113 pub fn into(self) -> Option<KeyBindingsConfig> {
114 let mut out = HashMap::new();
115
116 // simply loops over the serde hashmap and insert them into the new one
117 for (keycodeserde, map) in self.0.into_iter() {
118 out.insert(keycodeserde.to_keycode()?, map);
119 }
120
121 Some(KeyBindingsConfig(out))
122 }
123}
124
125impl KeyBindingsConfig {
126 /// generates a new file if the original one is invalid
127 pub fn load() -> Result<Self, Box<dyn Error>> {
128 let serde = *KeyBindingsConfigSerde::load()?;
129 // check if it be converted from `KeyBindingsConfigSerde` to `KeyBindingsConfig`
130 let try_into = serde.into();
131
132 if let Some(keybindings) = try_into {
133 return Ok(keybindings);
134 }
135
136 let config_path = home_dir().unwrap().join(format!(
137 ".config/youtube-tui/{}.{}",
138 KeyBindingsConfigSerde::LABEL,
139 EXTENSION
140 ));
141
142 // if it cannot, back it up and regenerate it
143 let mut new_path = config_path.clone();
144 new_path.pop();
145 new_path.push(format!(
146 "{}-{}.{}",
147 KeyBindingsConfigSerde::LABEL,
148 chrono::offset::Local::now(),
149 EXTENSION
150 ));
151 fs::rename(&config_path, &new_path)?;
152
153 // here generates a default and write it to the file
154 let default = KeyBindingsConfigSerde::default();
155
156 let mut file = OpenOptions::new()
157 .write(true)
158 .create(true)
159 .truncate(true)
160 .open(&config_path)?;
161
162 file.write_all(serde_yaml::to_string(&default)?.as_bytes())?;
163
164 match default.into() {
165 Some(keybindings) => Ok(keybindings),
166 // if the default still cannot be converted, panic and exit the program
167 None => panic!(
168 "the default for {}.{} is invalid",
169 KeyBindingsConfigSerde::LABEL,
170 EXTENSION
171 ),
172 }
173 }
174}
src/config/pages.rs +1
@@ -122,6 +122,7 @@ impl PageConfig {
122122
123123/// CenteredRow will have its items centered, while NonCenteredRow will align to the left
124124#[derive(Clone, Serialize, Deserialize)]
125#[serde(tag = "type", content = "items")]
125126pub enum PageRow {
126127 CenteredRow(Vec<PageItems>),
127128 NonCenteredRow(Vec<PageItems>),
src/config/search.rs +24 −9
@@ -7,10 +7,21 @@ use typemap::Key;
77
88// can be turned into URL Params for the search term with filters
99/// Search query & filters
10#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq)]
10#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
1111pub struct Search {
1212 pub query: String,
1313 pub filters: SearchFilters,
14 pub page: u16,
15}
16
17impl Default for Search {
18 fn default() -> Self {
19 Self {
20 query: String::new(),
21 filters: SearchFilters::default(),
22 page: 1,
23 }
24 }
1425}
1526
1627impl Key for Search {
@@ -23,14 +34,18 @@ impl ConfigTrait for Search {
2334
2435impl ToString for Search {
2536 fn to_string(&self) -> String {
26 vec![
27 format!("q={}", self.query),
28 self.filters.sort.as_url_string(),
29 self.filters.date.as_url_string(),
30 self.filters.duration.as_url_string(),
31 self.filters.r#type.as_url_string(),
32 ]
33 .join("&")
37 format!(
38 "{}&page={}",
39 vec![
40 format!("q={}", self.query),
41 self.filters.sort.as_url_string(),
42 self.filters.date.as_url_string(),
43 self.filters.duration.as_url_string(),
44 self.filters.r#type.as_url_string(),
45 ]
46 .join("&"),
47 self.page
48 )
3449 }
3550}
3651
src/config/serde.rs +175 −2
@@ -1,7 +1,7 @@
11//! Structs that impl `Into<T>` because `T` does not impl Serde but is used in config files
2
2use crossterm::event::KeyCode;
33use serde::{Deserialize, Serialize};
4use tui::widgets::BorderType;
4use tui::{style::Color, widgets::BorderType};
55
66/// `BorderType` but impl `serde`
77#[derive(Serialize, Deserialize, Clone, Copy)]
@@ -28,3 +28,176 @@ impl From<BorderTypeSerde> for BorderType {
2828 }
2929 }
3030}
31
32/// all terminal colors
33#[derive(Serialize, Deserialize, Clone)]
34pub enum ColorVariantSerde {
35 Reset,
36 Black,
37 Red,
38 Green,
39 Yellow,
40 Blue,
41 Magenta,
42 Cyan,
43 Gray,
44 DarkGray,
45 LightRed,
46 LightGreen,
47 LightYellow,
48 LightBlue,
49 LightMagenta,
50 LightCyan,
51 White,
52}
53
54/// a single color
55#[derive(Serialize, Deserialize, Clone)]
56#[serde(untagged)]
57pub enum ColorSerde {
58 ColorVariant(ColorVariantSerde),
59 Hex(String),
60}
61
62impl ColorSerde {
63 pub fn to_color(self) -> Option<Color> {
64 match self {
65 Self::ColorVariant(ColorVariantSerde::Reset) => Some(Color::Reset),
66 Self::ColorVariant(ColorVariantSerde::Black) => Some(Color::Black),
67 Self::ColorVariant(ColorVariantSerde::Red) => Some(Color::Red),
68 Self::ColorVariant(ColorVariantSerde::Green) => Some(Color::Green),
69 Self::ColorVariant(ColorVariantSerde::Yellow) => Some(Color::Yellow),
70 Self::ColorVariant(ColorVariantSerde::Blue) => Some(Color::Blue),
71 Self::ColorVariant(ColorVariantSerde::Magenta) => Some(Color::Magenta),
72 Self::ColorVariant(ColorVariantSerde::Cyan) => Some(Color::Cyan),
73 Self::ColorVariant(ColorVariantSerde::Gray) => Some(Color::Gray),
74 Self::ColorVariant(ColorVariantSerde::DarkGray) => Some(Color::DarkGray),
75 Self::ColorVariant(ColorVariantSerde::LightRed) => Some(Color::LightRed),
76 Self::ColorVariant(ColorVariantSerde::LightGreen) => Some(Color::LightGreen),
77 Self::ColorVariant(ColorVariantSerde::LightYellow) => Some(Color::LightYellow),
78 Self::ColorVariant(ColorVariantSerde::LightBlue) => Some(Color::LightBlue),
79 Self::ColorVariant(ColorVariantSerde::LightMagenta) => Some(Color::LightMagenta),
80 Self::ColorVariant(ColorVariantSerde::LightCyan) => Some(Color::LightCyan),
81 Self::ColorVariant(ColorVariantSerde::White) => Some(Color::White),
82 Self::Hex(s) => {
83 if s.len() != 7 || &s[0..1] != "#" {
84 return None;
85 }
86
87 Some(Color::Rgb(
88 from_hex(&s[1..3])?,
89 from_hex(&s[3..5])?,
90 from_hex(&s[5..7])?,
91 ))
92 }
93 }
94 }
95}
96
97/// converts a 2 digit hex number (00 - FF) to u8
98fn from_hex(s: &str) -> Option<u8> {
99 Some(from_hex_digit(&s[0..1])? * 16 + from_hex_digit(&s[1..2])?)
100}
101
102/// converts a single hex digit to u8
103fn from_hex_digit(d: &str) -> Option<u8> {
104 match d.to_uppercase().as_str() {
105 "0" => Some(0),
106 "1" => Some(1),
107 "2" => Some(2),
108 "3" => Some(3),
109 "4" => Some(4),
110 "5" => Some(5),
111 "6" => Some(6),
112 "7" => Some(7),
113 "8" => Some(8),
114 "9" => Some(9),
115 "A" => Some(10),
116 "B" => Some(11),
117 "C" => Some(12),
118 "D" => Some(13),
119 "E" => Some(14),
120 "F" => Some(15),
121 _ => None,
122 }
123}
124
125/// serde version of a single key code
126#[derive(Serialize, Deserialize, Clone, Hash, PartialEq, Eq)]
127#[serde(untagged)]
128pub enum KeyCodeSerde {
129 Char(char),
130 KeyVariants(KeyVariantsSerde),
131 F(String),
132}
133
134/// values of all default keys (excluding chars and function keys)
135#[derive(Serialize, Deserialize, Clone, Hash, PartialEq, Eq)]
136pub enum KeyVariantsSerde {
137 Backspace,
138 Enter,
139 Left,
140 Right,
141 Up,
142 Down,
143 Home,
144 End,
145 PageUp,
146 PageDown,
147 Tab,
148 BackTab,
149 Delete,
150 Insert,
151 Null,
152 Esc,
153 CapsLock,
154 ScrollLock,
155 NumLock,
156 PrintScreen,
157 Pause,
158 Menu,
159 KeypadBegin,
160}
161
162impl KeyCodeSerde {
163 pub fn to_keycode(self) -> Option<KeyCode> {
164 match self {
165 Self::KeyVariants(KeyVariantsSerde::Backspace) => Some(KeyCode::Backspace),
166 Self::KeyVariants(KeyVariantsSerde::Enter) => Some(KeyCode::Enter),
167 Self::KeyVariants(KeyVariantsSerde::Left) => Some(KeyCode::Left),
168 Self::KeyVariants(KeyVariantsSerde::Right) => Some(KeyCode::Right),
169 Self::KeyVariants(KeyVariantsSerde::Up) => Some(KeyCode::Up),
170 Self::KeyVariants(KeyVariantsSerde::Down) => Some(KeyCode::Down),
171 Self::KeyVariants(KeyVariantsSerde::Home) => Some(KeyCode::Home),
172 Self::KeyVariants(KeyVariantsSerde::End) => Some(KeyCode::End),
173 Self::KeyVariants(KeyVariantsSerde::PageUp) => Some(KeyCode::PageUp),
174 Self::KeyVariants(KeyVariantsSerde::PageDown) => Some(KeyCode::PageDown),
175 Self::KeyVariants(KeyVariantsSerde::Tab) => Some(KeyCode::Tab),
176 Self::KeyVariants(KeyVariantsSerde::BackTab) => Some(KeyCode::BackTab),
177 Self::KeyVariants(KeyVariantsSerde::Delete) => Some(KeyCode::Delete),
178 Self::KeyVariants(KeyVariantsSerde::Insert) => Some(KeyCode::Insert),
179 Self::KeyVariants(KeyVariantsSerde::Null) => Some(KeyCode::Null),
180 Self::KeyVariants(KeyVariantsSerde::Esc) => Some(KeyCode::Esc),
181 Self::KeyVariants(KeyVariantsSerde::CapsLock) => Some(KeyCode::CapsLock),
182 Self::KeyVariants(KeyVariantsSerde::ScrollLock) => Some(KeyCode::ScrollLock),
183 Self::KeyVariants(KeyVariantsSerde::NumLock) => Some(KeyCode::NumLock),
184 Self::KeyVariants(KeyVariantsSerde::PrintScreen) => Some(KeyCode::PrintScreen),
185 Self::KeyVariants(KeyVariantsSerde::Pause) => Some(KeyCode::Pause),
186 Self::KeyVariants(KeyVariantsSerde::Menu) => Some(KeyCode::Menu),
187 Self::KeyVariants(KeyVariantsSerde::KeypadBegin) => Some(KeyCode::KeypadBegin),
188 Self::Char(c) => Some(KeyCode::Char(c)),
189 Self::F(s) => {
190 if s[0..1].to_uppercase().as_str() != "F" {
191 return None;
192 }
193
194 let parsed = s[1..].parse::<u8>();
195
196 match parsed {
197 Ok(f) => Some(KeyCode::F(f)),
198 Err(_) => None,
199 }
200 }
201 }
202 }
203}
src/global/functions/download_all_images.rs +1 −1
@@ -35,7 +35,7 @@ impl From<&Item> for Option<DownloadRequest> {
3535 url: fullchannel.thumbnail_url.clone(),
3636 id: fullchannel.id.clone(),
3737 },
38 Item::Unknown(_) => return None,
38 Item::Unknown(_) | Item::Page(_) => return None,
3939 })
4040 }
4141}
src/global/functions/mod.rs +2
@@ -9,3 +9,5 @@ mod download_all_images;
99pub use download_all_images::download_all_images;
1010mod popup_area;
1111pub use popup_area::popup_area;
12mod run_command;
13pub use run_command::run_command;
src/global/functions/run_command.rs added +46
@@ -0,0 +1,46 @@
1use crate::global::structs::{MainMenuPage, Page, Task, Tasks};
2use std::io::Stdout;
3use tui::{backend::CrosstermBackend, Terminal};
4use tui_additions::framework::Framework;
5
6/// WIP text command support
7pub fn run_command(
8 command: &[&str],
9 framework: &mut Framework,
10 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
11) {
12 // match a command splitted by space to a bunch of avaliable commands
13 match command {
14 [] => {}
15 ["loadpage"] => { /* help message */ }
16 ["loadpage", page] => {
17 let page = match *page {
18 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
19 _ => None,
20 };
21
22 if let Some(page) = page {
23 framework
24 .data
25 .state
26 .get_mut::<Tasks>()
27 .unwrap()
28 .priority
29 .push(Task::LoadPage(page))
30 }
31 }
32 ["history"] => { /* help message */ }
33 ["history", "clear"] => {
34 framework.clear_history();
35 }
36 ["flush"] => loop {
37 // runs all stacked actions
38 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
39 let _res = tasks.run(framework, terminal);
40 continue;
41 }
42 break;
43 },
44 _ => {}
45 }
46}
src/global/structs/item.rs +9 −1
@@ -24,6 +24,7 @@ pub enum Item {
2424 FullVideo(FullVideoItem),
2525 FullPlaylist(FullPlaylistItem),
2626 FullChannel(FullChannelItem),
27 Page(bool), // true: next false: prev
2728 Unknown(SearchItemTransition),
2829}
2930
@@ -113,6 +114,13 @@ impl Display for Item {
113114 Self::FullVideo(video) => &video.title,
114115 Self::FullPlaylist(playlist) => &playlist.title,
115116 Self::FullChannel(channel) => &channel.name,
117 Self::Page(b) => {
118 if *b {
119 "Next page"
120 } else {
121 "Previous page"
122 }
123 }
116124 Self::Unknown(_) => "Unknown item",
117125 })
118126 }
@@ -183,7 +191,7 @@ impl Item {
183191 Self::FullVideo(video) => &video.id,
184192 Self::FullPlaylist(playlist) => &playlist.id,
185193 Self::FullChannel(channel) => &channel.id,
186 Self::Unknown(_) => "invalid",
194 Self::Unknown(_) | Self::Page(_) => "invalid",
187195 }
188196 }
189197
src/global/traits/configtrait.rs +1 −1
@@ -6,7 +6,7 @@ use std::{
66 io::Write,
77};
88
9const EXTENSION: &str = "yml";
9pub const EXTENSION: &str = "yml";
1010
1111/// Trait for loading, saving config files
1212pub trait ConfigTrait {
src/init.rs +14 −6
@@ -1,15 +1,17 @@
11use crate::{
22 config::{
3 AppearanceConfig, AppearanceConfigSerde, CommandsConfig, CommandsConfigSerde,
4 KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
3 AppearanceConfig, CommandsConfig, CommandsConfigSerde, KeyBindingsConfig, MainConfig,
4 MinDimentions, PagesConfig, Search,
55 },
66 global::{
7 functions::run_command,
78 structs::{InvidiousClient, Message, Page, Status, Tasks, WatchHistory},
89 traits::ConfigTrait,
910 },
1011};
1112use home::home_dir;
12use std::{error::Error, fs};
13use std::{error::Error, fs, io::Stdout};
14use tui::{backend::CrosstermBackend, Terminal};
1315use tui_additions::framework::Framework;
1416
1517/// app to run before the app starts
@@ -17,7 +19,10 @@ use tui_additions::framework::Framework;
1719// - create folders like `~/.config/youtube-tui/` and `~/.cache/youtube-tui/thumbnails/`
1820// - load all config files
1921// - insert data
20pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
22pub fn init(
23 framework: &mut Framework,
24 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
25) -> Result<(), Box<dyn Error>> {
2126 // creating files
2227 let home_dir = home_dir().unwrap();
2328 let config_path = home_dir.join(".config/youtube-tui/");
@@ -54,7 +59,7 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
5459 framework
5560 .data
5661 .global
57 .insert::<AppearanceConfig>(AppearanceConfig::from(*AppearanceConfigSerde::load()?));
62 .insert::<AppearanceConfig>(AppearanceConfig::load()?);
5863 framework.data.global.insert::<MainConfig>(main_config);
5964 framework
6065 .data
@@ -63,7 +68,7 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
6368 framework
6469 .data
6570 .global
66 .insert::<KeyBindingsConfig>(*KeyBindingsConfig::load()?);
71 .insert::<KeyBindingsConfig>(KeyBindingsConfig::load()?);
6772 framework.data.global.insert::<Message>(Message::None);
6873 framework
6974 .data
@@ -79,5 +84,8 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
7984 .state
8085 .insert::<MinDimentions>(MinDimentions::default());
8186
87 run_command(&["loadpage", "popular"], framework, terminal);
88 run_command(&["flush"], framework, terminal);
89 run_command(&["history", "clear"], framework, terminal);
8290 Ok(())
8391}
src/items/iteminfo.rs +16 −3
@@ -48,7 +48,11 @@ impl FrameworkItem for ItemInfo {
4848 && main_config.images.display()
4949 && !status.popup_opened
5050 {
51 let mut scroll = 0;
51 #[cfg(any(feature = "sixel", feature = "halfblock"))]
52 let scroll;
53
54 #[cfg(not(any(feature = "sixel", feature = "halfblock")))]
55 let scroll = 0;
5256
5357 #[cfg(any(feature = "sixel", feature = "halfblock"))]
5458 {
@@ -85,13 +89,15 @@ impl FrameworkItem for ItemInfo {
8589 .priority
8690 .push(Task::LazyRendered);
8791 } else {
88 scroll = 0;
92 scroll = self.lazy_scroll;
8993 }
94 } else {
95 scroll = self.lazy_scroll;
9096 }
9197 }
9298 scroll
9399 } else {
94 0
100 self.lazy_scroll
95101 };
96102
97103 self.lazy_scroll = scroll;
@@ -325,6 +331,13 @@ impl FrameworkItem for ItemInfo {
325331 Style::default().fg(appearance.colors.item_info.description),
326332 )),
327333 ),
334 Item::Page(b) => (
335 vec![(
336 if *b { "Next page" } else { "Previous page" }.to_string(),
337 Style::default().fg(appearance.colors.item_info.page_turner),
338 )],
339 None,
340 ),
328341 };
329342
330343 let mut y = if scroll >= area.height { 0 } else { scroll } + area.y;
src/items/itemlist.rs +46 −17
@@ -8,13 +8,14 @@ use tui_additions::{
88
99use super::ItemInfo;
1010use crate::{
11 config::{AppearanceConfig, KeyBindingsConfig, MainConfig},
11 config::{AppearanceConfig, KeyBindingsConfig, MainConfig, Search},
1212 global::{
1313 functions::download_all_images,
1414 structs::{
15 ChannelDisplayPage, ChannelDisplayPageType, FullPlaylistItem, FullVideoItem,
16 InvidiousClient, Item, KeyAction, MainMenuPage, MiniChannelItem, MiniPlaylistItem,
17 MiniVideoItem, Page, SingleItemPage, Status, Task, Tasks, WatchHistory,
15 ChannelDisplayPage, ChannelDisplayPageType, FullChannelItem, FullPlaylistItem,
16 FullVideoItem, InvidiousClient, Item, KeyAction, MainMenuPage, Message,
17 MiniChannelItem, MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, Status, Task,
18 Tasks, WatchHistory,
1819 },
1920 },
2021};
@@ -180,6 +181,12 @@ impl FrameworkItem for ItemList {
180181 .into_iter()
181182 .map(|item| Item::from_search_item(item, image_index))
182183 .collect();
184 if !self.items.is_empty() {
185 self.items.push(Item::Page(true));
186 }
187 if search.page != 1 {
188 self.items.insert(0, Item::Page(false));
189 }
183190 }
184191 _ => unreachable!("item `ItemList` cannot be used in `{page:?}`"),
185192 }
@@ -236,27 +243,49 @@ impl FrameworkItem for ItemList {
236243 let page_to_load = match &self.items[self.textlist.selected] {
237244 Item::MiniVideo(MiniVideoItem { id, .. })
238245 | Item::FullVideo(FullVideoItem { id, .. }) => {
239 Page::SingleItem(SingleItemPage::Video(id.clone()))
246 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
240247 }
241248 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
242249 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
243 Page::SingleItem(SingleItemPage::Playlist(id.clone()))
250 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
244251 }
245 Item::MiniChannel(MiniChannelItem { id, .. }) => {
246 Page::ChannelDisplay(ChannelDisplayPage {
252 Item::MiniChannel(MiniChannelItem { id, .. })
253 | Item::FullChannel(FullChannelItem { id, .. }) => {
254 Some(Page::ChannelDisplay(ChannelDisplayPage {
247255 id: id.clone(),
248256 r#type: ChannelDisplayPageType::Main,
249 })
257 }))
250258 }
251 _ => panic!("wtf did you just selected"),
259 Item::Unknown(_) => {
260 *framework.data.global.get_mut::<Message>().unwrap() =
261 Message::Message(String::from("Unknown item"));
262 framework
263 .data
264 .state
265 .get_mut::<Tasks>()
266 .unwrap()
267 .priority
268 .push(Task::RenderAll);
269 None
270 }
271 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
272 Page::Search(search) => Some(Page::Search(Search {
273 page: if *b { search.page + 1 } else { search.page - 1 },
274 ..search.clone()
275 })),
276 _ => unreachable!("Page turners can only be used in search pages"),
277 },
252278 };
253 framework
254 .data
255 .state
256 .get_mut::<Tasks>()
257 .unwrap()
258 .priority
259 .push(Task::LoadPage(page_to_load));
279
280 if let Some(page_to_load) = page_to_load {
281 framework
282 .data
283 .state
284 .get_mut::<Tasks>()
285 .unwrap()
286 .priority
287 .push(Task::LoadPage(page_to_load));
288 }
260289 false
261290 }
262291 _ => false,
src/main.rs +5 −2
@@ -16,7 +16,6 @@ use youtube_tui::{exit, init, run};
1616fn main() -> Result<(), Box<dyn Error>> {
1717 let state = State(Vec::new());
1818 let mut framework = Framework::new(state);
19 init(&mut framework)?;
2019
2120 enable_raw_mode()?;
2221 let mut stdout = io::stdout();
@@ -24,7 +23,11 @@ fn main() -> Result<(), Box<dyn Error>> {
2423 let backend = CrosstermBackend::new(stdout);
2524 let mut terminal = Terminal::new(backend)?;
2625
27 let res = run(&mut terminal, &mut framework);
26 let res = (|| -> Result<(), Box<dyn Error>> {
27 init(&mut framework, &mut terminal)?;
28 run(&mut terminal, &mut framework)?;
29 Ok(())
30 })();
2831
2932 disable_raw_mode()?;
3033 execute!(
src/run.rs +1 −9
@@ -5,7 +5,7 @@ use tui_additions::framework::{Framework, FrameworkDirection};
55
66use crate::{
77 config::KeyBindingsConfig,
8 global::structs::{KeyAction, MainMenuPage, Message, Page, Status, Task, Tasks},
8 global::structs::{KeyAction, Message, Status, Task, Tasks},
99};
1010
1111/// the main event loop of the program
@@ -13,14 +13,6 @@ pub fn run(
1313 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
1414 framework: &mut Framework,
1515) -> Result<(), Box<dyn Error>> {
16 // push the initial page load
17 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
18 tasks
19 .priority
20 .push(Task::LoadPage(Page::MainMenu(MainMenuPage::Popular)));
21 tasks.pop().unwrap().run(framework, terminal)?;
22 framework.clear_history();
23
2416 loop {
2517 // repeat forever until all tasks are ran (and Tasks is cleared)
2618 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {