src/items/singleitem.rs
1035 lines · 38341 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 render(
535 &mut self,
536 frame: &mut ratatui::Frame,
537 framework: &mut FrameworkClean,
538 area: Rect,
539 popup_render: bool,
540 info: tui_additions::framework::ItemInfo,
541 ) {
542 let status = framework.data.global.get::<Status>().unwrap();
543 if popup_render {
544 return;
545 }
546
547 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
548
549 if self.item.is_none() {
550 frame.render_widget(
551 Block::default()
552 .borders(Borders::ALL)
553 .border_type(appearance.borders),
554 area,
555 );
556 return;
557 }
558
559 if status.provider_updated {
560 set_envs(
561 self.infalte_item_update(
562 framework.data.global.get::<MainConfig>().unwrap(),
563 status,
564 )
565 .into_iter(),
566 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
567 );
568 }
569
570 self.update_appearance(appearance, &info);
571
572 let chunks = self.grid.chunks(area).unwrap()[0].clone();
573
574 frame.render_widget(self.grid.clone(), area);
575
576 match &mut self.r#type {
577 SingleItemType::Video(typeinfo) => {
578 // 2 by 1 grid, item info in the first cell and textlist at the second
579 if status.provider_updated {
580 typeinfo.update_provider().into_iter().for_each(|index| {
581 typeinfo.textlist.items[index] = typeinfo.commands[index].0.clone().replace(
582 "${provider}",
583 framework
584 .data
585 .global
586 .get::<Status>()
587 .unwrap()
588 .provider
589 .as_str(),
590 )
591 });
592 }
593 self.iteminfo
594 .render(frame, framework, chunks[0], popup_render, info);
595 typeinfo.textlist.set_height(chunks[1].height);
596 frame.render_widget(typeinfo.textlist.clone(), chunks[1]);
597 }
598 SingleItemType::Playlist(typeinfo) => {
599 // 3 by 1 grid if hovering a video inside the playlist
600 // if not then 2 by 1
601 //
602 // item info in the first cell, textlists in the second, hovering video on 3rd (if
603 // present)
604 if typeinfo.is_commands_view {
605 if status.provider_updated {
606 typeinfo.update_provider().into_iter().for_each(|index| {
607 typeinfo.commands_view.items[index] =
608 typeinfo.commands[index].0.clone().replace(
609 "${provider}",
610 framework
611 .data
612 .global
613 .get::<Status>()
614 .unwrap()
615 .provider
616 .as_str(),
617 )
618 });
619 }
620 typeinfo.commands_view.set_height(chunks[1].height);
621 frame.render_widget(typeinfo.commands_view.clone(), chunks[1]);
622 } else {
623 typeinfo.videos_view.set_height(chunks[1].height);
624 frame.render_widget(typeinfo.videos_view.clone(), chunks[1]);
625
626 if typeinfo.videos_view.selected != 0 {
627 typeinfo.hovered_video.render(
628 frame,
629 framework,
630 chunks[2],
631 popup_render,
632 info,
633 );
634 }
635 }
636 self.iteminfo
637 .render(frame, framework, chunks[0], popup_render, info);
638 }
639 SingleItemType::None => {}
640 }
641 }
642
643 fn load_item(
644 &mut self,
645 framework: &mut tui_additions::framework::FrameworkClean,
646 _info: tui_additions::framework::ItemInfo,
647 ) -> Result<(), Box<dyn std::error::Error>> {
648 *self = Self::default();
649
650 let page = framework.data.state.get::<Page>().unwrap();
651
652 let r#type = if let Page::SingleItem(r#type) = page {
653 r#type
654 } else {
655 unreachable!("item `SingleItem` cannot be used in {page:?}")
656 };
657
658 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
659 // load items using the invidious api
660 // gets the item that it needs to load from `data.state.Page`
661 let (item, r#type) = match r#type {
662 SingleItemPage::Video(id) => {
663 let home_dir = home_dir().unwrap();
664 let path = home_dir.join(format!(".cache/youtube-tui/info/{id}.json"));
665
666 let video = if path.exists() {
667 serde_json::from_str(&fs::read_to_string(path)?)?
668 } else {
669 load_video(id, mainconfig)?
670 };
671 (
672 video,
673 SingleItemType::Video(SingleVideoItem::new(
674 framework.data.global.get::<CommandsConfig>().unwrap(),
675 mainconfig,
676 id,
677 )),
678 )
679 }
680 SingleItemPage::Playlist(id) => {
681 let path = home_dir()
682 .unwrap()
683 .join(format!(".cache/youtube-tui/info/{id}.json"));
684
685 let playlist = if path.exists() {
686 serde_json::from_str(&fs::read_to_string(path)?)?
687 } else {
688 load_playlist(id, mainconfig)?
689 };
690 let r#type = SingleItemType::Playlist(
691 SinglePlaylistItem::new(
692 framework.data.global.get::<CommandsConfig>().unwrap(),
693 mainconfig,
694 id,
695 &playlist.fullplaylist().unwrap().videos,
696 )
697 .into(),
698 );
699
700 (playlist, r#type)
701 }
702 };
703
704 self.item = Some(item);
705 self.r#type = r#type;
706 self.iteminfo.item = self.item.clone();
707
708 if let Some(item) = &self.item {
709 // if item.is_unknown() {
710 // return Ok(());
711 // }
712
713 let item = item.clone();
714 // push to watch history
715 let watch_history = framework.data.global.get_mut::<WatchHistory>().unwrap();
716 watch_history.push(item)?;
717 watch_history.save()?;
718 }
719
720 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
721 // need to update provider every time the item loads or else it will display `${provider}`
722 // instead of the actual provider (e.g. `YouTube`)
723
724 set_envs(
725 self.r#type
726 .inflate_load(
727 mainconfig,
728 framework.data.global.get::<Status>().unwrap(),
729 &self.item,
730 )
731 .into_iter(),
732 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
733 );
734
735 set_envs(
736 self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
737 .into_iter(),
738 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
739 );
740
741 Ok(())
742 }
743
744 fn key_event(
745 &mut self,
746 framework: &mut tui_additions::framework::FrameworkClean,
747 key: crossterm::event::KeyEvent,
748 info: tui_additions::framework::ItemInfo,
749 ) -> Result<(), Box<dyn std::error::Error>> {
750 // discard any key inputs if `self.is_none()` becuase nothing can happen if self is none
751 if self.r#type.is_none() {
752 return Ok(());
753 }
754
755 let action = if let Some(action) = framework
756 .data
757 .global
758 .get::<KeyBindingsConfig>()
759 .unwrap()
760 .get(key)
761 {
762 action
763 } else {
764 return Ok(());
765 };
766
767 let updated = match &mut self.r#type {
768 SingleItemType::Video(singlevideoitem) => match action {
769 // move the cursor in the textlist, only update the screen if it is changed
770 KeyAction::MoveUp => singlevideoitem.textlist.up().is_ok(),
771 KeyAction::MoveDown => singlevideoitem.textlist.down().is_ok(),
772 KeyAction::MoveLeft | KeyAction::First => singlevideoitem.textlist.first().is_ok(),
773 KeyAction::MoveRight | KeyAction::End => singlevideoitem.textlist.last().is_ok(),
774 KeyAction::Select => {
775 self.select_at_cursor(framework);
776 return Ok(());
777 }
778 _ => false,
779 },
780 SingleItemType::Playlist(singleplaylistitem) => {
781 // there are 2 possible states in a playlist item
782 // they are handelled separately
783 if singleplaylistitem.is_commands_view {
784 match action {
785 KeyAction::MoveUp => singleplaylistitem.commands_view.up().is_ok(),
786 KeyAction::MoveDown => singleplaylistitem.commands_view.down().is_ok(),
787 KeyAction::MoveLeft | KeyAction::First => {
788 singleplaylistitem.commands_view.first().is_ok()
789 }
790 KeyAction::MoveRight | KeyAction::End => {
791 singleplaylistitem.commands_view.last().is_ok()
792 }
793 KeyAction::Select => {
794 self.select_at_cursor(framework);
795 return Ok(());
796 }
797 _ => false,
798 }
799 } else {
800 let updated = match action {
801 // checks if it is updated, if it is and selected is not 0 (is hovering on
802 // a video), then also need to update the iteminfo
803 KeyAction::MoveUp => {
804 if singleplaylistitem.videos_view.selected == 1 {
805 // going from a hovering video to not hovering will make the image
806 // stay on the screen, therefore it needs to be removed by clearing
807 // the screen
808 framework
809 .data
810 .state
811 .get_mut::<Tasks>()
812 .unwrap()
813 .priority
814 .push(Task::ClearPage);
815 } else if singleplaylistitem.videos_view.selected == 0 {
816 return Ok(());
817 }
818
819 let updated = singleplaylistitem.videos_view.up().is_ok();
820 if singleplaylistitem.videos_view.selected != 0 {
821 singleplaylistitem.hovered_video.item = Some(
822 self.item.as_ref().unwrap().fullplaylist()?.videos
823 [singleplaylistitem.videos_view.selected - 1]
824 .clone(),
825 );
826 }
827 updated
828 }
829 KeyAction::MoveDown => {
830 if singleplaylistitem.videos_view.selected
831 == singleplaylistitem.videos_view.items.len() - 1
832 {
833 return Ok(());
834 }
835
836 let updated = singleplaylistitem.videos_view.down().is_ok();
837 if updated && singleplaylistitem.videos_view.selected != 0 {
838 singleplaylistitem.hovered_video.item = Some(
839 self.item.as_ref().unwrap().fullplaylist()?.videos
840 [singleplaylistitem.videos_view.selected - 1]
841 .clone(),
842 );
843 }
844 updated
845 }
846 KeyAction::MoveLeft => {
847 if singleplaylistitem.videos_view.selected != 0 {
848 framework
849 .data
850 .state
851 .get_mut::<Tasks>()
852 .unwrap()
853 .priority
854 .push(Task::ClearPage);
855 } else if singleplaylistitem.videos_view.selected == 0 {
856 return Ok(());
857 }
858
859 let updated = singleplaylistitem.videos_view.first().is_ok();
860 singleplaylistitem.hovered_video.item = None;
861 updated
862 }
863 KeyAction::MoveRight => {
864 if singleplaylistitem.videos_view.selected
865 == singleplaylistitem.videos_view.items.len() - 1
866 {
867 return Ok(());
868 }
869 let updated = singleplaylistitem.videos_view.last().is_ok();
870 if updated && singleplaylistitem.videos_view.selected != 0 {
871 singleplaylistitem.hovered_video.item = Some(
872 self.item.as_ref().unwrap().fullplaylist()?.videos
873 [singleplaylistitem.videos_view.selected - 1]
874 .clone(),
875 );
876 }
877 updated
878 }
879 KeyAction::Select => {
880 if singleplaylistitem.videos_view.selected == 0 {
881 singleplaylistitem.is_commands_view =
882 !singleplaylistitem.is_commands_view;
883 self.update_appearance(
884 framework.data.global.get::<AppearanceConfig>().unwrap(),
885 &info,
886 );
887 *framework.data.global.get_mut::<Message>().unwrap() =
888 Message::Success(String::from("Switched view"));
889 } else {
890 framework
891 .data
892 .state
893 .get_mut::<Tasks>()
894 .unwrap()
895 .priority
896 .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
897 self.item.as_ref().unwrap().fullplaylist()?.videos
898 [singleplaylistitem.videos_view.selected - 1]
899 .minivideo()?
900 .id
901 .clone(),
902 ))));
903 }
904
905 true
906 }
907 _ => false,
908 };
909
910 if updated {
911 framework
912 .data
913 .global
914 .get_mut::<Status>()
915 .unwrap()
916 .render_image = true;
917 set_envs(
918 self.infalte_item_update(
919 framework.data.global.get::<MainConfig>().unwrap(),
920 framework.data.global.get::<Status>().unwrap(),
921 )
922 .into_iter(),
923 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
924 );
925 }
926
927 updated
928 }
929 }
930 SingleItemType::None => false,
931 };
932
933 if updated {
934 framework
935 .data
936 .state
937 .get_mut::<Tasks>()
938 .unwrap()
939 .priority
940 .push(Task::RenderAll);
941 }
942
943 Ok(())
944 }
945
946 fn mouse_event(
947 &mut self,
948 framework: &mut FrameworkClean,
949 x: u16,
950 y: u16,
951 _absolute_x: u16,
952 _absolute_y: u16,
953 ) -> bool {
954 let chunk = self
955 .grid
956 .chunks(
957 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
958 {
959 prev_frame
960 } else {
961 return false;
962 },
963 )
964 .unwrap()[0][1];
965
966 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
967 return false;
968 }
969
970 let textlist = match &mut self.r#type {
971 SingleItemType::Video(SingleVideoItem { textlist, .. }) => textlist,
972 SingleItemType::Playlist(singleplaylistitem) => {
973 if singleplaylistitem.is_commands_view {
974 &mut singleplaylistitem.commands_view
975 } else {
976 let y = (y - chunk.y) as usize + singleplaylistitem.videos_view.scroll;
977 if singleplaylistitem.videos_view.selected != 0 && y == 0 {
978 framework
979 .data
980 .state
981 .get_mut::<Tasks>()
982 .unwrap()
983 .priority
984 .push(Task::ClearPage);
985 }
986 &mut singleplaylistitem.videos_view
987 }
988 }
989 _ => return false,
990 };
991
992 let y = (y - chunk.y) as usize + textlist.scroll;
993
994 // clicking on already selected item
995 if y == textlist.selected || y == textlist.selected + 2 || y == textlist.selected + 1 {
996 self.select_at_cursor(framework);
997 return true;
998 }
999
1000 // clicking on rows after the last item
1001 if y > textlist.items.len() + 1 {
1002 return false;
1003 }
1004
1005 // moving the cursor
1006 if y <= textlist.selected {
1007 textlist.selected = y;
1008 }
1009
1010 if y >= textlist.selected + 2 {
1011 textlist.selected = y - 2;
1012 }
1013
1014 self.update();
1015
1016 set_envs(
1017 self.infalte_item_update(
1018 framework.data.global.get::<MainConfig>().unwrap(),
1019 framework.data.global.get::<Status>().unwrap(),
1020 )
1021 .into_iter(),
1022 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
1023 );
1024
1025 // render the new image
1026 framework
1027 .data
1028 .global
1029 .get_mut::<Status>()
1030 .unwrap()
1031 .render_image = true;
1032
1033 true
1034 }
1035}