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