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;
8/// Stores combinations of label and commands 8/// Stores combinations of label and commands
9#[derive(Clone)] 9#[derive(Clone)]
10pub struct CommandsConfig { 10pub struct CommandsConfig {
11 pub launch_command: String,
11 pub video: Vec<(String, String)>, 12 pub video: Vec<(String, String)>,
12 pub playlist: Vec<(String, String)>, 13 pub playlist: Vec<(String, String)>,
13} 14}
@@ -19,6 +20,7 @@ impl Key for CommandsConfig {
19impl From<CommandsConfigSerde> for CommandsConfig { 20impl From<CommandsConfigSerde> for CommandsConfig {
20 fn from(original: CommandsConfigSerde) -> Self { 21 fn from(original: CommandsConfigSerde) -> Self {
21 Self { 22 Self {
23 launch_command: original.launch_command,
22 video: original 24 video: original
23 .video 25 .video
24 .into_iter() 26 .into_iter()
@@ -37,6 +39,8 @@ impl From<CommandsConfigSerde> for CommandsConfig {
37// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look 39// uses vector to keep the ordering of the commands, and hashmap to have that key - value pair look
38#[derive(Serialize, Deserialize, Clone)] 40#[derive(Serialize, Deserialize, Clone)]
39pub struct CommandsConfigSerde { 41pub struct CommandsConfigSerde {
42 #[serde(default = "launch_command_default")]
43 pub launch_command: String,
40 #[serde(default = "video_default")] 44 #[serde(default = "video_default")]
41 pub video: Vec<HashMap<String, String>>, 45 pub video: Vec<HashMap<String, String>>,
42 #[serde(default = "playlist_default")] 46 #[serde(default = "playlist_default")]
@@ -50,6 +54,7 @@ impl ConfigTrait for CommandsConfigSerde {
50impl Default for CommandsConfigSerde { 54impl Default for CommandsConfigSerde {
51 fn default() -> Self { 55 fn default() -> Self {
52 Self { 56 Self {
57 launch_command: launch_command_default(),
53 video: video_default(), 58 video: video_default(),
54 playlist: playlist_default(), 59 playlist: playlist_default(),
55 } 60 }
@@ -59,6 +64,10 @@ impl Default for CommandsConfigSerde {
59// `${label}` will be replaced by the values set in `main.yml` in `env` 64// `${label}` will be replaced by the values set in `main.yml` in `env`
60// Different pages may contain different `env`s (for example `url` is different in each page) 65// Different pages may contain different `env`s (for example `url` is different in each page)
61 66
67fn launch_command_default() -> String {
68 String::from("loadpage popular ;; flush ;; history clear")
69}
70
62fn video_default() -> Vec<HashMap<String, String>> { 71fn video_default() -> Vec<HashMap<String, String>> {
63 vec![ 72 vec![
64 HashMap::from([( 73 HashMap::from([(
@@ -97,7 +106,7 @@ fn video_default() -> Vec<HashMap<String, String>> {
97 )]), 106 )]),
98 HashMap::from([( 107 HashMap::from([(
99 String::from("Mode: ${provider}"), 108 String::from("Mode: ${provider}"),
100 String::from("%switch-provider%"), 109 String::from("switchprovider"),
101 )]), 110 )]),
102 ] 111 ]
103} 112}
@@ -139,7 +148,7 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
139 )]), 148 )]),
140 HashMap::from([( 149 HashMap::from([(
141 String::from("Mode: ${provider}"), 150 String::from("Mode: ${provider}"),
142 String::from("%switch-provider%"), 151 String::from("switchprovider"),
143 )]), 152 )]),
144 ] 153 ]
145} 154}
src/config/mod.rs +2
@@ -11,5 +11,7 @@ mod keybindings;
11pub use keybindings::*; 11pub use keybindings::*;
12mod commands; 12mod commands;
13pub use commands::*; 13pub use commands::*;
14mod commandbindings;
15pub use commandbindings::*;
14 16
15pub mod serde; 17pub mod serde;
src/global/functions/run_command.rs +56 −48
@@ -6,20 +6,20 @@ use crate::{
6 }, 6 },
7 load_configs, 7 load_configs,
8}; 8};
9use std::{
10 io::Stdout,
11 env,
12 thread,
13};
14use run_script::ScriptOptions; 9use run_script::ScriptOptions;
10use std::{env, io::Stdout, thread};
15use tui::{backend::CrosstermBackend, Terminal}; 11use tui::{backend::CrosstermBackend, Terminal};
16use tui_additions::framework::Framework; 12use tui_additions::framework::Framework;
17 13
18use super::{fake_rand_range, from_channel_url, from_playlist_url, from_video_url, set_clipboard}; 14use super::{fake_rand_range, from_channel_url, from_playlist_url, from_video_url, set_clipboard};
19 15
20/// runs text command - command from the command line (not TUI) which response is just a string 16/// runs text command - command from the command line (not TUI) which response is just a string
21pub fn text_command(command: &[&str]) -> Option<String> { 17pub fn text_command(command: &str) -> Option<String> {
22 match command { 18 match command
19 .split_ascii_whitespace()
20 .collect::<Vec<_>>()
21 .as_slice()
22 {
23 ["help"] => Some(String::from(HELP_MSG)), 23 ["help"] => Some(String::from(HELP_MSG)),
24 ["version"] => Some(format!( 24 ["version"] => Some(format!(
25 "{} {}", 25 "{} {}",
@@ -30,25 +30,48 @@ pub fn text_command(command: &[&str]) -> Option<String> {
30 } 30 }
31} 31}
32 32
33/// runs a command in the TUI, returns true if its a loadpage command, false if not
34pub fn run_command( 33pub 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(
35 command: &[&str], 52 command: &[&str],
36 framework: &mut Framework, 53 framework: &mut Framework,
37 terminal: &mut Terminal<CrosstermBackend<Stdout>>, 54 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
38) -> bool { 55) {
39 // match a command splitted by space to a bunch of avaliable commands 56 // match a command splitted by space to a bunch of avaliable commands
40 match command { 57 match command {
41 [] => false, 58 [] => {}
42 ["help"] | ["h"] => { 59 ["help"] | ["h"] => {
43 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from( 60 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
44 "Avaliable commands can be viewed by running `youtube-tui help` in terminal", 61 "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
45 )); 62 ));
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()))
47 } 71 }
48 ["loadpage"] => { 72 ["loadpage"] => {
49 *framework.data.global.get_mut::<Message>().unwrap() = 73 *framework.data.global.get_mut::<Message>().unwrap() =
50 Message::Message(String::from("Usage: `loadpage {page}`")); 74 Message::Message(String::from("Usage: `loadpage {page}`"));
51 false
52 } 75 }
53 // loads a given page 76 // loads a given page
54 ["loadpage", page, ..] => { 77 ["loadpage", page, ..] => {
@@ -60,7 +83,7 @@ pub fn run_command(
60 if command.len() == 2 { 83 if command.len() == 2 {
61 *framework.data.global.get_mut::<Message>().unwrap() = 84 *framework.data.global.get_mut::<Message>().unwrap() =
62 Message::Message(String::from("Usage: `loadpage channel {id/url}`")); 85 Message::Message(String::from("Usage: `loadpage channel {id/url}`"));
63 return false; 86 return;
64 } 87 }
65 88
66 match from_channel_url(command[2]) { 89 match from_channel_url(command[2]) {
@@ -71,7 +94,7 @@ pub fn run_command(
71 Err(e) => { 94 Err(e) => {
72 *framework.data.global.get_mut::<Message>().unwrap() = 95 *framework.data.global.get_mut::<Message>().unwrap() =
73 Message::Error(e); 96 Message::Error(e);
74 return false; 97 return;
75 } 98 }
76 } 99 }
77 } 100 }
@@ -79,7 +102,7 @@ pub fn run_command(
79 if command.len() == 2 { 102 if command.len() == 2 {
80 *framework.data.global.get_mut::<Message>().unwrap() = 103 *framework.data.global.get_mut::<Message>().unwrap() =
81 Message::Message(String::from("Usage: `loadpage video {id/url}`")); 104 Message::Message(String::from("Usage: `loadpage video {id/url}`"));
82 return false; 105 return;
83 } 106 }
84 107
85 match from_video_url(command[2]) { 108 match from_video_url(command[2]) {
@@ -87,7 +110,7 @@ pub fn run_command(
87 Err(e) => { 110 Err(e) => {
88 *framework.data.global.get_mut::<Message>().unwrap() = 111 *framework.data.global.get_mut::<Message>().unwrap() =
89 Message::Error(e); 112 Message::Error(e);
90 return false; 113 return;
91 } 114 }
92 } 115 }
93 } 116 }
@@ -95,7 +118,7 @@ pub fn run_command(
95 if command.len() == 2 { 118 if command.len() == 2 {
96 *framework.data.global.get_mut::<Message>().unwrap() = 119 *framework.data.global.get_mut::<Message>().unwrap() =
97 Message::Message(String::from("Usage: `loadpage playlist {id/url}`")); 120 Message::Message(String::from("Usage: `loadpage playlist {id/url}`"));
98 return false; 121 return;
99 } 122 }
100 123
101 match from_playlist_url(command[2]) { 124 match from_playlist_url(command[2]) {
@@ -103,7 +126,7 @@ pub fn run_command(
103 Err(e) => { 126 Err(e) => {
104 *framework.data.global.get_mut::<Message>().unwrap() = 127 *framework.data.global.get_mut::<Message>().unwrap() =
105 Message::Error(e); 128 Message::Error(e);
106 return false; 129 return;
107 } 130 }
108 } 131 }
109 } 132 }
@@ -111,7 +134,7 @@ pub fn run_command(
111 if command.len() == 2 { 134 if command.len() == 2 {
112 *framework.data.global.get_mut::<Message>().unwrap() = 135 *framework.data.global.get_mut::<Message>().unwrap() =
113 Message::Message(String::from("Usage: `search {query}`")); 136 Message::Message(String::from("Usage: `search {query}`"));
114 return true; 137 return;
115 } 138 }
116 139
117 // search for a query, although the command is matched as an array, the original query can 140 // search for a query, although the command is matched as an array, the original query can
@@ -137,37 +160,34 @@ pub fn run_command(
137 .priority 160 .priority
138 .push(Task::LoadPage(page)) 161 .push(Task::LoadPage(page))
139 } 162 }
140
141 true
142 } 163 }
143 // redirects to the relevant `loadpage` command 164 // redirects to the relevant `loadpage` command
144 ["popular"] => run_command(&["loadpage", "popular"], framework, terminal), 165 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
145 ["trending"] => run_command(&["loadpage", "trending"], framework, terminal), 166 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
146 ["watchhistory"] => run_command(&["loadpage", "watchhistory"], framework, terminal), 167 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
147 ["search"] => run_command(&["loadpage", "search"], framework, terminal), 168 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
148 ["search", ..] => run_command( 169 ["search", ..] => run_single_command(
149 &format!("loadpage search {}", command[1..].join(" ")) 170 &format!("loadpage search {}", command[1..].join(" "))
150 .split(' ') 171 .split(' ')
151 .collect::<Vec<&str>>(), 172 .collect::<Vec<&str>>(),
152 framework, 173 framework,
153 terminal, 174 terminal,
154 ), 175 ),
155 ["channel"] => run_command(&["loadpage", "channel"], framework, terminal), 176 ["channel"] => run_single_command(&["loadpage", "channel"], framework, terminal),
156 ["channel", identifier] => { 177 ["channel", identifier] => {
157 run_command(&["loadpage", "channel", *identifier], framework, terminal) 178 run_single_command(&["loadpage", "channel", *identifier], framework, terminal)
158 } 179 }
159 ["video"] => run_command(&["loadpage", "video"], framework, terminal), 180 ["video"] => run_single_command(&["loadpage", "video"], framework, terminal),
160 ["video", identifier] => { 181 ["video", identifier] => {
161 run_command(&["loadpage", "video", *identifier], framework, terminal) 182 run_single_command(&["loadpage", "video", *identifier], framework, terminal)
162 } 183 }
163 ["playlist"] => run_command(&["loadpage", "playlist"], framework, terminal), 184 ["playlist"] => run_single_command(&["loadpage", "playlist"], framework, terminal),
164 ["playlist", identifier] => { 185 ["playlist", identifier] => {
165 run_command(&["loadpage", "playlist", *identifier], framework, terminal) 186 run_single_command(&["loadpage", "playlist", *identifier], framework, terminal)
166 } 187 }
167 ["history"] => { 188 ["history"] => {
168 *framework.data.global.get_mut::<Message>().unwrap() = 189 *framework.data.global.get_mut::<Message>().unwrap() =
169 Message::Message(String::from("Usage: `history [back/clear]`")); 190 Message::Message(String::from("Usage: `history [back/clear]`"))
170 false
171 } 191 }
172 ["history", "back"] | ["back"] => { 192 ["history", "back"] | ["back"] => {
173 let _ = framework.revert_last_history(); 193 let _ = framework.revert_last_history();
@@ -185,18 +205,16 @@ pub fn run_command(
185 .unwrap() 205 .unwrap()
186 .priority 206 .priority
187 .push(Task::RenderAll); 207 .push(Task::RenderAll);
188 run_command(&["flush"], framework, terminal); 208 run_single_command(&["flush"], framework, terminal);
189 framework 209 framework
190 .data 210 .data
191 .global 211 .global
192 .get_mut::<Status>() 212 .get_mut::<Status>()
193 .unwrap() 213 .unwrap()
194 .render_image = true; 214 .render_image = true;
195 false
196 } 215 }
197 ["history", "clear"] => { 216 ["history", "clear"] => {
198 framework.clear_history(); 217 framework.clear_history();
199 false
200 } 218 }
201 ["flush"] => loop { 219 ["flush"] => loop {
202 // runs all stacked actions 220 // runs all stacked actions
@@ -204,7 +222,7 @@ pub fn run_command(
204 let _res = tasks.run(framework, terminal); 222 let _res = tasks.run(framework, terminal);
205 continue; 223 continue;
206 } 224 }
207 break false; 225 break;
208 }, 226 },
209 ["reload"] | ["r"] => { 227 ["reload"] | ["r"] => {
210 framework 228 framework
@@ -214,7 +232,6 @@ pub fn run_command(
214 .unwrap() 232 .unwrap()
215 .priority 233 .priority
216 .push(Task::Reload); 234 .push(Task::Reload);
217 false
218 } 235 }
219 ["reload", "config"] | ["reload", "configs"] | ["r", "config"] | ["r", "configs"] => { 236 ["reload", "config"] | ["reload", "configs"] | ["r", "config"] | ["r", "configs"] => {
220 *framework.data.global.get_mut::<Message>().unwrap() = 237 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -222,17 +239,14 @@ pub fn run_command(
222 Ok(()) => Message::Success(String::from("Config files have been reloaded")), 239 Ok(()) => Message::Success(String::from("Config files have been reloaded")),
223 Err(e) => Message::Error(e.to_string()), 240 Err(e) => Message::Error(e.to_string()),
224 }; 241 };
225 false
226 } 242 }
227 ["q"] | ["quit"] | ["x"] | ["exit"] => { 243 ["q"] | ["quit"] | ["x"] | ["exit"] => {
228 framework.data.global.get_mut::<Status>().unwrap().exit = true; 244 framework.data.global.get_mut::<Status>().unwrap().exit = true;
229 false
230 } 245 }
231 ["hello", "world"] => { 246 ["hello", "world"] => {
232 let index = fake_rand_range(0, HELLO_WORLDS.len() as i64) as usize; 247 let index = fake_rand_range(0, HELLO_WORLDS.len() as i64) as usize;
233 *framework.data.global.get_mut::<Message>().unwrap() = 248 *framework.data.global.get_mut::<Message>().unwrap() =
234 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index])); 249 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
235 false
236 } 250 }
237 ["version"] | ["v"] => { 251 ["version"] | ["v"] => {
238 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!( 252 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!(
@@ -240,12 +254,10 @@ pub fn run_command(
240 env!("CARGO_PKG_NAME"), 254 env!("CARGO_PKG_NAME"),
241 env!("CARGO_PKG_VERSION") 255 env!("CARGO_PKG_VERSION")
242 )); 256 ));
243 false
244 } 257 }
245 ["run"] => { 258 ["run"] => {
246 *framework.data.global.get_mut::<Message>().unwrap() = 259 *framework.data.global.get_mut::<Message>().unwrap() =
247 Message::Message(String::from("Usage: run [command]")); 260 Message::Message(String::from("Usage: run [command]"));
248 false
249 } 261 }
250 ["run", ..] => { 262 ["run", ..] => {
251 let command = command[1..].join(" "); 263 let command = command[1..].join(" ");
@@ -254,23 +266,19 @@ pub fn run_command(
254 thread::spawn(move || { 266 thread::spawn(move || {
255 run_script::run(&command, &Vec::new(), &ScriptOptions::new()).unwrap(); 267 run_script::run(&command, &Vec::new(), &ScriptOptions::new()).unwrap();
256 }); 268 });
257 false
258 } 269 }
259 ["copy"] | ["cp"] => { 270 ["copy"] | ["cp"] => {
260 *framework.data.global.get_mut::<Message>().unwrap() = 271 *framework.data.global.get_mut::<Message>().unwrap() =
261 Message::Message(String::from("Usage: copy [text]")); 272 Message::Message(String::from("Usage: copy [text]"));
262 false
263 } 273 }
264 ["copy", ..] | ["cp", ..] => { 274 ["copy", ..] | ["cp", ..] => {
265 set_clipboard(command[1..].join(" ")); 275 set_clipboard(command[1..].join(" "));
266 *framework.data.global.get_mut::<Message>().unwrap() = 276 *framework.data.global.get_mut::<Message>().unwrap() =
267 Message::Success(String::from("Copied to clipboad")); 277 Message::Success(String::from("Copied to clipboad"));
268 false
269 } 278 }
270 _ => { 279 _ => {
271 *framework.data.global.get_mut::<Message>().unwrap() = 280 *framework.data.global.get_mut::<Message>().unwrap() =
272 Message::Error(format!("Unknown command: `{}`", command.join(" "))); 281 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
273 false
274 } 282 }
275 } 283 }
276} 284}
src/global/structs/status.rs +8
@@ -2,6 +2,8 @@ use tui::layout::Rect;
2use tui_additions::widgets::TextField; 2use tui_additions::widgets::TextField;
3use typemap::Key; 3use typemap::Key;
4 4
5use crate::config::Provider;
6
5/// a struct for storing different info, currently only stores one info 7/// a struct for storing different info, currently only stores one info
6#[derive(Clone)] 8#[derive(Clone)]
7pub struct Status { 9pub struct Status {
@@ -17,6 +19,10 @@ pub struct Status {
17 pub exit: bool, 19 pub exit: bool,
18 /// stores the area of the previously rendered frame 20 /// stores the area of the previously rendered frame
19 pub prev_frame: Option<Rect>, 21 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,
20} 26}
21 27
22impl Key for Status { 28impl Key for Status {
@@ -32,6 +38,8 @@ impl Default for Status {
32 command_capture: None, 38 command_capture: None,
33 exit: false, 39 exit: false,
34 prev_frame: None, 40 prev_frame: None,
41 provider: Provider::YouTube,
42 provider_updated: false,
35 } 43 }
36 } 44 }
37} 45}
src/global/structs/tasks.rs +1 −5
@@ -83,11 +83,7 @@ impl TaskQueue {
83 // if there is any commands, run them first as they may modify data, which is rendered 83 // if there is any commands, run them first as they may modify data, which is rendered
84 // later in this function 84 // later in this function
85 for command in self.commands.iter() { 85 for command in self.commands.iter() {
86 run_command( 86 run_command(command, framework, terminal);
87 &command.split_whitespace().collect::<Vec<_>>(),
88 framework,
89 terminal,
90 );
91 } 87 }
92 88
93 if self.clear_all { 89 if self.clear_all {
src/init.rs +29 −14
@@ -1,7 +1,7 @@
1use crate::{ 1use crate::{
2 config::{ 2 config::{
3 AppearanceConfig, CommandsConfig, CommandsConfigSerde, KeyBindingsConfig, MainConfig, 3 AppearanceConfig, CommandBindings, CommandBindingsSerde, CommandsConfig,
4 MinDimentions, PagesConfig, Search, 4 CommandsConfigSerde, KeyBindingsConfig, MainConfig, MinDimentions, PagesConfig, Search,
5 }, 5 },
6 global::{ 6 global::{
7 functions::run_command, 7 functions::run_command,
@@ -22,7 +22,7 @@ use tui_additions::framework::{Framework, FrameworkClean};
22pub fn init( 22pub fn init(
23 framework: &mut Framework, 23 framework: &mut Framework,
24 terminal: &mut Terminal<CrosstermBackend<Stdout>>, 24 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
25 command: &[&str], 25 command: Option<&str>,
26) -> Result<(), Box<dyn Error>> { 26) -> Result<(), Box<dyn Error>> {
27 // creating files 27 // creating files
28 let home_dir = home_dir().unwrap(); 28 let home_dir = home_dir().unwrap();
@@ -41,8 +41,13 @@ pub fn init(
41 // watch history init 41 // watch history init
42 WatchHistory::init_move(); 42 WatchHistory::init_move();
43 43
44 load_configs(&mut framework.split_clean().0).ok();
45
44 framework.data.global.insert::<Message>(Message::None); 46 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 });
46 51
47 framework.data.state.insert::<Tasks>(Tasks::default()); 52 framework.data.state.insert::<Tasks>(Tasks::default());
48 framework.data.state.insert::<Page>(Page::default()); 53 framework.data.state.insert::<Page>(Page::default());
@@ -50,14 +55,24 @@ pub fn init(
50 .data 55 .data
51 .state 56 .state
52 .insert::<MinDimentions>(MinDimentions::default()); 57 .insert::<MinDimentions>(MinDimentions::default());
58 framework
59 .data
60 .state
61 .insert::<StateEnvs>(StateEnvs::default());
53 62
54 load_configs(&mut framework.split_clean().0).ok(); 63 run_command(
55 64 command.unwrap_or(
56 if !run_command(command, framework, terminal) { 65 &framework
57 run_command(&["loadpage", "popular"], framework, terminal); 66 .data
58 } 67 .global
59 run_command(&["flush"], framework, terminal); 68 .get::<CommandsConfig>()
60 run_command(&["history", "clear"], framework, terminal); 69 .unwrap()
70 .launch_command
71 .clone(),
72 ),
73 framework,
74 terminal,
75 );
61 Ok(()) 76 Ok(())
62} 77}
63 78
@@ -97,11 +112,11 @@ pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>
97 .data 112 .data
98 .global 113 .global
99 .insert::<KeyBindingsConfig>(KeyBindingsConfig::load()?); 114 .insert::<KeyBindingsConfig>(KeyBindingsConfig::load()?);
100 framework.data.state.insert::<Search>(*Search::load()?);
101 framework 115 framework
102 .data 116 .data
103 .state 117 .global
104 .insert::<StateEnvs>(StateEnvs::default()); 118 .insert::<CommandBindings>((*CommandBindingsSerde::load()?).into().unwrap());
119 framework.data.state.insert::<Search>(*Search::load()?);
105 120
106 Ok(()) 121 Ok(())
107} 122}
src/items/itemlist.rs +70 −5
@@ -11,14 +11,14 @@ use tui_additions::{
11 11
12use super::ItemInfo; 12use super::ItemInfo;
13use crate::{ 13use crate::{
14 config::{AppearanceConfig, KeyBindingsConfig, MainConfig, Search}, 14 config::{AppearanceConfig, KeyBindingsConfig, MainConfig, Provider, Search},
15 global::{ 15 global::{
16 functions::download_all_images, 16 functions::{download_all_images, set_envs},
17 structs::{ 17 structs::{
18 ChannelDisplayPage, ChannelDisplayPageType, FullChannelItem, FullPlaylistItem, 18 ChannelDisplayPage, ChannelDisplayPageType, FullChannelItem, FullPlaylistItem,
19 FullVideoItem, InvidiousClient, Item, KeyAction, MainMenuPage, Message, 19 FullVideoItem, InvidiousClient, Item, KeyAction, MainMenuPage, Message,
20 MiniChannelItem, MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, Status, Task, 20 MiniChannelItem, MiniPlaylistItem, MiniVideoItem, Page, SingleItemPage, StateEnvs,
21 Tasks, WatchHistory, 21 Status, Task, Tasks, WatchHistory,
22 }, 22 },
23 }, 23 },
24}; 24};
@@ -34,7 +34,48 @@ pub struct ItemList {
34} 34}
35 35
36impl ItemList { 36impl 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
38 fn update_appearance( 79 fn update_appearance(
39 &mut self, 80 &mut self,
40 appearance: &AppearanceConfig, 81 appearance: &AppearanceConfig,
@@ -148,6 +189,20 @@ impl FrameworkItem for ItemList {
148 return; 189 return;
149 } 190 }
150 191
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
151 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap(); 206 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
152 let mainconfig = framework.data.global.get::<MainConfig>().unwrap(); 207 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
153 self.update_appearance(appearance, mainconfig, &info); 208 self.update_appearance(appearance, mainconfig, &info);
@@ -260,6 +315,16 @@ impl FrameworkItem for ItemList {
260 self.textlist.set_items(&self.items).unwrap(); 315 self.textlist.set_items(&self.items).unwrap();
261 self.update(); 316 self.update();
262 317
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
263 Ok(()) 328 Ok(())
264 } 329 }
265 330
src/items/singleitem.rs +192 −81
@@ -54,7 +54,6 @@ pub enum SingleItemType {
54pub struct SingleVideoItem { 54pub struct SingleVideoItem {
55 pub textlist: TextList, 55 pub textlist: TextList,
56 pub commands: Vec<(String, String)>, 56 pub commands: Vec<(String, String)>,
57 pub provider: Provider,
58} 57}
59 58
60#[derive(Clone)] 59#[derive(Clone)]
@@ -64,11 +63,10 @@ pub struct SinglePlaylistItem {
64 pub commands: Vec<(String, String)>, 63 pub commands: Vec<(String, String)>,
65 pub is_commands_view: bool, 64 pub is_commands_view: bool,
66 pub hovered_video: ItemInfo, 65 pub hovered_video: ItemInfo,
67 pub provider: Provider,
68} 66}
69 67
70impl SingleVideoItem { 68impl SingleVideoItem {
71 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig) -> Self { 69 pub fn new(commands: &CommandsConfig) -> Self {
72 Self { 70 Self {
73 textlist: TextList::default() 71 textlist: TextList::default()
74 .items( 72 .items(
@@ -85,21 +83,17 @@ impl SingleVideoItem {
85 .into_iter() 83 .into_iter()
86 .map(|(display, command)| (display, command)) 84 .map(|(display, command)| (display, command))
87 .collect(), 85 .collect(),
88 provider: mainconfig.provider,
89 } 86 }
90 } 87 }
91 88
92 /// updates the %switch-provider% command in the list 89 /// find all occurances of ${provider}
93 pub fn update_provider(&mut self) { 90 pub fn update_provider(&mut self) -> Vec<usize> {
94 self.commands 91 self.commands
95 .iter() 92 .iter()
96 .enumerate() 93 .enumerate()
97 .for_each(|(index, (display, command))| { 94 .filter(|(_index, (display, _command))| display.contains("${provider}"))
98 if command.as_str() == "%switch-provider%" { 95 .map(|(index, _)| index)
99 self.textlist.items[index] = 96 .collect()
100 display.replace("${provider}", self.provider.as_str());
101 }
102 })
103 } 97 }
104 98
105 pub fn update_appearance( 99 pub fn update_appearance(
@@ -125,13 +119,18 @@ impl SingleVideoItem {
125 } 119 }
126 120
127 /// creates a hashmap from `self`, containing info of the current item 121 /// 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)> {
129 let video_item = item.fullvideo().unwrap(); 128 let video_item = item.fullvideo().unwrap();
130 129
131 vec![ 130 vec![
132 ( 131 (
133 String::from("url"), 132 String::from("url"),
134 match self.provider { 133 match status.provider {
135 Provider::Invidious => format!( 134 Provider::Invidious => format!(
136 "'{}/watch?v={}'", 135 "'{}/watch?v={}'",
137 mainconfig.invidious_instance, video_item.id 136 mainconfig.invidious_instance, video_item.id
@@ -142,7 +141,52 @@ impl SingleVideoItem {
142 (String::from("id"), video_item.id.clone()), 141 (String::from("id"), video_item.id.clone()),
143 ( 142 (
144 String::from("embed-url"), 143 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 {
146 Provider::Invidious => format!( 190 Provider::Invidious => format!(
147 "'{}/embed/{}'", 191 "'{}/embed/{}'",
148 mainconfig.invidious_instance, video_item.id 192 mainconfig.invidious_instance, video_item.id
@@ -153,7 +197,7 @@ impl SingleVideoItem {
153 (String::from("channel-id"), video_item.channel_id.clone()), 197 (String::from("channel-id"), video_item.channel_id.clone()),
154 ( 198 (
155 String::from("channel-url"), 199 String::from("channel-url"),
156 match self.provider { 200 match status.provider {
157 Provider::YouTube => { 201 Provider::YouTube => {
158 format!("https://www.youtube.com/channel/{}", video_item.channel_id) 202 format!("https://www.youtube.com/channel/{}", video_item.channel_id)
159 } 203 }
@@ -168,11 +212,7 @@ impl SingleVideoItem {
168} 212}
169 213
170impl SinglePlaylistItem { 214impl SinglePlaylistItem {
171 pub fn new( 215 pub fn new(commands: &CommandsConfig, playlist_items: &[Item]) -> Self {
172 commands: &CommandsConfig,
173 mainconfig: &MainConfig,
174 playlist_items: &[Item],
175 ) -> Self {
176 let hovered_video = ItemInfo::new(if playlist_items.is_empty() { 216 let hovered_video = ItemInfo::new(if playlist_items.is_empty() {
177 None 217 None
178 } else { 218 } else {
@@ -207,7 +247,6 @@ impl SinglePlaylistItem {
207 .collect(), 247 .collect(),
208 hovered_video, 248 hovered_video,
209 is_commands_view: true, 249 is_commands_view: true,
210 provider: mainconfig.provider,
211 } 250 }
212 } 251 }
213 252
@@ -262,26 +301,38 @@ impl SinglePlaylistItem {
262 } 301 }
263 } 302 }
264 303
265 /// updates the %switch-provider% command in the list 304 /// find all occurances of ${provider}
266 pub fn update_provider(&mut self) { 305 pub fn update_provider(&mut self) -> Vec<usize> {
267 self.commands 306 self.commands
268 .iter() 307 .iter()
269 .enumerate() 308 .enumerate()
270 .for_each(|(index, (display, command))| { 309 .filter(|(_index, (display, _command))| display.contains("${provider}"))
271 if command.as_str() == "%switch-provider%" { 310 .map(|(index, _)| index)
272 self.commands_view.items[index] = 311 .collect()
273 display.replace("${provider}", self.provider.as_str());
274 }
275 })
276 } 312 }
277 313
278 /// creates a hashmap from `self`, containing info of the current item 314 /// 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)> {
280 let playlist_item = item.fullplaylist().unwrap(); 330 let playlist_item = item.fullplaylist().unwrap();
331
281 vec![ 332 vec![
282 ( 333 (
283 String::from("url"), 334 String::from("url"),
284 match self.provider { 335 match status.provider {
285 Provider::YouTube => { 336 Provider::YouTube => {
286 format!("https://www.youtube.com/playlist?list={}", playlist_item.id) 337 format!("https://www.youtube.com/playlist?list={}", playlist_item.id)
287 } 338 }
@@ -291,10 +342,9 @@ impl SinglePlaylistItem {
291 ), 342 ),
292 }, 343 },
293 ), 344 ),
294 (String::from("id"), playlist_item.id.clone()),
295 ( 345 (
296 String::from("all-videos"), 346 String::from("all-videos"),
297 match self.provider { 347 match status.provider {
298 Provider::YouTube => playlist_item 348 Provider::YouTube => playlist_item
299 .videos 349 .videos
300 .iter() 350 .iter()
@@ -317,10 +367,9 @@ impl SinglePlaylistItem {
317 .join(" "), 367 .join(" "),
318 }, 368 },
319 ), 369 ),
320 (String::from("channel-id"), playlist_item.channel_id.clone()),
321 ( 370 (
322 String::from("channel-url"), 371 String::from("channel-url"),
323 match self.provider { 372 match status.provider {
324 Provider::YouTube => format!( 373 Provider::YouTube => format!(
325 "https://www.youtube.com/channel/{}", 374 "https://www.youtube.com/channel/{}",
326 playlist_item.channel_id 375 playlist_item.channel_id
@@ -357,7 +406,12 @@ impl SingleItemType {
357 } 406 }
358 } 407 }
359 408
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)> {
361 let item = if let Some(item) = item.as_ref() { 415 let item = if let Some(item) = item.as_ref() {
362 item 416 item
363 } else { 417 } else {
@@ -365,8 +419,31 @@ impl SingleItemType {
365 }; 419 };
366 420
367 match self { 421 match self {
368 Self::Video(singlevideoitem) => singlevideoitem.inflate(mainconfig, item), 422 Self::Video(singlevideoitem) => singlevideoitem.inflate_load(mainconfig, status, item),
369 Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate(mainconfig, 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 }
370 Self::None => Vec::new(), 447 Self::None => Vec::new(),
371 } 448 }
372 } 449 }
@@ -404,17 +481,20 @@ impl SingleItem {
404 videos_view, 481 videos_view,
405 .. 482 ..
406 } = &mut **singleplaylistitem; 483 } = &mut **singleplaylistitem;
407 if videos_view.items.is_empty() { 484 if videos_view.items.is_empty() || videos_view.selected == 0 {
408 hovered_video.item = None; 485 hovered_video.item = None;
409 return; 486 return;
410 } 487 }
411 488
412 if self.item.as_ref().unwrap().fullplaylist().unwrap().videos[videos_view.selected].id() 489 if hovered_video.item.is_none()
413 != hovered_video.item.as_ref().unwrap().id() 490 || self.item.as_ref().unwrap().fullplaylist().unwrap().videos
491 [videos_view.selected - 1]
492 .id()
493 != hovered_video.item.as_ref().unwrap().id()
414 { 494 {
415 hovered_video.item = Some( 495 hovered_video.item = Some(
416 self.item.as_ref().unwrap().fullplaylist().unwrap().videos 496 self.item.as_ref().unwrap().fullplaylist().unwrap().videos
417 [videos_view.selected] 497 [videos_view.selected - 1]
418 .clone(), 498 .clone(),
419 ); 499 );
420 } 500 }
@@ -433,27 +513,14 @@ impl SingleItem {
433 .1 513 .1
434 .clone(); 514 .clone();
435 515
436 match command_string.as_str() { 516 // check if the command starts with an ':' which case should be captured
437 // checks for special cases that the items should consume the command 517 framework
438 // instead of running it 518 .data
439 "%switch-provider%" => { 519 .state
440 singlevideoitem.provider.rotate(); 520 .get_mut::<Tasks>()
441 singlevideoitem.update_provider(); 521 .unwrap()
442 *framework.data.global.get_mut::<Message>().unwrap() = Message::Success( 522 .priority
443 format!("Switched provider to {}", singlevideoitem.provider.as_str()), 523 .push(Task::Command(apply_envs(command_string)));
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 }
457 } 524 }
458 SingleItemType::Playlist(singleplaylistitem) => { 525 SingleItemType::Playlist(singleplaylistitem) => {
459 let command_string = singleplaylistitem.commands 526 let command_string = singleplaylistitem.commands
@@ -472,11 +539,6 @@ impl SingleItem {
472 *framework.data.global.get_mut::<Message>().unwrap() = 539 *framework.data.global.get_mut::<Message>().unwrap() =
473 Message::Success(String::from("Switched view")); 540 Message::Success(String::from("Switched view"));
474 } 541 }
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
480 _ => { 542 _ => {
481 // check if the command starts with an ':' which case should be captured 543 // check if the command starts with an ':' which case should be captured
482 framework 544 framework
@@ -500,14 +562,6 @@ impl SingleItem {
500 .priority 562 .priority
501 .push(Task::RenderAll); 563 .push(Task::RenderAll);
502 } 564 }
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 }
511} 565}
512 566
513impl FrameworkItem for SingleItem { 567impl FrameworkItem for SingleItem {
@@ -523,6 +577,25 @@ impl FrameworkItem for SingleItem {
523 return; 577 return;
524 } 578 }
525 579
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
526 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap(); 599 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
527 self.update_appearance(appearance, &info); 600 self.update_appearance(appearance, &info);
528 601
@@ -538,6 +611,18 @@ impl FrameworkItem for SingleItem {
538 match &mut self.r#type { 611 match &mut self.r#type {
539 SingleItemType::Video(typeinfo) => { 612 SingleItemType::Video(typeinfo) => {
540 // 2 by 1 grid, item info in the first cell and textlist at the second 613 // 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 });
541 self.iteminfo 626 self.iteminfo
542 .render(frame, framework, chunks[0], popup_render, info); 627 .render(frame, framework, chunks[0], popup_render, info);
543 typeinfo.textlist.set_height(chunks[1].height); 628 typeinfo.textlist.set_height(chunks[1].height);
@@ -552,6 +637,19 @@ impl FrameworkItem for SingleItem {
552 self.iteminfo 637 self.iteminfo
553 .render(frame, framework, chunks[0], popup_render, info); 638 .render(frame, framework, chunks[0], popup_render, info);
554 if typeinfo.is_commands_view { 639 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 });
555 typeinfo.commands_view.set_height(chunks[1].height); 653 typeinfo.commands_view.set_height(chunks[1].height);
556 frame.render_widget(typeinfo.commands_view.clone(), chunks[1]); 654 frame.render_widget(typeinfo.commands_view.clone(), chunks[1]);
557 } else { 655 } else {
@@ -597,7 +695,6 @@ impl FrameworkItem for SingleItem {
597 SingleItemPage::Video(id) => { 695 SingleItemPage::Video(id) => {
598 self.r#type = SingleItemType::Video(SingleVideoItem::new( 696 self.r#type = SingleItemType::Video(SingleVideoItem::new(
599 framework.data.global.get::<CommandsConfig>().unwrap(), 697 framework.data.global.get::<CommandsConfig>().unwrap(),
600 framework.data.global.get::<MainConfig>().unwrap(),
601 )); 698 ));
602 let video = Item::from_full_video(client.video(id, None)?, mainconfig.image_index); 699 let video = Item::from_full_video(client.video(id, None)?, mainconfig.image_index);
603 if mainconfig.images.display() { 700 if mainconfig.images.display() {
@@ -612,7 +709,6 @@ impl FrameworkItem for SingleItem {
612 self.r#type = SingleItemType::Playlist( 709 self.r#type = SingleItemType::Playlist(
613 SinglePlaylistItem::new( 710 SinglePlaylistItem::new(
614 framework.data.global.get::<CommandsConfig>().unwrap(), 711 framework.data.global.get::<CommandsConfig>().unwrap(),
615 framework.data.global.get::<MainConfig>().unwrap(),
616 videos, 712 videos,
617 ) 713 )
618 .into(), 714 .into(),
@@ -632,9 +728,24 @@ impl FrameworkItem for SingleItem {
632 self.iteminfo.item = self.item.clone(); 728 self.iteminfo.item = self.item.clone();
633 // need to update provider every time the item loads or else it will display `${provider}` 729 // need to update provider every time the item loads or else it will display `${provider}`
634 // instead of the actual provider (e.g. `YouTube`) 730 // instead of the actual provider (e.g. `YouTube`)
635 self.update_provider();
636 set_envs( 731 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(),
638 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0, 749 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
639 ); 750 );
640 751
src/main.rs +7 −4
@@ -14,10 +14,9 @@ use youtube_tui::{exit, global::functions::text_command, init, run};
14// 3. restore the terminal 14// 3. restore the terminal
15// 4. unwrap errors 15// 4. unwrap errors
16fn main() -> Result<(), Box<dyn Error>> { 16fn main() -> Result<(), Box<dyn Error>> {
17 let args = env::args().skip(1).collect::<Vec<_>>(); 17 let args = env::args().skip(1).collect::<Vec<_>>().join(" ");
18 let args_strs = args.iter().map(|s| s.as_str()).collect::<Vec<_>>();
19 18
20 if let Some(s) = text_command(&args_strs) { 19 if let Some(s) = text_command(&args) {
21 println!("{s}"); 20 println!("{s}");
22 return Ok(()); 21 return Ok(());
23 } 22 }
@@ -32,7 +31,11 @@ fn main() -> Result<(), Box<dyn Error>> {
32 let mut terminal = Terminal::new(backend)?; 31 let mut terminal = Terminal::new(backend)?;
33 32
34 let res = (|| -> Result<(), Box<dyn Error>> { 33 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 )?;
36 run(&mut terminal, &mut framework)?; 39 run(&mut terminal, &mut framework)?;
37 Ok(()) 40 Ok(())
38 })(); 41 })();
src/run.rs +28 −15
@@ -7,10 +7,10 @@ use tui_additions::{
7}; 7};
8 8
9use crate::{ 9use crate::{
10 config::{KeyBindingsConfig, MainConfig}, 10 config::{CommandBindings, KeyBindingsConfig, MainConfig},
11 global::{ 11 global::{
12 functions::{clear_envs, command_capture, set_envs}, 12 functions::{apply_envs, clear_envs, command_capture, run_command, set_envs},
13 structs::{KeyAction, Message, StateEnvs, Status, Task, Tasks}, 13 structs::{KeyAction, Message, Page, StateEnvs, Status, Task, Tasks},
14 }, 14 },
15}; 15};
16 16
@@ -96,6 +96,25 @@ pub fn run(
96 } 96 }
97 } 97 }
98 Event::Key(key) => { 98 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
99 // 1. get the corresponding action 118 // 1. get the corresponding action
100 // 2. check if action is deselect, if yes, deselect 119 // 2. check if action is deselect, if yes, deselect
101 // 3. check is anything is selected, if yes, run `.key_event()` with the key 120 // 3. check is anything is selected, if yes, run `.key_event()` with the key
@@ -194,12 +213,9 @@ pub fn run(
194 "This is already the beginning of history", 213 "This is already the beginning of history",
195 )) 214 ))
196 } else { 215 } else {
197 framework 216 let status = framework.data.global.get_mut::<Status>().unwrap();
198 .data 217 status.render_image = true;
199 .global 218 status.provider_updated = true;
200 .get_mut::<Status>()
201 .unwrap()
202 .render_image = true;
203 framework 219 framework
204 .data 220 .data
205 .state 221 .state
@@ -219,12 +235,9 @@ pub fn run(
219 "This is already the beginning of history", 235 "This is already the beginning of history",
220 )) 236 ))
221 } else { 237 } else {
222 framework 238 let status = framework.data.global.get_mut::<Status>().unwrap();
223 .data 239 status.render_image = true;
224 .global 240 status.provider_updated = true;
225 .get_mut::<Status>()
226 .unwrap()
227 .render_image = true;
228 framework 241 framework
229 .data 242 .data
230 .state 243 .state