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