Commit e2ab565c5c

e2ab565c5c2eac541a27ff7b20238193f5abadde

parent: 183ac39ccb

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2023-08-24 18:13 UTC

added search/command history, still not writing docs

Layout: unified · split

src/config/commandbindings.rs +1 −1
@@ -177,7 +177,7 @@ fn global_default() -> HashMap<KeyCodeSerde, HashMap<u8, String>> {
177 ), 177 ),
178 ( 178 (
179 KeyCodeSerde::Char(' '), 179 KeyCodeSerde::Char(' '),
180 HashMap::from([(0, String::from("tpause ;; echo mpv Player paused toggled"))]), 180 HashMap::from([(0, String::from("tpause ;; echo mpv Player pause toggled"))]),
181 ), 181 ),
182 ( 182 (
183 KeyCodeSerde::KeyVariants(super::serde::KeyVariantsSerde::Left), 183 KeyCodeSerde::KeyVariants(super::serde::KeyVariantsSerde::Left),
src/config/commands.rs +24 −8
@@ -100,12 +100,16 @@ fn video_default() -> Vec<HashMap<String, String>> {
100 )]), 100 )]),
101 HashMap::from([( 101 HashMap::from([(
102 String::from("Play audio"), 102 String::from("Play audio"),
103 String::from("mpv stop ;; resume ;; mpv sprop loop no ;; mpv loadfile '${embed-url}'"), 103 String::from("mpv stop ;; resume ;; mpv sprop loop-file no ;; mpv loadfile '${embed-url}' ;; echo mpv Player started"),
104 )]), 104 )]),
105 HashMap::from([( 105 HashMap::from([(
106 String::from("Play audio (loop)"), 106 String::from("Play audio (loop)"),
107 String::from("mpv stop ;; resume ;; mpv sprop loop inf ;; mpv loadfile '${embed-url}'"), 107 String::from("mpv stop ;; resume ;; mpv sprop loop-file inf ;; mpv loadfile '${embed-url}' ;; echo mpv Player started"),
108 )]), 108 )]),
109 // HashMap::from([(
110 // String::from("Add to queue"),
111 // String::from("mpv loadfile '${embed-url}' appendplay;; echo mpv Added to queue"),
112 // )]),
109 HashMap::from([( 113 HashMap::from([(
110 String::from("View channel"), 114 String::from("View channel"),
111 String::from("channel ${channel-id}"), 115 String::from("channel ${channel-id}"),
@@ -149,12 +153,16 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
149 )]), 153 )]),
150 HashMap::from([( 154 HashMap::from([(
151 String::from("[Offline] Play saved file (audio)"), 155 String::from("[Offline] Play saved file (audio)"),
152 String::from("mpv stop ;; resume ;; mpv sprop loop no ;; mpv loadfile '${offline-path}'"), 156 String::from("mpv stop ;; resume ;; mpv sprop loop-file no ;; mpv loadfile '${offline-path}' ;; echo mpv Player started"),
153 )]), 157 )]),
154 HashMap::from([( 158 HashMap::from([(
155 String::from("[Offline] Play saved file (audio loop)"), 159 String::from("[Offline] Play saved file (audio loop)"),
156 String::from("mpv stop ;; resume ;; mpv sprop loop inf ;; mpv loadfile '${offline-path}'"), 160 String::from("mpv stop ;; resume ;; mpv sprop loop-file inf ;; mpv loadfile '${offline-path}' ;; echo mpv Player started"),
157 )]), 161 )]),
162 // HashMap::from([(
163 // String::from("[Offline] Add to queue"),
164 // String::from("mpv loadfile '${offline-path}' appendplay ;; echo mpv Added to queue"),
165 // )]),
158 HashMap::from([( 166 HashMap::from([(
159 String::from("View channel"), 167 String::from("View channel"),
160 String::from("channel ${channel-id}"), 168 String::from("channel ${channel-id}"),
@@ -199,12 +207,16 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
199 )]), 207 )]),
200 HashMap::from([( 208 HashMap::from([(
201 String::from("Play all (audio)"), 209 String::from("Play all (audio)"),
202 String::from("mpv stop ;; resume ;; ${mpv-queuelist} ;; mpv playlist-play-index 0"), 210 String::from("mpv stop ;; resume ;; ${mpv-queuelist} ;; mpv sprop loop-playlist no ;; mpv playlist-play-index 0 ;; echo mpv Player started"),
203 )]), 211 )]),
204 HashMap::from([( 212 HashMap::from([(
205 String::from("Shuffle play all (audio loop)"), 213 String::from("Shuffle play all (audio loop)"),
206 String::from("mpv stop ;; resume ;; ${mpv-queuelist} ;; mpv playlist-shuffle ;; mpv playlist-play-index 0"), 214 String::from("mpv stop ;; resume ;; ${mpv-queuelist} ;; mpv sprop loop-playlist yes ;; mpv playlist-shuffle ;; mpv playlist-play-index 0 ;; echo mpv Player started"),
207 )]), 215 )]),
216 // HashMap::from([(
217 // String::from("Add all to queue"),
218 // String::from("${mpv-queuelist} ;; echo mpv Queued playlist"),
219 // )]),
208 HashMap::from([( 220 HashMap::from([(
209 String::from("View channel"), 221 String::from("View channel"),
210 String::from("channel ${channel-id}"), 222 String::from("channel ${channel-id}"),
@@ -249,12 +261,16 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
249 )]), 261 )]),
250 HashMap::from([( 262 HashMap::from([(
251 String::from("[Offline] Play all (audio)"), 263 String::from("[Offline] Play all (audio)"),
252 String::from("mpv stop ;; resume ;; ${offline-queuelist} ;; mpv playlist-play-index 0"), 264 String::from("mpv stop ;; resume ;; ${offline-queuelist} ;; mpv sprop loop-playlist no ;; mpv playlist-play-index 0 ;; echo mpv Player started"),
253 )]), 265 )]),
254 HashMap::from([( 266 HashMap::from([(
255 String::from("[Offline] Shuffle play all (audio loop)"), 267 String::from("[Offline] Shuffle play all (audio loop)"),
256 String::from("mpv stop ;; resume ;; ${offline-queuelist} ;; mpv playlist-shuffle ;; mpv playlist-play-index 0"), 268 String::from("mpv stop ;; resume ;; ${offline-queuelist} ;; mpv sprop loop-playlist yes ;; mpv playlist-shuffle ;; mpv playlist-play-index 0 ;; echo mpv Player started"),
257 )]), 269 )]),
270 // HashMap::from([(
271 // String::from("[Offline] Add all to queue"),
272 // String::from("${offline-queuelist} ;; echo mpv Queued playlist"),
273 // )]),
258 HashMap::from([( 274 HashMap::from([(
259 String::from("View channel"), 275 String::from("View channel"),
260 String::from("channel ${channel-id}"), 276 String::from("channel ${channel-id}"),
src/config/keybindings.rs +2 −2
@@ -55,11 +55,11 @@ impl Default for KeyBindingsConfigSerde {
55 ), 55 ),
56 ( 56 (
57 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Up), 57 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Up),
58 HashMap::from([(0, KeyAction::MoveUp)]), 58 HashMap::from([(0, KeyAction::MoveUp), (2, KeyAction::PreviousEntry)]),
59 ), 59 ),
60 ( 60 (
61 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Down), 61 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Down),
62 HashMap::from([(0, KeyAction::MoveDown)]), 62 HashMap::from([(0, KeyAction::MoveDown), (2, KeyAction::NextEntry)]),
63 ), 63 ),
64 // vim keybindings 64 // vim keybindings
65 ( 65 (
src/config/main.rs +33 −4
@@ -12,8 +12,6 @@ pub struct MainConfig {
12 pub invidious_instance: String, 12 pub invidious_instance: String,
13 #[serde(default = "write_to_config_default")] 13 #[serde(default = "write_to_config_default")]
14 pub write_config: WriteConfig, 14 pub write_config: WriteConfig,
15 #[serde(default = "max_watch_history_default")]
16 pub max_watch_history: usize,
17 #[serde(default = "allow_unicode_default")] 15 #[serde(default = "allow_unicode_default")]
18 pub allow_unicode: bool, 16 pub allow_unicode: bool,
19 #[serde(default = "message_bar_default_default")] 17 #[serde(default = "message_bar_default_default")]
@@ -22,7 +20,10 @@ pub struct MainConfig {
22 pub images: Images, 20 pub images: Images,
23 #[serde(default = "refresh_after_modifying_search_filters_default")] 21 #[serde(default = "refresh_after_modifying_search_filters_default")]
24 pub refresh_after_modifying_search_filters: bool, 22 pub refresh_after_modifying_search_filters: bool,
23 #[serde(default = "sync_config_default")]
25 pub syncing: SyncConfig, 24 pub syncing: SyncConfig,
25 #[serde(default)]
26 pub limits: Limits,
26 #[serde(default = "image_index_default")] 27 #[serde(default = "image_index_default")]
27 // The image to download from the array of images provided by the invidious api 28 // The image to download from the array of images provided by the invidious api
28 // 0 is usually `maxres` and 3 (default) is good enough for normal uses without having huge files sizes 29 // 0 is usually `maxres` and 3 (default) is good enough for normal uses without having huge files sizes
@@ -48,13 +49,13 @@ impl Default for MainConfig {
48 write_config: write_to_config_default(), 49 write_config: write_to_config_default(),
49 mouse_support: mouse_support_default(), 50 mouse_support: mouse_support_default(),
50 invidious_instance: invidious_instance_default(), 51 invidious_instance: invidious_instance_default(),
51 max_watch_history: max_watch_history_default(),
52 allow_unicode: allow_unicode_default(), 52 allow_unicode: allow_unicode_default(),
53 message_bar_default: message_bar_default_default(), 53 message_bar_default: message_bar_default_default(),
54 images: images_default(), 54 images: images_default(),
55 image_index: image_index_default(), 55 image_index: image_index_default(),
56 refresh_after_modifying_search_filters: refresh_after_modifying_search_filters_default( 56 refresh_after_modifying_search_filters: refresh_after_modifying_search_filters_default(
57 ), 57 ),
58 limits: Limits::default(),
58 syncing: sync_config_default(), 59 syncing: sync_config_default(),
59 provider: provider_default(), 60 provider: provider_default(),
60 shell: shell_default(), 61 shell: shell_default(),
@@ -90,6 +91,26 @@ const fn sync_config_default() -> SyncConfig {
90 } 91 }
91} 92}
92 93
94#[derive(Clone, Copy, Serialize, Deserialize)]
95pub struct Limits {
96 #[serde(default = "watch_history_default")]
97 pub watch_history: usize,
98 #[serde(default = "search_history_default")]
99 pub search_history: usize,
100 #[serde(default = "commands_history_default")]
101 pub commands_history: usize,
102}
103
104impl Default for Limits {
105 fn default() -> Self {
106 Self {
107 watch_history: watch_history_default(),
108 search_history: search_history_default(),
109 commands_history: commands_history_default(),
110 }
111 }
112}
113
93/// how images are handled/displayed 114/// how images are handled/displayed
94#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] 115#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
95pub enum Images { 116pub enum Images {
@@ -167,7 +188,15 @@ const fn provider_default() -> Provider {
167 Provider::YouTube 188 Provider::YouTube
168} 189}
169 190
170const fn max_watch_history_default() -> usize { 191const fn search_history_default() -> usize {
192 75
193}
194
195const fn commands_history_default() -> usize {
196 75
197}
198
199const fn watch_history_default() -> usize {
171 50 200 50
172} 201}
173 202
src/exit.rs +20 −9
@@ -2,23 +2,34 @@ use home::home_dir;
2use std::{error::Error, fs}; 2use std::{error::Error, fs};
3use tui_additions::framework::Framework; 3use tui_additions::framework::Framework;
4 4
5use crate::global::{structs::*, traits::Collection}; 5use crate::{
6 config::MainConfig,
7 global::{
8 structs::*,
9 traits::{Collection, CollectionNoId},
10 },
11};
6 12
7/// function to run when the app ends 13/// function to run when the app ends
8// exit tasks: 14// exit tasks:
9// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails` 15// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails`
10// - remove `~/.cache` 16// - remove `~/.cache`
11pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> { 17pub fn exit(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
12 framework 18 let limits = framework.data.global.get::<MainConfig>().unwrap().limits;
13 .data 19 let watchhistory = framework.data.global.get_mut::<WatchHistory>().unwrap();
14 .global 20 watchhistory.trim(limits.watch_history);
15 .get::<WatchHistory>() 21 watchhistory.exit_move();
16 .unwrap() 22 let _ = watchhistory.save();
17 .exit_move();
18 let subscriptions = framework.data.global.get::<Subscriptions>().unwrap(); 23 let subscriptions = framework.data.global.get::<Subscriptions>().unwrap();
19 subscriptions.exit_move(); 24 subscriptions.exit_move();
20 subscriptions.save()?; 25 let _ = subscriptions.save();
21 framework.data.global.get::<Library>().unwrap().exit_move(); 26 framework.data.global.get::<Library>().unwrap().exit_move();
27 let searchhistory = framework.data.global.get_mut::<SearchHistory>().unwrap();
28 searchhistory.trim(limits.search_history);
29 let _ = searchhistory.save();
30 let commandhistory = framework.data.global.get_mut::<CommandHistory>().unwrap();
31 commandhistory.trim(limits.commands_history);
32 let _ = commandhistory.save();
22 33
23 let home_dir = home_dir().unwrap(); 34 let home_dir = home_dir().unwrap();
24 let cache_path = home_dir.join(".cache/youtube-tui/"); 35 let cache_path = home_dir.join(".cache/youtube-tui/");
src/global/functions/command_capture.rs +66 −10
@@ -1,4 +1,4 @@
1use crate::global::{functions::*, structs::*}; 1use crate::global::{functions::*, structs::*, traits::CollectionNoId};
2 2
3#[cfg(feature = "clipboard")] 3#[cfg(feature = "clipboard")]
4use crate::config::*; 4use crate::config::*;
@@ -106,17 +106,55 @@ pub fn command_capture(framework: &mut FrameworkClean, key: KeyEvent) -> bool {
106 .push(Task::RenderAll); 106 .push(Task::RenderAll);
107 return true; 107 return true;
108 } 108 }
109 // warning: really shitty code, it works, dont touch
110 Some(KeyAction::PreviousEntry) => {
111 let status = framework.data.global.get::<Status>().unwrap();
112 let history = framework.data.global.get::<CommandHistory>().unwrap();
113 if status.command_history_index != Some(0) && !history.0.is_empty() {
114 let new_index = status.command_history_index.unwrap_or(history.0.len()) - 1;
115 let new_content = history.0[new_index].clone();
116
117 let status = framework.data.global.get_mut::<Status>().unwrap();
118 let text_field = status.command_capture.as_mut().unwrap();
119 if status.command_history_index.is_none() {
120 status.command_editing_cache = text_field.content.clone();
121 }
122 text_field.content = new_content;
123 status.command_history_index = Some(new_index);
124 let _ = text_field.last();
125 return true;
126 }
127 return false;
128 }
129 Some(KeyAction::NextEntry) => {
130 let status = framework.data.global.get::<Status>().unwrap();
131 if status.command_history_index.is_none() {
132 return false;
133 } else {
134 let history = framework.data.global.get::<CommandHistory>().unwrap();
135 if status.command_history_index == Some(history.0.len() - 1) {
136 let status = framework.data.global.get_mut::<Status>().unwrap();
137 let text_field = status.command_capture.as_mut().unwrap();
138 status.command_history_index = None;
139 text_field.content = status.command_editing_cache.clone();
140 } else {
141 let new_index = status.command_history_index.unwrap_or(history.0.len()) + 1;
142 let new_content = history.0[new_index].clone();
143
144 let status = framework.data.global.get_mut::<Status>().unwrap();
145 let text_field = status.command_capture.as_mut().unwrap();
146 text_field.content = new_content;
147 status.command_history_index = Some(new_index);
148 let _ = text_field.last();
149 }
150 return true;
151 }
152 }
109 _ => {} 153 _ => {}
110 } 154 }
111 155
112 let textfield = framework 156 let status = framework.data.global.get_mut::<Status>().unwrap();
113 .data 157 let textfield = status.command_capture.as_mut().unwrap();
114 .global
115 .get_mut::<Status>()
116 .unwrap()
117 .command_capture
118 .as_mut()
119 .unwrap();
120 // a textfield must have a width set, because we don't know the width yet just set it to the 158 // a textfield must have a width set, because we don't know the width yet just set it to the
121 // maximum value possible, so that the cursor will not be moved because of the small value 159 // maximum value possible, so that the cursor will not be moved because of the small value
122 textfield.set_width(u16::MAX); 160 textfield.set_width(u16::MAX);
@@ -129,13 +167,31 @@ pub fn command_capture(framework: &mut FrameworkClean, key: KeyEvent) -> bool {
129 KeyCode::Right => textfield.right().is_ok(), 167 KeyCode::Right => textfield.right().is_ok(),
130 KeyCode::Backspace => textfield.pop().is_ok(), 168 KeyCode::Backspace => textfield.pop().is_ok(),
131 KeyCode::Enter => { 169 KeyCode::Enter => {
170 let content = textfield.content.clone();
171 framework
172 .data
173 .global
174 .get_mut::<CommandHistory>()
175 .unwrap()
176 .push(content);
132 framework 177 framework
133 .data 178 .data
134 .state 179 .state
135 .get_mut::<Tasks>() 180 .get_mut::<Tasks>()
136 .unwrap() 181 .unwrap()
137 .priority 182 .priority
138 .push(Task::Command(apply_envs(textfield.content.clone()))); 183 .push(Task::Command(apply_envs(
184 framework
185 .data
186 .global
187 .get_mut::<Status>()
188 .unwrap()
189 .command_capture
190 .as_mut()
191 .unwrap()
192 .content
193 .clone(),
194 )));
139 framework 195 framework
140 .data 196 .data
141 .global 197 .global
src/global/functions/key_input.rs +1 −2
@@ -4,7 +4,6 @@ use crossterm::event::KeyEvent;
4use ratatui::{backend::CrosstermBackend, Terminal}; 4use ratatui::{backend::CrosstermBackend, Terminal};
5use tui_additions::{ 5use tui_additions::{
6 framework::{Framework, FrameworkDirection}, 6 framework::{Framework, FrameworkDirection},
7 widgets::TextField,
8}; 7};
9 8
10use crate::{config::*, global::structs::*, items::SearchBar}; 9use crate::{config::*, global::structs::*, items::SearchBar};
@@ -124,7 +123,7 @@ pub fn key_input(
124 .global 123 .global
125 .get_mut::<Status>() 124 .get_mut::<Status>()
126 .unwrap() 125 .unwrap()
127 .command_capture = Some(TextField::default()); 126 .reset_command_capture();
128 } 127 }
129 KeyAction::Exit => framework 128 KeyAction::Exit => framework
130 .data 129 .data
src/global/functions/run_command.rs +1 −1
@@ -70,7 +70,7 @@ pub fn run_single_command(
70 })() { 70 })() {
71 Ok(item) => { 71 Ok(item) => {
72 let library = framework.data.global.get_mut::<Library>().unwrap(); 72 let library = framework.data.global.get_mut::<Library>().unwrap();
73 let _ = library.push(item, None); 73 let _ = library.push(item);
74 let _ = library.save(); 74 let _ = library.save();
75 *framework.data.global.get_mut::<Message>().unwrap() = 75 *framework.data.global.get_mut::<Message>().unwrap() =
76 Message::Success(String::from("Bookmark added")) 76 Message::Success(String::from("Bookmark added"))
src/global/structs/history.rs added +75
@@ -0,0 +1,75 @@
1use crate::global::{
2 structs::Item,
3 traits::{Collection, CollectionNoId},
4};
5use serde::{Deserialize, Serialize};
6use typemap::Key;
7
8#[derive(Clone, Default, Serialize, Deserialize)]
9pub struct WatchHistory(pub Vec<Item>);
10
11impl Key for WatchHistory {
12 type Value = Self;
13}
14
15impl Collection<Item> for WatchHistory {
16 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json";
17
18 fn items(&self) -> &Vec<Item> {
19 &self.0
20 }
21
22 fn items_mut(&mut self) -> &mut Vec<Item> {
23 &mut self.0
24 }
25
26 fn from_items(items: Vec<Item>) -> Self {
27 Self(items)
28 }
29}
30
31#[derive(Clone, Default, Serialize, Deserialize)]
32pub struct SearchHistory(pub Vec<String>);
33
34impl Key for SearchHistory {
35 type Value = Self;
36}
37
38impl CollectionNoId<String> for SearchHistory {
39 const INDEX_PATH: &'static str = ".local/share/youtube-tui/search_history.json";
40
41 fn items(&self) -> &Vec<String> {
42 &self.0
43 }
44
45 fn items_mut(&mut self) -> &mut Vec<String> {
46 &mut self.0
47 }
48
49 fn from_items(items: Vec<String>) -> Self {
50 Self(items)
51 }
52}
53
54#[derive(Clone, Default, Serialize, Deserialize)]
55pub struct CommandHistory(pub Vec<String>);
56
57impl Key for CommandHistory {
58 type Value = Self;
59}
60
61impl CollectionNoId<String> for CommandHistory {
62 const INDEX_PATH: &'static str = ".local/share/youtube-tui/command_history.json";
63
64 fn items(&self) -> &Vec<String> {
65 &self.0
66 }
67
68 fn items_mut(&mut self) -> &mut Vec<String> {
69 &mut self.0
70 }
71
72 fn from_items(items: Vec<String>) -> Self {
73 Self(items)
74 }
75}
src/global/structs/keyaction.rs +4
@@ -42,4 +42,8 @@ pub enum KeyAction {
42 First, 42 First,
43 /// move cursor to the last position 43 /// move cursor to the last position
44 End, 44 End,
45 /// Previous entry
46 PreviousEntry,
47 /// Next entry
48 NextEntry,
45} 49}
src/global/structs/mod.rs +2 −2
@@ -1,5 +1,6 @@
1//! enums and structs 1//! enums and structs
2mod errors; 2mod errors;
3mod history;
3mod invidiousclient; 4mod invidiousclient;
4mod item; 5mod item;
5mod keyaction; 6mod keyaction;
@@ -12,9 +13,9 @@ mod state_env;
12mod status; 13mod status;
13mod subscriptions; 14mod subscriptions;
14mod tasks; 15mod tasks;
15mod watchhistory;
16 16
17pub use errors::*; 17pub use errors::*;
18pub use history::*;
18pub use invidiousclient::*; 19pub use invidiousclient::*;
19pub use item::*; 20pub use item::*;
20pub use keyaction::*; 21pub use keyaction::*;
@@ -27,4 +28,3 @@ pub use state_env::*;
27pub use status::*; 28pub use status::*;
28pub use subscriptions::*; 29pub use subscriptions::*;
29pub use tasks::*; 30pub use tasks::*;
30pub use watchhistory::*;
src/global/structs/status.rs +14
@@ -15,6 +15,10 @@ pub struct Status {
15 pub render_image: bool, 15 pub render_image: bool,
16 /// the textfield for command capture 16 /// the textfield for command capture
17 pub command_capture: Option<TextField>, 17 pub command_capture: Option<TextField>,
18 /// used for command history and stuff
19 pub command_history_index: Option<usize>,
20 /// currently editing command
21 pub command_editing_cache: String,
18 /// if true, exit in the next iteration 22 /// if true, exit in the next iteration
19 pub exit: bool, 23 pub exit: bool,
20 /// stores the area of the previously rendered frame 24 /// stores the area of the previously rendered frame
@@ -39,6 +43,8 @@ impl Default for Status {
39 render_image: true, 43 render_image: true,
40 command_capture: None, 44 command_capture: None,
41 exit: false, 45 exit: false,
46 command_history_index: None,
47 command_editing_cache: String::new(),
42 prev_frame: None, 48 prev_frame: None,
43 provider: Provider::YouTube, 49 provider: Provider::YouTube,
44 provider_updated: false, 50 provider_updated: false,
@@ -52,3 +58,11 @@ impl Status {
52 *self = Self::default(); 58 *self = Self::default();
53 } 59 }
54} 60}
61
62impl Status {
63 pub fn reset_command_capture(&mut self) {
64 self.command_capture = Some(TextField::default());
65 self.command_history_index = None;
66 self.command_editing_cache = String::new();
67 }
68}
src/global/structs/subscriptions.rs +1 −1
@@ -329,7 +329,7 @@ impl Collection<SubItem> for Subscriptions {
329 Ok(()) 329 Ok(())
330 } 330 }
331 331
332 fn push(&mut self, _: SubItem, _: Option<usize>) -> Result<(), Box<dyn Error>> { 332 fn push(&mut self, _: SubItem) -> Result<(), Box<dyn Error>> {
333 unimplemented!("not in use"); 333 unimplemented!("not in use");
334 } 334 }
335 335
src/global/structs/watchhistory.rs deleted −26
@@ -1,26 +0,0 @@
1use crate::global::{structs::Item, traits::Collection};
2use serde::{Deserialize, Serialize};
3use typemap::Key;
4
5#[derive(Clone, Default, Serialize, Deserialize)]
6pub struct WatchHistory(pub Vec<Item>);
7
8impl Key for WatchHistory {
9 type Value = Self;
10}
11
12impl Collection<Item> for WatchHistory {
13 const INDEX_PATH: &'static str = ".local/share/youtube-tui/watch_history.json";
14
15 fn items(&self) -> &Vec<Item> {
16 &self.0
17 }
18
19 fn items_mut(&mut self) -> &mut Vec<Item> {
20 &mut self.0
21 }
22
23 fn from_items(items: Vec<Item>) -> Self {
24 Self(items)
25 }
26}
src/global/traits/collection.rs +92 −6
@@ -23,6 +23,13 @@ where
23 23
24 fn from_items(items: Vec<T>) -> Self; 24 fn from_items(items: Vec<T>) -> Self;
25 25
26 fn trim(&mut self, length: usize) {
27 let items = self.items_mut();
28 if items.len() > length {
29 items.drain(0..items.len() - length);
30 }
31 }
32
26 /// saves the current state of watch history into a file 33 /// saves the current state of watch history into a file
27 fn save(&self) -> Result<(), Box<dyn Error>> { 34 fn save(&self) -> Result<(), Box<dyn Error>> {
28 let save_string = serde_json::to_string_pretty( 35 let save_string = serde_json::to_string_pretty(
@@ -47,7 +54,7 @@ where
47 } 54 }
48 55
49 /// add an item to watch history 56 /// add an item to watch history
50 fn push(&mut self, item: T, max_length: Option<usize>) -> Result<(), Box<dyn Error>> { 57 fn push(&mut self, item: T) -> Result<(), Box<dyn Error>> {
51 let info = home_dir().unwrap().join(".cache/youtube-tui/info/"); 58 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
52 59
53 // removes duplicates and place them on top (if exists) 60 // removes duplicates and place them on top (if exists)
@@ -69,11 +76,6 @@ where
69 76
70 self.items_mut().push(item); 77 self.items_mut().push(item);
71 78
72 // if length of history exceeds the maximum history length, removes that oldest item
73 if self.items().len() > max_length.unwrap_or(usize::MAX) {
74 self.items_mut().remove(0);
75 }
76
77 Ok(()) 79 Ok(())
78 } 80 }
79 81
@@ -158,3 +160,87 @@ where
158 } 160 }
159 } 161 }
160} 162}
163
164pub trait CollectionNoId<T>
165where
166 Self: Default + Clone + Serialize + DeserializeOwned,
167 T: Serialize + DeserializeOwned + PartialEq,
168{
169 const INDEX_PATH: &'static str;
170
171 fn items(&self) -> &Vec<T>;
172 fn items_mut(&mut self) -> &mut Vec<T>;
173
174 fn from_items(items: Vec<T>) -> Self;
175
176 fn trim(&mut self, length: usize) {
177 let items = self.items_mut();
178 if items.len() > length {
179 items.drain(0..items.len() - length);
180 }
181 }
182 /// saves the current state of watch history into a file
183 fn save(&self) -> Result<(), Box<dyn Error>> {
184 let save_string = serde_json::to_string_pretty(&self)?;
185 let path = home_dir().unwrap().join(Self::INDEX_PATH);
186
187 let mut file = OpenOptions::new()
188 .write(true)
189 .create(true)
190 .truncate(true)
191 .open(path)?;
192
193 file.write_all(save_string.as_bytes())?;
194
195 Ok(())
196 }
197
198 /// add an item to watch history
199 fn push(&mut self, item: T) {
200 // removes duplicates and place them on top (if exists)
201 if let Some(index) = self
202 .items_mut()
203 .iter_mut()
204 .position(|item_in_iter| *item_in_iter == item)
205 {
206 self.items_mut().remove(index);
207 }
208
209 self.items_mut().push(item);
210 }
211
212 /// loads watch history from file
213 fn load() -> Self {
214 let path = home_dir().unwrap().join(Self::INDEX_PATH);
215 let res = (|| -> Result<Vec<T>, Box<dyn Error>> {
216 let file_string = fs::read_to_string(&path)?;
217 let deserialized = serde_json::from_str(&file_string)?;
218 Ok(deserialized)
219 })();
220
221 // if res is err, then the file either doesn't exist of has be altered incorrectly, in
222 // which case returns Self::default()
223 let items = match res {
224 Ok(res) => res,
225 Err(_) => Vec::new(),
226 };
227
228 Self::from_items(items)
229 }
230
231 /// remove item based on their id
232 fn remove(&mut self, matcher: &T) -> bool {
233 let items = self.items_mut();
234
235 if let Some(found) = items
236 .iter()
237 .enumerate()
238 .find(|(_index, item)| *item == matcher)
239 {
240 items.remove(found.0);
241 true
242 } else {
243 false
244 }
245 }
246}
src/init.rs +8
@@ -43,6 +43,14 @@ pub fn init(
43 43
44 load_configs(&mut framework.split_clean().0)?; 44 load_configs(&mut framework.split_clean().0)?;
45 45
46 framework
47 .data
48 .global
49 .insert::<CommandHistory>(CommandHistory::load());
50 framework
51 .data
52 .global
53 .insert::<SearchHistory>(SearchHistory::load());
46 framework 54 framework
47 .data 55 .data
48 .global 56 .global
src/items/messagebar.rs +1 −1
@@ -74,7 +74,7 @@ impl FrameworkItem for MessageBar {
74 let mut seeker_len = length - total_len - 4; 74 let mut seeker_len = length - total_len - 4;
75 let seeker_pad = if seeker_len > 10 { seeker_len / 10 } else { 0 }; 75 let seeker_pad = if seeker_len > 10 { seeker_len / 10 } else { 0 };
76 seeker_len -= seeker_pad * 2; 76 seeker_len -= seeker_pad * 2;
77 let seeker_pos = seeker_len * playerhead as usize / duration as usize; 77 let seeker_pos = (seeker_len - 1) * playerhead as usize / duration as usize;
78 format!( 78 format!(
79 "{left_chunk} {}├{}-{}┤{} {right_chunk}", 79 "{left_chunk} {}├{}-{}┤{} {right_chunk}",
80 " ".repeat(seeker_pad), 80 " ".repeat(seeker_pad),
src/items/searchbar.rs +40 −1
@@ -1,6 +1,9 @@
1use std::error::Error; 1use std::error::Error;
2 2
3use crate::{config::*, global::structs::*}; 3use crate::{
4 config::*,
5 global::{structs::*, traits::CollectionNoId},
6};
4 7
5#[cfg(feature = "clipboard")] 8#[cfg(feature = "clipboard")]
6use crate::global::functions::get_clipboard; 9use crate::global::functions::get_clipboard;
@@ -18,6 +21,8 @@ use tui_additions::{framework::FrameworkItem, widgets::TextField};
18#[derive(Clone, Default)] 21#[derive(Clone, Default)]
19pub struct SearchBar { 22pub struct SearchBar {
20 pub text_field: TextField, 23 pub text_field: TextField,
24 pub history_index: Option<usize>,
25 pub custom_value_cache: String,
21} 26}
22 27
23impl FrameworkItem for SearchBar { 28impl FrameworkItem for SearchBar {
@@ -112,6 +117,34 @@ impl FrameworkItem for SearchBar {
112 Some(KeyAction::End | KeyAction::MoveDown) => { 117 Some(KeyAction::End | KeyAction::MoveDown) => {
113 self.text_field.cursor = self.text_field.content.len() 118 self.text_field.cursor = self.text_field.content.len()
114 } 119 }
120 Some(KeyAction::PreviousEntry) => {
121 let history = framework.data.global.get::<SearchHistory>().unwrap();
122 if self.history_index != Some(0) && !history.0.is_empty() {
123 if self.history_index.is_none() {
124 self.custom_value_cache = self.text_field.content.clone();
125 self.history_index = None
126 }
127 self.history_index = Some(self.history_index.unwrap_or(history.0.len()) - 1);
128 self.text_field.content = history.0[self.history_index.unwrap()].clone();
129 let _ = self.text_field.last();
130 } else {
131 render = false
132 }
133 }
134 Some(KeyAction::NextEntry) => {
135 let history = framework.data.global.get::<SearchHistory>().unwrap();
136 if self.history_index.is_none() {
137 render = false
138 } else if self.history_index == Some(history.0.len() - 1) {
139 self.history_index = None;
140 self.text_field.content = self.custom_value_cache.clone();
141 let _ = self.text_field.last();
142 } else {
143 self.history_index = self.history_index.map(|n| n + 1);
144 self.text_field.content = history.0[self.history_index.unwrap()].clone();
145 let _ = self.text_field.last();
146 }
147 }
115 _ => render = false, 148 _ => render = false,
116 } 149 }
117 150
@@ -150,6 +183,12 @@ impl FrameworkItem for SearchBar {
150 183
151 let search = framework.data.state.get_mut::<Search>().unwrap(); 184 let search = framework.data.state.get_mut::<Search>().unwrap();
152 search.query = self.text_field.content.clone(); 185 search.query = self.text_field.content.clone();
186 framework
187 .data
188 .global
189 .get_mut::<SearchHistory>()
190 .unwrap()
191 .push(search.query.clone());
153 let search = search.clone(); 192 let search = search.clone();
154 let tasks = framework.data.state.get_mut::<Tasks>().unwrap(); 193 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
155 tasks.priority.push(Task::LoadPage(Page::Search(search))); 194 tasks.priority.push(Task::LoadPage(Page::Search(search)));
src/items/singleitem.rs +1 −8
@@ -743,16 +743,9 @@ impl FrameworkItem for SingleItem {
743 } 743 }
744 744
745 let item = item.clone(); 745 let item = item.clone();
746 let max_watch_history = framework
747 .data
748 .global
749 .get::<MainConfig>()
750 .unwrap()
751 .max_watch_history;
752
753 // push to watch history 746 // push to watch history
754 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap(); 747 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
755 watch_history.push(item, Some(max_watch_history))?; 748 watch_history.push(item)?;
756 watch_history.save()?; 749 watch_history.save()?;
757 } 750 }
758 751
src/main.rs +1 −1
@@ -48,7 +48,7 @@ fn main() -> Result<(), Box<dyn Error>> {
48 )?; 48 )?;
49 terminal.show_cursor()?; 49 terminal.show_cursor()?;
50 50
51 let exit_res = exit(&framework); 51 let exit_res = exit(&mut framework);
52 52
53 res?; 53 res?;
54 exit_res?; 54 exit_res?;