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