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"
11781178[[package]]
11791179name = "tui-additions"
11801180version = "0.2.1"
1181source = "registry+https://github.com/rust-lang/crates.io-index"
1182checksum = "1de5841ec45de71c46252a832bb1e3e69abf2ee2492eb309ea077c8d78e798e7"
11831181dependencies = [
11841182 "crossterm 0.26.1",
11851183 "dyn-clone",
Cargo.toml +2 −2
@@ -29,7 +29,7 @@ viuer = {version = "0.6", default-features = false, optional = true}
2929home = "0.5"
3030chrono = {version = "0.4", default-features = false, features = ["clock"]}
3131typemap = {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"]}
3333invidious = {version = "0.5"}
3434serde_yaml = {version = "0.9", default-features = false}
3535dyn-clone = {version = "1.0", default-features = false}
@@ -39,7 +39,7 @@ urlencoding = "2.1"
3939ratatui = {version = "0.21", default-features = false, features = ["serde"]}
4040libmpv = { git = "https://github.com/sudipghimire533/libmpv-rs", optional = true }
4141
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"]}
4343# invidious = {path = "../../Rust/Packages/invidious"}
4444
4545[package.metadata.docs.rs]
src/config/commands.rs +10 −12
@@ -100,13 +100,11 @@ fn video_default() -> Vec<HashMap<String, String>> {
100100 )]),
101101 HashMap::from([(
102102 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}'"),
104104 )]),
105105 HashMap::from([(
106106 String::from("Play audio (loop)"),
107 String::from(
108 "parrun ${terminal-emulator} ${video-player} '${embed-url}' --no-video --loop-file=inf",
109 ),
107 String::from("mpv sprop loop inf ;; mpv loadfile '${embed-url}'"),
110108 )]),
111109 HashMap::from([(
112110 String::from("View channel"),
@@ -147,15 +145,15 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
147145 )]),
148146 HashMap::from([(
149147 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"),
151149 )]),
152150 HashMap::from([(
153151 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}'"),
155153 )]),
156154 HashMap::from([(
157155 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}'"),
159157 )]),
160158 HashMap::from([(
161159 String::from("View channel"),
@@ -197,15 +195,15 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
197195 )]),
198196 HashMap::from([(
199197 String::from("Play all (videos)"),
200 String::from("parrun ${video-player} ${all-videos}"),
198 String::from("parrun ${video-player} ${url}"),
201199 )]),
202200 HashMap::from([(
203201 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"),
205203 )]),
206204 HashMap::from([(
207205 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"),
209207 )]),
210208 HashMap::from([(
211209 String::from("View channel"),
@@ -251,11 +249,11 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
251249 )]),
252250 HashMap::from([(
253251 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"),
255253 )]),
256254 HashMap::from([(
257255 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"),
259257 )]),
260258 HashMap::from([(
261259 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;
1515pub use commands::*;
1616mod commandbindings;
1717pub use commandbindings::*;
18mod commands_remap;
19pub use commands_remap::*;
1820
1921pub 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;
3333pub use remove_word::*;
3434mod key_input;
3535pub 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> {
2222 .collect::<Vec<_>>()
2323 .as_slice()
2424 {
25 ["help"] => Some(String::from(HELP_MSG)),
25 ["help"] => Some(help_msg(
26 &CommandsRemapConfig::load(WriteConfig::Dont).unwrap(),
27 )),
2628 ["version"] => Some(format!(
2729 "{} {}",
2830 env!("CARGO_PKG_NAME"),
@@ -101,7 +103,7 @@ pub fn run_single_command(
101103 run_single_command(&["bookmark", id], framework, terminal);
102104 }
103105 }
104 ["help"] | ["h"] => {
106 ["help"] => {
105107 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
106108 "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
107109 ));
@@ -115,10 +117,6 @@ pub fn run_single_command(
115117 Message::Success(format!("Provider updated to {}", status.provider.as_str()));
116118 update_provider(&mut framework.data);
117119 }
118 ["loadpage"] => {
119 *framework.data.global.get_mut::<Message>().unwrap() =
120 Message::Message(String::from("Usage: `loadpage {page}`"));
121 }
122120 // loads a given page
123121 ["loadpage", page, ..] => {
124122 let page = match *page {
@@ -209,37 +207,6 @@ pub fn run_single_command(
209207 .push(Task::LoadPage(page))
210208 }
211209 }
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 }
243210 ["history", "back"] | ["back"] => {
244211 let _ = framework.revert_last_history();
245212 framework
@@ -284,14 +251,14 @@ pub fn run_single_command(
284251 .priority
285252 .push(Task::Reload);
286253 }
287 ["reload", "config"] | ["reload", "configs"] | ["r", "config"] | ["r", "configs"] => {
254 ["reload", "configs"] => {
288255 *framework.data.global.get_mut::<Message>().unwrap() =
289256 match load_configs(&mut framework.split_clean().0) {
290257 Ok(()) => Message::Success(String::from("Config files have been reloaded")),
291258 Err(e) => Message::Error(e.to_string()),
292259 };
293260 }
294 ["q"] | ["quit"] | ["x"] | ["exit"] => {
261 ["quit"] => {
295262 framework.data.global.get_mut::<Status>().unwrap().exit = true;
296263 }
297264 ["hello", "world"] => {
@@ -299,17 +266,13 @@ pub fn run_single_command(
299266 *framework.data.global.get_mut::<Message>().unwrap() =
300267 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
301268 }
302 ["version"] | ["v"] => {
269 ["version"] => {
303270 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(format!(
304271 "{} {}",
305272 env!("CARGO_PKG_NAME"),
306273 env!("CARGO_PKG_VERSION")
307274 ));
308275 }
309 ["run"] | ["parrun"] => {
310 *framework.data.global.get_mut::<Message>().unwrap() =
311 Message::Message(String::from("Usage: run/parrun [command]"));
312 }
313276 ["run", ..] => {
314277 let command = command[1..].join(" ");
315278 *framework.data.global.get_mut::<Message>().unwrap() =
@@ -334,17 +297,13 @@ pub fn run_single_command(
334297 .stderr(Stdio::null())
335298 .spawn();
336299 }
337 ["copy"] | ["cp"] => {
338 *framework.data.global.get_mut::<Message>().unwrap() =
339 Message::Message(String::from("Usage: copy [text]"));
340 }
341300 #[cfg(feature = "clipboard")]
342 ["copy", ..] | ["cp", ..] => {
301 ["copy", ..] => {
343302 set_clipboard(command[1..].join(" "));
344303 *framework.data.global.get_mut::<Message>().unwrap() =
345304 Message::Success(String::from("Copied to clipboad"));
346305 }
347 ["sub", identifier] | ["sync", identifier] => {
306 ["sync", identifier] => {
348307 let id = if identifier.len() == 24 {
349308 identifier.to_string()
350309 } else {
@@ -514,13 +473,13 @@ pub fn run_single_command(
514473 };
515474 }
516475 #[cfg(feature = "mpv")]
517 ["mpv", "set_property", name, value] | ["mpv", "sprop", name, value] => {
476 ["mpv", "set_property", name, ..] | ["mpv", "sprop", name, ..] => {
518477 let res = framework
519478 .data
520479 .global
521480 .get::<MpvWrapper>()
522481 .unwrap()
523 .set_property(name.to_string(), value.to_string());
482 .set_property(name.to_string(), command[3..].join(" "));
524483
525484 *framework.data.global.get_mut::<Message>().unwrap() = match res {
526485 MpvResponse::Copy => Message::Mpv("Value set".to_string()),
@@ -541,7 +500,22 @@ pub fn run_single_command(
541500 _ => unreachable!(),
542501 };
543502 }
503 ["echo", ..] => {
504 *framework.data.global.get_mut::<Message>().unwrap() =
505 Message::Message(command[1..].join(" "))
506 }
544507 _ => {
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
545519 *framework.data.global.get_mut::<Message>().unwrap() =
546520 Message::Error(format!("Unknown command: `{}`", command.join(" ")));
547521 }
@@ -579,7 +553,8 @@ const HELLO_WORLDS: &[&str] = &[
579553 "<h1>Hello World<\\h1>",
580554];
581555
582const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
556fn help_msg(cmdefines: &CommandsRemapConfig) -> String {
557 format!("\x1b[32mYouTube TUI commands\x1b[0m
583558
584559\x1b[37mfor more visit https://siriusmart.github.io/youtube-tui/commands.html\x1b[0m
585560
@@ -626,13 +601,9 @@ const HELP_MSG: &str = "\x1b[32mYouTube TUI commands\x1b[0m
626601 \x1b[33munsub [id or url]\x1b[0m Remove channel from subscription
627602 \x1b[33msyncall\x1b[0m Sync all subscriptions
628603
629\x1b[91mALT:\x1b[0m
630\x1b[37malts links back to the original command\x1b[30m
631 \x1b[33m[page] (additional options)\x1b[0m `loadpage [page]`
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]`
604\x1b[91mCUSTOM COMMANDS:\x1b[0m
605\x1b[37mdefined in cmdefine.yml\x1b[30m
606{}
637607
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) {
163163 ),
164164 },
165165 ),
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 ),
166188 ],
167189 };
168190
src/global/structs/mpv.rs +7
@@ -107,6 +107,13 @@ impl MpvWrapper {
107107 }
108108}
109109
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
110117#[derive(Debug)]
111118pub enum MpvAction {
112119 Command {
src/global/structs/tasks.rs +70 −12
@@ -7,7 +7,7 @@ use ratatui::{
77 backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal,
88};
99use std::{error::Error, io::Stdout, mem};
10use tui_additions::framework::{CursorState, Framework};
10use tui_additions::framework::{CursorState, Framework, FrameworkItem};
1111use typemap::Key;
1212
1313/// tasks to be put on taskqueues
@@ -176,13 +176,8 @@ impl TaskQueue {
176176 }
177177
178178 match self.render {
179 RenderTask::All => {
180 Self::render(framework, terminal)?;
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 }
179 RenderTask::All => Self::render(framework, terminal)?,
180 RenderTask::Only(locations) => Self::render_onlys(framework, terminal, locations)?,
186181 RenderTask::None => {}
187182 }
188183
@@ -224,12 +219,29 @@ impl TaskQueue {
224219 Ok(())
225220 }
226221
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
227240 /// this function renders onto the given frame
228241 pub fn render_with_frame(
229242 framework: &mut Framework,
230243 frame: &mut Frame<CrosstermBackend<Stdout>>,
231244 ) {
232 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
233245 let area = frame.size();
234246
235247 framework
@@ -239,6 +251,52 @@ impl TaskQueue {
239251 .unwrap()
240252 .prev_frame = Some(area);
241253
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
242300 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
243301 if area.width < min_dimentions.width || area.height < min_dimentions.height {
244302 let paragraph = Paragraph::new(format!(
@@ -260,10 +318,10 @@ impl TaskQueue {
260318 .text_error),
261319 );
262320 frame.render_widget(paragraph, area);
263 return;
321 true
322 } else {
323 false
264324 }
265
266 framework.render(frame);
267325 }
268326}
269327
src/init.rs +4
@@ -122,6 +122,10 @@ pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>
122122 .data
123123 .global
124124 .insert::<PagesConfig>(*PagesConfig::load(main_config.write_config)?);
125 framework
126 .data
127 .global
128 .insert::<CommandsRemapConfig>(*CommandsRemapConfig::load(main_config.write_config)?);
125129 framework
126130 .data
127131 .global
src/items/itemlist.rs +1 −1
@@ -388,7 +388,7 @@ impl FrameworkItem for ItemList {
388388 };
389389
390390 // only create a render task if the key event actually changed something
391 if updated {
391 if updated && !self.items.is_empty() {
392392 self.update(framework);
393393 set_envs(
394394 self.infalte_item_update(
src/items/messagebar.rs +37 −2
@@ -4,7 +4,7 @@ use ratatui::{
44 style::Style,
55 widgets::{Block, Borders, Paragraph},
66};
7use tui_additions::framework::FrameworkItem;
7use tui_additions::framework::{FrameworkClean, FrameworkItem};
88
99/// a message bar item, contains no fields because the message is taken from `data.global.Message`
1010#[derive(Clone, Copy, Default)]
@@ -23,8 +23,26 @@ impl FrameworkItem for MessageBar {
2323 return;
2424 }
2525
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
2744 let message = framework.data.global.get::<Message>().unwrap();
45 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
2846
2947 // the Option<TextList> that is Some if keys were captured for entering command
3048 let command_capture = &framework
@@ -84,3 +102,20 @@ impl FrameworkItem for MessageBar {
84102 false
85103 }
86104}
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 {
6565
6666impl SingleVideoItem {
6767 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig, id: &str) -> Self {
68 let saved = (|| -> Option<()> {
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();
68 let saved = find_library_item(id, mainconfig).is_some();
8069 if saved {
8170 Self::new_with_map(
8271 commands
@@ -188,6 +177,14 @@ impl SingleVideoItem {
188177 ),
189178 },
190179 ),
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 ),
191188 ]
192189 }
193190}
@@ -199,18 +196,7 @@ impl SinglePlaylistItem {
199196 id: &str,
200197 playlist_items: &[Item],
201198 ) -> Self {
202 let saved = (|| -> Option<()> {
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();
199 let saved = find_library_item(id, mainconfig).is_some();
214200 if saved {
215201 Self::new_with_map(
216202 commands
@@ -329,8 +315,9 @@ impl SinglePlaylistItem {
329315 }
330316
331317 /// 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)> {
333319 let playlist_item = item.fullplaylist().unwrap();
320 let path = find_library_item(&playlist_item.id, mainconfig);
334321
335322 vec![
336323 (String::from("id"), playlist_item.id.clone()),
@@ -345,6 +332,36 @@ impl SinglePlaylistItem {
345332 .collect::<Vec<&str>>()
346333 .join(" "),
347334 ),
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 ),
348365 ]
349366 }
350367}
@@ -385,7 +402,7 @@ impl SingleItemType {
385402
386403 match self {
387404 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),
389406 Self::None => Vec::new(),
390407 }
391408 }
src/run.rs +5 −8
@@ -11,7 +11,7 @@ use tui_additions::framework::Framework;
1111use crate::{
1212 config::*,
1313 global::{functions::*, structs::*},
14 items::SearchFilter,
14 items::{MessageBar, SearchFilter},
1515};
1616
1717/// the main event loop of the program
@@ -48,13 +48,10 @@ pub fn run(
4848 )? {
4949 // do tick changes
5050 last_tick = Instant::now();
51 // dbg!(framework
52 // .data
53 // .global
54 // .get::<Status>()
55 // .unwrap()
56 // .mpv
57 // .sender.send(MpvAction::RequestI64 { name: "audio-pts".to_string() }));
51 // TaskQueue::render_filter(framework, terminal, |item| (*item).type_id() == TypeId::of::<MessageBar>())?;
52 if MessageBar::is_mpv_render(&framework.split_clean().0) {
53 TaskQueue::render(framework, terminal)?;
54 }
5855 continue;
5956 }
6057