Commit 53f9719013

53f9719013f3ec23ff18989f1a29588f2a56644a

parent: 99be1b008d

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-12-17 14:39 UTC

full mouse click support

Layout: unified · split

Cargo.lock +102 −17
@@ -19,9 +19,9 @@ dependencies = [
19 19
20[[package]] 20[[package]]
21name = "ansi_colours" 21name = "ansi_colours"
22version = "1.1.1" 22version = "1.2.1"
23source = "registry+https://github.com/rust-lang/crates.io-index" 23source = "registry+https://github.com/rust-lang/crates.io-index"
24checksum = "32678233b67f9056b0c144b39d46dc3218637e8d84ad6038ded339e08b19620d" 24checksum = "7db9d9767fde724f83933a716ee182539788f293828244e9d999695ce0f7ba1e"
25dependencies = [ 25dependencies = [
26 "rgb", 26 "rgb",
27] 27]
@@ -50,6 +50,12 @@ version = "1.3.2"
50source = "registry+https://github.com/rust-lang/crates.io-index" 50source = "registry+https://github.com/rust-lang/crates.io-index"
51checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 51checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
52 52
53[[package]]
54name = "block"
55version = "0.1.6"
56source = "registry+https://github.com/rust-lang/crates.io-index"
57checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
58
53[[package]] 59[[package]]
54name = "bumpalo" 60name = "bumpalo"
55version = "3.11.1" 61version = "3.11.1"
@@ -82,9 +88,9 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
82 88
83[[package]] 89[[package]]
84name = "cc" 90name = "cc"
85version = "1.0.77" 91version = "1.0.78"
86source = "registry+https://github.com/rust-lang/crates.io-index" 92source = "registry+https://github.com/rust-lang/crates.io-index"
87checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" 93checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d"
88 94
89[[package]] 95[[package]]
90name = "cfg-if" 96name = "cfg-if"
@@ -104,6 +110,28 @@ dependencies = [
104 "winapi", 110 "winapi",
105] 111]
106 112
113[[package]]
114name = "clipboard"
115version = "0.5.0"
116source = "registry+https://github.com/rust-lang/crates.io-index"
117checksum = "25a904646c0340239dcf7c51677b33928bf24fdf424b79a57909c0109075b2e7"
118dependencies = [
119 "clipboard-win",
120 "objc",
121 "objc-foundation",
122 "objc_id",
123 "x11-clipboard",
124]
125
126[[package]]
127name = "clipboard-win"
128version = "2.2.0"
129source = "registry+https://github.com/rust-lang/crates.io-index"
130checksum = "e3a093d6fed558e5fe24c3dfc85a68bb68f1c824f440d3ba5aca189e2998786b"
131dependencies = [
132 "winapi",
133]
134
107[[package]] 135[[package]]
108name = "codespan-reporting" 136name = "codespan-reporting"
109version = "0.11.1" 137version = "0.11.1"
@@ -723,9 +751,9 @@ dependencies = [
723 751
724[[package]] 752[[package]]
725name = "ipnet" 753name = "ipnet"
726version = "2.6.0" 754version = "2.7.0"
727source = "registry+https://github.com/rust-lang/crates.io-index" 755source = "registry+https://github.com/rust-lang/crates.io-index"
728checksum = "ec947b7a4ce12e3b87e353abae7ce124d025b6c7d6c5aea5cc0bcf92e9510ded" 756checksum = "11b0d96e660696543b251e58030cf9787df56da39dab19ad60eae7353040917e"
729 757
730[[package]] 758[[package]]
731name = "itoa" 759name = "itoa"
@@ -803,6 +831,15 @@ version = "0.1.0"
803source = "registry+https://github.com/rust-lang/crates.io-index" 831source = "registry+https://github.com/rust-lang/crates.io-index"
804checksum = "a8ca8afbe8af1785e09636acb5a41e08a765f5f0340568716c18a8700ba3c0d3" 832checksum = "a8ca8afbe8af1785e09636acb5a41e08a765f5f0340568716c18a8700ba3c0d3"
805 833
834[[package]]
835name = "malloc_buf"
836version = "0.0.6"
837source = "registry+https://github.com/rust-lang/crates.io-index"
838checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
839dependencies = [
840 "libc",
841]
842
806[[package]] 843[[package]]
807name = "memchr" 844name = "memchr"
808version = "2.5.0" 845version = "2.5.0"
@@ -912,6 +949,35 @@ dependencies = [
912 "libc", 949 "libc",
913] 950]
914 951
952[[package]]
953name = "objc"
954version = "0.2.7"
955source = "registry+https://github.com/rust-lang/crates.io-index"
956checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
957dependencies = [
958 "malloc_buf",
959]
960
961[[package]]
962name = "objc-foundation"
963version = "0.1.1"
964source = "registry+https://github.com/rust-lang/crates.io-index"
965checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"
966dependencies = [
967 "block",
968 "objc",
969 "objc_id",
970]
971
972[[package]]
973name = "objc_id"
974version = "0.1.1"
975source = "registry+https://github.com/rust-lang/crates.io-index"
976checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b"
977dependencies = [
978 "objc",
979]
980
915[[package]] 981[[package]]
916name = "once_cell" 982name = "once_cell"
917version = "1.16.0" 983version = "1.16.0"
@@ -1062,11 +1128,10 @@ dependencies = [
1062 1128
1063[[package]] 1129[[package]]
1064name = "rayon" 1130name = "rayon"
1065version = "1.6.0" 1131version = "1.6.1"
1066source = "registry+https://github.com/rust-lang/crates.io-index" 1132source = "registry+https://github.com/rust-lang/crates.io-index"
1067checksum = "1e060280438193c554f654141c9ea9417886713b7acd75974c85b18a69a88e0b" 1133checksum = "6db3a213adf02b3bcfd2d3846bb41cb22857d131789e01df434fb7e7bc0759b7"
1068dependencies = [ 1134dependencies = [
1069 "crossbeam-deque",
1070 "either", 1135 "either",
1071 "rayon-core", 1136 "rayon-core",
1072] 1137]
@@ -1206,18 +1271,18 @@ dependencies = [
1206 1271
1207[[package]] 1272[[package]]
1208name = "serde" 1273name = "serde"
1209version = "1.0.149" 1274version = "1.0.151"
1210source = "registry+https://github.com/rust-lang/crates.io-index" 1275source = "registry+https://github.com/rust-lang/crates.io-index"
1211checksum = "256b9932320c590e707b94576e3cc1f7c9024d0ee6612dfbcf1cb106cbe8e055" 1276checksum = "97fed41fc1a24994d044e6db6935e69511a1153b52c15eb42493b26fa87feba0"
1212dependencies = [ 1277dependencies = [
1213 "serde_derive", 1278 "serde_derive",
1214] 1279]
1215 1280
1216[[package]] 1281[[package]]
1217name = "serde_derive" 1282name = "serde_derive"
1218version = "1.0.149" 1283version = "1.0.151"
1219source = "registry+https://github.com/rust-lang/crates.io-index" 1284source = "registry+https://github.com/rust-lang/crates.io-index"
1220checksum = "b4eae9b04cbffdfd550eb462ed33bc6a1b68c935127d008b27444d08380f94e4" 1285checksum = "255abe9a125a985c05190d687b320c12f9b1f0b99445e608c21ba0782c719ad8"
1221dependencies = [ 1286dependencies = [
1222 "proc-macro2", 1287 "proc-macro2",
1223 "quote", 1288 "quote",
@@ -1397,9 +1462,9 @@ dependencies = [
1397 1462
1398[[package]] 1463[[package]]
1399name = "tiff" 1464name = "tiff"
1400version = "0.8.0" 1465version = "0.8.1"
1401source = "registry+https://github.com/rust-lang/crates.io-index" 1466source = "registry+https://github.com/rust-lang/crates.io-index"
1402checksum = "f17def29300a156c19ae30814710d9c63cd50288a49c6fd3a10ccfbe4cf886fd" 1467checksum = "7449334f9ff2baf290d55d73983a7d6fa15e01198faef72af07e2a8db851e471"
1403dependencies = [ 1468dependencies = [
1404 "flate2", 1469 "flate2",
1405 "jpeg-decoder", 1470 "jpeg-decoder",
@@ -1516,9 +1581,9 @@ dependencies = [
1516 1581
1517[[package]] 1582[[package]]
1518name = "tui-additions" 1583name = "tui-additions"
1519version = "0.1.11" 1584version = "0.1.12"
1520source = "registry+https://github.com/rust-lang/crates.io-index" 1585source = "registry+https://github.com/rust-lang/crates.io-index"
1521checksum = "42473ced74bd112a4c96a03aa03bfdce0d3545a0696164379ac901efe2cd6e73" 1586checksum = "3bfce9dd63be9026ffd15ea51ee0afb2fe386263decb04e2bcc0c23556a79a1f"
1522dependencies = [ 1587dependencies = [
1523 "crossterm", 1588 "crossterm",
1524 "dyn-clone", 1589 "dyn-clone",
@@ -1868,11 +1933,31 @@ dependencies = [
1868 "winapi", 1933 "winapi",
1869] 1934]
1870 1935
1936[[package]]
1937name = "x11-clipboard"
1938version = "0.3.3"
1939source = "registry+https://github.com/rust-lang/crates.io-index"
1940checksum = "89bd49c06c9eb5d98e6ba6536cf64ac9f7ee3a009b2f53996d405b3944f6bcea"
1941dependencies = [
1942 "xcb",
1943]
1944
1945[[package]]
1946name = "xcb"
1947version = "0.8.2"
1948source = "registry+https://github.com/rust-lang/crates.io-index"
1949checksum = "5e917a3f24142e9ff8be2414e36c649d47d6cc2ba81f16201cdef96e533e02de"
1950dependencies = [
1951 "libc",
1952 "log",
1953]
1954
1871[[package]] 1955[[package]]
1872name = "youtube-tui" 1956name = "youtube-tui"
1873version = "0.6.0" 1957version = "0.6.0"
1874dependencies = [ 1958dependencies = [
1875 "chrono", 1959 "chrono",
1960 "clipboard",
1876 "crossterm", 1961 "crossterm",
1877 "dyn-clone", 1962 "dyn-clone",
1878 "execute", 1963 "execute",
Cargo.toml +1
@@ -37,6 +37,7 @@ futures = {version = "0.3", default-features = false}
37reqwest = {version = "0.11", default-features = false} 37reqwest = {version = "0.11", default-features = false}
38serde_json = {version = "1.0", default-features = false} 38serde_json = {version = "1.0", default-features = false}
39execute = {version = "0.2", default-features = false} 39execute = {version = "0.2", default-features = false}
40clipboard = {version = "0.5"}
40 41
41# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]} 42# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
42# invidious = {path = "../../Rust/Packages/invidious", default-features = false, features = ["reqwest"]} 43# invidious = {path = "../../Rust/Packages/invidious", default-features = false, features = ["reqwest"]}
README.md +1 −1
@@ -16,7 +16,7 @@ It is like an *app launcher*, it launches other programs to do the heavy lifting
16 16
17> ### Mouse support 17> ### Mouse support
18> 18>
19> Mouse click support partially implemented, now it works for selecting/deselecting, interacting with buttons and moving the cursor in the search bar. 19> Mouse support completely implemented, currently writing docs.
20 20
21## Customisable 21## Customisable
22 22
src/config/appearance.rs +9
@@ -92,6 +92,7 @@ pub struct ColorsConfig {
92 pub message_outline: Color, 92 pub message_outline: Color,
93 pub message_error_outline: Color, 93 pub message_error_outline: Color,
94 pub message_success_outline: Color, 94 pub message_success_outline: Color,
95 pub command_capture: Color,
95 pub item_info: ItemInfoColors, 96 pub item_info: ItemInfoColors,
96} 97}
97 98
@@ -136,6 +137,8 @@ pub struct ColorsConfigSerde {
136 pub message_error_outline: ColorSerde, 137 pub message_error_outline: ColorSerde,
137 #[serde(default = "message_success_outline_default")] 138 #[serde(default = "message_success_outline_default")]
138 pub message_success_outline: ColorSerde, 139 pub message_success_outline: ColorSerde,
140 #[serde(default = "command_capture_default")]
141 pub command_capture: ColorSerde,
139 #[serde(default)] 142 #[serde(default)]
140 pub item_info: ItemInfoColorsSerde, 143 pub item_info: ItemInfoColorsSerde,
141} 144}
@@ -184,6 +187,7 @@ impl ColorsConfigSerde {
184 message_outline: self.message_outline.to_color()?, 187 message_outline: self.message_outline.to_color()?,
185 message_error_outline: self.message_error_outline.to_color()?, 188 message_error_outline: self.message_error_outline.to_color()?,
186 message_success_outline: self.message_success_outline.to_color()?, 189 message_success_outline: self.message_success_outline.to_color()?,
190 command_capture: self.command_capture.to_color()?,
187 item_info: self.item_info.into()?, 191 item_info: self.item_info.into()?,
188 }) 192 })
189 } 193 }
@@ -222,6 +226,7 @@ impl Default for ColorsConfigSerde {
222 message_error_outline: message_error_outline_default(), 226 message_error_outline: message_error_outline_default(),
223 message_success_outline: message_success_outline_default(), 227 message_success_outline: message_success_outline_default(),
224 text_error: text_error_default(), 228 text_error: text_error_default(),
229 command_capture: command_capture_default(),
225 item_info: ItemInfoColorsSerde::default(), 230 item_info: ItemInfoColorsSerde::default(),
226 } 231 }
227 } 232 }
@@ -356,3 +361,7 @@ fn genre_default() -> ColorSerde {
356fn page_turner_default() -> ColorSerde { 361fn page_turner_default() -> ColorSerde {
357 ColorSerde::ColorVariant(ColorVariantSerde::Gray) 362 ColorSerde::ColorVariant(ColorVariantSerde::Gray)
358} 363}
364
365fn command_capture_default() -> ColorSerde {
366 ColorSerde::Hex(String::from("#64FF64"))
367}
src/config/commands.rs +8
@@ -75,6 +75,10 @@ fn video_default() -> Vec<HashMap<String, String>> {
75 "${terminal-emulator} ${video-player} ${embed-url} --no-video --loop-file=inf", 75 "${terminal-emulator} ${video-player} ${embed-url} --no-video --loop-file=inf",
76 ), 76 ),
77 )]), 77 )]),
78 HashMap::from([(
79 String::from("View channel"),
80 String::from(":channel ${channel_id}"),
81 )]),
78 HashMap::from([( 82 HashMap::from([(
79 String::from("Open in browser"), 83 String::from("Open in browser"),
80 String::from("${browser} ${url}"), 84 String::from("${browser} ${url}"),
@@ -117,6 +121,10 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
117 String::from("Shuffle play all audio (loop)"), 121 String::from("Shuffle play all audio (loop)"),
118 String::from("${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"), 122 String::from("${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"),
119 )]), 123 )]),
124 HashMap::from([(
125 String::from("View channel"),
126 String::from(":channel ${channel_id}"),
127 )]),
120 HashMap::from([( 128 HashMap::from([(
121 String::from("Open in browser"), 129 String::from("Open in browser"),
122 String::from("${browser} ${url}"), 130 String::from("${browser} ${url}"),
src/config/keybindings.rs +23 −1
@@ -3,7 +3,7 @@ use crate::global::{
3 structs::KeyAction, 3 structs::KeyAction,
4 traits::{ConfigTrait, EXTENSION}, 4 traits::{ConfigTrait, EXTENSION},
5}; 5};
6use crossterm::event::KeyCode; 6use crossterm::event::{KeyCode, KeyEvent};
7use home::home_dir; 7use home::home_dir;
8use serde::{Deserialize, Serialize}; 8use serde::{Deserialize, Serialize};
9use std::{ 9use std::{
@@ -91,6 +91,10 @@ impl Default for KeyBindingsConfigSerde {
91 KeyCodeSerde::Char('r'), 91 KeyCodeSerde::Char('r'),
92 HashMap::from([(2, KeyAction::Reload)]), 92 HashMap::from([(2, KeyAction::Reload)]),
93 ), 93 ),
94 (
95 KeyCodeSerde::Char(':'),
96 HashMap::from([(0, KeyAction::StartCommandCapture)]),
97 ),
94 // history 98 // history
95 ( 99 (
96 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace), 100 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace),
@@ -104,6 +108,15 @@ impl Default for KeyBindingsConfigSerde {
104 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home), 108 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home),
105 HashMap::from([(0, KeyAction::FirstHistory)]), 109 HashMap::from([(0, KeyAction::FirstHistory)]),
106 ), 110 ),
111 // clipboard
112 (
113 KeyCodeSerde::Char('c'),
114 HashMap::from([(2, KeyAction::Copy)]),
115 ),
116 (
117 KeyCodeSerde::Char('v'),
118 HashMap::from([(2, KeyAction::Paste)]),
119 ),
107 ])) 120 ]))
108 } 121 }
109} 122}
@@ -171,4 +184,13 @@ impl KeyBindingsConfig {
171 ), 184 ),
172 } 185 }
173 } 186 }
187
188 // gets the keyaction with the key
189 pub fn get(&self, key: KeyEvent) -> Option<KeyAction> {
190 if let Some(keyactions) = self.0.get(&key.code) {
191 keyactions.get(&key.modifiers.bits()).copied()
192 } else {
193 None
194 }
195 }
174} 196}
src/config/main.rs +7
@@ -6,6 +6,8 @@ use typemap::Key;
6/// `main.yml`, the main config file 6/// `main.yml`, the main config file
7#[derive(Serialize, Deserialize, Clone)] 7#[derive(Serialize, Deserialize, Clone)]
8pub struct MainConfig { 8pub struct MainConfig {
9 #[serde(default = "mouse_support_default")]
10 pub mouse_support: bool,
9 #[serde(default = "invidious_instance_default")] 11 #[serde(default = "invidious_instance_default")]
10 pub invidious_instance: String, 12 pub invidious_instance: String,
11 #[serde(default = "max_watch_history_default")] 13 #[serde(default = "max_watch_history_default")]
@@ -36,6 +38,7 @@ impl Key for MainConfig {
36impl Default for MainConfig { 38impl Default for MainConfig {
37 fn default() -> Self { 39 fn default() -> Self {
38 Self { 40 Self {
41 mouse_support: mouse_support_default(),
39 invidious_instance: invidious_instance_default(), 42 invidious_instance: invidious_instance_default(),
40 max_watch_history: max_watch_history_default(), 43 max_watch_history: max_watch_history_default(),
41 allow_unicode: allow_unicode_default(), 44 allow_unicode: allow_unicode_default(),
@@ -130,6 +133,10 @@ const fn max_watch_history_default() -> usize {
130 50 133 50
131} 134}
132 135
136const fn mouse_support_default() -> bool {
137 true
138}
139
133fn default_env() -> HashMap<String, String> { 140fn default_env() -> HashMap<String, String> {
134 HashMap::from([ 141 HashMap::from([
135 (String::from("video-player"), String::from("mpv")), 142 (String::from("video-player"), String::from("mpv")),
src/global/functions/clipboard.rs added +13
@@ -0,0 +1,13 @@
1use clipboard::{ClipboardContext, ClipboardProvider};
2
3/// get the clipboard content
4pub fn get_clipboard() -> String {
5 let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
6 ctx.get_contents().unwrap_or_default()
7}
8
9/// set the clipboard content, panics if failed
10pub fn set_clipboard(s: String) {
11 let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
12 ctx.set_contents(s).unwrap();
13}
src/global/functions/command_capture.rs added +80
@@ -0,0 +1,80 @@
1use super::get_clipboard;
2use crate::{
3 config::KeyBindingsConfig,
4 global::structs::{KeyAction, Message, Status, Task, Tasks},
5};
6use crossterm::event::{KeyCode, KeyEvent};
7use tui_additions::framework::FrameworkClean;
8
9/// handles key input when the user is entering commands
10pub fn command_capture(framework: &mut FrameworkClean, key: KeyEvent) -> bool {
11 if framework
12 .data
13 .global
14 .get::<KeyBindingsConfig>()
15 .unwrap()
16 .get(key)
17 == Some(KeyAction::Paste)
18 {
19 let textfield = framework
20 .data
21 .global
22 .get_mut::<Status>()
23 .unwrap()
24 .command_capture
25 .as_mut()
26 .unwrap();
27 // a textfield must have a width set, because we don't know the width yet just set it to the
28 // maximum value possible, so that the cursor will not be moved because of the small value
29 textfield.set_width(u16::MAX);
30 let content = get_clipboard();
31 if content.is_empty() {
32 *framework.data.global.get_mut::<Message>().unwrap() =
33 Message::Error(String::from("Clipboard empty"));
34 return true;
35 }
36
37 content.chars().for_each(|c| {
38 let _ = textfield.push(c);
39 });
40 return true;
41 }
42
43 let textfield = framework
44 .data
45 .global
46 .get_mut::<Status>()
47 .unwrap()
48 .command_capture
49 .as_mut()
50 .unwrap();
51 // a textfield must have a width set, because we don't know the width yet just set it to the
52 // maximum value possible, so that the cursor will not be moved because of the small value
53 textfield.set_width(u16::MAX);
54
55 match key.code {
56 KeyCode::Char(c) => textfield.push(c).is_ok(),
57 KeyCode::Up => textfield.first().is_ok(),
58 KeyCode::Down => textfield.last().is_ok(),
59 KeyCode::Left => textfield.left().is_ok(),
60 KeyCode::Right => textfield.right().is_ok(),
61 KeyCode::Backspace => textfield.pop().is_ok(),
62 KeyCode::Enter => {
63 framework
64 .data
65 .state
66 .get_mut::<Tasks>()
67 .unwrap()
68 .priority
69 .push(Task::Command(textfield.content.clone()));
70 framework
71 .data
72 .global
73 .get_mut::<Status>()
74 .unwrap()
75 .command_capture = None;
76 true
77 }
78 _ => false,
79 }
80}
src/global/functions/download_all_images.rs +1
@@ -9,6 +9,7 @@ pub struct DownloadRequest {
9} 9}
10 10
11impl From<&Item> for Option<DownloadRequest> { 11impl From<&Item> for Option<DownloadRequest> {
12 // turn `Item` into a thumbnail download request
12 fn from(item: &Item) -> Self { 13 fn from(item: &Item) -> Self {
13 Some(match item { 14 Some(match item {
14 Item::MiniVideo(minivideo) => DownloadRequest { 15 Item::MiniVideo(minivideo) => DownloadRequest {
src/global/functions/fake_rand.rs added +11
@@ -0,0 +1,11 @@
1use chrono::Utc;
2use std::ops::{Add, Rem, Sub};
3
4/// generate a random number between range
5pub fn fake_rand_range<T>(from: T, to: T) -> T
6where T: From<i64> + Sub + Rem<<T as std::ops::Sub>::Output> + std::convert::From<<<T as std::ops::Rem<<T as std::ops::Sub>::Output>>::Output as std::ops::Add<T>>::Output> + Copy, <T as Rem<<T as Sub>::Output>>::Output: Add<T>
7{
8 let timestamp = Utc::now().timestamp();
9
10 (<i64 as Into<T>>::into(timestamp) % (to - from) + from).into()
11}
src/global/functions/mod.rs +8
@@ -11,3 +11,11 @@ mod popup_area;
11pub use popup_area::popup_area; 11pub use popup_area::popup_area;
12mod run_command; 12mod run_command;
13pub use run_command::run_command; 13pub use run_command::run_command;
14mod command_capture;
15pub use command_capture::command_capture;
16mod fake_rand;
17pub use fake_rand::*;
18mod clipboard;
19pub use self::clipboard::*;
20mod type_name_of_val;
21pub use type_name_of_val::*;
src/global/functions/run_command.rs +147 −8
@@ -1,8 +1,17 @@
1use crate::global::structs::{MainMenuPage, Page, Task, Tasks}; 1use crate::{
2 config::Search,
3 global::structs::{
4 ChannelDisplayPage, ChannelDisplayPageType, MainMenuPage, Message, Page, Status, Task,
5 Tasks,
6 },
7 load_configs,
8};
2use std::io::Stdout; 9use std::io::Stdout;
3use tui::{backend::CrosstermBackend, Terminal}; 10use tui::{backend::CrosstermBackend, Terminal};
4use tui_additions::framework::Framework; 11use tui_additions::framework::Framework;
5 12
13use super::fake_rand_range;
14
6/// WIP text command support 15/// WIP text command support
7pub fn run_command( 16pub fn run_command(
8 command: &[&str], 17 command: &[&str],
@@ -12,11 +21,81 @@ pub fn run_command(
12 // match a command splitted by space to a bunch of avaliable commands 21 // match a command splitted by space to a bunch of avaliable commands
13 match command { 22 match command {
14 [] => {} 23 [] => {}
15 ["loadpage"] => { /* help message */ } 24 ["help"] | ["h"] => {
16 ["loadpage", page] => { 25 *framework.data.global.get_mut::<Message>().unwrap() = Message::Message(String::from(
26 "Avaliable commands can be viewed by running `youtube-tui help` in terminal",
27 ))
28 }
29 ["loadpage"] => {
30 *framework.data.global.get_mut::<Message>().unwrap() =
31 Message::Message(String::from("Usage: `loadpage {page}`"))
32 }
33 // loads a given page
34 ["loadpage", page, ..] => {
17 let page = match *page { 35 let page = match *page {
18 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)), 36 "popular" => Some(Page::MainMenu(MainMenuPage::Popular)),
19 _ => None, 37 "trending" => Some(Page::MainMenu(MainMenuPage::Trending)),
38 "history" => Some(Page::MainMenu(MainMenuPage::History)),
39 "channel" => {
40 if command.len() == 2 {
41 *framework.data.global.get_mut::<Message>().unwrap() =
42 Message::Message(String::from(
43 "Usage: `loadpage channel {id/url}` or `channel {id/url}`",
44 ));
45 return;
46 }
47 // a youtube channel id is exactly 24 characters long, so if the identifier to 24 chars
48 // long, then just assume its the channel id
49 let id = if command[2].len() == 24 {
50 command[2].to_string()
51 } else {
52 // the channel id comes after `/channel/` in an url
53 let index = if let Some(index) = command[2].find("/channel/") {
54 // if there isnt 24 characters after `/channel/`, that url must not have
55 // contained a channel id
56 if command[2].len() < index + 33 {
57 *framework.data.global.get_mut::<Message>().unwrap() =
58 Message::Error(format!(
59 "Cannot find channel id from string `{}`",
60 command[2]
61 ));
62 return;
63 }
64 index + 9
65 } else {
66 *framework.data.global.get_mut::<Message>().unwrap() = Message::Error(
67 format!("Cannot find channel id from string `{}`", command[2]),
68 );
69 return;
70 };
71
72 command[2][index..index + 24].to_string()
73 };
74
75 Some(Page::ChannelDisplay(ChannelDisplayPage {
76 id,
77 r#type: ChannelDisplayPageType::Main,
78 }))
79 }
80 "search" => {
81 if command.len() == 2 {
82 *framework.data.global.get_mut::<Message>().unwrap() =
83 Message::Message(String::from("Usage: `search {query}`"));
84 return;
85 }
86
87 // search for a query, although the command is matched as an array, the original query can
88 // be reconstructed by joining the string with a space in between
89 let search = framework.data.state.get_mut::<Search>().unwrap();
90 search.query = command[2..].join(" ");
91 let cloned = search.clone();
92 Some(Page::Search(cloned))
93 }
94 _ => {
95 *framework.data.global.get_mut::<Message>().unwrap() =
96 Message::Error(format!("Unknown page: `{page}`"));
97 None
98 }
20 }; 99 };
21 100
22 if let Some(page) = page { 101 if let Some(page) = page {
@@ -29,10 +108,21 @@ pub fn run_command(
29 .push(Task::LoadPage(page)) 108 .push(Task::LoadPage(page))
30 } 109 }
31 } 110 }
32 ["history"] => { /* help message */ } 111 // redirects to the relevant `loadpage` command
33 ["history", "clear"] => { 112 ["search"] => run_command(&["loadpage", "search"], framework, terminal),
34 framework.clear_history(); 113 ["search", ..] => run_command(
114 &format!("loadpage search {}", command[1..].join(" "))
115 .split(' ')
116 .collect::<Vec<&str>>(),
117 framework,
118 terminal,
119 ),
120 ["channel"] => run_command(&["loadpage", "channel"], framework, terminal),
121 ["channel", identifier] => {
122 run_command(&["loadpage", "channel", *identifier], framework, terminal)
35 } 123 }
124 ["history"] => { /* help message */ }
125 ["history", "clear"] => framework.clear_history(),
36 ["flush"] => loop { 126 ["flush"] => loop {
37 // runs all stacked actions 127 // runs all stacked actions
38 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() { 128 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
@@ -41,6 +131,55 @@ pub fn run_command(
41 } 131 }
42 break; 132 break;
43 }, 133 },
44 _ => {} 134 ["reload", "config"] | ["reload", "configs"] => {
135 *framework.data.global.get_mut::<Message>().unwrap() =
136 match load_configs(&mut framework.split_clean().0) {
137 Ok(()) => Message::Success(String::from("Config files have been reloaded")),
138 Err(e) => Message::Error(e.to_string()),
139 }
140 }
141 ["q"] | ["quit"] | ["x"] | ["exit"] => {
142 framework.data.global.get_mut::<Status>().unwrap().exit = true;
143 }
144 ["hello", "world"] => {
145 let index = fake_rand_range(0, HELLO_WORLDS.len() as i64) as usize;
146 *framework.data.global.get_mut::<Message>().unwrap() =
147 Message::Message(format!("Line #{index}: {}", HELLO_WORLDS[index]));
148 }
149 _ => {
150 *framework.data.global.get_mut::<Message>().unwrap() =
151 Message::Error(format!("Unknown command: `{}`", command.join(" ")))
152 }
45 } 153 }
46} 154}
155
156const HELLO_WORLDS: &[&str] = &[
157 "printf(\"Hello World\")",
158 "std::cout << \"Hello World\"",
159 "DISPLAY \"Hello World\". .",
160 "printIn(\"Hello World\")",
161 "disp('Hello World')",
162 "System.Console.WriteLine(\"Hello World\")",
163 "console.lof 'Hello World'",
164 "WriteLn('Hello World')",
165 "print('Hello World')",
166 "main = putStrLn \"Hello World\"",
167 "writeln ('Hello, world.')",
168 "puts 'Hello World'",
169 "print(\"Hello World\")",
170 "db 'Hello World', 10, 0",
171 "cat('Hello World')",
172 "println('Hello World')",
173 "echo \"Hello World\"",
174 "System.out.println(\"Hello World\")",
175 "println('Hello World\")",
176 "printfn \"Hello World\"",
177 "(print \"Hello World\")",
178 "console.log(\"Hello World\")",
179 "BEGIN DISPLAY(\"Hello World\") END.",
180 "print \"Hello World\"",
181 "puts \"Hello World\"",
182 "console.log 'Hello World'",
183 "print *, \"Hello World\"",
184 "<h1>Hello World<\\h1>",
185];
src/global/functions/type_name_of_val.rs added +5
@@ -0,0 +1,5 @@
1use std::any::type_name;
2
3pub fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
4 type_name::<T>()
5}
src/global/structs/keyaction.rs +6
@@ -26,4 +26,10 @@ pub enum KeyAction {
26 FirstHistory, 26 FirstHistory,
27 /// reload the current page 27 /// reload the current page
28 Reload, 28 Reload,
29 /// start command capture
30 StartCommandCapture,
31 /// copy text
32 r#Copy,
33 /// paste text
34 Paste,
29} 35}
src/global/structs/status.rs +13
@@ -1,11 +1,20 @@
1use tui::layout::Rect;
2use tui_additions::widgets::TextField;
1use typemap::Key; 3use typemap::Key;
2 4
3/// a struct for storing different info, currently only stores one info 5/// a struct for storing different info, currently only stores one info
4#[derive(Clone)] 6#[derive(Clone)]
5pub struct Status { 7pub struct Status {
6 pub popup_opened: bool, 8 pub popup_opened: bool,
9 pub search_filter_opened: bool,
7 /// to prevent rerendering the same image 10 /// to prevent rerendering the same image
8 pub render_image: bool, 11 pub render_image: bool,
12 /// the textfield for command capture
13 pub command_capture: Option<TextField>,
14 /// if true, exit in the next iteration
15 pub exit: bool,
16 /// stores the area of the previously rendered frame
17 pub prev_frame: Option<Rect>,
9} 18}
10 19
11impl Key for Status { 20impl Key for Status {
@@ -16,7 +25,11 @@ impl Default for Status {
16 fn default() -> Self { 25 fn default() -> Self {
17 Self { 26 Self {
18 popup_opened: false, 27 popup_opened: false,
28 search_filter_opened: false,
19 render_image: true, 29 render_image: true,
30 command_capture: None,
31 exit: false,
32 prev_frame: None,
20 } 33 }
21 } 34 }
22} 35}
src/global/structs/tasks.rs +25 −1
@@ -1,4 +1,7 @@
1use crate::config::{AppearanceConfig, MinDimentions}; 1use crate::{
2 config::{AppearanceConfig, MinDimentions},
3 global::functions::run_command,
4};
2 5
3use super::{message::Message, page::Page, status::Status}; 6use super::{message::Message, page::Page, status::Status};
4use std::{error::Error, io::Stdout, mem}; 7use std::{error::Error, io::Stdout, mem};
@@ -17,6 +20,7 @@ pub enum Task {
17 LoadPage(Page), 20 LoadPage(Page),
18 ClearPage, 21 ClearPage,
19 LazyRendered, 22 LazyRendered,
23 Command(String),
20} 24}
21 25
22/// multiple tasks joined together, with duplicates removed 26/// multiple tasks joined together, with duplicates removed
@@ -27,6 +31,7 @@ pub struct TaskQueue {
27 pub load_page: Option<Page>, 31 pub load_page: Option<Page>,
28 pub clear_all: bool, 32 pub clear_all: bool,
29 pub lazy_rendered: bool, 33 pub lazy_rendered: bool,
34 pub commands: Vec<String>,
30} 35}
31 36
32impl Default for TaskQueue { 37impl Default for TaskQueue {
@@ -37,6 +42,7 @@ impl Default for TaskQueue {
37 load_page: None, 42 load_page: None,
38 clear_all: false, 43 clear_all: false,
39 lazy_rendered: false, 44 lazy_rendered: false,
45 commands: Vec::new(),
40 } 46 }
41 } 47 }
42} 48}
@@ -60,6 +66,7 @@ impl TaskQueue {
60 Task::LoadPage(page) => self.load_page = Some(page), 66 Task::LoadPage(page) => self.load_page = Some(page),
61 Task::ClearPage => self.clear_all = true, 67 Task::ClearPage => self.clear_all = true,
62 Task::LazyRendered => self.lazy_rendered = true, 68 Task::LazyRendered => self.lazy_rendered = true,
69 Task::Command(s) => self.commands.push(s),
63 // _ => {} 70 // _ => {}
64 } 71 }
65 } 72 }
@@ -74,6 +81,16 @@ impl TaskQueue {
74 framework: &mut Framework, 81 framework: &mut Framework,
75 terminal: &mut Terminal<CrosstermBackend<Stdout>>, 82 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
76 ) -> Result<(), Box<dyn Error>> { 83 ) -> Result<(), Box<dyn Error>> {
84 // if there is any commands, run them first as they may modify data, which is rendered
85 // later in this function
86 for command in self.commands.iter() {
87 run_command(
88 &command.split_whitespace().collect::<Vec<_>>(),
89 framework,
90 terminal,
91 );
92 }
93
77 if self.clear_all { 94 if self.clear_all {
78 terminal.clear()?; 95 terminal.clear()?;
79 } 96 }
@@ -174,6 +191,13 @@ impl TaskQueue {
174 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap(); 191 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
175 let area = frame.size(); 192 let area = frame.size();
176 193
194 framework
195 .data
196 .global
197 .get_mut::<Status>()
198 .unwrap()
199 .prev_frame = Some(area);
200
177 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking 201 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
178 if area.width < min_dimentions.width || area.height < min_dimentions.height { 202 if area.width < min_dimentions.width || area.height < min_dimentions.height {
179 let paragraph = Paragraph::new(format!( 203 let paragraph = Paragraph::new(format!(
src/init.rs +31 −22
@@ -12,7 +12,7 @@ use crate::{
12use home::home_dir; 12use home::home_dir;
13use std::{error::Error, fs, io::Stdout}; 13use std::{error::Error, fs, io::Stdout};
14use tui::{backend::CrosstermBackend, Terminal}; 14use tui::{backend::CrosstermBackend, Terminal};
15use tui_additions::framework::Framework; 15use tui_additions::framework::{Framework, FrameworkClean};
16 16
17/// app to run before the app starts 17/// app to run before the app starts
18// init tasks: 18// init tasks:
@@ -25,15 +25,10 @@ pub fn init(
25) -> Result<(), Box<dyn Error>> { 25) -> Result<(), Box<dyn Error>> {
26 // creating files 26 // creating files
27 let home_dir = home_dir().unwrap(); 27 let home_dir = home_dir().unwrap();
28 let config_path = home_dir.join(".config/youtube-tui/");
29 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/"); 28 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
30 let history_thumbnails_path = 29 let history_thumbnails_path =
31 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/"); 30 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/");
32 31
33 if !&config_path.exists() {
34 fs::create_dir_all(&config_path).unwrap();
35 }
36
37 if !&cache_thumbnails_path.exists() { 32 if !&cache_thumbnails_path.exists() {
38 fs::create_dir_all(&cache_thumbnails_path).unwrap(); 33 fs::create_dir_all(&cache_thumbnails_path).unwrap();
39 } 34 }
@@ -45,6 +40,32 @@ pub fn init(
45 // watch history init 40 // watch history init
46 WatchHistory::init_move(); 41 WatchHistory::init_move();
47 42
43 framework.data.global.insert::<Message>(Message::None);
44 framework.data.global.insert::<Status>(Status::default());
45
46 framework.data.state.insert::<Tasks>(Tasks::default());
47 framework.data.state.insert::<Page>(Page::default());
48 framework
49 .data
50 .state
51 .insert::<MinDimentions>(MinDimentions::default());
52
53 load_configs(&mut framework.split_clean().0).ok();
54
55 run_command(&["loadpage", "popular"], framework, terminal);
56 run_command(&["flush"], framework, terminal);
57 run_command(&["history", "clear"], framework, terminal);
58 Ok(())
59}
60
61pub fn load_configs(framework: &mut FrameworkClean) -> Result<(), Box<dyn Error>> {
62 let home_dir = home_dir().unwrap();
63 let config_path = home_dir.join(".config/youtube-tui/");
64
65 if !&config_path.exists() {
66 fs::create_dir_all(&config_path).unwrap();
67 }
68
48 // inserting data 69 // inserting data
49 let main_config = *MainConfig::load()?; 70 let main_config = *MainConfig::load()?;
50 71
@@ -52,6 +73,10 @@ pub fn init(
52 .data 73 .data
53 .global 74 .global
54 .insert::<InvidiousClient>(InvidiousClient::new(main_config.invidious_instance.clone())); 75 .insert::<InvidiousClient>(InvidiousClient::new(main_config.invidious_instance.clone()));
76 framework
77 .data
78 .global
79 .insert::<CommandsConfig>(CommandsConfig::from(*CommandsConfigSerde::load()?));
55 framework 80 framework
56 .data 81 .data
57 .global 82 .global
@@ -69,23 +94,7 @@ pub fn init(
69 .data 94 .data
70 .global 95 .global
71 .insert::<KeyBindingsConfig>(KeyBindingsConfig::load()?); 96 .insert::<KeyBindingsConfig>(KeyBindingsConfig::load()?);
72 framework.data.global.insert::<Message>(Message::None);
73 framework
74 .data
75 .global
76 .insert::<CommandsConfig>(CommandsConfig::from(*CommandsConfigSerde::load()?));
77 framework.data.global.insert::<Status>(Status::default());
78
79 framework.data.state.insert::<Tasks>(Tasks::default());
80 framework.data.state.insert::<Page>(Page::default());
81 framework.data.state.insert::<Search>(*Search::load()?); 97 framework.data.state.insert::<Search>(*Search::load()?);
82 framework
83 .data
84 .state
85 .insert::<MinDimentions>(MinDimentions::default());
86 98
87 run_command(&["loadpage", "popular"], framework, terminal);
88 run_command(&["flush"], framework, terminal);
89 run_command(&["history", "clear"], framework, terminal);
90 Ok(()) 99 Ok(())
91} 100}
src/items/channeldisplay.rs +147 −41
@@ -10,12 +10,12 @@ use crate::{
10 }, 10 },
11}; 11};
12use tui::{ 12use tui::{
13 layout::Constraint, 13 layout::{Constraint, Rect},
14 style::Style, 14 style::Style,
15 widgets::{Block, Borders}, 15 widgets::{Block, Borders},
16}; 16};
17use tui_additions::{ 17use tui_additions::{
18 framework::FrameworkItem, 18 framework::{FrameworkClean, FrameworkItem},
19 widgets::{Grid, TextList}, 19 widgets::{Grid, TextList},
20}; 20};
21 21
@@ -95,6 +95,79 @@ impl ChannelDisplay {
95 } 95 }
96 } 96 }
97 97
98 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
99 match self {
100 Self::None | Self::Main { .. } => {}
101 Self::Videos {
102 videos, textlist, ..
103 } => {
104 // on select loads that in singleitem
105 if !videos.is_empty() {
106 framework
107 .data
108 .state
109 .get_mut::<Tasks>()
110 .unwrap()
111 .priority
112 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
113 videos[textlist.selected].minivideo().unwrap().id.clone(),
114 ))));
115 } else {
116 *framework.data.global.get_mut::<Message>().unwrap() =
117 Message::Error(String::from("There is nothing to select"));
118 }
119 }
120 Self::Playlists {
121 playlists,
122 textlist,
123 ..
124 } => {
125 if !playlists.is_empty() {
126 framework
127 .data
128 .state
129 .get_mut::<Tasks>()
130 .unwrap()
131 .priority
132 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist(
133 playlists[textlist.selected]
134 .miniplaylist()
135 .unwrap()
136 .id
137 .clone(),
138 ))));
139 } else {
140 *framework.data.global.get_mut::<Message>().unwrap() =
141 Message::Error(String::from("There is nothing to select"));
142 }
143 }
144 }
145 }
146
147 fn update(&mut self) {
148 match self {
149 Self::Videos {
150 videos: items,
151 textlist,
152 iteminfo,
153 ..
154 }
155 | Self::Playlists {
156 playlists: items,
157 textlist,
158 iteminfo,
159 ..
160 } => {
161 if !items.is_empty()
162 && items[textlist.selected].id() != iteminfo.item.as_ref().unwrap().id()
163 {
164 iteminfo.item = Some(items[textlist.selected].clone())
165 }
166 }
167 _ => {}
168 }
169 }
170
98 pub fn selectable(&self) -> bool { 171 pub fn selectable(&self) -> bool {
99 !(matches!(self, Self::Main { .. }) || matches!(self, Self::None)) 172 !(matches!(self, Self::Main { .. }) || matches!(self, Self::None))
100 } 173 }
@@ -176,19 +249,14 @@ impl FrameworkItem for ChannelDisplay {
176 key: crossterm::event::KeyEvent, 249 key: crossterm::event::KeyEvent,
177 _info: tui_additions::framework::ItemInfo, 250 _info: tui_additions::framework::ItemInfo,
178 ) -> Result<(), Box<dyn std::error::Error>> { 251 ) -> Result<(), Box<dyn std::error::Error>> {
179 let action = if let Some(keyactions) = framework 252 let action = if let Some(action) = framework
180 .data 253 .data
181 .global 254 .global
182 .get::<KeyBindingsConfig>() 255 .get::<KeyBindingsConfig>()
183 .unwrap() 256 .unwrap()
184 .0 257 .get(key)
185 .get(&key.code)
186 { 258 {
187 if let Some(action) = keyactions.get(&key.modifiers.bits()) { 259 action
188 *action
189 } else {
190 return Ok(());
191 }
192 } else { 260 } else {
193 return Ok(()); 261 return Ok(());
194 }; 262 };
@@ -206,22 +274,8 @@ impl FrameworkItem for ChannelDisplay {
206 KeyAction::MoveLeft => textlist.first().is_ok(), 274 KeyAction::MoveLeft => textlist.first().is_ok(),
207 KeyAction::MoveRight => textlist.last().is_ok(), 275 KeyAction::MoveRight => textlist.last().is_ok(),
208 KeyAction::Select => { 276 KeyAction::Select => {
209 // on select loads that in singleitem 277 self.select_at_cursor(framework);
210 if !videos.is_empty() { 278 return Ok(());
211 framework
212 .data
213 .state
214 .get_mut::<Tasks>()
215 .unwrap()
216 .priority
217 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
218 videos[textlist.selected].minivideo()?.id.clone(),
219 ))));
220 } else {
221 *framework.data.global.get_mut::<Message>().unwrap() =
222 Message::Error(String::from("There is nothing to select"));
223 }
224 true
225 } 279 }
226 _ => false, 280 _ => false,
227 }; 281 };
@@ -256,21 +310,8 @@ impl FrameworkItem for ChannelDisplay {
256 KeyAction::MoveLeft => textlist.first().is_ok(), 310 KeyAction::MoveLeft => textlist.first().is_ok(),
257 KeyAction::MoveRight => textlist.last().is_ok(), 311 KeyAction::MoveRight => textlist.last().is_ok(),
258 KeyAction::Select => { 312 KeyAction::Select => {
259 if !playlists.is_empty() { 313 self.select_at_cursor(framework);
260 framework 314 return Ok(());
261 .data
262 .state
263 .get_mut::<Tasks>()
264 .unwrap()
265 .priority
266 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist(
267 playlists[textlist.selected].miniplaylist()?.id.clone(),
268 ))));
269 } else {
270 *framework.data.global.get_mut::<Message>().unwrap() =
271 Message::Error(String::from("There is nothing to select"));
272 }
273 true
274 } 315 }
275 _ => false, 316 _ => false,
276 }; 317 };
@@ -385,4 +426,69 @@ impl FrameworkItem for ChannelDisplay {
385 426
386 Ok(()) 427 Ok(())
387 } 428 }
429
430 fn mouse_event(
431 &mut self,
432 framework: &mut tui_additions::framework::FrameworkClean,
433 x: u16,
434 y: u16,
435 _absolute_x: u16,
436 _absolute_y: u16,
437 ) -> bool {
438 match self {
439 Self::None | Self::Main { .. } => false,
440 Self::Videos { textlist, grid, .. } | Self::Playlists { textlist, grid, .. } => {
441 let chunk = grid
442 .chunks(
443 if let Some(prev_frame) =
444 framework.data.global.get::<Status>().unwrap().prev_frame
445 {
446 prev_frame
447 } else {
448 return false;
449 },
450 )
451 .unwrap()[0][0];
452
453 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
454 return false;
455 }
456
457 let y = (y - chunk.y) as usize + textlist.scroll;
458
459 // clicking on already selected item
460 if y == textlist.selected
461 || y == textlist.selected + 2
462 || y == textlist.selected + 1
463 {
464 self.select_at_cursor(framework);
465 return true;
466 }
467
468 // clicking on rows after the last item
469 if y > textlist.items.len() + 1 {
470 return false;
471 }
472
473 // moving the cursor
474 if y <= textlist.selected {
475 textlist.selected = y;
476 } else if y >= textlist.selected + 2 {
477 textlist.selected = y - 2;
478 }
479
480 self.update();
481
482 // render the new image
483 framework
484 .data
485 .global
486 .get_mut::<Status>()
487 .unwrap()
488 .render_image = true;
489
490 true
491 }
492 }
493 }
388} 494}
src/items/itemlist.rs +120 −56
@@ -1,8 +1,11 @@
1use std::error::Error; 1use std::error::Error;
2 2
3use tui::{layout::Constraint, style::Style}; 3use tui::{
4 layout::{Constraint, Rect},
5 style::Style,
6};
4use tui_additions::{ 7use tui_additions::{
5 framework::FrameworkItem, 8 framework::{FrameworkClean, FrameworkItem},
6 widgets::{Grid, TextList}, 9 widgets::{Grid, TextList},
7}; 10};
8 11
@@ -65,6 +68,55 @@ impl ItemList {
65 } 68 }
66 } 69 }
67 } 70 }
71
72 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
73 let page_to_load = match &self.items[self.textlist.selected] {
74 Item::MiniVideo(MiniVideoItem { id, .. })
75 | Item::FullVideo(FullVideoItem { id, .. }) => {
76 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
77 }
78 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
79 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
80 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
81 }
82 Item::MiniChannel(MiniChannelItem { id, .. })
83 | Item::FullChannel(FullChannelItem { id, .. }) => {
84 Some(Page::ChannelDisplay(ChannelDisplayPage {
85 id: id.clone(),
86 r#type: ChannelDisplayPageType::Main,
87 }))
88 }
89 Item::Unknown(_) => {
90 *framework.data.global.get_mut::<Message>().unwrap() =
91 Message::Message(String::from("Unknown item"));
92 framework
93 .data
94 .state
95 .get_mut::<Tasks>()
96 .unwrap()
97 .priority
98 .push(Task::RenderAll);
99 None
100 }
101 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
102 Page::Search(search) => Some(Page::Search(Search {
103 page: if *b { search.page + 1 } else { search.page - 1 },
104 ..search.clone()
105 })),
106 _ => unreachable!("Page turners can only be used in search pages"),
107 },
108 };
109
110 if let Some(page_to_load) = page_to_load {
111 framework
112 .data
113 .state
114 .get_mut::<Tasks>()
115 .unwrap()
116 .priority
117 .push(Task::LoadPage(page_to_load));
118 }
119 }
68} 120}
69 121
70impl Default for ItemList { 122impl Default for ItemList {
@@ -216,19 +268,14 @@ impl FrameworkItem for ItemList {
216 key: crossterm::event::KeyEvent, 268 key: crossterm::event::KeyEvent,
217 _info: tui_additions::framework::ItemInfo, 269 _info: tui_additions::framework::ItemInfo,
218 ) -> Result<(), Box<dyn Error>> { 270 ) -> Result<(), Box<dyn Error>> {
219 let action = if let Some(keyactions) = framework 271 let action = if let Some(action) = framework
220 .data 272 .data
221 .global 273 .global
222 .get::<KeyBindingsConfig>() 274 .get::<KeyBindingsConfig>()
223 .unwrap() 275 .unwrap()
224 .0 276 .get(key)
225 .get(&key.code)
226 { 277 {
227 if let Some(action) = keyactions.get(&key.modifiers.bits()) { 278 action
228 *action
229 } else {
230 return Ok(());
231 }
232 } else { 279 } else {
233 return Ok(()); 280 return Ok(());
234 }; 281 };
@@ -240,52 +287,7 @@ impl FrameworkItem for ItemList {
240 KeyAction::MoveLeft => self.textlist.first().is_ok(), 287 KeyAction::MoveLeft => self.textlist.first().is_ok(),
241 KeyAction::MoveRight => self.textlist.last().is_ok(), 288 KeyAction::MoveRight => self.textlist.last().is_ok(),
242 KeyAction::Select => { 289 KeyAction::Select => {
243 let page_to_load = match &self.items[self.textlist.selected] { 290 self.select_at_cursor(framework);
244 Item::MiniVideo(MiniVideoItem { id, .. })
245 | Item::FullVideo(FullVideoItem { id, .. }) => {
246 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
247 }
248 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
249 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
250 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
251 }
252 Item::MiniChannel(MiniChannelItem { id, .. })
253 | Item::FullChannel(FullChannelItem { id, .. }) => {
254 Some(Page::ChannelDisplay(ChannelDisplayPage {
255 id: id.clone(),
256 r#type: ChannelDisplayPageType::Main,
257 }))
258 }
259 Item::Unknown(_) => {
260 *framework.data.global.get_mut::<Message>().unwrap() =
261 Message::Message(String::from("Unknown item"));
262 framework
263 .data
264 .state
265 .get_mut::<Tasks>()
266 .unwrap()
267 .priority
268 .push(Task::RenderAll);
269 None
270 }
271 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
272 Page::Search(search) => Some(Page::Search(Search {
273 page: if *b { search.page + 1 } else { search.page - 1 },
274 ..search.clone()
275 })),
276 _ => unreachable!("Page turners can only be used in search pages"),
277 },
278 };
279
280 if let Some(page_to_load) = page_to_load {
281 framework
282 .data
283 .state
284 .get_mut::<Tasks>()
285 .unwrap()
286 .priority
287 .push(Task::LoadPage(page_to_load));
288 }
289 false 291 false
290 } 292 }
291 _ => false, 293 _ => false,
@@ -311,6 +313,68 @@ impl FrameworkItem for ItemList {
311 313
312 Ok(()) 314 Ok(())
313 } 315 }
316
317 fn mouse_event(
318 &mut self,
319 framework: &mut tui_additions::framework::FrameworkClean,
320 x: u16,
321 y: u16,
322 _absolute_x: u16,
323 _absolute_y: u16,
324 ) -> bool {
325 let chunk = self
326 .grid
327 .chunks(
328 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
329 {
330 prev_frame
331 } else {
332 return false;
333 },
334 )
335 .unwrap()[0][0];
336
337 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
338 return false;
339 }
340
341 let y = (y - chunk.y) as usize + self.textlist.scroll;
342
343 // clicking on already selected item
344 if y == self.textlist.selected
345 || y == self.textlist.selected + 2
346 || y == self.textlist.selected + 1
347 {
348 self.select_at_cursor(framework);
349 return true;
350 }
351
352 // clicking on rows after the last item
353 if y > self.textlist.items.len() + 1 {
354 return false;
355 }
356
357 // moving the cursor
358 if y <= self.textlist.selected {
359 self.textlist.selected = y;
360 }
361
362 if y >= self.textlist.selected + 2 {
363 self.textlist.selected = y - 2;
364 }
365
366 self.update();
367
368 // render the new image
369 framework
370 .data
371 .global
372 .get_mut::<Status>()
373 .unwrap()
374 .render_image = true;
375
376 true
377 }
314} 378}
315 379
316impl ItemList { 380impl ItemList {
src/items/messagebar.rs +35 −6
@@ -1,8 +1,9 @@
1use crate::{ 1use crate::{
2 config::{AppearanceConfig, MainConfig}, 2 config::{AppearanceConfig, MainConfig},
3 global::structs::Message, 3 global::structs::{Message, Status},
4}; 4};
5use tui::{ 5use tui::{
6 layout::Rect,
6 style::Style, 7 style::Style,
7 widgets::{Block, Borders, Paragraph}, 8 widgets::{Block, Borders, Paragraph},
8}; 9};
@@ -28,17 +29,45 @@ impl FrameworkItem for MessageBar {
28 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap(); 29 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
29 let message = framework.data.global.get::<Message>().unwrap(); 30 let message = framework.data.global.get::<Message>().unwrap();
30 31
32 // the Option<TextList> that is Some if keys were captured for entering command
33 let command_capture = &framework
34 .data
35 .global
36 .get::<Status>()
37 .unwrap()
38 .command_capture;
39
31 // display with different border style according to type of message and config 40 // display with different border style according to type of message and config
32 let block = Block::default() 41 let block = Block::default()
33 .borders(Borders::ALL) 42 .borders(Borders::ALL)
34 .border_type(appearance.borders) 43 .border_type(appearance.borders)
35 .border_style(Style::default().fg(match message { 44 .border_style(Style::default().fg(if command_capture.is_some() {
36 Message::None => appearance.colors.outline, 45 appearance.colors.command_capture
37 Message::Success(_) => appearance.colors.message_success_outline, 46 } else {
38 Message::Error(_) => appearance.colors.message_error_outline, 47 match message {
39 Message::Message(_) => appearance.colors.message_outline, 48 Message::None => appearance.colors.outline,
49 Message::Success(_) => appearance.colors.message_success_outline,
50 Message::Error(_) => appearance.colors.message_error_outline,
51 Message::Message(_) => appearance.colors.message_outline,
52 }
40 })); 53 }));
41 54
55 // if keys are captured, render the textlist instead of the message text, and exits the
56 // function
57 if let Some(textfield) = command_capture {
58 let paragraph = Paragraph::new(":").block(block);
59 frame.render_widget(paragraph, area);
60 let mut textfield = textfield.clone();
61 textfield.set_width(area.width - 3);
62 let _ = textfield.update();
63 frame.render_widget(
64 textfield,
65 Rect::new(area.x + 2, area.y + 1, area.width - 3, 1),
66 );
67
68 return;
69 }
70
42 let paragraph = Paragraph::new( 71 let paragraph = Paragraph::new(
43 message.to_string( 72 message.to_string(
44 &framework 73 &framework
src/items/searchbar.rs +50 −3
@@ -1,8 +1,11 @@
1use std::error::Error; 1use std::error::Error;
2 2
3use crate::{ 3use crate::{
4 config::{AppearanceConfig, Search}, 4 config::{AppearanceConfig, KeyBindingsConfig, Search},
5 global::structs::{Message, Page, Task, Tasks}, 5 global::{
6 functions::get_clipboard,
7 structs::{KeyAction, Message, Page, Task, Tasks},
8 },
6}; 9};
7use crossterm::event::KeyCode; 10use crossterm::event::KeyCode;
8use tui::{ 11use tui::{
@@ -76,6 +79,43 @@ impl FrameworkItem for SearchBar {
76 key: crossterm::event::KeyEvent, 79 key: crossterm::event::KeyEvent,
77 _info: tui_additions::framework::ItemInfo, 80 _info: tui_additions::framework::ItemInfo,
78 ) -> Result<(), Box<dyn Error>> { 81 ) -> Result<(), Box<dyn Error>> {
82 // pasting clipboard content
83 if framework
84 .data
85 .global
86 .get::<KeyBindingsConfig>()
87 .unwrap()
88 .get(key)
89 == Some(KeyAction::Paste)
90 {
91 let content = get_clipboard();
92 if content.is_empty() {
93 *framework.data.global.get_mut::<Message>().unwrap() =
94 Message::Error(String::from("Clipboard empty"));
95 framework
96 .data
97 .state
98 .get_mut::<Tasks>()
99 .unwrap()
100 .priority
101 .push(Task::RenderAll);
102 return Ok(());
103 }
104
105 // push all characters at cursor location
106 content.chars().for_each(|c| {
107 let _ = self.text_field.push(c);
108 });
109 framework
110 .data
111 .state
112 .get_mut::<Tasks>()
113 .unwrap()
114 .priority
115 .push(Task::RenderAll);
116 return Ok(());
117 }
118
79 let updated = match key.code { 119 let updated = match key.code {
80 KeyCode::Backspace => self.text_field.remove(self.text_field.cursor).is_ok(), 120 KeyCode::Backspace => self.text_field.remove(self.text_field.cursor).is_ok(),
81 KeyCode::Char(c) => self.text_field.push(c).is_ok(), 121 KeyCode::Char(c) => self.text_field.push(c).is_ok(),
@@ -116,7 +156,14 @@ impl FrameworkItem for SearchBar {
116 Ok(()) 156 Ok(())
117 } 157 }
118 158
119 fn mouse_event(&mut self, _framework: &mut tui_additions::framework::FrameworkClean, mut x: u16, y: u16) -> bool { 159 fn mouse_event(
160 &mut self,
161 _framework: &mut tui_additions::framework::FrameworkClean,
162 mut x: u16,
163 y: u16,
164 _absolute_x: u16,
165 _absolute_y: u16,
166 ) -> bool {
120 if y != 1 || x == 0 { 167 if y != 1 || x == 0 {
121 return false; 168 return false;
122 } 169 }
src/items/searchfilters.rs +103 −19
@@ -6,7 +6,7 @@ use crate::{
6 }, 6 },
7}; 7};
8use tui::{ 8use tui::{
9 layout::{Alignment, Constraint}, 9 layout::{Alignment, Constraint, Rect},
10 style::Style, 10 style::Style,
11 widgets::{Block, Borders, Clear, Paragraph}, 11 widgets::{Block, Borders, Clear, Paragraph},
12}; 12};
@@ -29,6 +29,8 @@ pub struct SearchFilter {
29 pub left_options: Vec<&'static str>, 29 pub left_options: Vec<&'static str>,
30 pub current_hover: bool, 30 pub current_hover: bool,
31 pub grid: Grid, 31 pub grid: Grid,
32 /// if the popup is opened
33 pub opened: bool,
32 pub previous_state: Option<SearchFilters>, 34 pub previous_state: Option<SearchFilters>,
33} 35}
34 36
@@ -46,6 +48,7 @@ impl Default for SearchFilter {
46 vec![Constraint::Percentage(100)], 48 vec![Constraint::Percentage(100)],
47 ) 49 )
48 .unwrap(), 50 .unwrap(),
51 opened: false,
49 previous_state: None, 52 previous_state: None,
50 } 53 }
51 } 54 }
@@ -186,12 +189,12 @@ impl FrameworkItem for SearchFilter {
186 } 189 }
187 190
188 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool { 191 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
189 framework 192 self.opened = true;
190 .data 193
191 .global 194 let status = framework.data.global.get_mut::<Status>().unwrap();
192 .get_mut::<Status>() 195
193 .unwrap() 196 status.popup_opened = true;
194 .popup_opened = true; 197 status.search_filter_opened = true;
195 framework 198 framework
196 .data 199 .data
197 .state 200 .state
@@ -220,10 +223,12 @@ impl FrameworkItem for SearchFilter {
220 } 223 }
221 224
222 fn deselect(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool { 225 fn deselect(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
223 *framework.data.global.get_mut::<Status>().unwrap() = Status { 226 self.opened = true;
224 popup_opened: false, 227
225 render_image: true, 228 let status = framework.data.global.get_mut::<Status>().unwrap();
226 }; 229 status.popup_opened = false;
230 status.search_filter_opened = false;
231 status.render_image = true;
227 232
228 // refresh page only if changed and enabled in options 233 // refresh page only if changed and enabled in options
229 let search_options = framework.data.state.get::<Search>().unwrap().clone(); 234 let search_options = framework.data.state.get::<Search>().unwrap().clone();
@@ -259,19 +264,14 @@ impl FrameworkItem for SearchFilter {
259 key: crossterm::event::KeyEvent, 264 key: crossterm::event::KeyEvent,
260 _info: tui_additions::framework::ItemInfo, 265 _info: tui_additions::framework::ItemInfo,
261 ) -> Result<(), Box<dyn std::error::Error>> { 266 ) -> Result<(), Box<dyn std::error::Error>> {
262 let action = if let Some(keyactions) = framework 267 let action = if let Some(action) = framework
263 .data 268 .data
264 .global 269 .global
265 .get::<KeyBindingsConfig>() 270 .get::<KeyBindingsConfig>()
266 .unwrap() 271 .unwrap()
267 .0 272 .get(key)
268 .get(&key.code)
269 { 273 {
270 if let Some(action) = keyactions.get(&key.modifiers.bits()) { 274 action
271 *action
272 } else {
273 return Ok(());
274 }
275 } else { 275 } else {
276 return Ok(()); 276 return Ok(());
277 }; 277 };
@@ -327,4 +327,88 @@ impl FrameworkItem for SearchFilter {
327 327
328 Ok(()) 328 Ok(())
329 } 329 }
330
331 // returns true if the popup is clicked at all
332 fn mouse_event(
333 &mut self,
334 framework: &mut FrameworkClean,
335 _x: u16,
336 _y: u16,
337 absolute_x: u16,
338 absolute_y: u16,
339 ) -> bool {
340 if !self.opened {
341 return false;
342 }
343
344 let previous_frame_area = match framework.data.global.get::<Status>().unwrap().prev_frame {
345 Some(previous_frame_area) => previous_frame_area,
346 None => return false,
347 };
348
349 let popup_area = match popup_area(
350 (POPUP_WIDTH_PERCENTAGE, POPOUP_HEIGHT_PERCENTAGE),
351 (POPUP_MIN_WIDTH, POPUP_MIN_HEIGHT),
352 previous_frame_area,
353 ) {
354 Ok(popup_area) => popup_area,
355 Err(_) => return false,
356 };
357
358 if !popup_area.intersects(Rect::new(absolute_x, absolute_y, 1, 1)) {
359 return false;
360 }
361
362 let chunks = self.grid.chunks(popup_area).unwrap().remove(0);
363
364 // get which playlist is clicked
365 let (is_left_list, textlist) =
366 if chunks[0].intersects(Rect::new(absolute_x, absolute_y, 1, 1)) {
367 (true, &mut self.left_textlist)
368 } else if chunks[1].intersects(Rect::new(absolute_x, absolute_y, 1, 1)) {
369 (false, &mut self.right_textlist)
370 } else {
371 // if the grid is clicked, returns true to indicate the popup is clicked
372 return true;
373 };
374
375 if is_left_list == self.current_hover {
376 self.current_hover = !self.current_hover;
377 }
378
379 let y = (absolute_y - chunks[0].y) as usize;
380
381 if y >= textlist.selected && y <= textlist.selected + 2 {
382 self.update(framework);
383 return true;
384 } else if y < textlist.selected {
385 textlist.selected = y;
386 let _ = textlist.update();
387 } else if textlist.items.len() >= y - 1 {
388 textlist.selected = y - 2;
389 let _ = textlist.update();
390 }
391
392 if is_left_list {
393 self.right_textlist
394 .set_items(&self.right_options[self.left_textlist.selected])
395 .unwrap();
396 } else {
397 framework
398 .data
399 .state
400 .get_mut::<Search>()
401 .unwrap()
402 .filters
403 .set_index(
404 self.left_textlist.selected,
405 self.right_textlist.selected,
406 framework.data.global.get_mut::<Message>().unwrap(),
407 );
408 }
409
410 self.update(framework);
411
412 true
413 }
330} 414}
src/items/singleitem.rs +269 −118
@@ -10,9 +10,12 @@ use crate::{
10 }, 10 },
11}; 11};
12use std::{collections::HashMap, thread}; 12use std::{collections::HashMap, thread};
13use tui::{layout::Constraint, style::Style}; 13use tui::{
14 layout::{Constraint, Rect},
15 style::Style,
16};
14use tui_additions::{ 17use tui_additions::{
15 framework::FrameworkItem, 18 framework::{FrameworkClean, FrameworkItem},
16 widgets::{Grid, TextList}, 19 widgets::{Grid, TextList},
17}; 20};
18 21
@@ -69,7 +72,13 @@ impl SingleVideoItem {
69 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig) -> Self { 72 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig) -> Self {
70 Self { 73 Self {
71 textlist: TextList::default() 74 textlist: TextList::default()
72 .items(&commands.video.iter().map(|command| &command.0).collect::<Vec<_>>()) 75 .items(
76 &commands
77 .video
78 .iter()
79 .map(|command| &command.0)
80 .collect::<Vec<_>>(),
81 )
73 .unwrap(), 82 .unwrap(),
74 commands: commands 83 commands: commands
75 .video 84 .video
@@ -129,11 +138,9 @@ impl SingleVideoItem {
129 mainconfig.invidious_instance, video_item.id 138 mainconfig.invidious_instance, video_item.id
130 ), 139 ),
131 Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id), 140 Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id),
132 // Provider::Piped => {
133 // format!("'{}/watch?v={}'", mainconfig.piped_instance, video_item.id)
134 // }
135 }, 141 },
136 ), 142 ),
143 (String::from("id"), video_item.id.clone()),
137 ( 144 (
138 String::from("embed-url"), 145 String::from("embed-url"),
139 match self.provider { 146 match self.provider {
@@ -142,9 +149,19 @@ impl SingleVideoItem {
142 mainconfig.invidious_instance, video_item.id 149 mainconfig.invidious_instance, video_item.id
143 ), 150 ),
144 Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id), 151 Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id),
145 // Provider::Piped => { 152 },
146 // format!("'{}/embed/{}'", mainconfig.piped_instance, video_item.id) 153 ),
147 // } 154 (String::from("channel_id"), video_item.channel_id.clone()),
155 (
156 String::from("channel_url"),
157 match self.provider {
158 Provider::YouTube => {
159 format!("https://www.youtube.com/channel/{}", video_item.channel_id)
160 }
161 Provider::Invidious => format!(
162 "{}/channel/{}",
163 mainconfig.invidious_instance, video_item.channel_id
164 ),
148 }, 165 },
149 ), 166 ),
150 ]) 167 ])
@@ -175,7 +192,13 @@ impl SinglePlaylistItem {
175 }); 192 });
176 Self { 193 Self {
177 commands_view: TextList::default() 194 commands_view: TextList::default()
178 .items(&commands.playlist.iter().map(|command| &command.0).collect::<Vec<_>>()) 195 .items(
196 &commands
197 .playlist
198 .iter()
199 .map(|command| &command.0)
200 .collect::<Vec<_>>(),
201 )
179 .unwrap(), 202 .unwrap(),
180 videos_view: TextList::default() 203 videos_view: TextList::default()
181 .items(&{ 204 .items(&{
@@ -278,12 +301,9 @@ impl SinglePlaylistItem {
278 "{}/playlist?list={}", 301 "{}/playlist?list={}",
279 mainconfig.invidious_instance, playlist_item.id 302 mainconfig.invidious_instance, playlist_item.id
280 ), 303 ),
281 // Provider::Piped => format!(
282 // "{}/playlist?list={}",
283 // mainconfig.piped_instance, playlist_item.id
284 // ),
285 }, 304 },
286 ), 305 ),
306 (String::from("id"), playlist_item.id.clone()),
287 ( 307 (
288 String::from("all-videos"), 308 String::from("all-videos"),
289 match self.provider { 309 match self.provider {
@@ -307,18 +327,20 @@ impl SinglePlaylistItem {
307 }) 327 })
308 .collect::<Vec<_>>() 328 .collect::<Vec<_>>()
309 .join(" "), 329 .join(" "),
310 // Provider::Piped => playlist_item 330 },
311 // .videos 331 ),
312 // .iter() 332 (String::from("channel_id"), playlist_item.channel_id.clone()),
313 // .map(|video| { 333 (
314 // format!( 334 String::from("channel_url"),
315 // "'{}/watch?v={}'", 335 match self.provider {
316 // mainconfig.piped_instance, 336 Provider::YouTube => format!(
317 // video.minivideo().id 337 "https://www.youtube.com/channel/{}",
318 // ) 338 playlist_item.channel_id
319 // }) 339 ),
320 // .collect::<Vec<_>>() 340 Provider::Invidious => format!(
321 // .join(" "), 341 "{}/channel/{}",
342 mainconfig.invidious_instance, playlist_item.channel_id
343 ),
322 }, 344 },
323 ), 345 ),
324 ]) 346 ])
@@ -380,6 +402,149 @@ impl SingleItem {
380 .update_appearance(appearance, iteminfo, &mut self.grid); 402 .update_appearance(appearance, iteminfo, &mut self.grid);
381 } 403 }
382 404
405 fn update(&mut self) {
406 if let SingleItemType::Playlist(singleplaylistitem) = &mut self.r#type {
407 let SinglePlaylistItem {
408 hovered_video,
409 videos_view,
410 ..
411 } = &mut **singleplaylistitem;
412 if videos_view.items.is_empty() {
413 hovered_video.item = None;
414 return;
415 }
416
417 if self.item.as_ref().unwrap().fullplaylist().unwrap().videos[videos_view.selected].id()
418 != hovered_video.item.as_ref().unwrap().id()
419 {
420 hovered_video.item = Some(
421 self.item.as_ref().unwrap().fullplaylist().unwrap().videos
422 [videos_view.selected]
423 .clone(),
424 );
425 }
426 }
427 }
428
429 fn select_at_cursor(
430 &mut self,
431 framework: &mut FrameworkClean,
432 // info: tui_additions::framework::ItemInfo,
433 ) {
434 match &mut self.r#type {
435 SingleItemType::Video(singlevideoitem) => {
436 let command_string = singlevideoitem.commands[singlevideoitem.textlist.selected]
437 .1
438 .clone();
439
440 match command_string.as_str() {
441 // checks for special cases that the items should consume the command
442 // instead of running it
443 "%switch-provider%" => {
444 singlevideoitem.provider.rotate();
445 singlevideoitem.update_provider();
446 *framework.data.global.get_mut::<Message>().unwrap() = Message::Success(
447 format!("Switched provider to {}", singlevideoitem.provider.as_str()),
448 );
449 }
450 _ => {
451 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
452 // joins the env from the one in mainconfig and video info
453 let env = singlevideoitem.inflate(
454 mainconfig.env.clone(),
455 mainconfig,
456 self.item.as_ref().unwrap(),
457 );
458 let command_string = apply_env(command_string, &env);
459
460 // check if the command starts with an ':' which case should be captured
461 if &command_string[0..1] == ":" {
462 framework
463 .data
464 .state
465 .get_mut::<Tasks>()
466 .unwrap()
467 .priority
468 .push(Task::Command(command_string[1..].to_string()))
469 }
470
471 *framework.data.global.get_mut::<Message>().unwrap() =
472 Message::Success(command_string.clone());
473
474 // this allows creating commands from string
475 let mut command = execute::command(command_string);
476
477 // run the command in a new thread so it doesn't freeze the current one
478 thread::spawn(move || {
479 let _ = command.output();
480 });
481 }
482 }
483 }
484 SingleItemType::Playlist(singleplaylistitem) => {
485 let command_string = singleplaylistitem.commands
486 [singleplaylistitem.commands_view.selected]
487 .1
488 .clone();
489
490 // checks for special cases
491 match command_string.as_str() {
492 "%switch-view%" => {
493 singleplaylistitem.is_commands_view = !singleplaylistitem.is_commands_view;
494 // self.update_appearance(
495 // framework.data.global.get::<AppearanceConfig>().unwrap(),
496 // &info,
497 // );
498 *framework.data.global.get_mut::<Message>().unwrap() =
499 Message::Success(String::from("Switched view"));
500 }
501 "%switch-provider%" => {
502 singleplaylistitem.provider.rotate();
503 singleplaylistitem.update_provider();
504 }
505 // same as before if string is not a special case then the run the command
506 _ => {
507 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
508 let env = singleplaylistitem.inflate(
509 mainconfig.env.clone(),
510 mainconfig,
511 self.item.as_ref().unwrap(),
512 );
513 let command_string = apply_env(command_string, &env);
514
515 // check if the command starts with an ':' which case should be captured
516 if &command_string[0..1] == ":" {
517 framework
518 .data
519 .state
520 .get_mut::<Tasks>()
521 .unwrap()
522 .priority
523 .push(Task::Command(command_string[1..].to_string()))
524 }
525
526 *framework.data.global.get_mut::<Message>().unwrap() =
527 Message::Success(command_string.clone());
528 let mut command = execute::command(command_string);
529
530 thread::spawn(move || {
531 let _ = command.output();
532 });
533 }
534 };
535 }
536 _ => return,
537 }
538
539 framework
540 .data
541 .state
542 .get_mut::<Tasks>()
543 .unwrap()
544 .priority
545 .push(Task::RenderAll);
546 }
547
383 pub fn update_provider(&mut self) { 548 pub fn update_provider(&mut self) {
384 match &mut self.r#type { 549 match &mut self.r#type {
385 SingleItemType::Video(singlevideoitem) => singlevideoitem.update_provider(), 550 SingleItemType::Video(singlevideoitem) => singlevideoitem.update_provider(),
@@ -541,19 +706,14 @@ impl FrameworkItem for SingleItem {
541 return Ok(()); 706 return Ok(());
542 } 707 }
543 708
544 let action = if let Some(keyactions) = framework 709 let action = if let Some(action) = framework
545 .data 710 .data
546 .global 711 .global
547 .get::<KeyBindingsConfig>() 712 .get::<KeyBindingsConfig>()
548 .unwrap() 713 .unwrap()
549 .0 714 .get(key)
550 .get(&key.code)
551 { 715 {
552 if let Some(action) = keyactions.get(&key.modifiers.bits()) { 716 action
553 *action
554 } else {
555 return Ok(());
556 }
557 } else { 717 } else {
558 return Ok(()); 718 return Ok(());
559 }; 719 };
@@ -566,47 +726,8 @@ impl FrameworkItem for SingleItem {
566 KeyAction::MoveLeft => singlevideoitem.textlist.first().is_ok(), 726 KeyAction::MoveLeft => singlevideoitem.textlist.first().is_ok(),
567 KeyAction::MoveRight => singlevideoitem.textlist.last().is_ok(), 727 KeyAction::MoveRight => singlevideoitem.textlist.last().is_ok(),
568 KeyAction::Select => { 728 KeyAction::Select => {
569 let command_string = singlevideoitem.commands 729 self.select_at_cursor(framework);
570 [singlevideoitem.textlist.selected] 730 return Ok(());
571 .1
572 .clone();
573
574 match command_string.as_str() {
575 // checks for special cases that the items should consume the command
576 // instead of running it
577 "%switch-provider%" => {
578 singlevideoitem.provider.rotate();
579 singlevideoitem.update_provider();
580 *framework.data.global.get_mut::<Message>().unwrap() =
581 Message::Success(format!(
582 "Switched provider to {}",
583 singlevideoitem.provider.as_str()
584 ));
585 }
586 _ => {
587 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
588 // joins the env from the one in mainconfig and video info
589 let env = singlevideoitem.inflate(
590 mainconfig.env.clone(),
591 mainconfig,
592 self.item.as_ref().unwrap(),
593 );
594 let command_string = apply_env(command_string, &env);
595
596 *framework.data.global.get_mut::<Message>().unwrap() =
597 Message::Success(command_string.clone());
598
599 // this allows creating commands from string
600 let mut command = execute::command(command_string);
601
602 // run the command in a new thread so it doesn't freeze the current one
603 thread::spawn(move || {
604 let _ = command.output();
605 });
606 }
607 }
608
609 true
610 } 731 }
611 _ => false, 732 _ => false,
612 }, 733 },
@@ -620,49 +741,8 @@ impl FrameworkItem for SingleItem {
620 KeyAction::MoveLeft => singleplaylistitem.commands_view.first().is_ok(), 741 KeyAction::MoveLeft => singleplaylistitem.commands_view.first().is_ok(),
621 KeyAction::MoveRight => singleplaylistitem.commands_view.last().is_ok(), 742 KeyAction::MoveRight => singleplaylistitem.commands_view.last().is_ok(),
622 KeyAction::Select => { 743 KeyAction::Select => {
623 let command_string = singleplaylistitem.commands 744 self.select_at_cursor(framework);
624 [singleplaylistitem.commands_view.selected] 745 return Ok(());
625 .1
626 .clone();
627
628 // checks for special cases
629 match command_string.as_str() {
630 "%switch-view%" => {
631 singleplaylistitem.is_commands_view =
632 !singleplaylistitem.is_commands_view;
633 self.update_appearance(
634 framework.data.global.get::<AppearanceConfig>().unwrap(),
635 &info,
636 );
637 *framework.data.global.get_mut::<Message>().unwrap() =
638 Message::Success(String::from("Switched view"));
639 }
640 "%switch-provider%" => {
641 singleplaylistitem.provider.rotate();
642 singleplaylistitem.update_provider();
643 }
644 // same as before if string is not a special case then the run the command
645 _ => {
646 let mainconfig =
647 framework.data.global.get::<MainConfig>().unwrap();
648 let env = singleplaylistitem.inflate(
649 mainconfig.env.clone(),
650 mainconfig,
651 self.item.as_ref().unwrap(),
652 );
653 let command_string = apply_env(command_string, &env);
654
655 *framework.data.global.get_mut::<Message>().unwrap() =
656 Message::Success(command_string.clone());
657 let mut command = execute::command(command_string);
658
659 thread::spawn(move || {
660 let _ = command.output();
661 });
662 }
663 };
664
665 true
666 } 746 }
667 _ => false, 747 _ => false,
668 } 748 }
@@ -778,6 +858,77 @@ impl FrameworkItem for SingleItem {
778 858
779 Ok(()) 859 Ok(())
780 } 860 }
861
862 fn mouse_event(
863 &mut self,
864 framework: &mut FrameworkClean,
865 x: u16,
866 y: u16,
867 _absolute_x: u16,
868 _absolute_y: u16,
869 ) -> bool {
870 let chunk = self
871 .grid
872 .chunks(
873 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
874 {
875 prev_frame
876 } else {
877 return false;
878 },
879 )
880 .unwrap()[0][1];
881
882 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
883 return false;
884 }
885
886 let textlist = match &mut self.r#type {
887 SingleItemType::Video(SingleVideoItem { textlist, .. }) => textlist,
888 SingleItemType::Playlist(singleplaylistitem) => {
889 if singleplaylistitem.is_commands_view {
890 &mut singleplaylistitem.commands_view
891 } else {
892 &mut singleplaylistitem.videos_view
893 }
894 }
895 _ => return false,
896 };
897
898 let y = (y - chunk.y) as usize + textlist.scroll;
899
900 // clicking on already selected item
901 if y == textlist.selected || y == textlist.selected + 2 || y == textlist.selected + 1 {
902 self.select_at_cursor(framework);
903 return true;
904 }
905
906 // clicking on rows after the last item
907 if y > textlist.items.len() + 1 {
908 return false;
909 }
910
911 // moving the cursor
912 if y <= textlist.selected {
913 textlist.selected = y;
914 }
915
916 if y >= textlist.selected + 2 {
917 textlist.selected = y - 2;
918 }
919
920 self.update();
921
922 // render the new image
923 framework
924 .data
925 .global
926 .get_mut::<Status>()
927 .unwrap()
928 .render_image = true;
929
930 true
931 }
781} 932}
782 933
783/// apply the env hashmap to a command string 934/// apply the env hashmap to a command string
src/run.rs +108 −16
@@ -1,11 +1,17 @@
1use crossterm::event::{self, Event, MouseEventKind, MouseButton}; 1use crossterm::event::{self, Event, MouseButton, MouseEventKind};
2use std::{error::Error, io::Stdout}; 2use std::{error::Error, io::Stdout};
3use tui::{backend::CrosstermBackend, Terminal}; 3use tui::{backend::CrosstermBackend, Terminal};
4use tui_additions::framework::{Framework, FrameworkDirection}; 4use tui_additions::{
5 framework::{Framework, FrameworkDirection},
6 widgets::TextField,
7};
5 8
6use crate::{ 9use crate::{
7 config::KeyBindingsConfig, 10 config::{KeyBindingsConfig, MainConfig},
8 global::structs::{KeyAction, Message, Status, Task, Tasks}, 11 global::{
12 functions::command_capture,
13 structs::{KeyAction, Message, Status, Task, Tasks},
14 },
9}; 15};
10 16
11/// the main event loop of the program 17/// the main event loop of the program
@@ -20,15 +26,67 @@ pub fn run(
20 continue; 26 continue;
21 } 27 }
22 28
29 // exits the function is `.exit` is true - a way for items/commands to exit the program
30 if framework.data.global.get::<Status>().unwrap().exit {
31 break;
32 }
23 *framework.data.global.get_mut::<Message>().unwrap() = Message::None; 33 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
24 34
25 match event::read()? { 35 match event::read()? {
26 Event::Mouse(mouse) => { 36 Event::Mouse(mouse)
37 if framework
38 .data
39 .global
40 .get::<MainConfig>()
41 .unwrap()
42 .mouse_support =>
43 {
27 if mouse.kind != MouseEventKind::Down(MouseButton::Left) { 44 if mouse.kind != MouseEventKind::Down(MouseButton::Left) {
28 continue; 45 continue;
29 } 46 }
30 47
31 let updated = framework.mouse_event(mouse.column, mouse.row); 48 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
49
50 // check if the search filter popup is clicked
51 let mut searchfilter_clicked = false;
52 if framework
53 .data
54 .global
55 .get::<Status>()
56 .unwrap()
57 .search_filter_opened
58 {
59 let (mut frameworkclean, state) = framework.split_clean();
60 for row in state.0.iter_mut() {
61 for item in row.items.iter_mut() {
62 match item.item.r#type() {
63 "youtube_tui::items::searchfilters::SearchFilter" => {
64 if item.item.mouse_event(
65 &mut frameworkclean,
66 0,
67 0,
68 mouse.column,
69 mouse.row,
70 ) {
71 searchfilter_clicked = true;
72 break;
73 }
74 }
75 _ => {}
76 }
77 }
78
79 if searchfilter_clicked {
80 break;
81 }
82 }
83 }
84
85 let updated = if searchfilter_clicked {
86 true
87 } else {
88 framework.mouse_event(mouse.column, mouse.row)
89 };
32 90
33 if updated { 91 if updated {
34 framework 92 framework
@@ -39,25 +97,19 @@ pub fn run(
39 .priority 97 .priority
40 .push(Task::RenderAll); 98 .push(Task::RenderAll);
41 } 99 }
42 }, 100 }
43 Event::Key(key) => { 101 Event::Key(key) => {
44 // 1. get the corresponding action 102 // 1. get the corresponding action
45 // 2. check if action is deselect, if yes, deselect 103 // 2. check if action is deselect, if yes, deselect
46 // 3. check is anything is selected, if yes, run `.key_event()` with the key 104 // 3. check is anything is selected, if yes, run `.key_event()` with the key
47 // 4. if nothing is selected, do stuff like moving the cursor or exiting 105 // 4. if nothing is selected, do stuff like moving the cursor or exiting
48 106
49 let action = if let Some(keyactions) = framework 107 let action = framework
50 .data 108 .data
51 .global 109 .global
52 .get::<KeyBindingsConfig>() 110 .get::<KeyBindingsConfig>()
53 .unwrap() 111 .unwrap()
54 .0 112 .get(key);
55 .get(&key.code)
56 {
57 keyactions.get(&key.modifiers.bits()).copied()
58 } else {
59 None
60 };
61 113
62 if action == Some(KeyAction::Deselect) { 114 if action == Some(KeyAction::Deselect) {
63 let _ = framework.deselect(); 115 let _ = framework.deselect();
@@ -68,6 +120,13 @@ pub fn run(
68 .unwrap() 120 .unwrap()
69 .priority 121 .priority
70 .push(Task::RenderAll); 122 .push(Task::RenderAll);
123 framework
124 .data
125 .global
126 .get_mut::<Status>()
127 .unwrap()
128 .command_capture = None;
129 continue;
71 } 130 }
72 131
73 // if something is selected, pass the key input into that item 132 // if something is selected, pass the key input into that item
@@ -78,9 +137,42 @@ pub fn run(
78 *framework.data.global.get_mut::<Message>().unwrap() = 137 *framework.data.global.get_mut::<Message>().unwrap() =
79 Message::Error(format!("{}", e)); 138 Message::Error(format!("{}", e));
80 }; 139 };
81 } else if let Some(action) = action { 140 continue;
141 }
142
143 // the first part check for if the keys should be captured for entering commands
144 if framework
145 .data
146 .global
147 .get::<Status>()
148 .unwrap()
149 .command_capture
150 .is_some()
151 // the second part runs the command, and see if the returned boolean
152 // `is_updated` is true, if so update the screen
153 && command_capture(&mut framework.split_clean().0, key)
154 {
155 framework
156 .data
157 .state
158 .get_mut::<Tasks>()
159 .unwrap()
160 .priority
161 .push(Task::RenderAll);
162 continue;
163 }
164
165 if let Some(action) = action {
82 let mut render = true; 166 let mut render = true;
83 match action { 167 match action {
168 KeyAction::StartCommandCapture => {
169 framework
170 .data
171 .global
172 .get_mut::<Status>()
173 .unwrap()
174 .command_capture = Some(TextField::default());
175 }
84 KeyAction::Exit => break, 176 KeyAction::Exit => break,
85 KeyAction::MoveUp => framework.r#move(FrameworkDirection::Up)?, 177 KeyAction::MoveUp => framework.r#move(FrameworkDirection::Up)?,
86 KeyAction::MoveDown => framework.r#move(FrameworkDirection::Down)?, 178 KeyAction::MoveDown => framework.r#move(FrameworkDirection::Down)?,