Commit d4894e125c

d4894e125c4642ec2a0f36a7e5fb0d0306049e0f

parent: 05e733814a

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-10-29 19:58 UTC

Item info, app generally usable

Layout: unified · split

Cargo.lock +77 −17
@@ -82,9 +82,9 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
8282
8383[[package]]
8484name = "cc"
85version = "1.0.73"
85version = "1.0.74"
8686source = "registry+https://github.com/rust-lang/crates.io-index"
87checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11"
87checksum = "581f5dba903aac52ea3feb5ec4810848460ee833876f1f9b0fdeab1f19091574"
8888
8989[[package]]
9090name = "cfg-if"
@@ -304,6 +304,43 @@ dependencies = [
304304 "cfg-if",
305305]
306306
307[[package]]
308name = "execute"
309version = "0.2.11"
310source = "registry+https://github.com/rust-lang/crates.io-index"
311checksum = "313431b1c5e3a6ec9b864333defee57d2ddb50de77abab419e4baedb6cdff292"
312dependencies = [
313 "execute-command-macro",
314 "execute-command-tokens",
315 "generic-array",
316]
317
318[[package]]
319name = "execute-command-macro"
320version = "0.1.8"
321source = "registry+https://github.com/rust-lang/crates.io-index"
322checksum = "a5fbc65a0cf735106743f4c38c9a3671c1e734b5c2c20d21a3c93c696daa3157"
323dependencies = [
324 "execute-command-macro-impl",
325]
326
327[[package]]
328name = "execute-command-macro-impl"
329version = "0.1.8"
330source = "registry+https://github.com/rust-lang/crates.io-index"
331checksum = "5109f6bc9cd57feda665da326f3f6c57e0498c8fe9f7d12d7b8abc96719ca91b"
332dependencies = [
333 "execute-command-tokens",
334 "quote",
335 "syn",
336]
337
338[[package]]
339name = "execute-command-tokens"
340version = "0.1.6"
341source = "registry+https://github.com/rust-lang/crates.io-index"
342checksum = "8ba569491c70ec8471e34aa7e9c0b9e82bb5d2464c0398442d17d3c4af814e5a"
343
307344[[package]]
308345name = "exr"
309346version = "1.5.2"
@@ -470,6 +507,16 @@ dependencies = [
470507 "slab",
471508]
472509
510[[package]]
511name = "generic-array"
512version = "0.14.6"
513source = "registry+https://github.com/rust-lang/crates.io-index"
514checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
515dependencies = [
516 "typenum",
517 "version_check",
518]
519
473520[[package]]
474521name = "getrandom"
475522version = "0.2.8"
@@ -495,9 +542,9 @@ dependencies = [
495542
496543[[package]]
497544name = "h2"
498version = "0.3.14"
545version = "0.3.15"
499546source = "registry+https://github.com/rust-lang/crates.io-index"
500checksum = "5ca32592cf21ac7ccab1825cd87f6c9b3d9022c44d086172ed0966bec8af30be"
547checksum = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4"
501548dependencies = [
502549 "bytes",
503550 "fnv",
@@ -618,9 +665,9 @@ dependencies = [
618665
619666[[package]]
620667name = "iana-time-zone"
621version = "0.1.51"
668version = "0.1.53"
622669source = "registry+https://github.com/rust-lang/crates.io-index"
623checksum = "f5a6ef98976b22b3b7f2f3a806f858cb862044cfa66805aa3ad84cb3d3b785ed"
670checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765"
624671dependencies = [
625672 "android_system_properties",
626673 "core-foundation-sys",
@@ -743,9 +790,9 @@ checksum = "03087c2bad5e1034e8cace5926dec053fb3790248370865f5117a7d0213354c8"
743790
744791[[package]]
745792name = "libc"
746version = "0.2.135"
793version = "0.2.137"
747794source = "registry+https://github.com/rust-lang/crates.io-index"
748checksum = "68783febc7782c6c5cb401fbda4de5a9898be1762314da0bb2c10ced61f18b0c"
795checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89"
749796
750797[[package]]
751798name = "link-cplusplus"
@@ -822,14 +869,14 @@ dependencies = [
822869
823870[[package]]
824871name = "mio"
825version = "0.8.4"
872version = "0.8.5"
826873source = "registry+https://github.com/rust-lang/crates.io-index"
827checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf"
874checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"
828875dependencies = [
829876 "libc",
830877 "log",
831878 "wasi",
832 "windows-sys 0.36.1",
879 "windows-sys 0.42.0",
833880]
834881
835882[[package]]
@@ -901,9 +948,9 @@ dependencies = [
901948
902949[[package]]
903950name = "once_cell"
904version = "1.15.0"
951version = "1.16.0"
905952source = "registry+https://github.com/rust-lang/crates.io-index"
906checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1"
953checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860"
907954
908955[[package]]
909956name = "openssl"
@@ -1013,9 +1060,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
10131060
10141061[[package]]
10151062name = "pkg-config"
1016version = "0.3.25"
1063version = "0.3.26"
10171064source = "registry+https://github.com/rust-lang/crates.io-index"
1018checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae"
1065checksum = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"
10191066
10201067[[package]]
10211068name = "png"
@@ -1385,9 +1432,9 @@ dependencies = [
13851432
13861433[[package]]
13871434name = "tiff"
1388version = "0.7.3"
1435version = "0.7.4"
13891436source = "registry+https://github.com/rust-lang/crates.io-index"
1390checksum = "7259662e32d1e219321eb309d5f9d898b779769d81b76e762c07c8e5d38fcb65"
1437checksum = "9f71e422515e83e3ab8a03d4781d05ebf864fc61f4546e6ecffa58cbd34181a0"
13911438dependencies = [
13921439 "flate2",
13931440 "jpeg-decoder",
@@ -1524,6 +1571,12 @@ dependencies = [
15241571 "unsafe-any",
15251572]
15261573
1574[[package]]
1575name = "typenum"
1576version = "1.15.0"
1577source = "registry+https://github.com/rust-lang/crates.io-index"
1578checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
1579
15271580[[package]]
15281581name = "unicode-bidi"
15291582version = "0.3.8"
@@ -1589,6 +1642,12 @@ version = "0.2.15"
15891642source = "registry+https://github.com/rust-lang/crates.io-index"
15901643checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
15911644
1645[[package]]
1646name = "version_check"
1647version = "0.9.4"
1648source = "registry+https://github.com/rust-lang/crates.io-index"
1649checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
1650
15921651[[package]]
15931652name = "viuer"
15941653version = "0.6.2"
@@ -1851,6 +1910,7 @@ dependencies = [
18511910 "chrono",
18521911 "crossterm",
18531912 "dyn-clone",
1913 "execute",
18541914 "futures",
18551915 "home",
18561916 "invidious",
Cargo.toml +1
@@ -28,6 +28,7 @@ tokio = "1.21"
2828futures = "0.3"
2929reqwest = "0.11"
3030serde_json = "1.0"
31execute = "0.2"
3132
3233# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
3334# invidious = {path = "../../Rust/Packages/invidious", default-features = false, features = ["reqwest"]}
README.md +9 −61
@@ -10,49 +10,20 @@ An aesthetically pleasing YouTube TUI written in Rust.
1010
1111> ## Warning
1212>
13> The current code on GitHub is a rewritten-from-scratch version of the old code, it is not functional yet. Therefore if you would like to try the TUI out, please install it from `crates.io` (seen Installation).
14>
15> ### Changes
16>
17> #### Framework
18> Now uses the TUI framework from `tui-additions` which I wrote specifically for this project. The main benefits of this are that all "items" are no longer related to each other, so changing one of them won't break the others. This modular framework also make fixing bugs in existing items and adding new ones much easier (which is the main reason that I decided to rewrite the entire thing from scratch).
19>
20> The main drawbacks of using a framework is there are limitations of what I can do (the old code does excatly what I wanted it to, but it's a hella mess), and the performance may take a hit (just slightly, TUIs written in Rust are still ***blazingly fast!!!***).
21>
22> #### Config files readability
23>
24> The old config files uses the YAML format, which is usually very easy to read, but when it comes to `tuples` and custom `struct` representation it actually look pure gibberish.
25>
26> The new config files are also in YAML, but I prevented tuples from appearing in them by removing stuff nobody is gonna change anyways and options that are gonna break the entire thing anyways, so that even a 6 year old Roblox player would have the ability to read and modify their config.
27>
28> No docs on the config until I finish the whole thing, so if you want to figure out stuff go read the code yourself it's not that bad now.
29>
30> #### Sixels!
31>
32> You can now display PNGs in terminal yay! Terrible performance, but running with `--release` flag improves a bit.
33>
34> #### Code readability
35>
36> The code is now more idiomatic and i put comments so yeah go read it and i will memorize the arch wiki
37>
38> ### Progress
39>
40> #### Done
41>
42> - Config files
43> - Home and search page
44> - Search fully functional
45>
46> #### To do before release
47>
48> - Item info (WIP), channels page
13> The current code on GitHub is a rewritten-from-scratch version of the old code, it is currently *somewhat* usable. All the config files are undocumented and you'll need to *read the code* or wait for the documentation to come out after the code is done.
14>
15> The default config files are in the `example config files/` folder, go ahead and appreciate :D
16>
17> ### Todo before release:
4918> - Watch history
50> - Basically back to where it is before the rewrite
19> - Channel page
20>
21> The previous release on `crates.io` is unaffected, and it should be used instead.
22
5123
5224## Overview
5325YouTube TUI is a text user interface that provides a clean TUI for browsing YouTube. It can perform YouTube query searches, view and inspect channels, and play the desired content as a regular video or audio-only stream for saving bandwidth.
5426
55
5627![Screenshot](https://cdn.discordapp.com/attachments/906941311142219816/990684947830419526/Screenshot_20220626_192433.png)
5728
5829## User manual
@@ -67,22 +38,6 @@ YouTube TUI is a text user interface that provides a clean TUI for browsing YouT
6738cargo install youtube-tui
6839```
6940
70### Clone from GitHub and build
71```bash
72git clone https://github.com/sirusmart/youtube-tui && cd youtube-tui && cargo build --release
73```
74Once build, the compiled binary will be located at `./target/release/youtube-tui`. The program is not in your path yet, so you'll have to manually move to to a place from which you would be able to execute it. A common way to do so is to copy the binary executable to `/usr/local/bin/youtube-tui`.
75
76> ### Dependencies
77>
78> This program does not requires any dependencies, but it is suggested these three things on your system that can be launched via command:
79>
80> 1. A video player (Defaults to `mpv`)
81> 2. A terminal emulator (Defaults to `konsole`)
82> 3. A YouTube downloader (Defaults to `yt-dlp`, strongly suggest NOT to use `youtube-dl` because it is now very slow)
83>
84> None of these dependencies are required as you can change them in config (in `commands.yml`)
85
8641## Usage
8742
8843* A video player (Defaults to `MPV`)
@@ -128,13 +83,6 @@ Here's the [opened issue](https://github.com/iv-org/invidious/issues/3154)
12883* Channel search and channel video sort
12984* Recommended videos
13085
131## Help needed
132
133Guys please I need help I'm kinda bad at coding tbh, so these are stuff that I need help with
134
135* Publishing to the AUR
136* Printing full resolution images to the terminal with Sixel
137
13886## Credits
13987
14088* [ytfzf](https://github.com/pystardust/ytfzf) by [pystardust](https://github.com/pystardust) - The TUI I used to watch on YouTube, gave me an idea of how this program is going to work
example config files/appearance.yml added +37
@@ -0,0 +1,37 @@
1borders: Rounded
2colors:
3 text: Reset
4 text_special: Reset
5 text_secondary: Reset
6 text_error: LightRed
7 outline: Reset
8 outline_selected: LightBlue
9 outline_hover: LightRed
10 outline_secondary: LightYellow
11 message_outline: !Rgb
12 - 255
13 - 127
14 - 0
15 message_error_outline: LightRed
16 message_success_outline: LightGreen
17 item_info:
18 tag: Gray
19 title: LightBlue
20 description: Gray
21 author: LightGreen
22 viewcount: LightYellow
23 length: LightCyan
24 published: LightMagenta
25 video_count: !Rgb
26 - 131
27 - 141
28 - 255
29 sub_count: LightYellow
30 likes: !Rgb
31 - 200
32 - 255
33 - 129
34 genre: !Rgb
35 - 255
36 - 121
37 - 215
example config files/commands.yml added +18
@@ -0,0 +1,18 @@
1video:
2- Play video: ${video-player} ${embed-url}
3- Play audio: ${terminal-emulator} ${video-player} ${embed-url} --no-video
4- Play audio (loop): ${terminal-emulator} ${video-player} ${embed-url} --no-video --loop-file=inf
5- Open in browser: ${browser} ${url}
6- Download video (webm): ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${embed-url}
7- Download audio (opus): ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${embed-url} -x
8- 'Mode: ${provider}': '%switch-provider%'
9playlist:
10- Switch view: '%switch-view%'
11- Play all videos: ${video-player} ${all-videos}
12- Play all audio: ${terminal-emulator} ${video-player} ${all-videos} --no-video
13- Shuffle play all audio: ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle
14- Shuffle play all audio (loop): ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf
15- Open in browser: ${browser} ${url}
16- Download all video (webm): ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos}
17- Download all audio (opus): ${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos} -x
18- 'Mode: ${provider}': '%switch-provider%'
example config files/keybindings.yml added +26
@@ -0,0 +1,26 @@
1!Char 'r':
2 2: Reload
3Right:
4 0: MoveRight
5Down:
6 0: MoveDown
7!Char 'h':
8 0: MoveLeft
9Enter:
10 0: Select
11!Char 'l':
12 0: MoveRight
13Backspace:
14 0: Back
15!Char 'j':
16 0: MoveDown
17!Char 'k':
18 0: MoveUp
19Left:
20 0: MoveLeft
21Esc:
22 0: Deselect
23Up:
24 0: MoveUp
25!Char 'q':
26 0: Exit
example config files/main.yml added +14
@@ -0,0 +1,14 @@
1invidious_instance: https://vid.puffyan.us
2piped_instance: https://piped.garudalinux.org
3allow_unicode: false
4message_bar_default: All good :)
5images: HalfBlocks
6refresh_after_modifying_search_filters: true
7image_index: 4
8provider: YouTube
9env:
10 terminal-emulator: konsole -e
11 youtube-downloader: yt-dlp
12 browser: firefox
13 download-path: '''~/Downloads/%(title)s-%(id)s.%(ext)s'''
14 video-player: mpv
example config files/pages.yml added +33
@@ -0,0 +1,33 @@
1main_menu:
2 layout:
3 - !NonCenteredRow
4 - SearchBar
5 - SearchFilters
6 - !CenteredRow
7 - Trending
8 - Popular
9 - !NonCenteredRow
10 - ItemList
11 - !NonCenteredRow
12 - MessageBar
13 message: Loading main menu...
14search:
15 layout:
16 - !NonCenteredRow
17 - SearchBar
18 - SearchFilters
19 - !NonCenteredRow
20 - ItemList
21 - !NonCenteredRow
22 - MessageBar
23 message: Loading search results...
24singleitem:
25 layout:
26 - !NonCenteredRow
27 - SearchBar
28 - SearchFilters
29 - !NonCenteredRow
30 - SingleItemInfo
31 - !NonCenteredRow
32 - MessageBar
33 message: Loading item details...
example config files/search.yml added +6
@@ -0,0 +1,6 @@
1query: ''
2filters:
3 sort: Relevance
4 date: None
5 duration: None
6 type: All
src/config/commands.rs +82 −11
@@ -7,8 +7,8 @@ use crate::global::traits::ConfigTrait;
77
88#[derive(Clone)]
99pub struct CommandsConfig {
10 pub video: HashMap<String, String>,
11 pub playlist: HashMap<String, String>,
10 pub video: Vec<(String, String)>,
11 pub playlist: Vec<(String, String)>,
1212}
1313
1414impl Key for CommandsConfig {
@@ -18,12 +18,21 @@ impl Key for CommandsConfig {
1818impl From<CommandsConfigSerde> for CommandsConfig {
1919 fn from(original: CommandsConfigSerde) -> Self {
2020 Self {
21 video: HashMap::from_iter(original.video.into_iter().map(|item| item.into_iter().last().unwrap())),
22 playlist: HashMap::from_iter(original.playlist.into_iter().map(|item| item.into_iter().last().unwrap())),
21 video: original
22 .video
23 .into_iter()
24 .map(|hashmap| hashmap.into_iter().last().unwrap())
25 .collect(),
26 playlist: original
27 .playlist
28 .into_iter()
29 .map(|hashmap| hashmap.into_iter().last().unwrap())
30 .collect(),
2331 }
2432 }
2533}
2634
35// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look
2736#[derive(Serialize, Deserialize, Clone)]
2837pub struct CommandsConfigSerde {
2938 #[serde(default = "video_default")]
@@ -45,20 +54,82 @@ impl Default for CommandsConfigSerde {
4554 }
4655}
4756
57// `${label}` will be replaced by the values set in `main.yml` in `env`
58// Different pages may contain different `env`s (for example `url` is different in each page)
59
4860fn video_default() -> Vec<HashMap<String, String>> {
49 vec![HashMap::from(
50 [(
51 String::from("Play video"),
52 String::from("${video-player} ${embed-url}"),
53 )])]
61 vec![
62 HashMap::from([(
63 String::from("Play video"),
64 String::from("${video-player} ${embed-url}"),
65 )]),
66 HashMap::from([(
67 String::from("Play audio"),
68 String::from("${terminal-emulator} ${video-player} ${embed-url} --no-video"),
69 )]),
70 HashMap::from([(
71 String::from("Play audio (loop)"),
72 String::from(
73 "${terminal-emulator} ${video-player} ${embed-url} --no-video --loop-file=inf",
74 ),
75 )]),
76 HashMap::from([(
77 String::from("Open in browser"),
78 String::from("${browser} ${url}"),
79 )]),
80 HashMap::from([(
81 String::from("Download video (webm)"),
82 String::from(
83 "${terminal-emulator} ${youtube-downloader} -o ${download-path} ${embed-url}",
84 ),
85 )]),
86 HashMap::from([(
87 String::from("Download audio (opus)"),
88 String::from(
89 "${terminal-emulator} ${youtube-downloader} -o ${download-path} ${embed-url} -x",
90 ),
91 )]),
92 HashMap::from([(
93 String::from("Mode: ${provider}"),
94 String::from("%switch-provider%"),
95 )]),
96 ]
5497}
5598
5699fn playlist_default() -> Vec<HashMap<String, String>> {
57100 vec![
58101 HashMap::from([(String::from("Switch view"), String::from("%switch-view%"))]),
59102 HashMap::from([(
60 String::from("Play entire playlist"),
61 String::from("${video-player} ${embed-url}"),
103 String::from("Play all videos"),
104 String::from("${video-player} ${all-videos}"),
105 )]),
106 HashMap::from([(
107 String::from("Play all audio"),
108 String::from("${terminal-emulator} ${video-player} ${all-videos} --no-video"),
109 )]),
110 HashMap::from([(
111 String::from("Shuffle play all audio"),
112 String::from("${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle"),
113 )]),
114 HashMap::from([(
115 String::from("Shuffle play all audio (loop)"),
116 String::from("${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"),
117 )]),
118 HashMap::from([(
119 String::from("Open in browser"),
120 String::from("${browser} ${url}"),
121 )]),
122 HashMap::from([(
123 String::from("Download all video (webm)"),
124 String::from("${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos}")
125 )]),
126 HashMap::from([(
127 String::from("Download all audio (opus)"),
128 String::from("${terminal-emulator} ${youtube-downloader} -o ${download-path} ${all-videos} -x")
129 )]),
130 HashMap::from([(
131 String::from("Mode: ${provider}"),
132 String::from("%switch-provider%"),
62133 )]),
63134 ]
64135}
src/config/main.rs +56 −3
@@ -8,6 +8,8 @@ use typemap::Key;
88pub struct MainConfig {
99 #[serde(default = "invidious_instance_default")]
1010 pub invidious_instance: String,
11 #[serde(default = "piped_instance_default")]
12 pub piped_instance: String,
1113 #[serde(default = "allow_unicode_default")]
1214 pub allow_unicode: bool,
1315 #[serde(default = "message_bar_default_default")]
@@ -21,7 +23,9 @@ pub struct MainConfig {
2123 // 0 is usually `maxres` and 3 (default) is good enough for normal uses without having huge files sizes
2224 // Check `https://{any invidious instance}/api/v1/videos/{any valid video id}` property videoThumbnails in Firefox dev tools to see it for yourself
2325 pub image_index: usize,
24 #[serde(default)]
26 #[serde(default = "provider_default")]
27 pub provider: Provider,
28 #[serde(default = "default_env")]
2529 pub env: HashMap<String, String>,
2630}
2731
@@ -33,14 +37,16 @@ impl Default for MainConfig {
3337 fn default() -> Self {
3438 Self {
3539 invidious_instance: invidious_instance_default(),
40 piped_instance: piped_instance_default(),
3641 allow_unicode: allow_unicode_default(),
3742 message_bar_default: message_bar_default_default(),
3843 images: images_default(),
3944 image_index: image_index_default(),
4045 refresh_after_modifying_search_filters: refresh_after_modifying_search_filters_default(
4146 ),
47 provider: provider_default(),
4248
43 env: HashMap::default(),
49 env: default_env(),
4450 }
4551 }
4652}
@@ -66,10 +72,37 @@ impl Images {
6672 }
6773}
6874
75#[derive(Clone, Copy, Serialize, Deserialize, PartialEq)]
76pub enum Provider {
77 YouTube,
78 Invidious,
79 // Piped,
80}
81
82impl Provider {
83 pub fn as_str(&self) -> &str {
84 match self {
85 Self::YouTube => "YouTube",
86 Self::Invidious => "Invidious",
87 }
88 }
89
90 pub fn rotate(&mut self) {
91 *self = match self {
92 Self::YouTube => Self::Invidious,
93 Self::Invidious => Self::YouTube,
94 };
95 }
96}
97
6998// default functions
7099
71100fn invidious_instance_default() -> String {
72 String::from("https://invidious.sethforprivacy.com")
101 String::from("https://vid.puffyan.us")
102}
103
104fn piped_instance_default() -> String {
105 String::from("https://piped.garudalinux.org")
73106}
74107
75108fn message_bar_default_default() -> String {
@@ -91,3 +124,23 @@ const fn allow_unicode_default() -> bool {
91124const fn refresh_after_modifying_search_filters_default() -> bool {
92125 true
93126}
127
128const fn provider_default() -> Provider {
129 Provider::YouTube
130}
131
132fn default_env() -> HashMap<String, String> {
133 HashMap::from([
134 (String::from("video-player"), String::from("mpv")),
135 (String::from("browser"), String::from("firefox")),
136 (
137 String::from("terminal-emulator"),
138 String::from("konsole -e"),
139 ),
140 (String::from("youtube-downloader"), String::from("yt-dlp")),
141 (
142 String::from("download-path"),
143 String::from("'~/Downloads/%(title)s-%(id)s.%(ext)s'"),
144 ),
145 ])
146}
src/global/structs/item.rs +37
@@ -98,6 +98,43 @@ impl Display for Item {
9898 }
9999}
100100
101impl Item {
102 pub fn fullvideo(&self) -> &FullVideoItem {
103 match self {
104 Self::FullVideo(fullvideo) => fullvideo,
105 _ => panic!("not a fullvideo"),
106 }
107 }
108
109 pub fn minivideo(&self) -> &MiniVideoItem {
110 match self {
111 Self::MiniVideo(minivideo) => minivideo,
112 _ => panic!("not a minivideo"),
113 }
114 }
115
116 pub fn miniplaylist(&self) -> &MiniPlaylistItem {
117 match self {
118 Self::MiniPlaylist(miniplaylist) => miniplaylist,
119 _ => panic!("not a miniplaylist"),
120 }
121 }
122
123 pub fn fullplaylist(&self) -> &FullPlaylistItem {
124 match self {
125 Self::FullPlaylist(fullplaylist) => fullplaylist,
126 _ => panic!("not a fullplaylist"),
127 }
128 }
129
130 pub fn minichannel(&self) -> &MiniChannelItem {
131 match self {
132 Self::MiniChannel(minichannel) => minichannel,
133 _ => panic!("not a minichannel"),
134 }
135 }
136}
137
101138impl Item {
102139 // the file save path for thumbnails (which is by their id)
103140 pub fn thumbnail_id(&self) -> &str {
src/global/structs/tasks.rs +25 −25
@@ -74,31 +74,6 @@ impl TaskQueue {
7474 terminal.clear()?;
7575 }
7676
77 match self.render {
78 RenderTask::All => {
79 Self::render(framework, terminal)?;
80 }
81 RenderTask::Only(_locations) => {
82 // need to file an issue to tui-rs suggesting this as a feature
83 unimplemented!("tui-rs does not support partial re-rendering");
84 }
85 RenderTask::None => {}
86 }
87
88 if self.reload {
89 // reload simply runs `.load()` on all items
90 *framework.data.global.get_mut::<Message>().unwrap() =
91 Message::Message(String::from("Reloading page..."));
92 Self::render_force_clear(framework, terminal)?;
93 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
94 {
95 Message::Error(format!("{}", e))
96 } else {
97 Message::None
98 };
99 Self::render(framework, terminal)?;
100 }
101
10277 // save state in history, then replace all items by whats in the new page and run `.load()` on them
10378 if let Some(page) = self.load_page {
10479 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -126,6 +101,31 @@ impl TaskQueue {
126101 Self::render(framework, terminal)?;
127102 }
128103
104 if self.reload {
105 // reload simply runs `.load()` on all items
106 *framework.data.global.get_mut::<Message>().unwrap() =
107 Message::Message(String::from("Reloading page..."));
108 Self::render_force_clear(framework, terminal)?;
109 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
110 {
111 Message::Error(format!("{}", e))
112 } else {
113 Message::None
114 };
115 Self::render(framework, terminal)?;
116 }
117
118 match self.render {
119 RenderTask::All => {
120 Self::render(framework, terminal)?;
121 }
122 RenderTask::Only(_locations) => {
123 // need to file an issue to tui-rs suggesting this as a feature
124 unimplemented!("tui-rs does not support partial re-rendering");
125 }
126 RenderTask::None => {}
127 }
128
129129 Ok(())
130130 }
131131
src/init.rs +2 −2
@@ -1,7 +1,7 @@
11use crate::{
22 config::{
3 AppearanceConfig, AppearanceConfigSerde, CommandsConfig, KeyBindingsConfig, MainConfig,
4 MinDimentions, PagesConfig, Search, CommandsConfigSerde,
3 AppearanceConfig, AppearanceConfigSerde, CommandsConfig, CommandsConfigSerde,
4 KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
55 },
66 global::{
77 structs::{InvidiousClient, Message, Page, Status, Tasks},
src/items/iteminfo.rs +8 −6
@@ -49,6 +49,8 @@ impl FrameworkItem for ItemInfo {
4949 .join(item.thumbnail_id());
5050 if thumbnail_path.exists() {
5151 let config = Config {
52 // channel thumbnails are squares, limiting their maximum width can prevent the
53 // entire page being taken up by the image
5254 width: Some(if let Item::MiniChannel(_) = item {
5355 area.width / 2
5456 } else {
@@ -85,7 +87,7 @@ impl FrameworkItem for ItemInfo {
8587 minivideo.title.to_owned(),
8688 Style::default().fg(appearance.colors.item_info.title),
8789 ),
88 ],
90 ],
8991 minivideo.description.as_ref().map(|description| {
9092 (
9193 description.to_owned(),
@@ -104,9 +106,9 @@ impl FrameworkItem for ItemInfo {
104106 Style::default().fg(appearance.colors.item_info.length),
105107 ));
106108 out.0.push((
107 format!("Uploaded by {}", minivideo.channel),
108 Style::default().fg(appearance.colors.item_info.author),
109 ));
109 format!("Uploaded by {}", minivideo.channel),
110 Style::default().fg(appearance.colors.item_info.author),
111 ));
110112 if let Some(published) = &minivideo.published {
111113 out.0.push((
112114 format!("Published {}", published),
@@ -264,10 +266,10 @@ impl FrameworkItem for ItemInfo {
264266 ),
265267 };
266268
267 // puts each "span" in its own line
268269 let mut y = if scroll >= area.height { 0 } else { scroll } + area.y;
269270 let bottom = area.bottom();
270271
272 // puts each "span" in its own line
271273 for (text, style) in spans.into_iter().take((bottom - y) as usize) {
272274 let paragraph = Paragraph::new(text).style(style);
273275 frame.render_widget(
@@ -285,7 +287,7 @@ impl FrameworkItem for ItemInfo {
285287 return;
286288 }
287289
288 // renders the "text"
290 // displays description only if its a non empty string
289291 let (text, style) = text.unwrap();
290292 if text.is_empty() {
291293 return;
src/items/itemlist.rs +14 −7
@@ -12,7 +12,8 @@ use crate::{
1212 global::{
1313 functions::download_all_images,
1414 structs::{
15 InvidiousClient, Item, KeyAction, MainMenuPage, Page, SingleItemPage, Task, Tasks,
15 FullPlaylistItem, FullVideoItem, InvidiousClient, Item, KeyAction, MainMenuPage,
16 MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, Task, Tasks,
1617 },
1718 },
1819};
@@ -28,6 +29,7 @@ pub struct ItemList {
2829}
2930
3031impl ItemList {
32 /// updates the styles of different things that may be updated by deselect/selects
3133 fn update_appearance(
3234 &mut self,
3335 appearance: &AppearanceConfig,
@@ -127,6 +129,8 @@ impl FrameworkItem for ItemList {
127129 framework: &mut tui_additions::framework::FrameworkClean,
128130 _info: tui_additions::framework::ItemInfo,
129131 ) -> Result<(), Box<dyn Error>> {
132 *self = Self::default();
133
130134 let page = framework.data.state.get::<Page>().unwrap();
131135 let image_index = framework
132136 .data
@@ -215,13 +219,16 @@ impl FrameworkItem for ItemList {
215219 KeyAction::MoveRight => self.textlist.last().is_ok(),
216220 KeyAction::Select => {
217221 let page_to_load = match &self.items[self.textlist.selected] {
218 Item::MiniVideo(video) => {
219 Page::SingleItem(SingleItemPage::Video(video.id.clone()))
222 Item::MiniVideo(MiniVideoItem { id, .. })
223 | Item::FullVideo(FullVideoItem { id, .. }) => {
224 Page::SingleItem(SingleItemPage::Video(id.clone()))
220225 }
221 Item::MiniPlaylist(playlist) => {
222 Page::SingleItem(SingleItemPage::Playlist(playlist.id.clone()))
226 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
227 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
228 Page::SingleItem(SingleItemPage::Playlist(id.clone()))
223229 }
224 _ => unimplemented!(),
230 Item::MiniChannel(_) => unimplemented!(),
231 _ => panic!("wtf did you just selected"),
225232 };
226233 framework
227234 .data
@@ -243,7 +250,7 @@ impl FrameworkItem for ItemList {
243250 .state
244251 .get_mut::<Tasks>()
245252 .unwrap()
246 .last
253 .priority
247254 .push(Task::RenderAll);
248255 }
249256
src/items/messagebar.rs +1
@@ -28,6 +28,7 @@ impl FrameworkItem for MessageBar {
2828 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
2929 let message = framework.data.global.get::<Message>().unwrap();
3030
31 // display with different border style according to type of message and config
3132 let block = Block::default()
3233 .borders(Borders::ALL)
3334 .border_type(appearance.borders)
src/items/searchbar.rs +15 −2
@@ -2,7 +2,7 @@ use std::error::Error;
22
33use crate::{
44 config::{AppearanceConfig, Search},
5 global::structs::{Page, Task, Tasks},
5 global::structs::{Message, Page, Task, Tasks},
66};
77use crossterm::event::KeyCode;
88use tui::{
@@ -18,7 +18,7 @@ pub struct SearchBar {
1818}
1919
2020impl FrameworkItem for SearchBar {
21 // basically is a text field with borders
21 // basically is a TextField with borders
2222 fn render(
2323 &mut self,
2424 frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
@@ -83,6 +83,19 @@ impl FrameworkItem for SearchBar {
8383 KeyCode::Right => self.text_field.right().is_ok(),
8484 KeyCode::Left => self.text_field.left().is_ok(),
8585 KeyCode::Enter => {
86 if self.text_field.content.is_empty() {
87 *framework.data.global.get_mut::<Message>().unwrap() =
88 Message::Message(String::from("Search string must not be empty"));
89 framework
90 .data
91 .state
92 .get_mut::<Tasks>()
93 .unwrap()
94 .priority
95 .push(Task::RenderAll);
96 return Ok(());
97 }
98
8699 let mut search = framework.data.state.get_mut::<Search>().unwrap();
87100 search.query = self.text_field.content.clone();
88101 let search = search.clone();
src/items/singleitem.rs +549 −64
@@ -1,14 +1,17 @@
1use std::collections::HashMap;
1use super::ItemInfo;
2use crate::{
3 config::{AppearanceConfig, CommandsConfig, KeyBindingsConfig, MainConfig, Provider},
4 global::{
5 functions::download_all_images,
6 structs::{InvidiousClient, Item, KeyAction, Message, Page, SingleItemPage, Task, Tasks},
7 },
8};
9use std::{collections::HashMap, thread};
210use tui::{layout::Constraint, style::Style};
311use tui_additions::{
412 framework::FrameworkItem,
513 widgets::{Grid, TextList},
614};
7use super::ItemInfo;
8use crate::{
9 config::{AppearanceConfig, MainConfig, CommandsConfig},
10 global::{structs::{InvidiousClient, Item, Message, Page, SingleItemPage}, functions::download_all_images}
11};
1215
1316impl Default for SingleItem {
1417 fn default() -> Self {
@@ -34,37 +37,65 @@ pub struct SingleItem {
3437 pub r#type: SingleItemType,
3538}
3639
40/// variations that the struct can hold
3741#[derive(Clone)]
3842pub enum SingleItemType {
3943 None,
4044 Video(SingleVideoItem),
41 Playlist(SinglePlaylistItem),
45 Playlist(Box<SinglePlaylistItem>),
4246}
4347
4448#[derive(Clone)]
4549pub struct SingleVideoItem {
4650 pub textlist: TextList,
47 pub commands: HashMap<String, String>,
51 pub commands: Vec<(String, String)>,
52 pub provider: Provider,
4853}
4954
5055#[derive(Clone)]
5156pub struct SinglePlaylistItem {
5257 pub commands_view: TextList,
5358 pub videos_view: TextList,
54 pub commands: HashMap<String, String>,
59 pub commands: Vec<(String, String)>,
5560 pub is_commands_view: bool,
5661 pub hovered_video: ItemInfo,
62 pub provider: Provider,
5763}
5864
5965impl SingleVideoItem {
60 pub fn new(commands: &CommandsConfig) -> Self {
66 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig) -> Self {
6167 Self {
62 textlist: TextList::default().items(&commands.video.keys().collect()).unwrap(),
63 commands: commands.video.clone(),
68 textlist: TextList::default()
69 .items(&commands.video.iter().map(|command| &command.0).collect())
70 .unwrap(),
71 commands: commands
72 .video
73 .clone()
74 .into_iter()
75 .map(|(display, command)| (display, command))
76 .collect(),
77 provider: mainconfig.provider,
6478 }
6579 }
6680
67 pub fn update_appearance(&mut self, appearance: &AppearanceConfig, iteminfo: &tui_additions::framework::ItemInfo) {
81 /// updates the %switch-provider% command in the list
82 pub fn update_provider(&mut self) {
83 self.commands
84 .iter()
85 .enumerate()
86 .for_each(|(index, (display, command))| {
87 if command.as_str() == "%switch-provider%" {
88 self.textlist.items[index] =
89 display.replace("${provider}", self.provider.as_str());
90 }
91 })
92 }
93
94 pub fn update_appearance(
95 &mut self,
96 appearance: &AppearanceConfig,
97 iteminfo: &tui_additions::framework::ItemInfo,
98 ) {
6899 self.textlist.set_border_type(appearance.borders);
69100 self.textlist
70101 .set_style(Style::default().fg(appearance.colors.text));
@@ -81,30 +112,104 @@ impl SingleVideoItem {
81112 .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
82113 }
83114 }
115
116 /// creates a hashmap from `self`, containing info of the current item
117 pub fn inflate_map(&self, mainconfig: &MainConfig, item: &Item) -> HashMap<String, String> {
118 let video_item = item.fullvideo();
119
120 HashMap::from([
121 (
122 String::from("url"),
123 match self.provider {
124 Provider::Invidious => format!(
125 "'{}/watch?v={}'",
126 mainconfig.invidious_instance, video_item.id
127 ),
128 Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id),
129 // Provider::Piped => {
130 // format!("'{}/watch?v={}'", mainconfig.piped_instance, video_item.id)
131 // }
132 },
133 ),
134 (
135 String::from("embed-url"),
136 match self.provider {
137 Provider::Invidious => format!(
138 "'{}/embed/{}'",
139 mainconfig.invidious_instance, video_item.id
140 ),
141 Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id),
142 // Provider::Piped => {
143 // format!("'{}/embed/{}'", mainconfig.piped_instance, video_item.id)
144 // }
145 },
146 ),
147 ])
148 }
149
150 /// add "env variables" from `self.inflate_map` to an existing hashmap
151 pub fn inflate(
152 &self,
153 mut env: HashMap<String, String>,
154 mainconfig: &MainConfig,
155 item: &Item,
156 ) -> HashMap<String, String> {
157 env.extend(self.inflate_map(mainconfig, item));
158 env
159 }
84160}
85161
86162impl SinglePlaylistItem {
87 pub fn new(commands: &CommandsConfig, playlist_items: &Vec<Item>) -> Self {
88 let mut hovered_video = ItemInfo::default();
89 hovered_video.item = if playlist_items.is_empty() {
90 None
91 } else {
92 Some(playlist_items[0].clone())
163 pub fn new(
164 commands: &CommandsConfig,
165 mainconfig: &MainConfig,
166 playlist_items: &[Item],
167 ) -> Self {
168 let hovered_video = ItemInfo {
169 item: if playlist_items.is_empty() {
170 None
171 } else {
172 Some(playlist_items[0].clone())
173 },
93174 };
94175 Self {
95 commands_view: TextList::default().items(&commands.playlist.keys().collect()).unwrap(),
96 videos_view: TextList::default().items(&playlist_items).unwrap(),
97 commands: commands.playlist.clone(),
176 commands_view: TextList::default()
177 .items(&commands.playlist.iter().map(|command| &command.0).collect())
178 .unwrap(),
179 videos_view: TextList::default()
180 .items(&{
181 let mut items = vec!["Switch view"];
182 items.extend(
183 playlist_items
184 .iter()
185 .map(|item| item.minivideo().title.as_str()),
186 );
187 items
188 })
189 .unwrap(),
190 commands: commands
191 .playlist
192 .clone()
193 .into_iter()
194 .map(|(display, command)| (display, command))
195 .collect(),
98196 hovered_video,
99197 is_commands_view: true,
198 provider: mainconfig.provider,
100199 }
101200 }
102201
103 pub fn update_appearance(&mut self, appearance: &AppearanceConfig, iteminfo: &tui_additions::framework::ItemInfo, grid: &mut Grid) {
202 pub fn update_appearance(
203 &mut self,
204 appearance: &AppearanceConfig,
205 iteminfo: &tui_additions::framework::ItemInfo,
206 grid: &mut Grid,
207 ) {
104208 if self.is_commands_view {
105209 grid.widths = vec![Constraint::Percentage(30), Constraint::Percentage(70)];
106210 self.commands_view.set_border_type(appearance.borders);
107 self.commands_view.set_style(Style::default().fg(appearance.colors.text));
211 self.commands_view
212 .set_style(Style::default().fg(appearance.colors.text));
108213
109214 if iteminfo.selected {
110215 self.commands_view
@@ -118,9 +223,18 @@ impl SinglePlaylistItem {
118223 .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
119224 }
120225 } else {
121 grid.widths = vec![Constraint::Percentage(30), Constraint::Percentage(40), Constraint::Percentage(30)];
226 grid.widths = if self.videos_view.selected == 0 {
227 vec![Constraint::Percentage(30), Constraint::Percentage(70)]
228 } else {
229 vec![
230 Constraint::Percentage(30),
231 Constraint::Percentage(40),
232 Constraint::Percentage(30),
233 ]
234 };
122235 self.videos_view.set_border_type(appearance.borders);
123 self.videos_view.set_style(Style::default().fg(appearance.colors.text));
236 self.videos_view
237 .set_style(Style::default().fg(appearance.colors.text));
124238
125239 if iteminfo.selected {
126240 self.videos_view
@@ -135,14 +249,107 @@ impl SinglePlaylistItem {
135249 }
136250 }
137251 }
252
253 /// updates the %switch-provider% command in the list
254 pub fn update_provider(&mut self) {
255 self.commands
256 .iter()
257 .enumerate()
258 .for_each(|(index, (display, command))| {
259 if command.as_str() == "%switch-provider%" {
260 self.commands_view.items[index] =
261 display.replace("${provider}", self.provider.as_str());
262 }
263 })
264 }
265
266 /// creates a hashmap from `self`, containing info of the current item
267 pub fn inflate_map(&self, mainconfig: &MainConfig, item: &Item) -> HashMap<String, String> {
268 let playlist_item = item.fullplaylist();
269 HashMap::from([
270 (
271 String::from("url"),
272 match self.provider {
273 Provider::YouTube => {
274 format!("https://www.youtube.com/playlist?list={}", playlist_item.id)
275 }
276 Provider::Invidious => format!(
277 "{}/playlist?list={}",
278 mainconfig.invidious_instance, playlist_item.id
279 ),
280 // Provider::Piped => format!(
281 // "{}/playlist?list={}",
282 // mainconfig.piped_instance, playlist_item.id
283 // ),
284 },
285 ),
286 (
287 String::from("all-videos"),
288 match self.provider {
289 Provider::YouTube => playlist_item
290 .videos
291 .iter()
292 .map(|video| format!("'https://youtu.be/{}'", video.minivideo().id))
293 .collect::<Vec<_>>()
294 .join(" "),
295 Provider::Invidious => playlist_item
296 .videos
297 .iter()
298 .map(|video| {
299 format!(
300 "'{}/watch?v={}'",
301 mainconfig.invidious_instance,
302 video.minivideo().id
303 )
304 })
305 .collect::<Vec<_>>()
306 .join(" "),
307 // Provider::Piped => playlist_item
308 // .videos
309 // .iter()
310 // .map(|video| {
311 // format!(
312 // "'{}/watch?v={}'",
313 // mainconfig.piped_instance,
314 // video.minivideo().id
315 // )
316 // })
317 // .collect::<Vec<_>>()
318 // .join(" "),
319 },
320 ),
321 ])
322 }
323
324 /// add "env variables" from `self.inflate_map` to an existing hashmap
325 pub fn inflate(
326 &self,
327 mut env: HashMap<String, String>,
328 mainconfig: &MainConfig,
329 item: &Item,
330 ) -> HashMap<String, String> {
331 env.extend(self.inflate_map(mainconfig, item));
332 env
333 }
138334}
139335
140336impl SingleItemType {
141 pub fn update_appearance(&mut self, appearance: &AppearanceConfig, iteminfo: &tui_additions::framework::ItemInfo, grid: &mut Grid) {
337 pub fn is_none(&self) -> bool {
338 matches!(self, Self::None)
339 }
340
341 pub fn update_appearance(
342 &mut self,
343 appearance: &AppearanceConfig,
344 iteminfo: &tui_additions::framework::ItemInfo,
345 grid: &mut Grid,
346 ) {
142347 match self {
143 Self::None => {},
144 Self::Playlist(playlistitem) => playlistitem.update_appearance(appearance, iteminfo, grid),
145 Self::Video(videoitem) => videoitem.update_appearance(appearance, iteminfo)
348 Self::None => {}
349 Self::Playlist(playlistitem) => {
350 playlistitem.update_appearance(appearance, iteminfo, grid)
351 }
352 Self::Video(videoitem) => videoitem.update_appearance(appearance, iteminfo),
146353 }
147354 }
148355}
@@ -168,7 +375,16 @@ impl SingleItem {
168375 }
169376 }
170377
171 self.r#type.update_appearance(appearance, iteminfo, &mut self.grid);
378 self.r#type
379 .update_appearance(appearance, iteminfo, &mut self.grid);
380 }
381
382 pub fn update_provider(&mut self) {
383 match &mut self.r#type {
384 SingleItemType::Video(singlevideoitem) => singlevideoitem.update_provider(),
385 SingleItemType::Playlist(singleplaylistitem) => singleplaylistitem.update_provider(),
386 SingleItemType::None => {}
387 }
172388 }
173389}
174390
@@ -199,12 +415,18 @@ impl FrameworkItem for SingleItem {
199415
200416 match &mut self.r#type {
201417 SingleItemType::Video(typeinfo) => {
418 // 2 by 1 grid, item info in the first cell and textlist at the second
202419 self.iteminfo
203420 .render(frame, framework, chunks[0], popup_render, info);
204421 typeinfo.textlist.set_height(chunks[1].height);
205422 frame.render_widget(typeinfo.textlist.clone(), chunks[1]);
206423 }
207424 SingleItemType::Playlist(typeinfo) => {
425 // 3 by 1 grid if hovering a video inside the playlist
426 // if not then 2 by 1
427 //
428 // item info in the first cell, textlists in the second, hovering video on 3rd (if
429 // present)
208430 self.iteminfo
209431 .render(frame, framework, chunks[0], popup_render, info);
210432 if typeinfo.is_commands_view {
@@ -213,7 +435,16 @@ impl FrameworkItem for SingleItem {
213435 } else {
214436 typeinfo.videos_view.set_height(chunks[1].height);
215437 frame.render_widget(typeinfo.videos_view.clone(), chunks[1]);
216 typeinfo.hovered_video.render(frame, framework, chunks[2], popup_render, info);
438
439 if typeinfo.videos_view.selected != 0 {
440 typeinfo.hovered_video.render(
441 frame,
442 framework,
443 chunks[2],
444 popup_render,
445 info,
446 );
447 }
217448 }
218449 }
219450 SingleItemType::None => {}
@@ -225,6 +456,8 @@ impl FrameworkItem for SingleItem {
225456 framework: &mut tui_additions::framework::FrameworkClean,
226457 _info: tui_additions::framework::ItemInfo,
227458 ) -> Result<(), Box<dyn std::error::Error>> {
459 *self = Self::default();
460
228461 let page = framework.data.state.get::<Page>().unwrap();
229462
230463 let r#type = if let Page::SingleItem(r#type) = page {
@@ -236,48 +469,300 @@ impl FrameworkItem for SingleItem {
236469 let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
237470 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
238471
472 // load items using the invidious api
473 // gets the item that it needs to load from `data.state.Page`
239474 self.item = match r#type {
240 SingleItemPage::Video(id) => match client.video(id, None) {
241 Ok(video) => {
242 self.r#type = SingleItemType::Video(SingleVideoItem::new(framework.data.global.get::<CommandsConfig>().unwrap()));
243 let video = Item::from_full_video(video, mainconfig.image_index);
244 if mainconfig.images.display() {
245 download_all_images(vec![(&video).into()]);
475 SingleItemPage::Video(id) => {
476 self.r#type = SingleItemType::Video(SingleVideoItem::new(
477 framework.data.global.get::<CommandsConfig>().unwrap(),
478 framework.data.global.get::<MainConfig>().unwrap(),
479 ));
480 let video = Item::from_full_video(client.video(id, None)?, mainconfig.image_index);
481 if mainconfig.images.display() {
482 download_all_images(vec![(&video).into()]);
483 }
484 Some(video)
485 }
486 SingleItemPage::Playlist(id) => {
487 let playlist =
488 Item::from_full_playlist(client.playlist(id, None)?, mainconfig.image_index);
489 let videos = &playlist.fullplaylist().videos;
490 self.r#type = SingleItemType::Playlist(
491 SinglePlaylistItem::new(
492 framework.data.global.get::<CommandsConfig>().unwrap(),
493 framework.data.global.get::<MainConfig>().unwrap(),
494 videos,
495 )
496 .into(),
497 );
498
499 if mainconfig.images.display() {
500 download_all_images({
501 let mut items = videos.iter().map(|item| item.into()).collect::<Vec<_>>();
502 items.extend([(&playlist).into()].into_iter());
503 items
504 });
505 }
506
507 Some(playlist)
508 }
509 };
510 self.iteminfo.item = self.item.clone();
511 // need to update provider every time the item loads or else it will display `${provider}`
512 // instead of the actual provider (e.g. `YouTube`)
513 self.update_provider();
514
515 Ok(())
516 }
517
518 fn key_event(
519 &mut self,
520 framework: &mut tui_additions::framework::FrameworkClean,
521 key: crossterm::event::KeyEvent,
522 info: tui_additions::framework::ItemInfo,
523 ) -> Result<(), Box<dyn std::error::Error>> {
524 // discard any key inputs if `self.is_none()` becuase nothing can happen if self is none
525 if self.r#type.is_none() {
526 return Ok(());
527 }
528
529 let action = if let Some(keyactions) = framework
530 .data
531 .global
532 .get::<KeyBindingsConfig>()
533 .unwrap()
534 .0
535 .get(&key.code)
536 {
537 if let Some(action) = keyactions.get(&key.modifiers.bits()) {
538 *action
539 } else {
540 return Ok(());
541 }
542 } else {
543 return Ok(());
544 };
545
546 let updated = match &mut self.r#type {
547 SingleItemType::Video(singlevideoitem) => match action {
548 // move the cursor in the textlist, only update the screen if it is changed
549 KeyAction::MoveUp => singlevideoitem.textlist.up().is_ok(),
550 KeyAction::MoveDown => singlevideoitem.textlist.down().is_ok(),
551 KeyAction::MoveLeft => singlevideoitem.textlist.first().is_ok(),
552 KeyAction::MoveRight => singlevideoitem.textlist.last().is_ok(),
553 KeyAction::Select => {
554 let command_string = singlevideoitem.commands
555 [singlevideoitem.textlist.selected]
556 .1
557 .clone();
558
559 match command_string.as_str() {
560 // checks for special cases that the items should consume the command
561 // instead of running it
562 "%switch-provider%" => {
563 singlevideoitem.provider.rotate();
564 singlevideoitem.update_provider();
565 *framework.data.global.get_mut::<Message>().unwrap() =
566 Message::Success(format!(
567 "Switched provider to {}",
568 singlevideoitem.provider.as_str()
569 ));
570 }
571 _ => {
572 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
573 // joins the env from the one in mainconfig and video info
574 let env = singlevideoitem.inflate(
575 mainconfig.env.clone(),
576 mainconfig,
577 self.item.as_ref().unwrap(),
578 );
579 let command_string = apply_env(command_string, &env);
580
581 *framework.data.global.get_mut::<Message>().unwrap() =
582 Message::Success(command_string.clone());
583
584 // this allows creating commands from string
585 let mut command = execute::command(command_string);
586
587 // run the command in a new thread so it doesn't freeze the current one
588 thread::spawn(move || {
589 let _ = command.output();
590 });
591 }
246592 }
247 Some(video)
248 },
249 Err(e) => {
250 *self = Self::default();
251 *framework.data.global.get_mut::<Message>().unwrap() =
252 Message::Error(e.to_string());
253 None
593
594 true
254595 }
596 _ => false,
255597 },
256 SingleItemPage::Playlist(id) => match client.playlist(id, None) {
257 Ok(playlist) => {
258 let playlist = Item::from_full_playlist(playlist, mainconfig.image_index);
259 let videos = if let Item::FullPlaylist(playlist) = &playlist {
260 &playlist.videos
261 } else {
262 unreachable!();
263 };
264 self.r#type = SingleItemType::Playlist(SinglePlaylistItem::new(framework.data.global.get::<CommandsConfig>().unwrap(), videos));
265 if mainconfig.images.display() {
266 download_all_images(vec![(&playlist).into()]);
598 SingleItemType::Playlist(singleplaylistitem) => {
599 // there are 2 possible states in a playlist item
600 // they are handelled separately
601 if singleplaylistitem.is_commands_view {
602 match action {
603 KeyAction::MoveUp => singleplaylistitem.commands_view.up().is_ok(),
604 KeyAction::MoveDown => singleplaylistitem.commands_view.down().is_ok(),
605 KeyAction::MoveLeft => singleplaylistitem.commands_view.first().is_ok(),
606 KeyAction::MoveRight => singleplaylistitem.commands_view.last().is_ok(),
607 KeyAction::Select => {
608 let command_string = singleplaylistitem.commands
609 [singleplaylistitem.commands_view.selected]
610 .1
611 .clone();
612
613 // checks for special cases
614 match command_string.as_str() {
615 "%switch-view%" => {
616 singleplaylistitem.is_commands_view =
617 !singleplaylistitem.is_commands_view;
618 self.update_appearance(
619 framework.data.global.get::<AppearanceConfig>().unwrap(),
620 &info,
621 );
622 *framework.data.global.get_mut::<Message>().unwrap() =
623 Message::Success(String::from("Switched view"));
624 }
625 "%switch-provider%" => {
626 singleplaylistitem.provider.rotate();
627 singleplaylistitem.update_provider();
628 }
629 // same as before if string is not a special case then the run the command
630 _ => {
631 let mainconfig =
632 framework.data.global.get::<MainConfig>().unwrap();
633 let env = singleplaylistitem.inflate(
634 mainconfig.env.clone(),
635 mainconfig,
636 self.item.as_ref().unwrap(),
637 );
638 let command_string = apply_env(command_string, &env);
639
640 *framework.data.global.get_mut::<Message>().unwrap() =
641 Message::Success(command_string.clone());
642 let mut command = execute::command(command_string);
643
644 thread::spawn(move || {
645 let _ = command.output();
646 });
647 }
648 };
649
650 true
651 }
652 _ => false,
267653 }
654 } else {
655 match action {
656 // checks if it is updated, if it is and selected is not 0 (is hovering on
657 // a video), then also need to update the iteminfo
658 KeyAction::MoveUp => {
659 let updated = singleplaylistitem.videos_view.up().is_ok();
660 if updated && singleplaylistitem.videos_view.selected != 0 {
661 singleplaylistitem.hovered_video.item = Some(
662 self.item.as_ref().unwrap().fullplaylist().videos
663 [singleplaylistitem.videos_view.selected - 1]
664 .clone(),
665 );
666 } else {
667 // going from a hovering video to not hovering will make the image
668 // stay on the screen, therefore it needs to be removed by clearing
669 // the screen
670 framework
671 .data
672 .state
673 .get_mut::<Tasks>()
674 .unwrap()
675 .priority
676 .push(Task::ClearPage);
677 }
678 updated
679 }
680 KeyAction::MoveDown => {
681 let updated = singleplaylistitem.videos_view.down().is_ok();
682 if updated && singleplaylistitem.videos_view.selected != 0 {
683 singleplaylistitem.hovered_video.item = Some(
684 self.item.as_ref().unwrap().fullplaylist().videos
685 [singleplaylistitem.videos_view.selected - 1]
686 .clone(),
687 );
688 }
689 updated
690 }
691 KeyAction::MoveLeft => {
692 let updated = singleplaylistitem.videos_view.first().is_ok();
693 if updated && singleplaylistitem.videos_view.selected != 0 {
694 singleplaylistitem.hovered_video.item = Some(
695 self.item.as_ref().unwrap().fullplaylist().videos
696 [singleplaylistitem.videos_view.selected - 1]
697 .clone(),
698 );
699 }
700 updated
701 }
702 KeyAction::MoveRight => {
703 let updated = singleplaylistitem.videos_view.last().is_ok();
704 if updated && singleplaylistitem.videos_view.selected != 0 {
705 singleplaylistitem.hovered_video.item = Some(
706 self.item.as_ref().unwrap().fullplaylist().videos
707 [singleplaylistitem.videos_view.selected - 1]
708 .clone(),
709 );
710 }
711 updated
712 }
713 KeyAction::Select => {
714 if singleplaylistitem.videos_view.selected == 0 {
715 singleplaylistitem.is_commands_view =
716 !singleplaylistitem.is_commands_view;
717 self.update_appearance(
718 framework.data.global.get::<AppearanceConfig>().unwrap(),
719 &info,
720 );
721 *framework.data.global.get_mut::<Message>().unwrap() =
722 Message::Success(String::from("Switched view"));
723 } else {
724 framework
725 .data
726 .state
727 .get_mut::<Tasks>()
728 .unwrap()
729 .priority
730 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
731 self.item.as_ref().unwrap().fullplaylist().videos
732 [singleplaylistitem.videos_view.selected - 1]
733 .minivideo()
734 .id
735 .clone(),
736 ))));
737 }
268738
269 Some(playlist)
270 },
271 Err(e) => {
272 *self = Self::default();
273 *framework.data.global.get_mut::<Message>().unwrap() =
274 Message::Error(e.to_string());
275 None
739 true
740 }
741 _ => false,
742 }
276743 }
277744 }
745 SingleItemType::None => false,
278746 };
279 self.iteminfo.item = self.item.clone();
747
748 if updated {
749 framework
750 .data
751 .state
752 .get_mut::<Tasks>()
753 .unwrap()
754 .priority
755 .push(Task::RenderAll);
756 }
280757
281758 Ok(())
282759 }
283760}
761
762/// apply the env hashmap to a command string
763pub fn apply_env(mut command: String, env: &HashMap<String, String>) -> String {
764 env.iter().for_each(|(key, value)| {
765 command = command.replace(&format!("${{{key}}}"), value);
766 });
767 command
768}
src/run.rs +16 −6
@@ -14,12 +14,9 @@ pub fn run(
1414 mut framework: Framework,
1515) -> Result<(), Box<dyn Error>> {
1616 // push the initial page load
17 let tasks = framework
18 .data
19 .state
20 .get_mut::<Tasks>()
21 .unwrap();
22 tasks.priority
17 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
18 tasks
19 .priority
2320 .push(Task::LoadPage(Page::MainMenu(MainMenuPage::Trending)));
2421 tasks.pop().unwrap().run(&mut framework, terminal)?;
2522 framework.clear_history();
@@ -31,6 +28,8 @@ pub fn run(
3128 continue;
3229 }
3330
31 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
32
3433 match event::read()? {
3534 Event::Key(key) => {
3635 // 1. get the corresponding action
@@ -62,6 +61,9 @@ pub fn run(
6261 .push(Task::RenderAll);
6362 }
6463
64 // if something is selected, pass the key input into that item
65 // if nothing is selected, the following big chunk of code handles to movement of
66 // cursor and stuff
6567 if framework.is_selected() {
6668 if let Err(e) = framework.key_input(key) {
6769 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -88,6 +90,14 @@ pub fn run(
8890 Message::Error(String::from(
8991 "This is already the beginning of history",
9092 ))
93 } else {
94 framework
95 .data
96 .state
97 .get_mut::<Tasks>()
98 .unwrap()
99 .priority
100 .push(Task::ClearPage);
91101 }
92102 }
93103 KeyAction::Select => {