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 = [
1919
2020[[package]]
2121name = "ansi_colours"
22version = "1.1.1"
22version = "1.2.1"
2323source = "registry+https://github.com/rust-lang/crates.io-index"
24checksum = "32678233b67f9056b0c144b39d46dc3218637e8d84ad6038ded339e08b19620d"
24checksum = "7db9d9767fde724f83933a716ee182539788f293828244e9d999695ce0f7ba1e"
2525dependencies = [
2626 "rgb",
2727]
@@ -50,6 +50,12 @@ version = "1.3.2"
5050source = "registry+https://github.com/rust-lang/crates.io-index"
5151checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
5252
53[[package]]
54name = "block"
55version = "0.1.6"
56source = "registry+https://github.com/rust-lang/crates.io-index"
57checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
58
5359[[package]]
5460name = "bumpalo"
5561version = "3.11.1"
@@ -82,9 +88,9 @@ checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
8288
8389[[package]]
8490name = "cc"
85version = "1.0.77"
91version = "1.0.78"
8692source = "registry+https://github.com/rust-lang/crates.io-index"
87checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4"
93checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d"
8894
8995[[package]]
9096name = "cfg-if"
@@ -104,6 +110,28 @@ dependencies = [
104110 "winapi",
105111]
106112
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
107135[[package]]
108136name = "codespan-reporting"
109137version = "0.11.1"
@@ -723,9 +751,9 @@ dependencies = [
723751
724752[[package]]
725753name = "ipnet"
726version = "2.6.0"
754version = "2.7.0"
727755source = "registry+https://github.com/rust-lang/crates.io-index"
728checksum = "ec947b7a4ce12e3b87e353abae7ce124d025b6c7d6c5aea5cc0bcf92e9510ded"
756checksum = "11b0d96e660696543b251e58030cf9787df56da39dab19ad60eae7353040917e"
729757
730758[[package]]
731759name = "itoa"
@@ -803,6 +831,15 @@ version = "0.1.0"
803831source = "registry+https://github.com/rust-lang/crates.io-index"
804832checksum = "a8ca8afbe8af1785e09636acb5a41e08a765f5f0340568716c18a8700ba3c0d3"
805833
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
806843[[package]]
807844name = "memchr"
808845version = "2.5.0"
@@ -912,6 +949,35 @@ dependencies = [
912949 "libc",
913950]
914951
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
915981[[package]]
916982name = "once_cell"
917983version = "1.16.0"
@@ -1062,11 +1128,10 @@ dependencies = [
10621128
10631129[[package]]
10641130name = "rayon"
1065version = "1.6.0"
1131version = "1.6.1"
10661132source = "registry+https://github.com/rust-lang/crates.io-index"
1067checksum = "1e060280438193c554f654141c9ea9417886713b7acd75974c85b18a69a88e0b"
1133checksum = "6db3a213adf02b3bcfd2d3846bb41cb22857d131789e01df434fb7e7bc0759b7"
10681134dependencies = [
1069 "crossbeam-deque",
10701135 "either",
10711136 "rayon-core",
10721137]
@@ -1206,18 +1271,18 @@ dependencies = [
12061271
12071272[[package]]
12081273name = "serde"
1209version = "1.0.149"
1274version = "1.0.151"
12101275source = "registry+https://github.com/rust-lang/crates.io-index"
1211checksum = "256b9932320c590e707b94576e3cc1f7c9024d0ee6612dfbcf1cb106cbe8e055"
1276checksum = "97fed41fc1a24994d044e6db6935e69511a1153b52c15eb42493b26fa87feba0"
12121277dependencies = [
12131278 "serde_derive",
12141279]
12151280
12161281[[package]]
12171282name = "serde_derive"
1218version = "1.0.149"
1283version = "1.0.151"
12191284source = "registry+https://github.com/rust-lang/crates.io-index"
1220checksum = "b4eae9b04cbffdfd550eb462ed33bc6a1b68c935127d008b27444d08380f94e4"
1285checksum = "255abe9a125a985c05190d687b320c12f9b1f0b99445e608c21ba0782c719ad8"
12211286dependencies = [
12221287 "proc-macro2",
12231288 "quote",
@@ -1397,9 +1462,9 @@ dependencies = [
13971462
13981463[[package]]
13991464name = "tiff"
1400version = "0.8.0"
1465version = "0.8.1"
14011466source = "registry+https://github.com/rust-lang/crates.io-index"
1402checksum = "f17def29300a156c19ae30814710d9c63cd50288a49c6fd3a10ccfbe4cf886fd"
1467checksum = "7449334f9ff2baf290d55d73983a7d6fa15e01198faef72af07e2a8db851e471"
14031468dependencies = [
14041469 "flate2",
14051470 "jpeg-decoder",
@@ -1516,9 +1581,9 @@ dependencies = [
15161581
15171582[[package]]
15181583name = "tui-additions"
1519version = "0.1.11"
1584version = "0.1.12"
15201585source = "registry+https://github.com/rust-lang/crates.io-index"
1521checksum = "42473ced74bd112a4c96a03aa03bfdce0d3545a0696164379ac901efe2cd6e73"
1586checksum = "3bfce9dd63be9026ffd15ea51ee0afb2fe386263decb04e2bcc0c23556a79a1f"
15221587dependencies = [
15231588 "crossterm",
15241589 "dyn-clone",
@@ -1868,11 +1933,31 @@ dependencies = [
18681933 "winapi",
18691934]
18701935
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
18711955[[package]]
18721956name = "youtube-tui"
18731957version = "0.6.0"
18741958dependencies = [
18751959 "chrono",
1960 "clipboard",
18761961 "crossterm",
18771962 "dyn-clone",
18781963 "execute",
Cargo.toml +1
@@ -37,6 +37,7 @@ futures = {version = "0.3", default-features = false}
3737reqwest = {version = "0.11", default-features = false}
3838serde_json = {version = "1.0", default-features = false}
3939execute = {version = "0.2", default-features = false}
40clipboard = {version = "0.5"}
4041
4142# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
4243# 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
1616
1717> ### Mouse support
1818>
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.
2020
2121## Customisable
2222
src/config/appearance.rs +9
@@ -92,6 +92,7 @@ pub struct ColorsConfig {
9292 pub message_outline: Color,
9393 pub message_error_outline: Color,
9494 pub message_success_outline: Color,
95 pub command_capture: Color,
9596 pub item_info: ItemInfoColors,
9697}
9798
@@ -136,6 +137,8 @@ pub struct ColorsConfigSerde {
136137 pub message_error_outline: ColorSerde,
137138 #[serde(default = "message_success_outline_default")]
138139 pub message_success_outline: ColorSerde,
140 #[serde(default = "command_capture_default")]
141 pub command_capture: ColorSerde,
139142 #[serde(default)]
140143 pub item_info: ItemInfoColorsSerde,
141144}
@@ -184,6 +187,7 @@ impl ColorsConfigSerde {
184187 message_outline: self.message_outline.to_color()?,
185188 message_error_outline: self.message_error_outline.to_color()?,
186189 message_success_outline: self.message_success_outline.to_color()?,
190 command_capture: self.command_capture.to_color()?,
187191 item_info: self.item_info.into()?,
188192 })
189193 }
@@ -222,6 +226,7 @@ impl Default for ColorsConfigSerde {
222226 message_error_outline: message_error_outline_default(),
223227 message_success_outline: message_success_outline_default(),
224228 text_error: text_error_default(),
229 command_capture: command_capture_default(),
225230 item_info: ItemInfoColorsSerde::default(),
226231 }
227232 }
@@ -356,3 +361,7 @@ fn genre_default() -> ColorSerde {
356361fn page_turner_default() -> ColorSerde {
357362 ColorSerde::ColorVariant(ColorVariantSerde::Gray)
358363}
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>> {
7575 "${terminal-emulator} ${video-player} ${embed-url} --no-video --loop-file=inf",
7676 ),
7777 )]),
78 HashMap::from([(
79 String::from("View channel"),
80 String::from(":channel ${channel_id}"),
81 )]),
7882 HashMap::from([(
7983 String::from("Open in browser"),
8084 String::from("${browser} ${url}"),
@@ -117,6 +121,10 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
117121 String::from("Shuffle play all audio (loop)"),
118122 String::from("${terminal-emulator} ${video-player} ${all-videos} --no-video --shuffle --loop-playlist=inf"),
119123 )]),
124 HashMap::from([(
125 String::from("View channel"),
126 String::from(":channel ${channel_id}"),
127 )]),
120128 HashMap::from([(
121129 String::from("Open in browser"),
122130 String::from("${browser} ${url}"),
src/config/keybindings.rs +23 −1
@@ -3,7 +3,7 @@ use crate::global::{
33 structs::KeyAction,
44 traits::{ConfigTrait, EXTENSION},
55};
6use crossterm::event::KeyCode;
6use crossterm::event::{KeyCode, KeyEvent};
77use home::home_dir;
88use serde::{Deserialize, Serialize};
99use std::{
@@ -91,6 +91,10 @@ impl Default for KeyBindingsConfigSerde {
9191 KeyCodeSerde::Char('r'),
9292 HashMap::from([(2, KeyAction::Reload)]),
9393 ),
94 (
95 KeyCodeSerde::Char(':'),
96 HashMap::from([(0, KeyAction::StartCommandCapture)]),
97 ),
9498 // history
9599 (
96100 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Backspace),
@@ -104,6 +108,15 @@ impl Default for KeyBindingsConfigSerde {
104108 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Home),
105109 HashMap::from([(0, KeyAction::FirstHistory)]),
106110 ),
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 ),
107120 ]))
108121 }
109122}
@@ -171,4 +184,13 @@ impl KeyBindingsConfig {
171184 ),
172185 }
173186 }
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 }
174196}
src/config/main.rs +7
@@ -6,6 +6,8 @@ use typemap::Key;
66/// `main.yml`, the main config file
77#[derive(Serialize, Deserialize, Clone)]
88pub struct MainConfig {
9 #[serde(default = "mouse_support_default")]
10 pub mouse_support: bool,
911 #[serde(default = "invidious_instance_default")]
1012 pub invidious_instance: String,
1113 #[serde(default = "max_watch_history_default")]
@@ -36,6 +38,7 @@ impl Key for MainConfig {
3638impl Default for MainConfig {
3739 fn default() -> Self {
3840 Self {
41 mouse_support: mouse_support_default(),
3942 invidious_instance: invidious_instance_default(),
4043 max_watch_history: max_watch_history_default(),
4144 allow_unicode: allow_unicode_default(),
@@ -130,6 +133,10 @@ const fn max_watch_history_default() -> usize {
130133 50
131134}
132135
136const fn mouse_support_default() -> bool {
137 true
138}
139
133140fn default_env() -> HashMap<String, String> {
134141 HashMap::from([
135142 (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 {
99}
1010
1111impl From<&Item> for Option<DownloadRequest> {
12 // turn `Item` into a thumbnail download request
1213 fn from(item: &Item) -> Self {
1314 Some(match item {
1415 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;
1111pub use popup_area::popup_area;
1212mod run_command;
1313pub 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};
29use std::io::Stdout;
310use tui::{backend::CrosstermBackend, Terminal};
411use tui_additions::framework::Framework;
512
13use super::fake_rand_range;
14
615/// WIP text command support
716pub fn run_command(
817 command: &[&str],
@@ -12,11 +21,81 @@ pub fn run_command(
1221 // match a command splitted by space to a bunch of avaliable commands
1322 match command {
1423 [] => {}
15 ["loadpage"] => { /* help message */ }
16 ["loadpage", page] => {
24 ["help"] | ["h"] => {
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, ..] => {
1735 let page = match *page {
1836 "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 }
2099 };
21100
22101 if let Some(page) = page {
@@ -29,10 +108,21 @@ pub fn run_command(
29108 .push(Task::LoadPage(page))
30109 }
31110 }
32 ["history"] => { /* help message */ }
33 ["history", "clear"] => {
34 framework.clear_history();
111 // redirects to the relevant `loadpage` command
112 ["search"] => run_command(&["loadpage", "search"], framework, terminal),
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)
35123 }
124 ["history"] => { /* help message */ }
125 ["history", "clear"] => framework.clear_history(),
36126 ["flush"] => loop {
37127 // runs all stacked actions
38128 if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
@@ -41,6 +131,55 @@ pub fn run_command(
41131 }
42132 break;
43133 },
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 }
45153 }
46154}
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 {
2626 FirstHistory,
2727 /// reload the current page
2828 Reload,
29 /// start command capture
30 StartCommandCapture,
31 /// copy text
32 r#Copy,
33 /// paste text
34 Paste,
2935}
src/global/structs/status.rs +13
@@ -1,11 +1,20 @@
1use tui::layout::Rect;
2use tui_additions::widgets::TextField;
13use typemap::Key;
24
35/// a struct for storing different info, currently only stores one info
46#[derive(Clone)]
57pub struct Status {
68 pub popup_opened: bool,
9 pub search_filter_opened: bool,
710 /// to prevent rerendering the same image
811 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>,
918}
1019
1120impl Key for Status {
@@ -16,7 +25,11 @@ impl Default for Status {
1625 fn default() -> Self {
1726 Self {
1827 popup_opened: false,
28 search_filter_opened: false,
1929 render_image: true,
30 command_capture: None,
31 exit: false,
32 prev_frame: None,
2033 }
2134 }
2235}
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};
25
36use super::{message::Message, page::Page, status::Status};
47use std::{error::Error, io::Stdout, mem};
@@ -17,6 +20,7 @@ pub enum Task {
1720 LoadPage(Page),
1821 ClearPage,
1922 LazyRendered,
23 Command(String),
2024}
2125
2226/// multiple tasks joined together, with duplicates removed
@@ -27,6 +31,7 @@ pub struct TaskQueue {
2731 pub load_page: Option<Page>,
2832 pub clear_all: bool,
2933 pub lazy_rendered: bool,
34 pub commands: Vec<String>,
3035}
3136
3237impl Default for TaskQueue {
@@ -37,6 +42,7 @@ impl Default for TaskQueue {
3742 load_page: None,
3843 clear_all: false,
3944 lazy_rendered: false,
45 commands: Vec::new(),
4046 }
4147 }
4248}
@@ -60,6 +66,7 @@ impl TaskQueue {
6066 Task::LoadPage(page) => self.load_page = Some(page),
6167 Task::ClearPage => self.clear_all = true,
6268 Task::LazyRendered => self.lazy_rendered = true,
69 Task::Command(s) => self.commands.push(s),
6370 // _ => {}
6471 }
6572 }
@@ -74,6 +81,16 @@ impl TaskQueue {
7481 framework: &mut Framework,
7582 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
7683 ) -> 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
7794 if self.clear_all {
7895 terminal.clear()?;
7996 }
@@ -174,6 +191,13 @@ impl TaskQueue {
174191 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
175192 let area = frame.size();
176193
194 framework
195 .data
196 .global
197 .get_mut::<Status>()
198 .unwrap()
199 .prev_frame = Some(area);
200
177201 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
178202 if area.width < min_dimentions.width || area.height < min_dimentions.height {
179203 let paragraph = Paragraph::new(format!(
src/init.rs +31 −22
@@ -12,7 +12,7 @@ use crate::{
1212use home::home_dir;
1313use std::{error::Error, fs, io::Stdout};
1414use tui::{backend::CrosstermBackend, Terminal};
15use tui_additions::framework::Framework;
15use tui_additions::framework::{Framework, FrameworkClean};
1616
1717/// app to run before the app starts
1818// init tasks:
@@ -25,15 +25,10 @@ pub fn init(
2525) -> Result<(), Box<dyn Error>> {
2626 // creating files
2727 let home_dir = home_dir().unwrap();
28 let config_path = home_dir.join(".config/youtube-tui/");
2928 let cache_thumbnails_path = home_dir.join(".cache/youtube-tui/thumbnails/");
3029 let history_thumbnails_path =
3130 home_dir.join(".local/share/youtube-tui/watch_history/thumbnails/");
3231
33 if !&config_path.exists() {
34 fs::create_dir_all(&config_path).unwrap();
35 }
36
3732 if !&cache_thumbnails_path.exists() {
3833 fs::create_dir_all(&cache_thumbnails_path).unwrap();
3934 }
@@ -45,6 +40,32 @@ pub fn init(
4540 // watch history init
4641 WatchHistory::init_move();
4742
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
4869 // inserting data
4970 let main_config = *MainConfig::load()?;
5071
@@ -52,6 +73,10 @@ pub fn init(
5273 .data
5374 .global
5475 .insert::<InvidiousClient>(InvidiousClient::new(main_config.invidious_instance.clone()));
76 framework
77 .data
78 .global
79 .insert::<CommandsConfig>(CommandsConfig::from(*CommandsConfigSerde::load()?));
5580 framework
5681 .data
5782 .global
@@ -69,23 +94,7 @@ pub fn init(
6994 .data
7095 .global
7196 .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());
8197 framework.data.state.insert::<Search>(*Search::load()?);
82 framework
83 .data
84 .state
85 .insert::<MinDimentions>(MinDimentions::default());
8698
87 run_command(&["loadpage", "popular"], framework, terminal);
88 run_command(&["flush"], framework, terminal);
89 run_command(&["history", "clear"], framework, terminal);
9099 Ok(())
91100}
src/items/channeldisplay.rs +147 −41
@@ -10,12 +10,12 @@ use crate::{
1010 },
1111};
1212use tui::{
13 layout::Constraint,
13 layout::{Constraint, Rect},
1414 style::Style,
1515 widgets::{Block, Borders},
1616};
1717use tui_additions::{
18 framework::FrameworkItem,
18 framework::{FrameworkClean, FrameworkItem},
1919 widgets::{Grid, TextList},
2020};
2121
@@ -95,6 +95,79 @@ impl ChannelDisplay {
9595 }
9696 }
9797
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
98171 pub fn selectable(&self) -> bool {
99172 !(matches!(self, Self::Main { .. }) || matches!(self, Self::None))
100173 }
@@ -176,19 +249,14 @@ impl FrameworkItem for ChannelDisplay {
176249 key: crossterm::event::KeyEvent,
177250 _info: tui_additions::framework::ItemInfo,
178251 ) -> Result<(), Box<dyn std::error::Error>> {
179 let action = if let Some(keyactions) = framework
252 let action = if let Some(action) = framework
180253 .data
181254 .global
182255 .get::<KeyBindingsConfig>()
183256 .unwrap()
184 .0
185 .get(&key.code)
257 .get(key)
186258 {
187 if let Some(action) = keyactions.get(&key.modifiers.bits()) {
188 *action
189 } else {
190 return Ok(());
191 }
259 action
192260 } else {
193261 return Ok(());
194262 };
@@ -206,22 +274,8 @@ impl FrameworkItem for ChannelDisplay {
206274 KeyAction::MoveLeft => textlist.first().is_ok(),
207275 KeyAction::MoveRight => textlist.last().is_ok(),
208276 KeyAction::Select => {
209 // on select loads that in singleitem
210 if !videos.is_empty() {
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
277 self.select_at_cursor(framework);
278 return Ok(());
225279 }
226280 _ => false,
227281 };
@@ -256,21 +310,8 @@ impl FrameworkItem for ChannelDisplay {
256310 KeyAction::MoveLeft => textlist.first().is_ok(),
257311 KeyAction::MoveRight => textlist.last().is_ok(),
258312 KeyAction::Select => {
259 if !playlists.is_empty() {
260 framework
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
313 self.select_at_cursor(framework);
314 return Ok(());
274315 }
275316 _ => false,
276317 };
@@ -385,4 +426,69 @@ impl FrameworkItem for ChannelDisplay {
385426
386427 Ok(())
387428 }
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 }
388494}
src/items/itemlist.rs +120 −56
@@ -1,8 +1,11 @@
11use std::error::Error;
22
3use tui::{layout::Constraint, style::Style};
3use tui::{
4 layout::{Constraint, Rect},
5 style::Style,
6};
47use tui_additions::{
5 framework::FrameworkItem,
8 framework::{FrameworkClean, FrameworkItem},
69 widgets::{Grid, TextList},
710};
811
@@ -65,6 +68,55 @@ impl ItemList {
6568 }
6669 }
6770 }
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 }
68120}
69121
70122impl Default for ItemList {
@@ -216,19 +268,14 @@ impl FrameworkItem for ItemList {
216268 key: crossterm::event::KeyEvent,
217269 _info: tui_additions::framework::ItemInfo,
218270 ) -> Result<(), Box<dyn Error>> {
219 let action = if let Some(keyactions) = framework
271 let action = if let Some(action) = framework
220272 .data
221273 .global
222274 .get::<KeyBindingsConfig>()
223275 .unwrap()
224 .0
225 .get(&key.code)
276 .get(key)
226277 {
227 if let Some(action) = keyactions.get(&key.modifiers.bits()) {
228 *action
229 } else {
230 return Ok(());
231 }
278 action
232279 } else {
233280 return Ok(());
234281 };
@@ -240,52 +287,7 @@ impl FrameworkItem for ItemList {
240287 KeyAction::MoveLeft => self.textlist.first().is_ok(),
241288 KeyAction::MoveRight => self.textlist.last().is_ok(),
242289 KeyAction::Select => {
243 let page_to_load = match &self.items[self.textlist.selected] {
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 }
290 self.select_at_cursor(framework);
289291 false
290292 }
291293 _ => false,
@@ -311,6 +313,68 @@ impl FrameworkItem for ItemList {
311313
312314 Ok(())
313315 }
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 }
314378}
315379
316380impl ItemList {
src/items/messagebar.rs +35 −6
@@ -1,8 +1,9 @@
11use crate::{
22 config::{AppearanceConfig, MainConfig},
3 global::structs::Message,
3 global::structs::{Message, Status},
44};
55use tui::{
6 layout::Rect,
67 style::Style,
78 widgets::{Block, Borders, Paragraph},
89};
@@ -28,17 +29,45 @@ impl FrameworkItem for MessageBar {
2829 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
2930 let message = framework.data.global.get::<Message>().unwrap();
3031
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
3140 // display with different border style according to type of message and config
3241 let block = Block::default()
3342 .borders(Borders::ALL)
3443 .border_type(appearance.borders)
35 .border_style(Style::default().fg(match message {
36 Message::None => appearance.colors.outline,
37 Message::Success(_) => appearance.colors.message_success_outline,
38 Message::Error(_) => appearance.colors.message_error_outline,
39 Message::Message(_) => appearance.colors.message_outline,
44 .border_style(Style::default().fg(if command_capture.is_some() {
45 appearance.colors.command_capture
46 } else {
47 match message {
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 }
4053 }));
4154
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
4271 let paragraph = Paragraph::new(
4372 message.to_string(
4473 &framework
src/items/searchbar.rs +50 −3
@@ -1,8 +1,11 @@
11use std::error::Error;
22
33use crate::{
4 config::{AppearanceConfig, Search},
5 global::structs::{Message, Page, Task, Tasks},
4 config::{AppearanceConfig, KeyBindingsConfig, Search},
5 global::{
6 functions::get_clipboard,
7 structs::{KeyAction, Message, Page, Task, Tasks},
8 },
69};
710use crossterm::event::KeyCode;
811use tui::{
@@ -76,6 +79,43 @@ impl FrameworkItem for SearchBar {
7679 key: crossterm::event::KeyEvent,
7780 _info: tui_additions::framework::ItemInfo,
7881 ) -> 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
79119 let updated = match key.code {
80120 KeyCode::Backspace => self.text_field.remove(self.text_field.cursor).is_ok(),
81121 KeyCode::Char(c) => self.text_field.push(c).is_ok(),
@@ -116,7 +156,14 @@ impl FrameworkItem for SearchBar {
116156 Ok(())
117157 }
118158
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 {
120167 if y != 1 || x == 0 {
121168 return false;
122169 }
src/items/searchfilters.rs +103 −19
@@ -6,7 +6,7 @@ use crate::{
66 },
77};
88use tui::{
9 layout::{Alignment, Constraint},
9 layout::{Alignment, Constraint, Rect},
1010 style::Style,
1111 widgets::{Block, Borders, Clear, Paragraph},
1212};
@@ -29,6 +29,8 @@ pub struct SearchFilter {
2929 pub left_options: Vec<&'static str>,
3030 pub current_hover: bool,
3131 pub grid: Grid,
32 /// if the popup is opened
33 pub opened: bool,
3234 pub previous_state: Option<SearchFilters>,
3335}
3436
@@ -46,6 +48,7 @@ impl Default for SearchFilter {
4648 vec![Constraint::Percentage(100)],
4749 )
4850 .unwrap(),
51 opened: false,
4952 previous_state: None,
5053 }
5154 }
@@ -186,12 +189,12 @@ impl FrameworkItem for SearchFilter {
186189 }
187190
188191 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
189 framework
190 .data
191 .global
192 .get_mut::<Status>()
193 .unwrap()
194 .popup_opened = true;
192 self.opened = true;
193
194 let status = framework.data.global.get_mut::<Status>().unwrap();
195
196 status.popup_opened = true;
197 status.search_filter_opened = true;
195198 framework
196199 .data
197200 .state
@@ -220,10 +223,12 @@ impl FrameworkItem for SearchFilter {
220223 }
221224
222225 fn deselect(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
223 *framework.data.global.get_mut::<Status>().unwrap() = Status {
224 popup_opened: false,
225 render_image: true,
226 };
226 self.opened = true;
227
228 let status = framework.data.global.get_mut::<Status>().unwrap();
229 status.popup_opened = false;
230 status.search_filter_opened = false;
231 status.render_image = true;
227232
228233 // refresh page only if changed and enabled in options
229234 let search_options = framework.data.state.get::<Search>().unwrap().clone();
@@ -259,19 +264,14 @@ impl FrameworkItem for SearchFilter {
259264 key: crossterm::event::KeyEvent,
260265 _info: tui_additions::framework::ItemInfo,
261266 ) -> Result<(), Box<dyn std::error::Error>> {
262 let action = if let Some(keyactions) = framework
267 let action = if let Some(action) = framework
263268 .data
264269 .global
265270 .get::<KeyBindingsConfig>()
266271 .unwrap()
267 .0
268 .get(&key.code)
272 .get(key)
269273 {
270 if let Some(action) = keyactions.get(&key.modifiers.bits()) {
271 *action
272 } else {
273 return Ok(());
274 }
274 action
275275 } else {
276276 return Ok(());
277277 };
@@ -327,4 +327,88 @@ impl FrameworkItem for SearchFilter {
327327
328328 Ok(())
329329 }
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 }
330414}
src/items/singleitem.rs +269 −118
@@ -10,9 +10,12 @@ use crate::{
1010 },
1111};
1212use std::{collections::HashMap, thread};
13use tui::{layout::Constraint, style::Style};
13use tui::{
14 layout::{Constraint, Rect},
15 style::Style,
16};
1417use tui_additions::{
15 framework::FrameworkItem,
18 framework::{FrameworkClean, FrameworkItem},
1619 widgets::{Grid, TextList},
1720};
1821
@@ -69,7 +72,13 @@ impl SingleVideoItem {
6972 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig) -> Self {
7073 Self {
7174 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 )
7382 .unwrap(),
7483 commands: commands
7584 .video
@@ -129,11 +138,9 @@ impl SingleVideoItem {
129138 mainconfig.invidious_instance, video_item.id
130139 ),
131140 Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id),
132 // Provider::Piped => {
133 // format!("'{}/watch?v={}'", mainconfig.piped_instance, video_item.id)
134 // }
135141 },
136142 ),
143 (String::from("id"), video_item.id.clone()),
137144 (
138145 String::from("embed-url"),
139146 match self.provider {
@@ -142,9 +149,19 @@ impl SingleVideoItem {
142149 mainconfig.invidious_instance, video_item.id
143150 ),
144151 Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id),
145 // Provider::Piped => {
146 // format!("'{}/embed/{}'", mainconfig.piped_instance, video_item.id)
147 // }
152 },
153 ),
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 ),
148165 },
149166 ),
150167 ])
@@ -175,7 +192,13 @@ impl SinglePlaylistItem {
175192 });
176193 Self {
177194 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 )
179202 .unwrap(),
180203 videos_view: TextList::default()
181204 .items(&{
@@ -278,12 +301,9 @@ impl SinglePlaylistItem {
278301 "{}/playlist?list={}",
279302 mainconfig.invidious_instance, playlist_item.id
280303 ),
281 // Provider::Piped => format!(
282 // "{}/playlist?list={}",
283 // mainconfig.piped_instance, playlist_item.id
284 // ),
285304 },
286305 ),
306 (String::from("id"), playlist_item.id.clone()),
287307 (
288308 String::from("all-videos"),
289309 match self.provider {
@@ -307,18 +327,20 @@ impl SinglePlaylistItem {
307327 })
308328 .collect::<Vec<_>>()
309329 .join(" "),
310 // Provider::Piped => playlist_item
311 // .videos
312 // .iter()
313 // .map(|video| {
314 // format!(
315 // "'{}/watch?v={}'",
316 // mainconfig.piped_instance,
317 // video.minivideo().id
318 // )
319 // })
320 // .collect::<Vec<_>>()
321 // .join(" "),
330 },
331 ),
332 (String::from("channel_id"), playlist_item.channel_id.clone()),
333 (
334 String::from("channel_url"),
335 match self.provider {
336 Provider::YouTube => format!(
337 "https://www.youtube.com/channel/{}",
338 playlist_item.channel_id
339 ),
340 Provider::Invidious => format!(
341 "{}/channel/{}",
342 mainconfig.invidious_instance, playlist_item.channel_id
343 ),
322344 },
323345 ),
324346 ])
@@ -380,6 +402,149 @@ impl SingleItem {
380402 .update_appearance(appearance, iteminfo, &mut self.grid);
381403 }
382404
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
383548 pub fn update_provider(&mut self) {
384549 match &mut self.r#type {
385550 SingleItemType::Video(singlevideoitem) => singlevideoitem.update_provider(),
@@ -541,19 +706,14 @@ impl FrameworkItem for SingleItem {
541706 return Ok(());
542707 }
543708
544 let action = if let Some(keyactions) = framework
709 let action = if let Some(action) = framework
545710 .data
546711 .global
547712 .get::<KeyBindingsConfig>()
548713 .unwrap()
549 .0
550 .get(&key.code)
714 .get(key)
551715 {
552 if let Some(action) = keyactions.get(&key.modifiers.bits()) {
553 *action
554 } else {
555 return Ok(());
556 }
716 action
557717 } else {
558718 return Ok(());
559719 };
@@ -566,47 +726,8 @@ impl FrameworkItem for SingleItem {
566726 KeyAction::MoveLeft => singlevideoitem.textlist.first().is_ok(),
567727 KeyAction::MoveRight => singlevideoitem.textlist.last().is_ok(),
568728 KeyAction::Select => {
569 let command_string = singlevideoitem.commands
570 [singlevideoitem.textlist.selected]
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
729 self.select_at_cursor(framework);
730 return Ok(());
610731 }
611732 _ => false,
612733 },
@@ -620,49 +741,8 @@ impl FrameworkItem for SingleItem {
620741 KeyAction::MoveLeft => singleplaylistitem.commands_view.first().is_ok(),
621742 KeyAction::MoveRight => singleplaylistitem.commands_view.last().is_ok(),
622743 KeyAction::Select => {
623 let command_string = singleplaylistitem.commands
624 [singleplaylistitem.commands_view.selected]
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
744 self.select_at_cursor(framework);
745 return Ok(());
666746 }
667747 _ => false,
668748 }
@@ -778,6 +858,77 @@ impl FrameworkItem for SingleItem {
778858
779859 Ok(())
780860 }
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 }
781932}
782933
783934/// 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};
22use std::{error::Error, io::Stdout};
33use tui::{backend::CrosstermBackend, Terminal};
4use tui_additions::framework::{Framework, FrameworkDirection};
4use tui_additions::{
5 framework::{Framework, FrameworkDirection},
6 widgets::TextField,
7};
58
69use crate::{
7 config::KeyBindingsConfig,
8 global::structs::{KeyAction, Message, Status, Task, Tasks},
10 config::{KeyBindingsConfig, MainConfig},
11 global::{
12 functions::command_capture,
13 structs::{KeyAction, Message, Status, Task, Tasks},
14 },
915};
1016
1117/// the main event loop of the program
@@ -20,15 +26,67 @@ pub fn run(
2026 continue;
2127 }
2228
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 }
2333 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
2434
2535 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 {
2744 if mouse.kind != MouseEventKind::Down(MouseButton::Left) {
2845 continue;
2946 }
3047
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 };
3290
3391 if updated {
3492 framework
@@ -39,25 +97,19 @@ pub fn run(
3997 .priority
4098 .push(Task::RenderAll);
4199 }
42 },
100 }
43101 Event::Key(key) => {
44102 // 1. get the corresponding action
45103 // 2. check if action is deselect, if yes, deselect
46104 // 3. check is anything is selected, if yes, run `.key_event()` with the key
47105 // 4. if nothing is selected, do stuff like moving the cursor or exiting
48106
49 let action = if let Some(keyactions) = framework
107 let action = framework
50108 .data
51109 .global
52110 .get::<KeyBindingsConfig>()
53111 .unwrap()
54 .0
55 .get(&key.code)
56 {
57 keyactions.get(&key.modifiers.bits()).copied()
58 } else {
59 None
60 };
112 .get(key);
61113
62114 if action == Some(KeyAction::Deselect) {
63115 let _ = framework.deselect();
@@ -68,6 +120,13 @@ pub fn run(
68120 .unwrap()
69121 .priority
70122 .push(Task::RenderAll);
123 framework
124 .data
125 .global
126 .get_mut::<Status>()
127 .unwrap()
128 .command_capture = None;
129 continue;
71130 }
72131
73132 // if something is selected, pass the key input into that item
@@ -78,9 +137,42 @@ pub fn run(
78137 *framework.data.global.get_mut::<Message>().unwrap() =
79138 Message::Error(format!("{}", e));
80139 };
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 {
82166 let mut render = true;
83167 match action {
168 KeyAction::StartCommandCapture => {
169 framework
170 .data
171 .global
172 .get_mut::<Status>()
173 .unwrap()
174 .command_capture = Some(TextField::default());
175 }
84176 KeyAction::Exit => break,
85177 KeyAction::MoveUp => framework.r#move(FrameworkDirection::Up)?,
86178 KeyAction::MoveDown => framework.r#move(FrameworkDirection::Down)?,