src/items/singleitem.rs

940 lines · 35697 bytes

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