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