src/items/singleitem.rs
1115 lines · 42122 bytes
1use std::fs;
2
3use super::ItemInfo;
4use crate::{
5 config::*,
6 global::{functions::*, structs::*, traits::Collection},
7};
8use home::home_dir;
9use ratatui::{
10 layout::{Constraint, Rect},
11 style::Style,
12 widgets::{Block, Borders},
13};
14use tui_additions::{
15 framework::{FrameworkClean, FrameworkItem},
16 widgets::{Grid, TextList},
17};
18
19impl Default for SingleItem {
20 fn default() -> Self {
21 Self {
22 item: None,
23 iteminfo: ItemInfo::default(),
24 grid: Grid::new(
25 vec![Constraint::Percentage(30), Constraint::Percentage(70)],
26 vec![Constraint::Percentage(100)],
27 )
28 .unwrap(),
29 r#type: SingleItemType::None,
30 }
31 }
32}
33
34/// main item in the `SingleItem(_)` page
35#[derive(Clone)]
36pub struct SingleItem {
37 pub item: Option<Item>,
38 pub iteminfo: ItemInfo,
39 pub grid: Grid,
40 pub r#type: SingleItemType,
41}
42
43/// variations that the struct can hold
44#[derive(Clone)]
45pub enum SingleItemType {
46 None,
47 Video(SingleVideoItem),
48 Playlist(Box<SinglePlaylistItem>),
49}
50
51#[derive(Clone)]
52pub struct SingleVideoItem {
53 pub textlist: TextList,
54 pub commands: Vec<(String, String)>,
55}
56
57#[derive(Clone)]
58pub struct SinglePlaylistItem {
59 pub commands_view: TextList,
60 pub videos_view: TextList,
61 pub commands: Vec<(String, String)>,
62 pub is_commands_view: bool,
63 pub hovered_video: ItemInfo,
64}
65
66impl SingleVideoItem {
67 pub fn new(commands: &CommandsConfig, mainconfig: &MainConfig, id: &str) -> Self {
68 let saved = find_library_item(id, mainconfig).is_some();
69 if saved {
70 Self::new_with_map(commands.saved_video.clone().into_iter().collect())
71 } else {
72 Self::new_with_map(commands.video.clone().into_iter().collect())
73 }
74 }
75
76 pub fn new_with_map(commands: Vec<(String, String)>) -> Self {
77 Self {
78 textlist: TextList::default()
79 .items(
80 &commands
81 .iter()
82 .map(|command| &command.0)
83 .collect::<Vec<_>>(),
84 )
85 .unwrap(),
86 commands,
87 }
88 }
89
90 /// find all occurances of ${provider}
91 pub fn update_provider(&mut self) -> Vec<usize> {
92 self.commands
93 .iter()
94 .enumerate()
95 .filter(|(_index, (display, _command))| display.contains("${provider}"))
96 .map(|(index, _)| index)
97 .collect()
98 }
99
100 pub fn update_appearance(
101 &mut self,
102 appearance: &AppearanceConfig,
103 iteminfo: &tui_additions::framework::ItemInfo,
104 ) {
105 self.textlist.set_border_type(appearance.borders);
106 self.textlist
107 .set_style(Style::default().fg(appearance.colors.text));
108
109 if iteminfo.selected {
110 self.textlist
111 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
112 self.textlist
113 .set_selected_style(Style::default().fg(appearance.colors.text_special));
114 } else {
115 self.textlist
116 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
117 self.textlist
118 .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
119 }
120 }
121
122 /// creates a hashmap from `self`, containing info of the current item
123 pub fn inflate_load(
124 &self,
125 mainconfig: &MainConfig,
126 status: &Status,
127 item: &Item,
128 ) -> Vec<(String, String)> {
129 let video_item = item.fullvideo().unwrap();
130
131 vec![
132 (
133 String::from("url"),
134 match status.provider {
135 Provider::Invidious => format!(
136 "{}/watch?v={}",
137 mainconfig.invidious_instance, video_item.id
138 ),
139 Provider::YouTube => format!("'https://youtu.be/{}'", video_item.id),
140 },
141 ),
142 (String::from("id"), video_item.id.clone()),
143 (
144 String::from("embed-url"),
145 match status.provider {
146 Provider::Invidious => {
147 format!("{}/embed/{}", mainconfig.invidious_instance, video_item.id)
148 }
149 Provider::YouTube => format!("'https://youtube.com/embed/{}'", video_item.id),
150 },
151 ),
152 (String::from("channel-id"), video_item.channel_id.clone()),
153 (String::from("title"), video_item.title.clone()),
154 (
155 String::from("channel-url"),
156 match status.provider {
157 Provider::YouTube => {
158 format!("https://www.youtube.com/channel/{}", video_item.channel_id)
159 }
160 Provider::Invidious => format!(
161 "{}/channel/{}",
162 mainconfig.invidious_instance, video_item.channel_id
163 ),
164 },
165 ),
166 (
167 String::from("offline-path"),
168 find_library_item(&video_item.id, mainconfig)
169 .unwrap_or_default()
170 .to_str()
171 .unwrap()
172 .to_string(),
173 ),
174 ]
175 }
176}
177
178impl SinglePlaylistItem {
179 pub fn new(
180 commands: &CommandsConfig,
181 mainconfig: &MainConfig,
182 id: &str,
183 playlist_items: &[Item],
184 ) -> Self {
185 let saved = find_library_item(id, mainconfig).is_some();
186 if saved {
187 Self::new_with_map(
188 commands.saved_playlist.clone().into_iter().collect(),
189 playlist_items,
190 )
191 } else {
192 Self::new_with_map(
193 commands.playlist.clone().into_iter().collect(),
194 playlist_items,
195 )
196 }
197 }
198
199 pub fn new_with_map(commands: Vec<(String, String)>, playlist_items: &[Item]) -> Self {
200 let hovered_video = ItemInfo::new(if playlist_items.is_empty() {
201 None
202 } else {
203 Some(playlist_items[0].clone())
204 });
205
206 Self {
207 commands_view: TextList::default()
208 .items(
209 &commands
210 .iter()
211 .map(|command| &command.0)
212 .collect::<Vec<_>>(),
213 )
214 .unwrap(),
215 videos_view: TextList::default()
216 .items(&{
217 let mut items = vec!["Switch view"];
218 items.extend(
219 playlist_items
220 .iter()
221 .map(|item| item.minivideo().unwrap().title.as_str()),
222 );
223 items
224 })
225 .unwrap(),
226 commands,
227 hovered_video,
228 is_commands_view: true,
229 }
230 }
231
232 pub fn update_appearance(
233 &mut self,
234 appearance: &AppearanceConfig,
235 iteminfo: &tui_additions::framework::ItemInfo,
236 grid: &mut Grid,
237 ) {
238 if self.is_commands_view {
239 grid.widths = vec![Constraint::Percentage(30), Constraint::Percentage(70)];
240 self.commands_view.set_border_type(appearance.borders);
241 self.commands_view
242 .set_style(Style::default().fg(appearance.colors.text));
243
244 if iteminfo.selected {
245 self.commands_view
246 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
247 self.commands_view
248 .set_selected_style(Style::default().fg(appearance.colors.text_special));
249 } else {
250 self.commands_view
251 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
252 self.commands_view
253 .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
254 }
255 } else {
256 grid.widths = if self.videos_view.selected == 0 {
257 vec![Constraint::Percentage(30), Constraint::Percentage(70)]
258 } else {
259 vec![
260 Constraint::Percentage(30),
261 Constraint::Percentage(40),
262 Constraint::Percentage(30),
263 ]
264 };
265 self.videos_view.set_border_type(appearance.borders);
266 self.videos_view
267 .set_style(Style::default().fg(appearance.colors.text));
268
269 if iteminfo.selected {
270 self.videos_view
271 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
272 self.videos_view
273 .set_selected_style(Style::default().fg(appearance.colors.text_special));
274 } else {
275 self.videos_view
276 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
277 self.videos_view
278 .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
279 }
280 }
281 }
282
283 /// find all occurances of ${provider}
284 pub fn update_provider(&mut self) -> Vec<usize> {
285 self.commands
286 .iter()
287 .enumerate()
288 .filter(|(_index, (display, _command))| display.contains("${provider}"))
289 .map(|(index, _)| index)
290 .collect()
291 }
292
293 /// creates a hashmap from `self`, containing info of the current item
294 pub fn inflate_load(&self, item: &Item, mainconfig: &MainConfig) -> Vec<(String, String)> {
295 let playlist_item = item.fullplaylist().unwrap();
296 let path = find_library_item(&playlist_item.id, mainconfig);
297
298 vec![
299 (String::from("id"), playlist_item.id.clone()),
300 (String::from("channel-id"), playlist_item.channel_id.clone()),
301 (String::from("title"), playlist_item.title.clone()),
302 (
303 String::from("all-ids"),
304 playlist_item
305 .videos
306 .iter()
307 .map(|video| video.minivideo().unwrap().id.as_str())
308 .collect::<Vec<&str>>()
309 .join(" "),
310 ),
311 (
312 String::from("offline-path"),
313 path.clone()
314 .unwrap_or_default()
315 .to_str()
316 .unwrap()
317 .to_string(),
318 ),
319 (
320 String::from("offline-queuelist"),
321 match path {
322 Some(path) => match fs::read_dir(path) {
323 Ok(entries) => entries
324 .map(|entry| {
325 format!(
326 "mpv loadfile '{}' append",
327 match entry {
328 Ok(entry) =>
329 entry.path().as_os_str().to_str().unwrap().to_string(),
330 Err(_) => String::new(),
331 }
332 )
333 })
334 .collect::<Vec<_>>()
335 .join(" ;; "),
336 Err(e) => e.to_string(),
337 },
338 None => String::from("bad path"),
339 },
340 ),
341 ]
342 }
343}
344
345impl SingleItemType {
346 /// self is none
347 pub fn is_none(&self) -> bool {
348 matches!(self, Self::None)
349 }
350
351 /// update colours every render
352 pub fn update_appearance(
353 &mut self,
354 appearance: &AppearanceConfig,
355 iteminfo: &tui_additions::framework::ItemInfo,
356 grid: &mut Grid,
357 ) {
358 match self {
359 Self::None => {}
360 Self::Playlist(playlistitem) => {
361 playlistitem.update_appearance(appearance, iteminfo, grid)
362 }
363 Self::Video(videoitem) => videoitem.update_appearance(appearance, iteminfo),
364 }
365 }
366
367 pub fn inflate_load(
368 &self,
369 mainconfig: &MainConfig,
370 status: &Status,
371 item: &Option<Item>,
372 ) -> Vec<(String, String)> {
373 let item = if let Some(item) = item.as_ref() {
374 item
375 } else {
376 return Vec::new();
377 };
378
379 match self {
380 Self::Video(singlevideoitem) => singlevideoitem.inflate_load(mainconfig, status, item),
381 Self::Playlist(singleplaylistitem) => singleplaylistitem.inflate_load(item, mainconfig),
382 Self::None => Vec::new(),
383 }
384 }
385}
386
387impl SingleItem {
388 fn infalte_item_update(
389 &self,
390 mainconfig: &MainConfig,
391 status: &Status,
392 ) -> Vec<(String, String)> {
393 if let SingleItemType::Playlist(singleplaylistitem) = &self.r#type {
394 if singleplaylistitem.videos_view.selected == 0 {
395 return vec![(String::from("hover-url"), String::from("not avaliable"))];
396 }
397 vec![(
398 String::from("hover-url"),
399 match &self.item {
400 Some(item) => format!(
401 "{}/watch?v={}",
402 match status.provider {
403 Provider::YouTube => "https://youtube.com",
404 Provider::Invidious => &mainconfig.invidious_instance,
405 },
406 item.fullplaylist().unwrap().videos
407 [singleplaylistitem.videos_view.selected - 1]
408 .minivideo()
409 .unwrap()
410 .id
411 ),
412 None => String::from("not avaliable"),
413 },
414 )]
415 } else {
416 vec![(String::from("hover-url"), String::from("not avaliable"))]
417 }
418 }
419 /// update colours and layout every render
420 fn update_appearance(
421 &mut self,
422 appearance: &AppearanceConfig,
423 iteminfo: &tui_additions::framework::ItemInfo,
424 ) {
425 self.grid.set_border_type(appearance.borders);
426
427 if iteminfo.selected {
428 self.grid
429 .set_border_style(Style::default().fg(appearance.colors.outline_selected));
430 } else if iteminfo.hover {
431 self.grid
432 .set_border_style(Style::default().fg(appearance.colors.outline_hover));
433 } else {
434 self.grid
435 .set_border_style(Style::default().fg(appearance.colors.outline));
436 }
437
438 self.r#type
439 .update_appearance(appearance, iteminfo, &mut self.grid);
440 }
441
442 /// update hover item preview
443 fn update(&mut self) {
444 if let SingleItemType::Playlist(singleplaylistitem) = &mut self.r#type {
445 let SinglePlaylistItem {
446 hovered_video,
447 videos_view,
448 ..
449 } = &mut **singleplaylistitem;
450 if videos_view.items.is_empty() || videos_view.selected == 0 {
451 hovered_video.item = None;
452 return;
453 }
454
455 if hovered_video.item.is_none()
456 || self.item.as_ref().unwrap().fullplaylist().unwrap().videos
457 [videos_view.selected - 1]
458 .id()
459 != hovered_video.item.as_ref().unwrap().id()
460 {
461 hovered_video.item = Some(
462 self.item.as_ref().unwrap().fullplaylist().unwrap().videos
463 [videos_view.selected - 1]
464 .clone(),
465 );
466 }
467 }
468 }
469
470 /// handle enter presses
471 fn select_at_cursor(
472 &mut self,
473 framework: &mut FrameworkClean,
474 // info: tui_additions::framework::ItemInfo,
475 ) {
476 match &mut self.r#type {
477 SingleItemType::Video(singlevideoitem) => {
478 let command_string = singlevideoitem.commands[singlevideoitem.textlist.selected]
479 .1
480 .clone();
481
482 // check if the command starts with an ':' which case should be captured
483 framework
484 .data
485 .state
486 .get_mut::<Tasks>()
487 .unwrap()
488 .priority
489 .push(Task::Command(apply_envs(command_string)));
490 }
491 SingleItemType::Playlist(singleplaylistitem) => {
492 let command_string = singleplaylistitem.commands
493 [singleplaylistitem.commands_view.selected]
494 .1
495 .clone();
496
497 // checks for special cases
498 match command_string.as_str() {
499 "%switch-view%" => {
500 singleplaylistitem.is_commands_view = !singleplaylistitem.is_commands_view;
501 // self.update_appearance(
502 // framework.data.global.get::<AppearanceConfig>().unwrap(),
503 // &info,
504 // );
505 *framework.data.global.get_mut::<Message>().unwrap() =
506 Message::Success(String::from("Switched view"));
507 }
508 _ => {
509 // check if the command starts with an ':' which case should be captured
510 framework
511 .data
512 .state
513 .get_mut::<Tasks>()
514 .unwrap()
515 .priority
516 .push(Task::Command(apply_envs(command_string)));
517 }
518 };
519 }
520 _ => return,
521 }
522
523 framework
524 .data
525 .state
526 .get_mut::<Tasks>()
527 .unwrap()
528 .priority
529 .push(Task::RenderAll);
530 }
531}
532
533impl FrameworkItem for SingleItem {
534 fn message(
535 &mut self,
536 framework: &mut FrameworkClean,
537 data: std::collections::HashMap<String, Box<dyn std::any::Any>>,
538 ) -> bool {
539 if !data.contains_key("type") {
540 return false;
541 }
542
543 match &mut self.r#type {
544 SingleItemType::None => false,
545 SingleItemType::Video(SingleVideoItem { textlist, .. }) => {
546 data.get("type").is_some_and(|v| {
547 v.downcast_ref::<String>()
548 .is_some_and(|v| match v.as_str() {
549 "scrollup" => textlist.up().is_ok(),
550 "scrolldown" => textlist.down().is_ok(),
551 _ => false,
552 })
553 })
554 }
555 SingleItemType::Playlist(item) => {
556 if item.is_commands_view {
557 data.get("type").is_some_and(|v| {
558 v.downcast_ref::<String>()
559 .is_some_and(|v| match v.as_str() {
560 "scrollup" => item.commands_view.up().is_ok(),
561 "scrolldown" => item.commands_view.down().is_ok(),
562 _ => false,
563 })
564 })
565 } else {
566 let updated = data.get("type").is_some_and(|v| {
567 v.downcast_ref::<String>()
568 .is_some_and(|v| match v.as_str() {
569 "scrollup" => {
570 if item.videos_view.selected == 1 {
571 // going from a hovering video to not hovering will make the image
572 // stay on the screen, therefore it needs to be removed by clearing
573 // the screen
574 framework
575 .data
576 .state
577 .get_mut::<Tasks>()
578 .unwrap()
579 .priority
580 .push(Task::ClearPage);
581 }
582 item.videos_view.up().is_ok()
583 }
584 "scrolldown" => item.videos_view.down().is_ok(),
585 _ => false,
586 })
587 });
588
589 if updated {
590 if item.videos_view.selected != 0 {
591 item.hovered_video.item = Some(
592 self.item.as_ref().unwrap().fullplaylist().unwrap().videos
593 [item.videos_view.selected - 1]
594 .clone(),
595 );
596 }
597
598 framework
599 .data
600 .global
601 .get_mut::<Status>()
602 .unwrap()
603 .render_image = true;
604 set_envs(
605 self.infalte_item_update(
606 framework.data.global.get::<MainConfig>().unwrap(),
607 framework.data.global.get::<Status>().unwrap(),
608 )
609 .into_iter(),
610 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
611 );
612 }
613
614 updated
615 }
616 }
617 }
618 }
619 fn render(
620 &mut self,
621 frame: &mut ratatui::Frame,
622 framework: &mut FrameworkClean,
623 area: Rect,
624 popup_render: bool,
625 info: tui_additions::framework::ItemInfo,
626 ) {
627 let status = framework.data.global.get::<Status>().unwrap();
628 if popup_render {
629 return;
630 }
631
632 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
633
634 if self.item.is_none() {
635 frame.render_widget(
636 Block::default()
637 .borders(Borders::ALL)
638 .border_type(appearance.borders),
639 area,
640 );
641 return;
642 }
643
644 if status.provider_updated {
645 set_envs(
646 self.infalte_item_update(
647 framework.data.global.get::<MainConfig>().unwrap(),
648 status,
649 )
650 .into_iter(),
651 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
652 );
653 }
654
655 self.update_appearance(appearance, &info);
656
657 let chunks = self.grid.chunks(area).unwrap()[0].clone();
658
659 frame.render_widget(self.grid.clone(), area);
660
661 match &mut self.r#type {
662 SingleItemType::Video(typeinfo) => {
663 // 2 by 1 grid, item info in the first cell and textlist at the second
664 if status.provider_updated {
665 typeinfo.update_provider().into_iter().for_each(|index| {
666 typeinfo.textlist.items[index] = typeinfo.commands[index].0.clone().replace(
667 "${provider}",
668 framework
669 .data
670 .global
671 .get::<Status>()
672 .unwrap()
673 .provider
674 .as_str(),
675 )
676 });
677 }
678 self.iteminfo
679 .render(frame, framework, chunks[0], popup_render, info);
680 typeinfo.textlist.set_height(chunks[1].height);
681 frame.render_widget(typeinfo.textlist.clone(), chunks[1]);
682 }
683 SingleItemType::Playlist(typeinfo) => {
684 // 3 by 1 grid if hovering a video inside the playlist
685 // if not then 2 by 1
686 //
687 // item info in the first cell, textlists in the second, hovering video on 3rd (if
688 // present)
689 if typeinfo.is_commands_view {
690 if status.provider_updated {
691 typeinfo.update_provider().into_iter().for_each(|index| {
692 typeinfo.commands_view.items[index] =
693 typeinfo.commands[index].0.clone().replace(
694 "${provider}",
695 framework
696 .data
697 .global
698 .get::<Status>()
699 .unwrap()
700 .provider
701 .as_str(),
702 )
703 });
704 }
705 typeinfo.commands_view.set_height(chunks[1].height);
706 frame.render_widget(typeinfo.commands_view.clone(), chunks[1]);
707 } else {
708 typeinfo.videos_view.set_height(chunks[1].height);
709 frame.render_widget(typeinfo.videos_view.clone(), chunks[1]);
710
711 if typeinfo.videos_view.selected != 0 {
712 typeinfo.hovered_video.render(
713 frame,
714 framework,
715 chunks[2],
716 popup_render,
717 info,
718 );
719 }
720 }
721 self.iteminfo
722 .render(frame, framework, chunks[0], popup_render, info);
723 }
724 SingleItemType::None => {}
725 }
726 }
727
728 fn load_item(
729 &mut self,
730 framework: &mut tui_additions::framework::FrameworkClean,
731 _info: tui_additions::framework::ItemInfo,
732 ) -> Result<(), Box<dyn std::error::Error>> {
733 *self = Self::default();
734
735 let page = framework.data.state.get::<Page>().unwrap();
736
737 let r#type = if let Page::SingleItem(r#type) = page {
738 r#type
739 } else {
740 unreachable!("item `SingleItem` cannot be used in {page:?}")
741 };
742
743 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
744 // load items using the invidious api
745 // gets the item that it needs to load from `data.state.Page`
746 let (item, r#type) = match r#type {
747 SingleItemPage::Video(id) => {
748 let home_dir = home_dir().unwrap();
749 let path = home_dir.join(format!(".cache/youtube-tui/info/{id}.json"));
750
751 let video = if path.exists() {
752 serde_json::from_str(&fs::read_to_string(path)?)?
753 } else {
754 load_video(id, mainconfig)?
755 };
756 (
757 video,
758 SingleItemType::Video(SingleVideoItem::new(
759 framework.data.global.get::<CommandsConfig>().unwrap(),
760 mainconfig,
761 id,
762 )),
763 )
764 }
765 SingleItemPage::Playlist(id) => {
766 let path = home_dir()
767 .unwrap()
768 .join(format!(".cache/youtube-tui/info/{id}.json"));
769
770 let playlist = if path.exists() {
771 serde_json::from_str(&fs::read_to_string(path)?)?
772 } else {
773 load_playlist(id, mainconfig)?
774 };
775 let r#type = SingleItemType::Playlist(
776 SinglePlaylistItem::new(
777 framework.data.global.get::<CommandsConfig>().unwrap(),
778 mainconfig,
779 id,
780 &playlist.fullplaylist().unwrap().videos,
781 )
782 .into(),
783 );
784
785 (playlist, r#type)
786 }
787 };
788
789 self.item = Some(item);
790 self.r#type = r#type;
791 self.iteminfo.item = self.item.clone();
792
793 if let Some(item) = &self.item {
794 // if item.is_unknown() {
795 // return Ok(());
796 // }
797
798 let item = item.clone();
799 // push to watch history
800 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
801 watch_history.push(item)?;
802 watch_history.save()?;
803 }
804
805 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
806 // need to update provider every time the item loads or else it will display `${provider}`
807 // instead of the actual provider (e.g. `YouTube`)
808
809 set_envs(
810 self.r#type
811 .inflate_load(
812 mainconfig,
813 framework.data.global.get::<Status>().unwrap(),
814 &self.item,
815 )
816 .into_iter(),
817 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
818 );
819
820 set_envs(
821 self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
822 .into_iter(),
823 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
824 );
825
826 Ok(())
827 }
828
829 fn key_event(
830 &mut self,
831 framework: &mut tui_additions::framework::FrameworkClean,
832 key: crossterm::event::KeyEvent,
833 info: tui_additions::framework::ItemInfo,
834 ) -> Result<(), Box<dyn std::error::Error>> {
835 // discard any key inputs if `self.is_none()` becuase nothing can happen if self is none
836 if self.r#type.is_none() {
837 return Ok(());
838 }
839
840 let action = if let Some(action) = framework
841 .data
842 .global
843 .get::<KeyBindingsConfig>()
844 .unwrap()
845 .get(key)
846 {
847 action
848 } else {
849 return Ok(());
850 };
851
852 let updated = match &mut self.r#type {
853 SingleItemType::Video(singlevideoitem) => match action {
854 // move the cursor in the textlist, only update the screen if it is changed
855 KeyAction::MoveUp => singlevideoitem.textlist.up().is_ok(),
856 KeyAction::MoveDown => singlevideoitem.textlist.down().is_ok(),
857 KeyAction::MoveLeft | KeyAction::First => singlevideoitem.textlist.first().is_ok(),
858 KeyAction::MoveRight | KeyAction::End => singlevideoitem.textlist.last().is_ok(),
859 KeyAction::Select => {
860 self.select_at_cursor(framework);
861 return Ok(());
862 }
863 _ => false,
864 },
865 SingleItemType::Playlist(singleplaylistitem) => {
866 // there are 2 possible states in a playlist item
867 // they are handelled separately
868 if singleplaylistitem.is_commands_view {
869 match action {
870 KeyAction::MoveUp => singleplaylistitem.commands_view.up().is_ok(),
871 KeyAction::MoveDown => singleplaylistitem.commands_view.down().is_ok(),
872 KeyAction::MoveLeft | KeyAction::First => {
873 singleplaylistitem.commands_view.first().is_ok()
874 }
875 KeyAction::MoveRight | KeyAction::End => {
876 singleplaylistitem.commands_view.last().is_ok()
877 }
878 KeyAction::Select => {
879 self.select_at_cursor(framework);
880 return Ok(());
881 }
882 _ => false,
883 }
884 } else {
885 let updated = match action {
886 // checks if it is updated, if it is and selected is not 0 (is hovering on
887 // a video), then also need to update the iteminfo
888 KeyAction::MoveUp => {
889 if singleplaylistitem.videos_view.selected == 1 {
890 // going from a hovering video to not hovering will make the image
891 // stay on the screen, therefore it needs to be removed by clearing
892 // the screen
893 framework
894 .data
895 .state
896 .get_mut::<Tasks>()
897 .unwrap()
898 .priority
899 .push(Task::ClearPage);
900 } else if singleplaylistitem.videos_view.selected == 0 {
901 return Ok(());
902 }
903
904 let updated = singleplaylistitem.videos_view.up().is_ok();
905 if singleplaylistitem.videos_view.selected != 0 {
906 singleplaylistitem.hovered_video.item = Some(
907 self.item.as_ref().unwrap().fullplaylist()?.videos
908 [singleplaylistitem.videos_view.selected - 1]
909 .clone(),
910 );
911 }
912 updated
913 }
914 KeyAction::MoveDown => {
915 if singleplaylistitem.videos_view.selected
916 == singleplaylistitem.videos_view.items.len() - 1
917 {
918 return Ok(());
919 }
920
921 let updated = singleplaylistitem.videos_view.down().is_ok();
922 if updated && singleplaylistitem.videos_view.selected != 0 {
923 singleplaylistitem.hovered_video.item = Some(
924 self.item.as_ref().unwrap().fullplaylist()?.videos
925 [singleplaylistitem.videos_view.selected - 1]
926 .clone(),
927 );
928 }
929 updated
930 }
931 KeyAction::MoveLeft => {
932 if singleplaylistitem.videos_view.selected != 0 {
933 framework
934 .data
935 .state
936 .get_mut::<Tasks>()
937 .unwrap()
938 .priority
939 .push(Task::ClearPage);
940 } else if singleplaylistitem.videos_view.selected == 0 {
941 return Ok(());
942 }
943
944 let updated = singleplaylistitem.videos_view.first().is_ok();
945 singleplaylistitem.hovered_video.item = None;
946 updated
947 }
948 KeyAction::MoveRight => {
949 if singleplaylistitem.videos_view.selected
950 == singleplaylistitem.videos_view.items.len() - 1
951 {
952 return Ok(());
953 }
954 let updated = singleplaylistitem.videos_view.last().is_ok();
955 if updated && singleplaylistitem.videos_view.selected != 0 {
956 singleplaylistitem.hovered_video.item = Some(
957 self.item.as_ref().unwrap().fullplaylist()?.videos
958 [singleplaylistitem.videos_view.selected - 1]
959 .clone(),
960 );
961 }
962 updated
963 }
964 KeyAction::Select => {
965 if singleplaylistitem.videos_view.selected == 0 {
966 singleplaylistitem.is_commands_view =
967 !singleplaylistitem.is_commands_view;
968 self.update_appearance(
969 framework.data.global.get::<AppearanceConfig>().unwrap(),
970 &info,
971 );
972 *framework.data.global.get_mut::<Message>().unwrap() =
973 Message::Success(String::from("Switched view"));
974 } else {
975 framework
976 .data
977 .state
978 .get_mut::<Tasks>()
979 .unwrap()
980 .priority
981 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
982 self.item.as_ref().unwrap().fullplaylist()?.videos
983 [singleplaylistitem.videos_view.selected - 1]
984 .minivideo()?
985 .id
986 .clone(),
987 ))));
988 }
989
990 true
991 }
992 _ => false,
993 };
994
995 if updated {
996 framework
997 .data
998 .global
999 .get_mut::<Status>()
1000 .unwrap()
1001 .render_image = true;
1002 set_envs(
1003 self.infalte_item_update(
1004 framework.data.global.get::<MainConfig>().unwrap(),
1005 framework.data.global.get::<Status>().unwrap(),
1006 )
1007 .into_iter(),
1008 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
1009 );
1010 }
1011
1012 updated
1013 }
1014 }
1015 SingleItemType::None => false,
1016 };
1017
1018 if updated {
1019 framework
1020 .data
1021 .state
1022 .get_mut::<Tasks>()
1023 .unwrap()
1024 .priority
1025 .push(Task::RenderAll);
1026 }
1027
1028 Ok(())
1029 }
1030
1031 fn mouse_event(
1032 &mut self,
1033 framework: &mut FrameworkClean,
1034 x: u16,
1035 y: u16,
1036 _absolute_x: u16,
1037 _absolute_y: u16,
1038 ) -> bool {
1039 let chunk = self
1040 .grid
1041 .chunks(
1042 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
1043 {
1044 prev_frame
1045 } else {
1046 return false;
1047 },
1048 )
1049 .unwrap()[0][1];
1050
1051 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
1052 return false;
1053 }
1054
1055 let textlist = match &mut self.r#type {
1056 SingleItemType::Video(SingleVideoItem { textlist, .. }) => textlist,
1057 SingleItemType::Playlist(singleplaylistitem) => {
1058 if singleplaylistitem.is_commands_view {
1059 &mut singleplaylistitem.commands_view
1060 } else {
1061 let y = (y - chunk.y) as usize + singleplaylistitem.videos_view.scroll;
1062 if singleplaylistitem.videos_view.selected != 0 && y == 0 {
1063 framework
1064 .data
1065 .state
1066 .get_mut::<Tasks>()
1067 .unwrap()
1068 .priority
1069 .push(Task::ClearPage);
1070 }
1071 &mut singleplaylistitem.videos_view
1072 }
1073 }
1074 _ => return false,
1075 };
1076
1077 let y = (y - chunk.y) as usize + textlist.scroll;
1078
1079 // clicking on already selected item
1080 if y == textlist.selected || y == textlist.selected + 2 || y == textlist.selected + 1 {
1081 self.select_at_cursor(framework);
1082 return true;
1083 }
1084
1085 // clicking on rows after the last item
1086 if y > textlist.items.len() + 1 {
1087 let _ = textlist.last();
1088 } else if y <= textlist.selected {
1089 textlist.selected = y;
1090 } else if y >= textlist.selected + 2 {
1091 textlist.selected = y - 2;
1092 }
1093
1094 self.update();
1095
1096 set_envs(
1097 self.infalte_item_update(
1098 framework.data.global.get::<MainConfig>().unwrap(),
1099 framework.data.global.get::<Status>().unwrap(),
1100 )
1101 .into_iter(),
1102 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
1103 );
1104
1105 // render the new image
1106 framework
1107 .data
1108 .global
1109 .get_mut::<Status>()
1110 .unwrap()
1111 .render_image = true;
1112
1113 true
1114 }
1115}