Commit c819601c03

c819601c034e5b6dfb99be651db12273942a222f

parent: 964b7d9b87

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2023-01-15 19:56 UTC

command bindings

Layout: unified · split

src/config/commandbindings.rs added +194
@@ -0,0 +1,194 @@
1use crossterm::event::{KeyCode, KeyEvent};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use typemap::Key;
5
6use crate::global::{
7 structs::{ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Page, SingleItemPage},
8 traits::ConfigTrait,
9};
10
11use super::serde::KeyCodeSerde;
12
13#[derive(Clone)]
14pub struct CommandBindings {
15 pub global: HashMap<KeyCode, HashMap<u8, String>>,
16 pub search: HashMap<KeyCode, HashMap<u8, String>>,
17 pub popular: HashMap<KeyCode, HashMap<u8, String>>,
18 pub trending: HashMap<KeyCode, HashMap<u8, String>>,
19 pub video: HashMap<KeyCode, HashMap<u8, String>>,
20 pub playlist: HashMap<KeyCode, HashMap<u8, String>>,
21 pub channel_main: HashMap<KeyCode, HashMap<u8, String>>,
22 pub channel_videos: HashMap<KeyCode, HashMap<u8, String>>,
23 pub channel_playlists: HashMap<KeyCode, HashMap<u8, String>>,
24 pub watchhistory: HashMap<KeyCode, HashMap<u8, String>>,
25}
26
27impl Key for CommandBindings {
28 type Value = Self;
29}
30
31impl CommandBindings {
32 pub fn get_command(&self, key: &KeyEvent, page: &Page) -> String {
33 let mut out = String::new();
34
35 if let Some(command) = get_command(key, &self.global) {
36 out.push_str(command);
37 }
38
39 let command = match page {
40 Page::Search(_) => get_command(key, &self.search),
41 Page::MainMenu(MainMenuPage::Trending) => get_command(key, &self.trending),
42 Page::MainMenu(MainMenuPage::Popular) => get_command(key, &self.popular),
43 Page::MainMenu(MainMenuPage::History) => get_command(key, &self.watchhistory),
44 Page::SingleItem(SingleItemPage::Video(_)) => get_command(key, &self.video),
45 Page::SingleItem(SingleItemPage::Playlist(_)) => get_command(key, &self.playlist),
46 Page::ChannelDisplay(ChannelDisplayPage {
47 r#type: ChannelDisplayPageType::Main,
48 ..
49 }) => get_command(key, &self.channel_main),
50 Page::ChannelDisplay(ChannelDisplayPage {
51 r#type: ChannelDisplayPageType::Videos,
52 ..
53 }) => get_command(key, &self.channel_videos),
54 Page::ChannelDisplay(ChannelDisplayPage {
55 r#type: ChannelDisplayPageType::Playlists,
56 ..
57 }) => get_command(key, &self.channel_playlists),
58 };
59
60 if let Some(command) = command {
61 out.push_str("&&");
62 out.push_str(command);
63 }
64
65 out
66 }
67}
68
69#[derive(Clone, Serialize, Deserialize)]
70pub struct CommandBindingsSerde {
71 #[serde(default = "global_default")]
72 pub global: HashMap<KeyCodeSerde, HashMap<u8, String>>,
73 #[serde(default = "search_default")]
74 pub search: HashMap<KeyCodeSerde, HashMap<u8, String>>,
75 #[serde(default = "popular_default")]
76 pub popular: HashMap<KeyCodeSerde, HashMap<u8, String>>,
77 #[serde(default = "trending_default")]
78 pub trending: HashMap<KeyCodeSerde, HashMap<u8, String>>,
79 #[serde(default = "video_default")]
80 pub video: HashMap<KeyCodeSerde, HashMap<u8, String>>,
81 #[serde(default = "playlist_default")]
82 pub playlist: HashMap<KeyCodeSerde, HashMap<u8, String>>,
83 #[serde(default = "channel_main_default")]
84 pub channel_main: HashMap<KeyCodeSerde, HashMap<u8, String>>,
85 #[serde(default = "channel_videos_default")]
86 pub channel_videos: HashMap<KeyCodeSerde, HashMap<u8, String>>,
87 #[serde(default = "channel_playlists_default")]
88 pub channel_playlists: HashMap<KeyCodeSerde, HashMap<u8, String>>,
89 #[serde(default = "watchhistory_default")]
90 pub watchhistory: HashMap<KeyCodeSerde, HashMap<u8, String>>,
91}
92
93impl ConfigTrait for CommandBindingsSerde {
94 const LABEL: &'static str = "commandbindings";
95}
96
97impl CommandBindingsSerde {
98 pub fn into(self) -> Option<CommandBindings> {
99 Some(CommandBindings {
100 global: de_serde(self.global)?,
101 search: de_serde(self.search)?,
102 popular: de_serde(self.popular)?,
103 channel_main: de_serde(self.channel_main)?,
104 channel_videos: de_serde(self.channel_videos)?,
105 channel_playlists: de_serde(self.channel_playlists)?,
106 playlist: de_serde(self.playlist)?,
107 video: de_serde(self.video)?,
108 trending: de_serde(self.trending)?,
109 watchhistory: de_serde(self.watchhistory)?,
110 })
111 }
112}
113
114impl Default for CommandBindingsSerde {
115 fn default() -> Self {
116 Self {
117 global: global_default(),
118 search: search_default(),
119 popular: popular_default(),
120 channel_main: channel_main_default(),
121 channel_videos: channel_videos_default(),
122 channel_playlists: channel_playlists_default(),
123 playlist: playlist_default(),
124 video: video_default(),
125 trending: trending_default(),
126 watchhistory: watchhistory_default(),
127 }
128 }
129}
130
131fn de_serde(
132 original: HashMap<KeyCodeSerde, HashMap<u8, String>>,
133) -> Option<HashMap<KeyCode, HashMap<u8, String>>> {
134 let mut out = HashMap::new();
135
136 // simply loops over the serde hashmap and insert them into the new one
137 for (keycodeserde, map) in original.into_iter() {
138 out.insert(keycodeserde.to_keycode()?, map);
139 }
140
141 Some(out)
142}
143
144fn get_command<'a>(
145 key: &'a KeyEvent,
146 map: &'a HashMap<KeyCode, HashMap<u8, String>>,
147) -> Option<&'a str> {
148 Some(map.get(&key.code)?.get(&key.modifiers.bits())?)
149}
150
151// default functions
152
153fn global_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
154 HashMap::default()
155}
156
157fn search_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
158 HashMap::from([(
159 KeyCodeSerde::Char('f'),
160 HashMap::from([(2, String::from("run ${browser} ${url}"))]),
161 )])
162}
163
164fn channel_main_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
165 HashMap::default()
166}
167
168fn channel_playlists_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
169 HashMap::default()
170}
171
172fn channel_videos_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
173 HashMap::default()
174}
175
176fn playlist_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
177 HashMap::default()
178}
179
180fn popular_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
181 HashMap::default()
182}
183
184fn trending_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
185 HashMap::default()
186}
187
188fn video_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
189 HashMap::default()
190}
191
192fn watchhistory_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
193 HashMap::default()
194}
src/config/commands.rs +11 −2
@@ -8,6 +8,7 @@ use crate::global::traits::ConfigTrait;
88/// Stores combinations of label and commands
99#[derive(Clone)]
1010pub struct CommandsConfig {
11 pub launch_command: String,
1112 pub video: Vec<(String, String)>,
1213 pub playlist: Vec<(String, String)>,
1314}
@@ -19,6 +20,7 @@ impl Key for CommandsConfig {
1920impl From<CommandsConfigSerde> for CommandsConfig {
2021 fn from(original: CommandsConfigSerde) -> Self {
2122 Self {
23 launch_command: original.launch_command,
2224 video: original
2325 .video
2426 .into_iter()
@@ -37,6 +39,8 @@ impl From<CommandsConfigSerde> for CommandsConfig {
3739// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look
3840#[derive(Serialize, Deserialize, Clone)]
3941pub struct CommandsConfigSerde {
42 #[serde(default = "launch_command_default")]
43 pub launch_command: String,
4044 #[serde(default = "video_default")]
4145 pub video: Vec<HashMap<String, String>>,
4246 #[serde(default = "playlist_default")]
@@ -50,6 +54,7 @@ impl ConfigTrait for CommandsConfigSerde {
5054impl Default for CommandsConfigSerde {
5155 fn default() -> Self {
5256 Self {
57 launch_command: launch_command_default(),
5358 video: video_default(),
5459 playlist: playlist_default(),
5560 }
@@ -59,6 +64,10 @@ impl Default for CommandsConfigSerde {
5964// `${label}` will be replaced by the values set in `main.yml` in `env`
6065// Different pages may contain different `env`s (for example `url` is different in each page)
6166
67fn launch_command_default() -> String {
68 String::from("loadpage popular ;; flush ;; history clear")
69}
70
6271fn video_default() -> Vec<HashMap<String, String>> {
6372 vec![
6473 HashMap::from([(
@@ -97,7 +106,7 @@ fn video_default() -> Vec<HashMap<String, String>> {
97106 )]),
98107 HashMap::from([(
99108 String::from("Mode: ${provider}"),
100 String::from("%switch-provider%"),
109 String::from("switchprovider"),
101110 )]),
102111 ]
103112}
@@ -139,7 +148,7 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
139148 )]),
140149 HashMap::from([(
141150 String::from("Mode: ${provider}"),
142 String::from("%switch-provider%"),
151 String::from("switchprovider"),
143152 )]),
144153 ]
145154}
src/config/mod.rs +2
@@ -11,5 +11,7 @@ mod keybindings;
1111pub use keybindings::*;
1212mod commands;
1313pub use commands::*;
14mod commandbindings;
15pub use commandbindings::*;
1416
1517pub mod serde;
src/global/functions/run_command.rs +56 −48
@@ -6,20 +6,20 @@ use crate::{
66 },
77 load_configs,
88};
9use std::{
10 io::Stdout,
11 env,
12 thread,
13};
149use run_script::ScriptOptions;
10use std::{env, io::Stdout, thread};
1511use tui::{backend::CrosstermBackend, Terminal};
1612use tui_additions::framework::Framework;
1713
1814use super::{fake_rand_range, from_channel_url, from_playlist_url, from_video_url, set_clipboard};
1915
2016/// runs text command - command from the command line (not TUI) which response is just a string
21pub fn text_command(command: &[&str]) -> Option<String> {
22 match command {
17pub fn text_command(command: &str) -> Option<String> {
18 match command
19 .split_ascii_whitespace()
20 .collect::<Vec<_>>()
21 .as_slice()
22 {
2323 ["help"] => Some(String::from(HELP_MSG)),
2424 ["version"] => Some(format!(
2525 "{} {}",
@@ -30,25 +30,48 @@ pub fn text_command(command: &[&str]) -> Option<String> {
3030 }
3131}
3232
33/// runs a command in the TUI, returns true if its a loadpage command, false if not
3433pub fn run_command(
34 command: &str,
35 framework: &mut Framework,
36 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
37) {
38 command.split(";;").into_iter().for_each(|single_command| {
39 run_single_command(
40 &single_command
41 .trim()
42 .split_ascii_whitespace()
43 .collect::<Vec<_>>(),
44 framework,
45 terminal,
46 )
47 });
48}
49
50/// runs a command in the TUI, returns true if its a loadpage command, false if not
51pub fn run_single_command(
3552 command: &[&str],
3653 framework: &mut Framework,
3754 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
38) -> bool {
55) {
3956 // match a command splitted by space to a bunch of avaliable commands
4057 match command {
41 [] => false,
58 [] => {}
4259 ["help"] | ["h"] => {
4360 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
4461 "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
4562 ));
46 false
63 }
64 ["switchprovider"] => {
65 let status = framework.data.global.get_mut::<Status>().unwrap();
66
67 status.provider.rotate();
68 status.provider_updated = true;
69 *framework.data.global.get_mut::<Message>().unwrap() =
70 Message::Success(format!("Provider updated to {}", status.provider.as_str()))
4771 }
4872 ["loadpage"] => {
4973 *framework.data.global.get_mut::<Message>().unwrap() =
5074 Message::Message(String::from("Usage: `loadpage {page}`"));
51 false
5275 }
5376 // loads a given page
5477 ["loadpage", page, ..] => {
@@ -60,7 +83,7 @@ pub fn run_command(
6083 if command.len() == 2 {
6184 *framework.data.global.get_mut::<Message>().unwrap() =
6285 Message::Message(String::from("Usage: `loadpage channel {id/url}`"));
63 return false;
86 return;
6487 }
6588
6689 match from_channel_url(command[2]) {
@@ -71,7 +94,7 @@ pub fn run_command(
7194 Err(e) => {
7295 *framework.data.global.get_mut::<Message>().unwrap() =
7396 Message::Error(e);
74 return false;
97 return;
7598 }
7699 }
77100 }
@@ -79,7 +102,7 @@ pub fn run_command(
79102 if command.len() == 2 {
80103 *framework.data.global.get_mut::<Message>().unwrap() =
81104 Message::Message(String::from("Usage: `loadpage video {id/url}`"));
82 return false;
105 return;
83106 }
84107
85108 match from_video_url(command[2]) {
@@ -87,7 +110,7 @@ pub fn run_command(
87110 Err(e) => {
88111 *framework.data.global.get_mut::<Message>().unwrap() =
89112 Message::Error(e);
90 return false;
113 return;
91114 }
92115 }
93116 }
@@ -95,7 +118,7 @@ pub fn run_command(
95118 if command.len() == 2 {
96119 *framework.data.global.get_mut::<Message>().unwrap() =
97120 Message::Message(String::from("Usage: `loadpage playlist {id/url}`"));
98 return false;
121 return;
99122 }
100123
101124 match from_playlist_url(command[2]) {
@@ -103,7 +126,7 @@ pub fn run_command(
103126 Err(e) => {
104127 *framework.data.global.get_mut::<Message>().unwrap() =
105128 Message::Error(e);
106 return false;
129 return;
107130 }
108131 }
109132 }
@@ -111,7 +134,7 @@ pub fn run_command(
111134 if command.len() == 2 {
112135 *framework.data.global.get_mut::<Message>().unwrap() =
113136 Message::Message(String::from("Usage: `search {query}`"));
114 return true;
137 return;
115138 }
116139
117140 // search for a query, although the command is matched as an array, the original query can
@@ -137,37 +160,34 @@ pub fn run_command(
137160 .priority
138161 .push(Task::LoadPage(page))
139162 }
140
141 true
142163 }
143164 // redirects to the relevant `loadpage` command
144 ["popular"] => run_command(&["loadpage", "popular"], framework, terminal),
145 ["trending"] => run_command(&["loadpage", "trending"], framework, terminal),
146 ["watchhistory"] => run_command(&["loadpage", "watchhistory"], framework, terminal),
147 ["search"] => run_command(&["loadpage", "search"], framework, terminal),
148 ["search", ..] => run_command(
165 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
166 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
167 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
168 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
169 ["search", ..] => run_single_command(
149170 &format!("loadpage search {}", command[1..].join(" "))
150171 .split(' ')
151172 .collect::<Vec<&str>>(),
152173 framework,
153174 terminal,
154175 ),
155 ["channel"] => run_command(&["loadpage", "channel"], framework, terminal),
176 ["channel"] => run_single_command(&["loadpage", "channel"], framework, terminal),
156177 ["channel", identifier] => {
157 run_command(&["loadpage", "channel", *identifier], framework, terminal)
178 run_single_command(&["loadpage", "channel", *identifier], framework, terminal)
158179 }
159 ["video"] => run_command(&["loadpage", "video"], framework, terminal),
180 ["video"] => run_single_command(&["loadpage", "video"], framework, terminal),
160181 ["video", identifier] => {
161 run_command(&["loadpage", "video", *identifier], framework, terminal)
182 run_single_command(&["loadpage", "video", *identifier], framework, terminal)
162183 }
163 ["playlist"] => run_command(&["loadpage", "playlist"], framework, terminal),
184 ["playlist"] => run_single_command(&["loadpage", "playlist"], framework, terminal),
164185 ["playlist", identifier] => {
165 run_command(&["loadpage", "playlist", *identifier], framework, terminal)
186 run_single_command(&["loadpage", "playlist", *identifier], framework, terminal)
166187 }
167188 ["history"] => {
168189 *framework.data.global.get_mut::<Message>().unwrap() =
169 Message::Message(String::from("Usage: `history [back/clear]`"));
170 false
190 Message::Message(String::from("Usage: `history [back/clear]`"))
171191 }
172192 ["history", "back"] | ["back"] => {
173193 let _ = framework.revert_last_history();
@@ -185,18 +205,16 @@ pub fn run_command(
185205 .unwrap()
186206 .priority
187207 .push(Task::RenderAll);
188 run_command(&["flush"], framework, terminal);
208 run_single_command(&["flush"], framework, terminal);
189209 framework
190210 .data
191211 .global
192212 .get_mut::<Status>()
193213 .unwrap()
194214 .render_image = true;
195 false
196215 }
197216 ["history", "clear"] => {
198217 framework.clear_history();
199 false
200218 }
201219 ["flush"] => loop {
202220 // runs all stacked actions
@@ -204,7 +222,7 @@ pub fn run_command(
204222 let _res = tasks.run(framework, terminal);
205223 continue;
206224 }
207 break false;
225 break;
208226 },
209227 ["reload"] | ["r"] => {
210228 framework
@@ -214,7 +232,6 @@ pub fn run_command(
214232 .unwrap()
215233 .priority
216234 .push(Task::Reload);
217 false
218235 }
219236 ["reload", "config"] | ["reload", "configs"] | ["r", "config"] | ["r", "configs"] => {
220237 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -222,17 +239,14 @@ pub fn run_command(
222239 Ok(()) => Message::Success(String::from("Config files have been reloaded")),
223240 Err(e) => Message::Error(e.to_string()),
224241 };
225 false
226242 }
227243 ["q"] | ["quit"] | ["x"] | ["exit"] => {
228244 framework.data.global.get_mut::<Status>().unwrap().exit = true;
229 false
230245 }
231246 ["hello", "world"] => {
232247 let index = fake_rand_range(0, HELLO_WORLDS.len() as i64) as usize;
233248 *framework.data.global.get_mut::<Message>().unwrap() =
234249 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
235 false
236250 }
237251 ["version"] | ["v"] => {
238252 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!(
@@ -240,12 +254,10 @@ pub fn run_command(
240254 env!("CARGO_PKG_NAME"),
241255 env!("CARGO_PKG_VERSION")
242256 ));
243 false
244257 }
245258 ["run"] => {
246259 *framework.data.global.get_mut::<Message>().unwrap() =
247260 Message::Message(String::from("Usage: run [command]"));
248 false
249261 }
250262 ["run", ..] => {
251263 let command = command[1..].join(" ");
@@ -254,23 +266,19 @@ pub fn run_command(
254266 thread::spawn(move || {
255267 run_script::run(&command, &Vec::new(), &ScriptOptions::new()).unwrap();
256268 });
257 false
258269 }
259270 ["copy"] | ["cp"] => {
260271 *framework.data.global.get_mut::<Message>().unwrap() =
261272 Message::Message(String::from("Usage: copy [text]"));
262 false
263273 }
264274 ["copy", ..] | ["cp", ..] => {
265275 set_clipboard(command[1..].join(" "));
266276 *framework.data.global.get_mut::<Message>().unwrap() =
267277 Message::Success(String::from("Copied to clipboad"));
268 false
269278 }
270279 _ => {
271280 *framework.data.global.get_mut::<Message>().unwrap() =
272281 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
273 false
274282 }
275283 }
276284}
src/global/structs/status.rs +8
@@ -2,6 +2,8 @@ use tui::layout::Rect;
22use tui_additions::widgets::TextField;
33use typemap::Key;
44
5use crate::config::Provider;
6
57/// a struct for storing different info, currently only stores one info
68#[derive(Clone)]
79pub struct Status {
@@ -17,6 +19,10 @@ pub struct Status {
1719 pub exit: bool,
1820 /// stores the area of the previously rendered frame
1921 pub prev_frame: Option<Rect>,
22 /// stores global provider (yt/inv)
23 pub provider: Provider,
24 /// if provider is updated, lasts for 1 event loop
25 pub provider_updated: bool,
2026}
2127
2228impl Key for Status {
@@ -32,6 +38,8 @@ impl Default for Status {
3238 command_capture: None,
3339 exit: false,
3440 prev_frame: None,
41 provider: Provider::YouTube,
42 provider_updated: false,
3543 }
3644 }
3745}
src/global/structs/tasks.rs +1 −5
@@ -83,11 +83,7 @@ impl TaskQueue {
8383 // if there is any commands, run them first as they may modify data, which is rendered
8484 // later in this function
8585 for command in self.commands.iter() {
86 run_command(
87 &command.split_whitespace().collect::<Vec<_>>(),
88 framework,
89 terminal,
90 );
86 run_command(command, framework, terminal);
9187 }
9288
9389 if self.clear_all {
src/init.rs +29 −14
@@ -1,7 +1,7 @@
11use crate::{
22 config::{
3 AppearanceConfig, CommandsConfig, CommandsConfigSerde, KeyBindingsConfig, MainConfig,
4 MinDimentions, PagesConfig, Search,
3 AppearanceConfig, CommandBindings, CommandBindingsSerde, CommandsConfig,
4 CommandsConfigSerde, KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
55 },
66 global::{
77 functions::run_command,
@@ -22,7 +22,7 @@ use tui_additions::framework::{Framework, FrameworkClean};
2222pub fn init(
2323 framework: &mut Framework,
2424 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
25 command: &[&str],
25 command: Option<&str>,
2626) -> Result<(), Box<dyn Error>> {
2727 // creating files
2828 let home_dir = home_dir().unwrap();
@@ -41,8 +41,13 @@ pub fn init(
4141 // watch history init
4242 WatchHistory::init_move();
4343
44 load_configs(&mut framework.split_clean().0).ok();
45
4446 framework.data.global.insert::<Message>(Message::None);
45 framework.data.global.insert::<Status>(Status::default());
47 framework.data.global.insert::<Status>(Status {
48 provider: framework.data.global.get::<MainConfig>().unwrap().provider,
49 ..Status::default()
50 });
4651
4752 framework.data.state.insert::<Tasks>(Tasks::default());
4853 framework.data.state.insert::<Page>(Page::default());
@@ -50,14 +55,24 @@ pub fn init(
5055 .data
5156 .state
5257 .insert::<MinDimentions>(MinDimentions::default());
58 framework
59 .data
60 .state
61 .insert::<StateEnvs>(StateEnvs::default());
5362
54 load_configs(&mut framework.split_clean().0).ok();
55
56 if !run_command(command, framework, terminal) {
57 run_command(&["loadpage", "popular"], framework, terminal);
58 }
59 run_command(&["flush"], framework, terminal);
60 run_command(&["history", "clear"], framework, terminal);
63 run_command(
64 command.unwrap_or(
65 &framework
66 .data
67 .global
68 .get::<CommandsConfig>()
69 .unwrap()
70 .launch_command
71 .clone(),
72 ),
73 framework,
74 terminal,
75 );
6176 Ok(())
6277}
6378
@@ -97,11 +112,11 @@ pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>
97112 .data
98113 .global
99114 .insert::<KeyBindingsConfig>(KeyBindingsConfig::load()?);
100 framework.data.state.insert::<Search>(*Search::load()?);
101115 framework
102116 .data
103 .state
104 .insert::<StateEnvs>(StateEnvs::default());
117 .global
118 .insert::<CommandBindings>((*CommandBindingsSerde::load()?).into().unwrap());
119 framework.data.state.insert::<Search>(*Search::load()?);
105120
106121 Ok(())
107122}
src/items/itemlist.rs +70 −5
@@ -11,14 +11,14 @@ use tui_additions::{
1111
1212use super::ItemInfo;
1313use crate::{
14 config::{AppearanceConfig, KeyBindingsConfig, MainConfig, Search},
14 config::{AppearanceConfig, KeyBindingsConfig, MainConfig, Provider, Search},
1515 global::{
16 functions::download_all_images,
16 functions::{download_all_images, set_envs},
1717 structs::{
1818 ChannelDisplayPage, ChannelDisplayPageType, FullChannelItem, FullPlaylistItem,
1919 FullVideoItem, InvidiousClient, Item, KeyAction, MainMenuPage, Message,
20 MiniChannelItem, MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, Status, Task,
21 Tasks, WatchHistory,
20 MiniChannelItem, MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, StateEnvs,
21 Status, Task, Tasks, WatchHistory,
2222 },
2323 },
2424};
@@ -34,7 +34,48 @@ pub struct ItemList {
3434}
3535
3636impl ItemList {
37 /// updates the styles of different things that may be updated by deselect/selects
37 pub fn inflate_provider_update(
38 &self,
39 page: &Page,
40 mainconfig: &MainConfig,
41 status: &Status,
42 ) -> Vec<(String, String)> {
43 match page {
44 Page::Search(search) => vec![(
45 String::from("url"),
46 match status.provider {
47 Provider::YouTube => {
48 format!("'https://youtube.com/results?{}'", search.to_string())
49 }
50 Provider::Invidious => format!(
51 "'{}/search?{}'",
52 mainconfig.invidious_instance,
53 search.to_string()
54 ),
55 },
56 )],
57 Page::MainMenu(MainMenuPage::Popular) => vec![(
58 String::from("url"),
59 match status.provider {
60 Provider::YouTube => String::from("'https://youtube.com'"),
61 Provider::Invidious => {
62 format!("'{}/feed/popular'", mainconfig.invidious_instance)
63 }
64 },
65 )],
66 Page::MainMenu(MainMenuPage::Trending) => vec![(
67 String::from("url"),
68 match status.provider {
69 Provider::YouTube => String::from("'https://www.youtube.com/feed/trending'"),
70 Provider::Invidious => {
71 format!("{}/feed/trending'", mainconfig.invidious_instance)
72 }
73 },
74 )],
75 _ => Vec::new(),
76 }
77 }
78
3879 fn update_appearance(
3980 &mut self,
4081 appearance: &AppearanceConfig,
@@ -148,6 +189,20 @@ impl FrameworkItem for ItemList {
148189 return;
149190 }
150191
192 let status = framework.data.global.get::<Status>().unwrap();
193
194 if status.provider_updated {
195 set_envs(
196 self.inflate_provider_update(
197 framework.data.state.get::<Page>().unwrap(),
198 framework.data.global.get::<MainConfig>().unwrap(),
199 status,
200 )
201 .into_iter(),
202 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
203 );
204 }
205
151206 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
152207 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
153208 self.update_appearance(appearance, mainconfig, &info);
@@ -260,6 +315,16 @@ impl FrameworkItem for ItemList {
260315 self.textlist.set_items(&self.items).unwrap();
261316 self.update();
262317
318 set_envs(
319 self.inflate_provider_update(
320 framework.data.state.get::<Page>().unwrap(),
321 framework.data.global.get::<MainConfig>().unwrap(),
322 framework.data.global.get::<Status>().unwrap(),
323 )
324 .into_iter(),
325 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
326 );
327
263328 Ok(())
264329 }
265330
src/items/singleitem.rs +192 −81
@@ -54,7 +54,6 @@ pub enum SingleItemType {
5454pub struct SingleVideoItem {
5555 pub textlist: TextList,
5656 pub commands: Vec<(String, String)>,
57 pub provider: Provider,
5857}
5958
6059#[derive(Clone)]
@@ -64,11 +63,10 @@ pub struct SinglePlaylistItem {
6463 pub commands: Vec<(String, String)>,
6564 pub is_commands_view: bool,
6665 pub hovered_video: ItemInfo,
67 pub provider: Provider,
6866}
6967
7068impl SingleVideoItem {
71 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig) -> Self {
69 pub fn new(commands: &CommandsConfig) -> Self {
7270 Self {
7371 textlist: TextList::default()
7472 .items(
@@ -85,21 +83,17 @@ impl SingleVideoItem {
8583 .into_iter()
8684 .map(|(display, command)| (display, command))
8785 .collect(),
88 provider: mainconfig.provider,
8986 }
9087 }
9188
92 /// updates the %switch-provider% command in the list
93 pub fn update_provider(&mut self) {
89 /// find all occurances of ${provider}
90 pub fn update_provider(&mut self) -> Vec<usize> {
9491 self.commands
9592 .iter()
9693 .enumerate()
97 .for_each(|(index, (display, command))| {
98 if command.as_str() == "%switch-provider%" {
99 self.textlist.items[index] =
100 display.replace("${provider}", self.provider.as_str());
101 }
102 })
94 .filter(|(_index, (display, _command))| display.contains("${provider}"))
95 .map(|(index, _)| index)
96 .collect()
10397 }
10498
10599 pub fn update_appearance(
@@ -125,13 +119,18 @@ impl SingleVideoItem {
125119 }
126120
127121 /// creates a hashmap from `self`, containing info of the current item
128 pub fn inflate(&self, mainconfig: &MainConfig, item: &Item) -> Vec<(String, String)> {
122 pub fn inflate_load(
123 &self,
124 mainconfig: &MainConfig,
125 status: &Status,
126 item: &Item,
127 ) -> Vec<(String, String)> {
129128 let video_item = item.fullvideo().unwrap();
130129
131130 vec![
132131 (
133132 String::from("url"),
134 match self.provider {
133 match status.provider {
135134 Provider::Invidious => format!(
136135 "'{}/watch?v={}'",
137136 mainconfig.invidious_instance, video_item.id
@@ -142,7 +141,52 @@ impl SingleVideoItem {
142141 (String::from("id"), video_item.id.clone()),
143142 (
144143 String::from("embed-url"),
145 match self.provider {
144 match status.provider {
145 Provider::Invidious => format!(
146 "'{}/embed/{}'",
147 mainconfig.invidious_instance, video_item.id
148 ),
149 Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id),
150 },
151 ),
152 (String::from("channel-id"), video_item.channel_id.clone()),
153 (
154 String::from("channel-url"),
155 match status.provider {
156 Provider::YouTube => {
157 format!("https://www.youtube.com/channel/{}", video_item.channel_id)
158 }
159 Provider::Invidious => format!(
160 "{}/channel/{}",
161 mainconfig.invidious_instance, video_item.channel_id
162 ),
163 },
164 ),
165 ]
166 }
167
168 pub fn inflate_provider_update(
169 &self,
170 mainconfig: &MainConfig,
171 status: &Status,
172 item: &Item,
173 ) -> Vec<(String, String)> {
174 let video_item = item.fullvideo().unwrap();
175
176 vec![
177 (
178 String::from("url"),
179 match status.provider {
180 Provider::Invidious => format!(
181 "'{}/watch?v={}'",
182 mainconfig.invidious_instance, video_item.id
183 ),
184 Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id),
185 },
186 ),
187 (
188 String::from("embed-url"),
189 match status.provider {
146190 Provider::Invidious => format!(
147191 "'{}/embed/{}'",
148192 mainconfig.invidious_instance, video_item.id
@@ -153,7 +197,7 @@ impl SingleVideoItem {
153197 (String::from("channel-id"), video_item.channel_id.clone()),
154198 (
155199 String::from("channel-url"),
156 match self.provider {
200 match status.provider {
157201 Provider::YouTube => {
158202 format!("https://www.youtube.com/channel/{}", video_item.channel_id)
159203 }
@@ -168,11 +212,7 @@ impl SingleVideoItem {
168212}
169213
170214impl SinglePlaylistItem {
171 pub fn new(
172 commands: &CommandsConfig,
173 mainconfig: &MainConfig,
174 playlist_items: &[Item],
175 ) -> Self {
215 pub fn new(commands: &CommandsConfig, playlist_items: &[Item]) -> Self {
176216 let hovered_video = ItemInfo::new(if playlist_items.is_empty() {
177217 None
178218 } else {
@@ -207,7 +247,6 @@ impl SinglePlaylistItem {
207247 .collect(),
208248 hovered_video,
209249 is_commands_view: true,
210 provider: mainconfig.provider,
211250 }
212251 }
213252
@@ -262,26 +301,38 @@ impl SinglePlaylistItem {
262301 }
263302 }
264303
265 /// updates the %switch-provider% command in the list
266 pub fn update_provider(&mut self) {
304 /// find all occurances of ${provider}
305 pub fn update_provider(&mut self) -> Vec<usize> {
267306 self.commands
268307 .iter()
269308 .enumerate()
270 .for_each(|(index, (display, command))| {
271 if command.as_str() == "%switch-provider%" {
272 self.commands_view.items[index] =
273 display.replace("${provider}", self.provider.as_str());
274 }
275 })
309 .filter(|(_index, (display, _command))| display.contains("${provider}"))
310 .map(|(index, _)| index)
311 .collect()
276312 }
277313
278314 /// creates a hashmap from `self`, containing info of the current item
279 pub fn inflate(&self, mainconfig: &MainConfig, item: &Item) -> Vec<(String, String)> {
315 pub fn inflate_load(&self, item: &Item) -> Vec<(String, String)> {
316 let playlist_item = item.fullplaylist().unwrap();
317
318 vec![
319 (String::from("id"), playlist_item.id.clone()),
320 (String::from("channel-id"), playlist_item.channel_id.clone()),
321 ]
322 }
323
324 pub fn inflate_provider_update(
325 &self,
326 mainconfig: &MainConfig,
327 status: &Status,
328 item: &Item,
329 ) -> Vec<(String, String)> {
280330 let playlist_item = item.fullplaylist().unwrap();
331
281332 vec![
282333 (
283334 String::from("url"),
284 match self.provider {
335 match status.provider {
285336 Provider::YouTube => {
286337 format!("https://www.youtube.com/playlist?list={}", playlist_item.id)
287338 }
@@ -291,10 +342,9 @@ impl SinglePlaylistItem {
291342 ),
292343 },
293344 ),
294 (String::from("id"), playlist_item.id.clone()),
295345 (
296346 String::from("all-videos"),
297 match self.provider {
347 match status.provider {
298348 Provider::YouTube => playlist_item
299349 .videos
300350 .iter()
@@ -317,10 +367,9 @@ impl SinglePlaylistItem {
317367 .join(" "),
318368 },
319369 ),
320 (String::from("channel-id"), playlist_item.channel_id.clone()),
321370 (
322371 String::from("channel-url"),
323 match self.provider {
372 match status.provider {
324373 Provider::YouTube => format!(
325374 "https://www.youtube.com/channel/{}",
326375 playlist_item.channel_id
@@ -357,7 +406,12 @@ impl SingleItemType {
357406 }
358407 }
359408
360 pub fn inflate(&self, mainconfig: &MainConfig, item: &Option<Item>) -> Vec<(String, String)> {
409 pub fn inflate_load(
410 &self,
411 mainconfig: &MainConfig,
412 status: &Status,
413 item: &Option<Item>,
414 ) -> Vec<(String, String)> {
361415 let item = if let Some(item) = item.as_ref() {
362416 item
363417 } else {
@@ -365,8 +419,31 @@ impl SingleItemType {
365419 };
366420
367421 match self {
368 Self::Video(singlevideoitem) => singlevideoitem.inflate(mainconfig, item),
369 Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate(mainconfig, item),
422 Self::Video(singlevideoitem) => singlevideoitem.inflate_load(mainconfig, status, item),
423 Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate_load(item),
424 Self::None => Vec::new(),
425 }
426 }
427
428 pub fn inflate_provider_update(
429 &self,
430 mainconfig: &MainConfig,
431 status: &Status,
432 item: &Option<Item>,
433 ) -> Vec<(String, String)> {
434 let item = if let Some(item) = item.as_ref() {
435 item
436 } else {
437 return Vec::new();
438 };
439
440 match self {
441 Self::Video(singlevideoitem) => {
442 singlevideoitem.inflate_provider_update(mainconfig, status, item)
443 }
444 Self::Playlist(singleplaylistitem) => {
445 singleplaylistitem.inflate_provider_update(mainconfig, status, item)
446 }
370447 Self::None => Vec::new(),
371448 }
372449 }
@@ -404,17 +481,20 @@ impl SingleItem {
404481 videos_view,
405482 ..
406483 } = &mut **singleplaylistitem;
407 if videos_view.items.is_empty() {
484 if videos_view.items.is_empty() || videos_view.selected == 0 {
408485 hovered_video.item = None;
409486 return;
410487 }
411488
412 if self.item.as_ref().unwrap().fullplaylist().unwrap().videos[videos_view.selected].id()
413 != hovered_video.item.as_ref().unwrap().id()
489 if hovered_video.item.is_none()
490 || self.item.as_ref().unwrap().fullplaylist().unwrap().videos
491 [videos_view.selected - 1]
492 .id()
493 != hovered_video.item.as_ref().unwrap().id()
414494 {
415495 hovered_video.item = Some(
416496 self.item.as_ref().unwrap().fullplaylist().unwrap().videos
417 [videos_view.selected]
497 [videos_view.selected - 1]
418498 .clone(),
419499 );
420500 }
@@ -433,27 +513,14 @@ impl SingleItem {
433513 .1
434514 .clone();
435515
436 match command_string.as_str() {
437 // checks for special cases that the items should consume the command
438 // instead of running it
439 "%switch-provider%" => {
440 singlevideoitem.provider.rotate();
441 singlevideoitem.update_provider();
442 *framework.data.global.get_mut::<Message>().unwrap() = Message::Success(
443 format!("Switched provider to {}", singlevideoitem.provider.as_str()),
444 );
445 }
446 _ => {
447 // check if the command starts with an ':' which case should be captured
448 framework
449 .data
450 .state
451 .get_mut::<Tasks>()
452 .unwrap()
453 .priority
454 .push(Task::Command(apply_envs(command_string)));
455 }
456 }
516 // check if the command starts with an ':' which case should be captured
517 framework
518 .data
519 .state
520 .get_mut::<Tasks>()
521 .unwrap()
522 .priority
523 .push(Task::Command(apply_envs(command_string)));
457524 }
458525 SingleItemType::Playlist(singleplaylistitem) => {
459526 let command_string = singleplaylistitem.commands
@@ -472,11 +539,6 @@ impl SingleItem {
472539 *framework.data.global.get_mut::<Message>().unwrap() =
473540 Message::Success(String::from("Switched view"));
474541 }
475 "%switch-provider%" => {
476 singleplaylistitem.provider.rotate();
477 singleplaylistitem.update_provider();
478 }
479 // same as before if string is not a special case then the run the command
480542 _ => {
481543 // check if the command starts with an ':' which case should be captured
482544 framework
@@ -500,14 +562,6 @@ impl SingleItem {
500562 .priority
501563 .push(Task::RenderAll);
502564 }
503
504 pub fn update_provider(&mut self) {
505 match &mut self.r#type {
506 SingleItemType::Video(singlevideoitem) => singlevideoitem.update_provider(),
507 SingleItemType::Playlist(singleplaylistitem) => singleplaylistitem.update_provider(),
508 SingleItemType::None => {}
509 }
510 }
511565}
512566
513567impl FrameworkItem for SingleItem {
@@ -523,6 +577,25 @@ impl FrameworkItem for SingleItem {
523577 return;
524578 }
525579
580 if framework
581 .data
582 .global
583 .get::<Status>()
584 .unwrap()
585 .provider_updated
586 {
587 set_envs(
588 self.r#type
589 .inflate_provider_update(
590 framework.data.global.get::<MainConfig>().unwrap(),
591 framework.data.global.get::<Status>().unwrap(),
592 &self.item,
593 )
594 .into_iter(),
595 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
596 );
597 }
598
526599 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
527600 self.update_appearance(appearance, &info);
528601
@@ -538,6 +611,18 @@ impl FrameworkItem for SingleItem {
538611 match &mut self.r#type {
539612 SingleItemType::Video(typeinfo) => {
540613 // 2 by 1 grid, item info in the first cell and textlist at the second
614 typeinfo.update_provider().into_iter().for_each(|index| {
615 typeinfo.textlist.items[index] = typeinfo.commands[index].0.clone().replace(
616 "${provider}",
617 framework
618 .data
619 .global
620 .get::<Status>()
621 .unwrap()
622 .provider
623 .as_str(),
624 )
625 });
541626 self.iteminfo
542627 .render(frame, framework, chunks[0], popup_render, info);
543628 typeinfo.textlist.set_height(chunks[1].height);
@@ -552,6 +637,19 @@ impl FrameworkItem for SingleItem {
552637 self.iteminfo
553638 .render(frame, framework, chunks[0], popup_render, info);
554639 if typeinfo.is_commands_view {
640 typeinfo.update_provider().into_iter().for_each(|index| {
641 typeinfo.commands_view.items[index] =
642 typeinfo.commands[index].0.clone().replace(
643 "${provider}",
644 framework
645 .data
646 .global
647 .get::<Status>()
648 .unwrap()
649 .provider
650 .as_str(),
651 )
652 });
555653 typeinfo.commands_view.set_height(chunks[1].height);
556654 frame.render_widget(typeinfo.commands_view.clone(), chunks[1]);
557655 } else {
@@ -597,7 +695,6 @@ impl FrameworkItem for SingleItem {
597695 SingleItemPage::Video(id) => {
598696 self.r#type = SingleItemType::Video(SingleVideoItem::new(
599697 framework.data.global.get::<CommandsConfig>().unwrap(),
600 framework.data.global.get::<MainConfig>().unwrap(),
601698 ));
602699 let video = Item::from_full_video(client.video(id, None)?, mainconfig.image_index);
603700 if mainconfig.images.display() {
@@ -612,7 +709,6 @@ impl FrameworkItem for SingleItem {
612709 self.r#type = SingleItemType::Playlist(
613710 SinglePlaylistItem::new(
614711 framework.data.global.get::<CommandsConfig>().unwrap(),
615 framework.data.global.get::<MainConfig>().unwrap(),
616712 videos,
617713 )
618714 .into(),
@@ -632,9 +728,24 @@ impl FrameworkItem for SingleItem {
632728 self.iteminfo.item = self.item.clone();
633729 // need to update provider every time the item loads or else it will display `${provider}`
634730 // instead of the actual provider (e.g. `YouTube`)
635 self.update_provider();
636731 set_envs(
637 self.r#type.inflate(mainconfig, &self.item).into_iter(),
732 self.r#type
733 .inflate_load(
734 mainconfig,
735 framework.data.global.get::<Status>().unwrap(),
736 &self.item,
737 )
738 .into_iter(),
739 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
740 );
741 set_envs(
742 self.r#type
743 .inflate_provider_update(
744 mainconfig,
745 framework.data.global.get::<Status>().unwrap(),
746 &self.item,
747 )
748 .into_iter(),
638749 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
639750 );
640751
src/main.rs +7 −4
@@ -14,10 +14,9 @@ use youtube_tui::{exit, global::functions::text_command, init, run};
1414// 3. restore the terminal
1515// 4. unwrap errors
1616fn main() -> Result<(), Box<dyn Error>> {
17 let args = env::args().skip(1).collect::<Vec<_>>();
18 let args_strs = args.iter().map(|s| s.as_str()).collect::<Vec<_>>();
17 let args = env::args().skip(1).collect::<Vec<_>>().join(" ");
1918
20 if let Some(s) = text_command(&args_strs) {
19 if let Some(s) = text_command(&args) {
2120 println!("{s}");
2221 return Ok(());
2322 }
@@ -32,7 +31,11 @@ fn main() -> Result<(), Box<dyn Error>> {
3231 let mut terminal = Terminal::new(backend)?;
3332
3433 let res = (|| -> Result<(), Box<dyn Error>> {
35 init(&mut framework, &mut terminal, &args_strs)?;
34 init(
35 &mut framework,
36 &mut terminal,
37 if args.is_empty() { None } else { Some(&args) },
38 )?;
3639 run(&mut terminal, &mut framework)?;
3740 Ok(())
3841 })();
src/run.rs +28 −15
@@ -7,10 +7,10 @@ use tui_additions::{
77};
88
99use crate::{
10 config::{KeyBindingsConfig, MainConfig},
10 config::{CommandBindings, KeyBindingsConfig, MainConfig},
1111 global::{
12 functions::{clear_envs, command_capture, set_envs},
13 structs::{KeyAction, Message, StateEnvs, Status, Task, Tasks},
12 functions::{apply_envs, clear_envs, command_capture, run_command, set_envs},
13 structs::{KeyAction, Message, Page, StateEnvs, Status, Task, Tasks},
1414 },
1515};
1616
@@ -96,6 +96,25 @@ pub fn run(
9696 }
9797 }
9898 Event::Key(key) => {
99 let command_to_run = apply_envs(
100 framework
101 .data
102 .global
103 .get::<CommandBindings>()
104 .unwrap()
105 .get_command(&key, framework.data.state.get::<Page>().unwrap()),
106 );
107 if !command_to_run.is_empty() {
108 run_command(&command_to_run, framework, terminal);
109 framework
110 .data
111 .state
112 .get_mut::<Tasks>()
113 .unwrap()
114 .priority
115 .push(Task::RenderAll);
116 }
117
99118 // 1. get the corresponding action
100119 // 2. check if action is deselect, if yes, deselect
101120 // 3. check is anything is selected, if yes, run `.key_event()` with the key
@@ -194,12 +213,9 @@ pub fn run(
194213 "This is already the beginning of history",
195214 ))
196215 } else {
197 framework
198 .data
199 .global
200 .get_mut::<Status>()
201 .unwrap()
202 .render_image = true;
216 let status = framework.data.global.get_mut::<Status>().unwrap();
217 status.render_image = true;
218 status.provider_updated = true;
203219 framework
204220 .data
205221 .state
@@ -219,12 +235,9 @@ pub fn run(
219235 "This is already the beginning of history",
220236 ))
221237 } else {
222 framework
223 .data
224 .global
225 .get_mut::<Status>()
226 .unwrap()
227 .render_image = true;
238 let status = framework.data.global.get_mut::<Status>().unwrap();
239 status.render_image = true;
240 status.provider_updated = true;
228241 framework
229242 .data
230243 .state