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>> {
177177 ),
178178 (
179179 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"))]),
181181 ),
182182 (
183183 KeyCodeSerde::KeyVariants(super::serde::KeyVariantsSerde::Left),
src/config/commands.rs +24 −8
@@ -100,12 +100,16 @@ fn video_default() -> Vec<HashMap<String, String>> {
100100 )]),
101101 HashMap::from([(
102102 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"),
104104 )]),
105105 HashMap::from([(
106106 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"),
108108 )]),
109 // HashMap::from([(
110 // String::from("Add to queue"),
111 // String::from("mpv loadfile '${embed-url}' appendplay;; echo mpv Added to queue"),
112 // )]),
109113 HashMap::from([(
110114 String::from("View channel"),
111115 String::from("channel ${channel-id}"),
@@ -149,12 +153,16 @@ fn saved_video_default() -> Vec<HashMap<String, String>> {
149153 )]),
150154 HashMap::from([(
151155 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"),
153157 )]),
154158 HashMap::from([(
155159 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"),
157161 )]),
162 // HashMap::from([(
163 // String::from("[Offline] Add to queue"),
164 // String::from("mpv loadfile '${offline-path}' appendplay ;; echo mpv Added to queue"),
165 // )]),
158166 HashMap::from([(
159167 String::from("View channel"),
160168 String::from("channel ${channel-id}"),
@@ -199,12 +207,16 @@ fn playlist_default() -> Vec<HashMap<String, String>> {
199207 )]),
200208 HashMap::from([(
201209 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"),
203211 )]),
204212 HashMap::from([(
205213 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"),
207215 )]),
216 // HashMap::from([(
217 // String::from("Add all to queue"),
218 // String::from("${mpv-queuelist} ;; echo mpv Queued playlist"),
219 // )]),
208220 HashMap::from([(
209221 String::from("View channel"),
210222 String::from("channel ${channel-id}"),
@@ -249,12 +261,16 @@ fn saved_playlist_default() -> Vec<HashMap<String, String>> {
249261 )]),
250262 HashMap::from([(
251263 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"),
253265 )]),
254266 HashMap::from([(
255267 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"),
257269 )]),
270 // HashMap::from([(
271 // String::from("[Offline] Add all to queue"),
272 // String::from("${offline-queuelist} ;; echo mpv Queued playlist"),
273 // )]),
258274 HashMap::from([(
259275 String::from("View channel"),
260276 String::from("channel ${channel-id}"),
src/config/keybindings.rs +2 −2
@@ -55,11 +55,11 @@ impl Default for KeyBindingsConfigSerde {
5555 ),
5656 (
5757 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Up),
58 HashMap::from([(0, KeyAction::MoveUp)]),
58 HashMap::from([(0, KeyAction::MoveUp), (2, KeyAction::PreviousEntry)]),
5959 ),
6060 (
6161 KeyCodeSerde::KeyVariants(KeyVariantsSerde::Down),
62 HashMap::from([(0, KeyAction::MoveDown)]),
62 HashMap::from([(0, KeyAction::MoveDown), (2, KeyAction::NextEntry)]),
6363 ),
6464 // vim keybindings
6565 (
src/config/main.rs +33 −4
@@ -12,8 +12,6 @@ pub struct MainConfig {
1212 pub invidious_instance: String,
1313 #[serde(default = "write_to_config_default")]
1414 pub write_config: WriteConfig,
15 #[serde(default = "max_watch_history_default")]
16 pub max_watch_history: usize,
1715 #[serde(default = "allow_unicode_default")]
1816 pub allow_unicode: bool,
1917 #[serde(default = "message_bar_default_default")]
@@ -22,7 +20,10 @@ pub struct MainConfig {
2220 pub images: Images,
2321 #[serde(default = "refresh_after_modifying_search_filters_default")]
2422 pub refresh_after_modifying_search_filters: bool,
23 #[serde(default = "sync_config_default")]
2524 pub syncing: SyncConfig,
25 #[serde(default)]
26 pub limits: Limits,
2627 #[serde(default = "image_index_default")]
2728 // The image to download from the array of images provided by the invidious api
2829 // 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 {
4849 write_config: write_to_config_default(),
4950 mouse_support: mouse_support_default(),
5051 invidious_instance: invidious_instance_default(),
51 max_watch_history: max_watch_history_default(),
5252 allow_unicode: allow_unicode_default(),
5353 message_bar_default: message_bar_default_default(),
5454 images: images_default(),
5555 image_index: image_index_default(),
5656 refresh_after_modifying_search_filters: refresh_after_modifying_search_filters_default(
5757 ),
58 limits: Limits::default(),
5859 syncing: sync_config_default(),
5960 provider: provider_default(),
6061 shell: shell_default(),
@@ -90,6 +91,26 @@ const fn sync_config_default() -> SyncConfig {
9091 }
9192}
9293
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
93114/// how images are handled/displayed
94115#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
95116pub enum Images {
@@ -167,7 +188,15 @@ const fn provider_default() -> Provider {
167188 Provider::YouTube
168189}
169190
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 {
171200 50
172201}
173202
src/exit.rs +20 −9
@@ -2,23 +2,34 @@ use home::home_dir;
22use std::{error::Error, fs};
33use tui_additions::framework::Framework;
44
5use crate::global::{structs::*, traits::Collection};
5use crate::{
6 config::MainConfig,
7 global::{
8 structs::*,
9 traits::{Collection, CollectionNoId},
10 },
11};
612
713/// function to run when the app ends
814// exit tasks:
915// - move thumbnails of videos in watch history to `~/.local/share/youtube-tui/watch_history/thumbnails`
1016// - remove `~/.cache`
11pub fn exit(framework: &Framework) -> Result<(), Box<dyn Error>> {
12 framework
13 .data
14 .global
15 .get::<WatchHistory>()
16 .unwrap()
17 .exit_move();
17pub fn exit(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
18 let limits = framework.data.global.get::<MainConfig>().unwrap().limits;
19 let watchhistory = framework.data.global.get_mut::<WatchHistory>().unwrap();
20 watchhistory.trim(limits.watch_history);
21 watchhistory.exit_move();
22 let _ = watchhistory.save();
1823 let subscriptions = framework.data.global.get::<Subscriptions>().unwrap();
1924 subscriptions.exit_move();
20 subscriptions.save()?;
25 let _ = subscriptions.save();
2126 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();
2233
2334 let home_dir = home_dir().unwrap();
2435 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};
22
33#[cfg(feature = "clipboard")]
44use crate::config::*;
@@ -106,17 +106,55 @@ pub fn command_capture(framework: &mut FrameworkClean, key: KeyEvent) -> bool {
106106 .push(Task::RenderAll);
107107 return true;
108108 }
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 }
109153 _ => {}
110154 }
111155
112 let textfield = framework
113 .data
114 .global
115 .get_mut::<Status>()
116 .unwrap()
117 .command_capture
118 .as_mut()
119 .unwrap();
156 let status = framework.data.global.get_mut::<Status>().unwrap();
157 let textfield = status.command_capture.as_mut().unwrap();
120158 // a textfield must have a width set, because we don't know the width yet just set it to the
121159 // maximum value possible, so that the cursor will not be moved because of the small value
122160 textfield.set_width(u16::MAX);
@@ -129,13 +167,31 @@ pub fn command_capture(framework: &mut FrameworkClean, key: KeyEvent) -> bool {
129167 KeyCode::Right => textfield.right().is_ok(),
130168 KeyCode::Backspace => textfield.pop().is_ok(),
131169 KeyCode::Enter => {
170 let content = textfield.content.clone();
171 framework
172 .data
173 .global
174 .get_mut::<CommandHistory>()
175 .unwrap()
176 .push(content);
132177 framework
133178 .data
134179 .state
135180 .get_mut::<Tasks>()
136181 .unwrap()
137182 .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 )));
139195 framework
140196 .data
141197 .global
src/global/functions/key_input.rs +1 −2
@@ -4,7 +4,6 @@ use crossterm::event::KeyEvent;
44use ratatui::{backend::CrosstermBackend, Terminal};
55use tui_additions::{
66 framework::{Framework, FrameworkDirection},
7 widgets::TextField,
87};
98
109use crate::{config::*, global::structs::*, items::SearchBar};
@@ -124,7 +123,7 @@ pub fn key_input(
124123 .global
125124 .get_mut::<Status>()
126125 .unwrap()
127 .command_capture = Some(TextField::default());
126 .reset_command_capture();
128127 }
129128 KeyAction::Exit => framework
130129 .data
src/global/functions/run_command.rs +1 −1
@@ -70,7 +70,7 @@ pub fn run_single_command(
7070 })() {
7171 Ok(item) => {
7272 let library = framework.data.global.get_mut::<Library>().unwrap();
73 let _ = library.push(item, None);
73 let _ = library.push(item);
7474 let _ = library.save();
7575 *framework.data.global.get_mut::<Message>().unwrap() =
7676 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 {
4242 First,
4343 /// move cursor to the last position
4444 End,
45 /// Previous entry
46 PreviousEntry,
47 /// Next entry
48 NextEntry,
4549}
src/global/structs/mod.rs +2 −2
@@ -1,5 +1,6 @@
11//! enums and structs
22mod errors;
3mod history;
34mod invidiousclient;
45mod item;
56mod keyaction;
@@ -12,9 +13,9 @@ mod state_env;
1213mod status;
1314mod subscriptions;
1415mod tasks;
15mod watchhistory;
1616
1717pub use errors::*;
18pub use history::*;
1819pub use invidiousclient::*;
1920pub use item::*;
2021pub use keyaction::*;
@@ -27,4 +28,3 @@ pub use state_env::*;
2728pub use status::*;
2829pub use subscriptions::*;
2930pub use tasks::*;
30pub use watchhistory::*;
src/global/structs/status.rs +14
@@ -15,6 +15,10 @@ pub struct Status {
1515 pub render_image: bool,
1616 /// the textfield for command capture
1717 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,
1822 /// if true, exit in the next iteration
1923 pub exit: bool,
2024 /// stores the area of the previously rendered frame
@@ -39,6 +43,8 @@ impl Default for Status {
3943 render_image: true,
4044 command_capture: None,
4145 exit: false,
46 command_history_index: None,
47 command_editing_cache: String::new(),
4248 prev_frame: None,
4349 provider: Provider::YouTube,
4450 provider_updated: false,
@@ -52,3 +58,11 @@ impl Status {
5258 *self = Self::default();
5359 }
5460}
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 {
329329 Ok(())
330330 }
331331
332 fn push(&mut self, _: SubItem, _: Option<usize>) -> Result<(), Box<dyn Error>> {
332 fn push(&mut self, _: SubItem) -> Result<(), Box<dyn Error>> {
333333 unimplemented!("not in use");
334334 }
335335
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
2323
2424 fn from_items(items: Vec<T>) -> Self;
2525
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
2633 /// saves the current state of watch history into a file
2734 fn save(&self) -> Result<(), Box<dyn Error>> {
2835 let save_string = serde_json::to_string_pretty(
@@ -47,7 +54,7 @@ where
4754 }
4855
4956 /// 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>> {
5158 let info = home_dir().unwrap().join(".cache/youtube-tui/info/");
5259
5360 // removes duplicates and place them on top (if exists)
@@ -69,11 +76,6 @@ where
6976
7077 self.items_mut().push(item);
7178
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
7779 Ok(())
7880 }
7981
@@ -158,3 +160,87 @@ where
158160 }
159161 }
160162}
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(
4343
4444 load_configs(&mut framework.split_clean().0)?;
4545
46 framework
47 .data
48 .global
49 .insert::<CommandHistory>(CommandHistory::load());
50 framework
51 .data
52 .global
53 .insert::<SearchHistory>(SearchHistory::load());
4654 framework
4755 .data
4856 .global
src/items/messagebar.rs +1 −1
@@ -74,7 +74,7 @@ impl FrameworkItem for MessageBar {
7474 let mut seeker_len = length - total_len - 4;
7575 let seeker_pad = if seeker_len > 10 { seeker_len / 10 } else { 0 };
7676 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;
7878 format!(
7979 "{left_chunk} {}├{}-{}┤{} {right_chunk}",
8080 " ".repeat(seeker_pad),
src/items/searchbar.rs +40 −1
@@ -1,6 +1,9 @@
11use std::error::Error;
22
3use crate::{config::*, global::structs::*};
3use crate::{
4 config::*,
5 global::{structs::*, traits::CollectionNoId},
6};
47
58#[cfg(feature = "clipboard")]
69use crate::global::functions::get_clipboard;
@@ -18,6 +21,8 @@ use tui_additions::{framework::FrameworkItem, widgets::TextField};
1821#[derive(Clone, Default)]
1922pub struct SearchBar {
2023 pub text_field: TextField,
24 pub history_index: Option<usize>,
25 pub custom_value_cache: String,
2126}
2227
2328impl FrameworkItem for SearchBar {
@@ -112,6 +117,34 @@ impl FrameworkItem for SearchBar {
112117 Some(KeyAction::End | KeyAction::MoveDown) => {
113118 self.text_field.cursor = self.text_field.content.len()
114119 }
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 }
115148 _ => render = false,
116149 }
117150
@@ -150,6 +183,12 @@ impl FrameworkItem for SearchBar {
150183
151184 let search = framework.data.state.get_mut::<Search>().unwrap();
152185 search.query = self.text_field.content.clone();
186 framework
187 .data
188 .global
189 .get_mut::<SearchHistory>()
190 .unwrap()
191 .push(search.query.clone());
153192 let search = search.clone();
154193 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
155194 tasks.priority.push(Task::LoadPage(Page::Search(search)));
src/items/singleitem.rs +1 −8
@@ -743,16 +743,9 @@ impl FrameworkItem for SingleItem {
743743 }
744744
745745 let item = item.clone();
746 let max_watch_history = framework
747 .data
748 .global
749 .get::<MainConfig>()
750 .unwrap()
751 .max_watch_history;
752
753746 // push to watch history
754747 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
755 watch_history.push(item, Some(max_watch_history))?;
748 watch_history.push(item)?;
756749 watch_history.save()?;
757750 }
758751
src/main.rs +1 −1
@@ -48,7 +48,7 @@ fn main() -> Result<(), Box<dyn Error>> {
4848 )?;
4949 terminal.show_cursor()?;
5050
51 let exit_res = exit(&framework);
51 let exit_res = exit(&mut framework);
5252
5353 res?;
5454 exit_res?;