Commit ddf8315021

ddf8315021a0f2af6c9713c8de39169e13726c81

parent: 4c51d583a4

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2023-08-23 15:37 UTC

added custom command aliases, and made mpv stuff slightly better

Layout: unified · split

Cargo.lock −2
@@ -1178,8 +1178,6 @@ checksum = "efd1f82c56340fdf16f2a953d7bda4f8fdffba13d93b00844c25572110b26079"
1178[[package]] 1178[[package]]
1179name = "tui-additions" 1179name = "tui-additions"
1180version = "0.2.1" 1180version = "0.2.1"
1181source = "registry+https://github.com/rust-lang/crates.io-index"
1182checksum = "1de5841ec45de71c46252a832bb1e3e69abf2ee2492eb309ea077c8d78e798e7"
1183dependencies = [ 1181dependencies = [
1184 "crossterm 0.26.1", 1182 "crossterm 0.26.1",
1185 "dyn-clone", 1183 "dyn-clone",
Cargo.toml +2 −2
@@ -29,7 +29,7 @@ viuer = {version = "0.6", default-features = false, optional = true}
29home = "0.5" 29home = "0.5"
30chrono = {version = "0.4", default-features = false, features = ["clock"]} 30chrono = {version = "0.4", default-features = false, features = ["clock"]}
31typemap = {version = "0.3", default-features = false} 31typemap = {version = "0.3", default-features = false}
32tui-additions = {version = "0.2.1", default-features = false, features = ["framework", "widgets"]} 32# tui-additions = {version = "0.2.1", default-features = false, features = ["framework", "widgets"]}
33invidious = {version = "0.5"} 33invidious = {version = "0.5"}
34serde_yaml = {version = "0.9", default-features = false} 34serde_yaml = {version = "0.9", default-features = false}
35dyn-clone = {version = "1.0", default-features = false} 35dyn-clone = {version = "1.0", default-features = false}
@@ -39,7 +39,7 @@ urlencoding = "2.1"
39ratatui = {version = "0.21", default-features = false, features = ["serde"]} 39ratatui = {version = "0.21", default-features = false, features = ["serde"]}
40libmpv = { git = "https://github.com/sudipghimire533/libmpv-rs", optional = true } 40libmpv = { git = "https://github.com/sudipghimire533/libmpv-rs", optional = true }
41 41
42# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]} 42tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
43# invidious = {path = "../../Rust/Packages/invidious"} 43# invidious = {path = "../../Rust/Packages/invidious"}
44 44
45[package.metadata.docs.rs] 45[package.metadata.docs.rs]
src/config/commands.rs +10 −12
@@ -100,13 +100,11 @@ fn video_default() -> Vec<HashMap<String, String>> {
100 )]), 100 )]),
101 HashMap::from([( 101 HashMap::from([(
102 String::from("Play audio"), 102 String::from("Play audio"),
103 String::from("parrun ${terminal-emulator} ${video-player} '${embed-url}' --no-video"), 103 String::from("mpv sprop loop no ;; mpv loadfile '${embed-url}'"),
104 )]), 104 )]),
105 HashMap::from([( 105 HashMap::from([(
106 String::from("Play audio (loop)"), 106 String::from("Play audio (loop)"),
107 String::from( 107 String::from("mpv sprop loop inf ;; mpv loadfile '${embed-url}'"),
108 "parrun ${terminal-emulator} ${video-player} '${embed-url}' --no-video --loop-file=inf",
109 ),
110 )]), 108 )]),
111 HashMap::from([( 109 HashMap::from([(
112 String::from("View channel"), 110 String::from("View channel"),
@@ -147,15 +145,15 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
147 )]), 145 )]),
148 HashMap::from([( 146 HashMap::from([(
149 String::from("[Offline] Play saved file"), 147 String::from("[Offline] Play saved file"),
150 String::from("parrun ${video-player} ${save-path}*${id}* --force-window"), 148 String::from("parrun ${video-player} '${offline-path}' --force-window"),
151 )]), 149 )]),
152 HashMap::from([( 150 HashMap::from([(
153 String::from("[Offline] Play saved file (audio)"), 151 String::from("[Offline] Play saved file (audio)"),
154 String::from("parrun ${terminal-emulator} ${video-player} ${save-path}*${id}* --no-video"), 152 String::from("mpv sprop loop no ;; mpv loadfile '${offline-path}'"),
155 )]), 153 )]),
156 HashMap::from([( 154 HashMap::from([(
157 String::from("[Offline] Play saved file (audio loop)"), 155 String::from("[Offline] Play saved file (audio loop)"),
158 String::from("parrun ${terminal-emulator} ${video-player} ${save-path}*${id}* --no-video --loop"), 156 String::from("mpv sprop loop inf ;; mpv loadfile '${offline-path}'"),
159 )]), 157 )]),
160 HashMap::from([( 158 HashMap::from([(
161 String::from("View channel"), 159 String::from("View channel"),
@@ -197,15 +195,15 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
197 )]), 195 )]),
198 HashMap::from([( 196 HashMap::from([(
199 String::from("Play all (videos)"), 197 String::from("Play all (videos)"),
200 String::from("parrun ${video-player} ${all-videos}"), 198 String::from("parrun ${video-player} ${url}"),
201 )]), 199 )]),
202 HashMap::from([( 200 HashMap::from([(
203 String::from("Play all (audio)"), 201 String::from("Play all (audio)"),
204 String::from("parrun ${terminal-emulator} ${video-player} ${all-videos} --no-video"), 202 String::from("mpv stop ;; ${mpv-queuelist} ;; mpv playlist-play-index 0"),
205 )]), 203 )]),
206 HashMap::from([( 204 HashMap::from([(
207 String::from("Shuffle play all (audio loop)"), 205 String::from("Shuffle play all (audio loop)"),
208 String::from("parrun ${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"), 206 String::from("mpv stop ;; ${mpv-queuelist} ;; mpv playlist-shuffle ;; mpv playlist-play-index 0"),
209 )]), 207 )]),
210 HashMap::from([( 208 HashMap::from([(
211 String::from("View channel"), 209 String::from("View channel"),
@@ -251,11 +249,11 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
251 )]), 249 )]),
252 HashMap::from([( 250 HashMap::from([(
253 String::from("[Offline] Play all (audio)"), 251 String::from("[Offline] Play all (audio)"),
254 String::from("parrun ${terminal-emulator} bash -c '${video-player} ${save-path}*${id}*/* --no-video'"), 252 String::from("mpv stop ;; ${offline-queuelist} ;; mpv playlist-play-index 0"),
255 )]), 253 )]),
256 HashMap::from([( 254 HashMap::from([(
257 String::from("[Offline] Shuffle play all (audio loop)"), 255 String::from("[Offline] Shuffle play all (audio loop)"),
258 String::from("parrun ${terminal-emulator} bash -c '${video-player} ${save-path}*${id}*/* --no-video --loop-playlist=inf --shuffle'"), 256 String::from("mpv stop ;; ${offline-queuelist} ;; mpv playlist-shuffle ;; mpv playlist-play-index 0"),
259 )]), 257 )]),
260 HashMap::from([( 258 HashMap::from([(
261 String::from("View channel"), 259 String::from("View channel"),
src/config/commands_remap.rs added +59
@@ -0,0 +1,59 @@
1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use typemap::Key;
4
5use crate::global::traits::ConfigTrait;
6
7#[derive(Serialize, Deserialize, Clone)]
8pub struct CommandsRemapConfig(pub HashMap<String, String>);
9
10impl ConfigTrait for CommandsRemapConfig {
11 const LABEL: &'static str = "cmdefine";
12}
13
14impl Key for CommandsRemapConfig {
15 type Value = Self;
16}
17
18impl Default for CommandsRemapConfig {
19 fn default() -> Self {
20 Self(HashMap::from([
21 ("h".to_string(), "help".to_string()),
22 ("v".to_string(), "version".to_string()),
23 ("cp".to_string(), "copy".to_string()),
24 ("print".to_string(), "echo".to_string()),
25 ("popular".to_string(), "loadpage popular".to_string()),
26 ("trending".to_string(), "loadpage trending".to_string()),
27 (
28 "watchhistory".to_string(),
29 "loadpage watchhistory".to_string(),
30 ),
31 ("feed".to_string(), "loadpage feed".to_string()),
32 ("bookmarks".to_string(), "loadpage bookmarks".to_string()),
33 ("library".to_string(), "loadpage library".to_string()),
34 ("search".to_string(), "loadpage search".to_string()),
35 ("channel".to_string(), "loadpage channel".to_string()),
36 ("video".to_string(), "loadpage video".to_string()),
37 ("playlist".to_string(), "loadpage playlist".to_string()),
38 ("back".to_string(), "history back".to_string()),
39 ("r".to_string(), "reload".to_string()),
40 ("rc".to_string(), "reload configs".to_string()),
41 ("q".to_string(), "quit".to_string()),
42 ("x".to_string(), "quit".to_string()),
43 ("exit".to_string(), "quit".to_string()),
44 ("sub".to_string(), "sync".to_string()),
45 ]))
46 }
47}
48
49impl CommandsRemapConfig {
50 pub fn get(&self, cmd: &[&str]) -> Option<String> {
51 for i in (0..cmd.len() + 1).rev() {
52 if let Some(remapped) = self.0.get(&cmd[0..i].join(" ")) {
53 return Some(format!("{remapped} {}", cmd[i..cmd.len()].join(" ")));
54 }
55 }
56
57 None
58 }
59}
src/config/mod.rs +2
@@ -15,5 +15,7 @@ mod commands;
15pub use commands::*; 15pub use commands::*;
16mod commandbindings; 16mod commandbindings;
17pub use commandbindings::*; 17pub use commandbindings::*;
18mod commands_remap;
19pub use commands_remap::*;
18 20
19pub mod serde; 21pub mod serde;
src/global/functions/find_library.rs added +16
@@ -0,0 +1,16 @@
1use std::{fs, path::PathBuf};
2
3use home::home_dir;
4
5use crate::config::MainConfig;
6
7pub fn find_library_item(id: &str, mainconfig: &MainConfig) -> Option<PathBuf> {
8 fs::read_dir(
9 home_dir()
10 .unwrap()
11 .join(mainconfig.env.get("save-path")?.replacen("~/", "", 1)),
12 )
13 .ok()?
14 .filter_map(|entry| Some(entry.ok()?.path()))
15 .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))
16}
src/global/functions/mod.rs +2
@@ -33,3 +33,5 @@ mod remove_word;
33pub use remove_word::*; 33pub use remove_word::*;
34mod key_input; 34mod key_input;
35pub use key_input::*; 35pub use key_input::*;
36mod find_library;
37pub use find_library::*;
src/global/functions/run_command.rs +33 −62
@@ -22,7 +22,9 @@ pub fn text_command(command: &str) -> Option<String> {
22 .collect::<Vec<_>>() 22 .collect::<Vec<_>>()
23 .as_slice() 23 .as_slice()
24 { 24 {
25 ["help"] => Some(String::from(HELP_MSG)), 25 ["help"] => Some(help_msg(
26 &CommandsRemapConfig::load(WriteConfig::Dont).unwrap(),
27 )),
26 ["version"] => Some(format!( 28 ["version"] => Some(format!(
27 "{} {}", 29 "{} {}",
28 env!("CARGO_PKG_NAME"), 30 env!("CARGO_PKG_NAME"),
@@ -101,7 +103,7 @@ pub fn run_single_command(
101 run_single_command(&["bookmark", id], framework, terminal); 103 run_single_command(&["bookmark", id], framework, terminal);
102 } 104 }
103 } 105 }
104 ["help"] | ["h"] => { 106 ["help"] => {
105 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from( 107 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
106 "Avaliable commands can be viewed by running `youtube-tui help` in terminal", 108 "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
107 )); 109 ));
@@ -115,10 +117,6 @@ pub fn run_single_command(
115 Message::Success(format!("Provider updated to {}", status.provider.as_str())); 117 Message::Success(format!("Provider updated to {}", status.provider.as_str()));
116 update_provider(&mut framework.data); 118 update_provider(&mut framework.data);
117 } 119 }
118 ["loadpage"] => {
119 *framework.data.global.get_mut::<Message>().unwrap() =
120 Message::Message(String::from("Usage: `loadpage {page}`"));
121 }
122 // loads a given page 120 // loads a given page
123 ["loadpage", page, ..] => { 121 ["loadpage", page, ..] => {
124 let page = match *page { 122 let page = match *page {
@@ -209,37 +207,6 @@ pub fn run_single_command(
209 .push(Task::LoadPage(page)) 207 .push(Task::LoadPage(page))
210 } 208 }
211 } 209 }
212 // redirects to the relevant `loadpage` command
213 ["popular"] => run_single_command(&["loadpage", "popular"], framework, terminal),
214 ["trending"] => run_single_command(&["loadpage", "trending"], framework, terminal),
215 ["watchhistory"] => run_single_command(&["loadpage", "watchhistory"], framework, terminal),
216 ["feed"] => run_single_command(&["loadpage", "feed"], framework, terminal),
217 ["bookmarks"] => run_single_command(&["loadpage", "bookmarks"], framework, terminal),
218 ["library"] => run_single_command(&["loadpage", "library"], framework, terminal),
219 ["search"] => run_single_command(&["loadpage", "search"], framework, terminal),
220 ["search", ..] => run_single_command(
221 &format!("loadpage search {}", command[1..].join(" "))
222 .split(' ')
223 .collect::<Vec<&str>>(),
224 framework,
225 terminal,
226 ),
227 ["channel"] => run_single_command(&["loadpage", "channel"], framework, terminal),
228 ["channel", identifier] => {
229 run_single_command(&["loadpage", "channel", *identifier], framework, terminal)
230 }
231 ["video"] => run_single_command(&["loadpage", "video"], framework, terminal),
232 ["video", identifier] => {
233 run_single_command(&["loadpage", "video", *identifier], framework, terminal)
234 }
235 ["playlist"] => run_single_command(&["loadpage", "playlist"], framework, terminal),
236 ["playlist", identifier] => {
237 run_single_command(&["loadpage", "playlist", *identifier], framework, terminal)
238 }
239 ["history"] => {
240 *framework.data.global.get_mut::<Message>().unwrap() =
241 Message::Message(String::from("Usage: `history [back/clear]`"))
242 }
243 ["history", "back"] | ["back"] => { 210 ["history", "back"] | ["back"] => {
244 let _ = framework.revert_last_history(); 211 let _ = framework.revert_last_history();
245 framework 212 framework
@@ -284,14 +251,14 @@ pub fn run_single_command(
284 .priority 251 .priority
285 .push(Task::Reload); 252 .push(Task::Reload);
286 } 253 }
287 ["reload", "config"] | ["reload", "configs"] | ["r", "config"] | ["r", "configs"] => { 254 ["reload", "configs"] => {
288 *framework.data.global.get_mut::<Message>().unwrap() = 255 *framework.data.global.get_mut::<Message>().unwrap() =
289 match load_configs(&mut framework.split_clean().0) { 256 match load_configs(&mut framework.split_clean().0) {
290 Ok(()) => Message::Success(String::from("Config files have been reloaded")), 257 Ok(()) => Message::Success(String::from("Config files have been reloaded")),
291 Err(e) => Message::Error(e.to_string()), 258 Err(e) => Message::Error(e.to_string()),
292 }; 259 };
293 } 260 }
294 ["q"] | ["quit"] | ["x"] | ["exit"] => { 261 ["quit"] => {
295 framework.data.global.get_mut::<Status>().unwrap().exit = true; 262 framework.data.global.get_mut::<Status>().unwrap().exit = true;
296 } 263 }
297 ["hello", "world"] => { 264 ["hello", "world"] => {
@@ -299,17 +266,13 @@ pub fn run_single_command(
299 *framework.data.global.get_mut::<Message>().unwrap() = 266 *framework.data.global.get_mut::<Message>().unwrap() =
300 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index])); 267 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
301 } 268 }
302 ["version"] | ["v"] => { 269 ["version"] => {
303 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!( 270 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!(
304 "{} {}", 271 "{} {}",
305 env!("CARGO_PKG_NAME"), 272 env!("CARGO_PKG_NAME"),
306 env!("CARGO_PKG_VERSION") 273 env!("CARGO_PKG_VERSION")
307 )); 274 ));
308 } 275 }
309 ["run"] | ["parrun"] => {
310 *framework.data.global.get_mut::<Message>().unwrap() =
311 Message::Message(String::from("Usage: run/parrun [command]"));
312 }
313 ["run", ..] => { 276 ["run", ..] => {
314 let command = command[1..].join(" "); 277 let command = command[1..].join(" ");
315 *framework.data.global.get_mut::<Message>().unwrap() = 278 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -334,17 +297,13 @@ pub fn run_single_command(
334 .stderr(Stdio::null()) 297 .stderr(Stdio::null())
335 .spawn(); 298 .spawn();
336 } 299 }
337 ["copy"] | ["cp"] => {
338 *framework.data.global.get_mut::<Message>().unwrap() =
339 Message::Message(String::from("Usage: copy [text]"));
340 }
341 #[cfg(feature = "clipboard")] 300 #[cfg(feature = "clipboard")]
342 ["copy", ..] | ["cp", ..] => { 301 ["copy", ..] => {
343 set_clipboard(command[1..].join(" ")); 302 set_clipboard(command[1..].join(" "));
344 *framework.data.global.get_mut::<Message>().unwrap() = 303 *framework.data.global.get_mut::<Message>().unwrap() =
345 Message::Success(String::from("Copied to clipboad")); 304 Message::Success(String::from("Copied to clipboad"));
346 } 305 }
347 ["sub", identifier] | ["sync", identifier] => { 306 ["sync", identifier] => {
348 let id = if identifier.len() == 24 { 307 let id = if identifier.len() == 24 {
349 identifier.to_string() 308 identifier.to_string()
350 } else { 309 } else {
@@ -514,13 +473,13 @@ pub fn run_single_command(
514 }; 473 };
515 } 474 }
516 #[cfg(feature = "mpv")] 475 #[cfg(feature = "mpv")]
517 ["mpv", "set_property", name, value] | ["mpv", "sprop", name, value] => { 476 ["mpv", "set_property", name, ..] | ["mpv", "sprop", name, ..] => {
518 let res = framework 477 let res = framework
519 .data 478 .data
520 .global 479 .global
521 .get::<MpvWrapper>() 480 .get::<MpvWrapper>()
522 .unwrap() 481 .unwrap()
523 .set_property(name.to_string(), value.to_string()); 482 .set_property(name.to_string(), command[3..].join(" "));
524 483
525 *framework.data.global.get_mut::<Message>().unwrap() = match res { 484 *framework.data.global.get_mut::<Message>().unwrap() = match res {
526 MpvResponse::Copy => Message::Mpv("Value set".to_string()), 485 MpvResponse::Copy => Message::Mpv("Value set".to_string()),
@@ -541,7 +500,22 @@ pub fn run_single_command(
541 _ => unreachable!(), 500 _ => unreachable!(),
542 }; 501 };
543 } 502 }
503 ["echo", ..] => {
504 *framework.data.global.get_mut::<Message>().unwrap() =
505 Message::Message(command[1..].join(" "))
506 }
544 _ => { 507 _ => {
508 if let Some(cmd) = framework
509 .data
510 .global
511 .get_mut::<CommandsRemapConfig>()
512 .unwrap()
513 .get(command)
514 {
515 run_command(&cmd, framework, terminal);
516 return;
517 }
518
545 *framework.data.global.get_mut::<Message>().unwrap() = 519 *framework.data.global.get_mut::<Message>().unwrap() =
546 Message::Error(format!("Unknown command: `{}`", command.join(" "))); 520 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
547 } 521 }
@@ -579,7 +553,8 @@ const HELLO_WORLDS: &[&str] = &[
579 "<h1>Hello World<\\h1>", 553 "<h1>Hello World<\\h1>",
580]; 554];
581 555
582const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m 556fn help_msg(cmdefines: &CommandsRemapConfig) -> String {
557 format!("\x1b[32mYouTube TUI commands\x1b[0m
583 558
584\x1b[37mfor more visit https://siriusmart.github.io/youtube-tui/commands.html\x1b[0m 559\x1b[37mfor more visit https://siriusmart.github.io/youtube-tui/commands.html\x1b[0m
585 560
@@ -626,13 +601,9 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
626 \x1b[33munsub [id or url]\x1b[0m Remove channel from subscription 601 \x1b[33munsub [id or url]\x1b[0m Remove channel from subscription
627 \x1b[33msyncall\x1b[0m Sync all subscriptions 602 \x1b[33msyncall\x1b[0m Sync all subscriptions
628 603
629\x1b[91mALT:\x1b[0m 604\x1b[91mCUSTOM COMMANDS:\x1b[0m
630\x1b[37malts links back to the original command\x1b[30m 605\x1b[37mdefined in cmdefine.yml\x1b[30m
631 \x1b[33m[page] (additional options)\x1b[0m `loadpage [page]` 606{}
632 \x1b[33mback\x1b[0m `history back`
633 \x1b[33mr\x1b[0m `reload`
634 \x1b[33mreload/r config/configs\x1b[0m `reload configs`
635 \x1b[33mq, exit, x\x1b[0m `quit`
636 \x1b[33mcp [text]\x1b[0m `copy [text]`
637 607
638\x1b[37mOnly load page and informational commands should be used from command line, the rest can only be used in (`:`) command mode inside the TUI.\x1b[0m"; 608\x1b[37mOnly load page and informational commands should be used from command line, the rest can only be used in (`:`) command mode inside the TUI.\x1b[0m", cmdefines.0.iter().map(|(key, value)| format!(" \x1b[33m{: <28}\x1b[0m `{value}`", key)).collect::<Vec<_>>().join("\n"))
609}
src/global/functions/update_provider.rs +22
@@ -163,6 +163,28 @@ pub fn update_provider(data: &mut FrameworkData) {
163 ), 163 ),
164 }, 164 },
165 ), 165 ),
166 (
167 String::from("mpv-queuelist"),
168 match status.provider {
169 Provider::YouTube => env::var("all-ids")
170 .unwrap_or(String::from("env_not_found"))
171 .split(' ')
172 .map(|id| format!("mpv loadfile 'https://youtu.be/{id}' append"))
173 .collect::<Vec<_>>()
174 .join(" ;; "),
175 Provider::Invidious => env::var("all-ids")
176 .unwrap_or(String::from("env_not_found"))
177 .split(' ')
178 .map(|id| {
179 format!(
180 "mpv loadfile '{}/watch?v={id}' append",
181 mainconfig.invidious_instance,
182 )
183 })
184 .collect::<Vec<_>>()
185 .join(" ;; "),
186 },
187 ),
166 ], 188 ],
167 }; 189 };
168 190
src/global/structs/mpv.rs +7
@@ -107,6 +107,13 @@ impl MpvWrapper {
107 } 107 }
108} 108}
109 109
110impl MpvWrapper {
111 pub fn playing(&self) -> bool {
112 self.property("core-idle".to_string())
113 .is_some_and(|s| s.as_str() == "no" || s.as_str() == "false")
114 }
115}
116
110#[derive(Debug)] 117#[derive(Debug)]
111pub enum MpvAction { 118pub enum MpvAction {
112 Command { 119 Command {
src/global/structs/tasks.rs +70 −12
@@ -7,7 +7,7 @@ use ratatui::{
7 backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal, 7 backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal,
8}; 8};
9use std::{error::Error, io::Stdout, mem}; 9use std::{error::Error, io::Stdout, mem};
10use tui_additions::framework::{CursorState, Framework}; 10use tui_additions::framework::{CursorState, Framework, FrameworkItem};
11use typemap::Key; 11use typemap::Key;
12 12
13/// tasks to be put on taskqueues 13/// tasks to be put on taskqueues
@@ -176,13 +176,8 @@ impl TaskQueue {
176 } 176 }
177 177
178 match self.render { 178 match self.render {
179 RenderTask::All => { 179 RenderTask::All => Self::render(framework, terminal)?,
180 Self::render(framework, terminal)?; 180 RenderTask::Only(locations) => Self::render_onlys(framework, terminal, locations)?,
181 }
182 RenderTask::Only(_locations) => {
183 // need to file an issue to tui-rs suggesting this as a feature
184 unimplemented!("tui-rs does not support partial re-rendering");
185 }
186 RenderTask::None => {} 181 RenderTask::None => {}
187 } 182 }
188 183
@@ -224,12 +219,29 @@ impl TaskQueue {
224 Ok(()) 219 Ok(())
225 } 220 }
226 221
222 pub fn render_onlys(
223 framework: &mut Framework,
224 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
225 locations: Vec<(usize, usize)>,
226 ) -> Result<(), Box<dyn Error>> {
227 Self::render_onlys_with_frame(framework, &mut terminal.get_frame(), locations);
228 terminal.flush()?;
229 Ok(())
230 }
231
232 pub fn render_onlys_with_frame(
233 framework: &mut Framework,
234 frame: &mut Frame<CrosstermBackend<Stdout>>,
235 locations: Vec<(usize, usize)>,
236 ) {
237 framework.render_only_multiple(frame, &locations);
238 }
239
227 /// this function renders onto the given frame 240 /// this function renders onto the given frame
228 pub fn render_with_frame( 241 pub fn render_with_frame(
229 framework: &mut Framework, 242 framework: &mut Framework,
230 frame: &mut Frame<CrosstermBackend<Stdout>>, 243 frame: &mut Frame<CrosstermBackend<Stdout>>,
231 ) { 244 ) {
232 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
233 let area = frame.size(); 245 let area = frame.size();
234 246
235 framework 247 framework
@@ -239,6 +251,52 @@ impl TaskQueue {
239 .unwrap() 251 .unwrap()
240 .prev_frame = Some(area); 252 .prev_frame = Some(area);
241 253
254 if Self::protective_screen(framework, frame) {
255 return;
256 }
257
258 framework.render(frame);
259 }
260
261 pub fn render_filter(
262 framework: &mut Framework,
263 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
264 filter: impl Fn(&Box<dyn FrameworkItem>) -> bool,
265 ) -> Result<(), Box<dyn Error>> {
266 Self::render_filter_with_frame(framework, &mut terminal.get_frame(), filter);
267 terminal.flush()?;
268 Ok(())
269 }
270
271 pub fn render_filter_with_frame(
272 framework: &mut Framework,
273 frame: &mut Frame<CrosstermBackend<Stdout>>,
274 filter: impl Fn(&Box<dyn FrameworkItem>) -> bool,
275 ) {
276 let area = frame.size();
277
278 framework
279 .data
280 .global
281 .get_mut::<Status>()
282 .unwrap()
283 .prev_frame = Some(area);
284
285 if Self::protective_screen(framework, frame) {
286 return;
287 }
288
289 framework.render_filter(frame, filter);
290 }
291
292 /// this function renders onto the given frame
293 pub fn protective_screen(
294 framework: &mut Framework,
295 frame: &mut Frame<CrosstermBackend<Stdout>>,
296 ) -> bool {
297 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
298 let area = frame.size();
299
242 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking 300 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
243 if area.width < min_dimentions.width || area.height < min_dimentions.height { 301 if area.width < min_dimentions.width || area.height < min_dimentions.height {
244 let paragraph = Paragraph::new(format!( 302 let paragraph = Paragraph::new(format!(
@@ -260,10 +318,10 @@ impl TaskQueue {
260 .text_error), 318 .text_error),
261 ); 319 );
262 frame.render_widget(paragraph, area); 320 frame.render_widget(paragraph, area);
263 return; 321 true
322 } else {
323 false
264 } 324 }
265
266 framework.render(frame);
267 } 325 }
268} 326}
269 327
src/init.rs +4
@@ -122,6 +122,10 @@ pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>
122 .data 122 .data
123 .global 123 .global
124 .insert::<PagesConfig>(*PagesConfig::load(main_config.write_config)?); 124 .insert::<PagesConfig>(*PagesConfig::load(main_config.write_config)?);
125 framework
126 .data
127 .global
128 .insert::<CommandsRemapConfig>(*CommandsRemapConfig::load(main_config.write_config)?);
125 framework 129 framework
126 .data 130 .data
127 .global 131 .global
src/items/itemlist.rs +1 −1
@@ -388,7 +388,7 @@ impl FrameworkItem for ItemList {
388 }; 388 };
389 389
390 // only create a render task if the key event actually changed something 390 // only create a render task if the key event actually changed something
391 if updated { 391 if updated && !self.items.is_empty() {
392 self.update(framework); 392 self.update(framework);
393 set_envs( 393 set_envs(
394 self.infalte_item_update( 394 self.infalte_item_update(
src/items/messagebar.rs +37 −2
@@ -4,7 +4,7 @@ use ratatui::{
4 style::Style, 4 style::Style,
5 widgets::{Block, Borders, Paragraph}, 5 widgets::{Block, Borders, Paragraph},
6}; 6};
7use tui_additions::framework::FrameworkItem; 7use tui_additions::framework::{FrameworkClean, FrameworkItem};
8 8
9/// a message bar item, contains no fields because the message is taken from `data.global.Message` 9/// a message bar item, contains no fields because the message is taken from `data.global.Message`
10#[derive(Clone, Copy, Default)] 10#[derive(Clone, Copy, Default)]
@@ -23,8 +23,26 @@ impl FrameworkItem for MessageBar {
23 return; 23 return;
24 } 24 }
25 25
26 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap(); 26 let mpv = framework.data.global.get::<MpvWrapper>().unwrap();
27 if Self::is_mpv_render(framework) {
28 let duration = mpv
29 .property("duration".to_string())
30 .unwrap_or_default()
31 .parse::<f64>()
32 .unwrap() as u64;
33 let playerhead = mpv
34 .property("time-pos".to_string())
35 .unwrap_or_default()
36 .parse::<f64>()
37 .unwrap() as u64;
38 let percentage = playerhead * 100 / duration;
39
40 *framework.data.global.get_mut::<Message>().unwrap() =
41 Message::Mpv(format!("{playerhead}/{duration} [{percentage}%]"));
42 }
43
27 let message = framework.data.global.get::<Message>().unwrap(); 44 let message = framework.data.global.get::<Message>().unwrap();
45 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
28 46
29 // the Option<TextList> that is Some if keys were captured for entering command 47 // the Option<TextList> that is Some if keys were captured for entering command
30 let command_capture = &framework 48 let command_capture = &framework
@@ -84,3 +102,20 @@ impl FrameworkItem for MessageBar {
84 false 102 false
85 } 103 }
86} 104}
105
106impl MessageBar {
107 pub fn is_mpv_render(framework: &FrameworkClean) -> bool {
108 framework.data.global.get::<MpvWrapper>().unwrap().playing()
109 && matches!(
110 framework.data.global.get::<Message>().unwrap(),
111 Message::Mpv(_) | Message::None
112 )
113 && framework
114 .data
115 .global
116 .get::<Status>()
117 .unwrap()
118 .command_capture
119 .is_none()
120 }
121}
src/items/singleitem.rs +43 −26
@@ -65,18 +65,7 @@ pub struct SinglePlaylistItem {
65 65
66impl SingleVideoItem { 66impl SingleVideoItem {
67 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig, id: &str) -> Self { 67 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig, id: &str) -> Self {
68 let saved = (|| -> Option<()> { 68 let saved = find_library_item(id, mainconfig).is_some();
69 fs::read_dir(
70 home_dir()
71 .unwrap()
72 .join(mainconfig.env.get("save-path")?.replacen("~/", "", 1)),
73 )
74 .ok()?
75 .filter_map(|entry| Some(entry.ok()?.path().file_stem()?.to_os_string()))
76 .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))?;
77 Some(())
78 })()
79 .is_some();
80 if saved { 69 if saved {
81 Self::new_with_map( 70 Self::new_with_map(
82 commands 71 commands
@@ -188,6 +177,14 @@ impl SingleVideoItem {
188 ), 177 ),
189 }, 178 },
190 ), 179 ),
180 (
181 String::from("offline-path"),
182 find_library_item(&video_item.id, mainconfig)
183 .unwrap_or_default()
184 .to_str()
185 .unwrap()
186 .to_string(),
187 ),
191 ] 188 ]
192 } 189 }
193} 190}
@@ -199,18 +196,7 @@ impl SinglePlaylistItem {
199 id: &str, 196 id: &str,
200 playlist_items: &[Item], 197 playlist_items: &[Item],
201 ) -> Self { 198 ) -> Self {
202 let saved = (|| -> Option<()> { 199 let saved = find_library_item(id, mainconfig).is_some();
203 fs::read_dir(
204 home_dir()
205 .unwrap()
206 .join(mainconfig.env.get("save-path")?.replacen("~/", "", 1)),
207 )
208 .ok()?
209 .filter_map(|entry| Some(entry.ok()?.path().file_stem()?.to_os_string()))
210 .find(|stem| stem.as_os_str().to_str().unwrap_or_default().contains(id))?;
211 Some(())
212 })()
213 .is_some();
214 if saved { 200 if saved {
215 Self::new_with_map( 201 Self::new_with_map(
216 commands 202 commands
@@ -329,8 +315,9 @@ impl SinglePlaylistItem {
329 } 315 }
330 316
331 /// creates a hashmap from `self`, containing info of the current item 317 /// creates a hashmap from `self`, containing info of the current item
332 pub fn inflate_load(&self, item: &Item) -> Vec<(String, String)> { 318 pub fn inflate_load(&self, item: &Item, mainconfig: &MainConfig) -> Vec<(String, String)> {
333 let playlist_item = item.fullplaylist().unwrap(); 319 let playlist_item = item.fullplaylist().unwrap();
320 let path = find_library_item(&playlist_item.id, mainconfig);
334 321
335 vec![ 322 vec![
336 (String::from("id"), playlist_item.id.clone()), 323 (String::from("id"), playlist_item.id.clone()),
@@ -345,6 +332,36 @@ impl SinglePlaylistItem {
345 .collect::<Vec<&str>>() 332 .collect::<Vec<&str>>()
346 .join(" "), 333 .join(" "),
347 ), 334 ),
335 (
336 String::from("offline-path"),
337 path.clone()
338 .unwrap_or_default()
339 .to_str()
340 .unwrap()
341 .to_string(),
342 ),
343 (
344 String::from("offline-queuelist"),
345 match path {
346 Some(path) => match fs::read_dir(path) {
347 Ok(entries) => entries
348 .map(|entry| {
349 format!(
350 "mpv loadfile '{}'",
351 match entry {
352 Ok(entry) =>
353 entry.path().as_os_str().to_str().unwrap().to_string(),
354 Err(_) => String::new(),
355 }
356 )
357 })
358 .collect::<Vec<_>>()
359 .join(" ;; "),
360 Err(e) => e.to_string(),
361 },
362 None => String::from("bad path"),
363 },
364 ),
348 ] 365 ]
349 } 366 }
350} 367}
@@ -385,7 +402,7 @@ impl SingleItemType {
385 402
386 match self { 403 match self {
387 Self::Video(singlevideoitem) => singlevideoitem.inflate_load(mainconfig, status, item), 404 Self::Video(singlevideoitem) => singlevideoitem.inflate_load(mainconfig, status, item),
388 Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate_load(item), 405 Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate_load(item, mainconfig),
389 Self::None => Vec::new(), 406 Self::None => Vec::new(),
390 } 407 }
391 } 408 }
src/run.rs +5 −8
@@ -11,7 +11,7 @@ use tui_additions::framework::Framework;
11use crate::{ 11use crate::{
12 config::*, 12 config::*,
13 global::{functions::*, structs::*}, 13 global::{functions::*, structs::*},
14 items::SearchFilter, 14 items::{MessageBar, SearchFilter},
15}; 15};
16 16
17/// the main event loop of the program 17/// the main event loop of the program
@@ -48,13 +48,10 @@ pub fn run(
48 )? { 48 )? {
49 // do tick changes 49 // do tick changes
50 last_tick = Instant::now(); 50 last_tick = Instant::now();
51 // dbg!(framework 51 // TaskQueue::render_filter(framework, terminal, |item| (*item).type_id() == TypeId::of::<MessageBar>())?;
52 // .data 52 if MessageBar::is_mpv_render(&framework.split_clean().0) {
53 // .global 53 TaskQueue::render(framework, terminal)?;
54 // .get::<Status>() 54 }
55 // .unwrap()
56 // .mpv
57 // .sender.send(MpvAction::RequestI64 { name: "audio-pts".to_string() }));
58 continue; 55 continue;
59 } 56 }
60 57