src/items/channeldisplay.rs

769 lines · 27773 bytes

  1use super::ItemInfo;
  2use crate::{
  3    config::*,
  4    global::{functions::*, structs::*, traits::SearchProviderWrapper},
  5};
  6use ratatui::{
  7    layout::{Constraint, Rect},
  8    style::Style,
  9    widgets::{Block, Borders},
 10};
 11use tui_additions::{
 12    framework::{FrameworkClean, FrameworkItem},
 13    widgets::{Grid, TextList},
 14};
 15
 16/// the 4 pages that a channel has (including the default "blank" page when loading)
 17#[derive(Clone)]
 18pub enum ChannelDisplay {
 19    /// a blank item, will turn into one of the other variants when `.load()` depending on the page
 20    None,
 21    /// main channel display page
 22    Main {
 23        channel: Box<Item>,
 24        iteminfo: Box<ItemInfo>,
 25        grid: Grid,
 26        textlist: TextList,
 27        commands: Vec<(String, String)>,
 28    },
 29    /// latest videos
 30    Videos {
 31        videos: Vec<Item>,
 32        textlist: TextList,
 33        iteminfo: Box<ItemInfo>,
 34        grid: Grid,
 35    },
 36    /// created playlists
 37    Playlists {
 38        playlists: Vec<Item>,
 39        textlist: TextList,
 40        iteminfo: Box<ItemInfo>,
 41        grid: Grid,
 42    },
 43}
 44
 45impl Default for ChannelDisplay {
 46    fn default() -> Self {
 47        Self::None
 48    }
 49}
 50
 51impl ChannelDisplay {
 52    pub fn new_textlist_with_map(commands: Vec<(String, String)>) -> TextList {
 53        TextList::default()
 54            .items(
 55                &commands
 56                    .iter()
 57                    .map(|command| &command.0)
 58                    .collect::<Vec<_>>(),
 59            )
 60            .unwrap()
 61    }
 62
 63    fn inflate_load(&self, mainconfig: &MainConfig, status: &Status) -> Vec<(String, String)> {
 64        match self {
 65            Self::Main { channel, .. } => {
 66                vec![
 67                    (
 68                        String::from("url"),
 69                        match status.provider {
 70                            Provider::Invidious => format!(
 71                                "{}/channel/{}{}",
 72                                mainconfig.invidious_instance,
 73                                channel.id().unwrap_or_default(),
 74                                match self {
 75                                    Self::None | Self::Main { .. } => "",
 76                                    Self::Videos { .. } => "videos",
 77                                    Self::Playlists { .. } => "playlists",
 78                                }
 79                            ),
 80                            Provider::YouTube => {
 81                                format!("'https://youtu.be/{}'", channel.id().unwrap_or_default())
 82                            }
 83                        },
 84                    ),
 85                    (
 86                        String::from("id"),
 87                        channel.id().unwrap_or_default().to_string(),
 88                    ),
 89                    (
 90                        String::from("name"),
 91                        channel.fullchannel().unwrap().name.clone(),
 92                    ),
 93                ]
 94            }
 95            // TODO?
 96            _ => Vec::new(),
 97        }
 98    }
 99
100    fn infalte_item_update(
101        &self,
102        mainconfig: &MainConfig,
103        status: &Status,
104    ) -> Vec<(String, String)> {
105        match self {
106            ChannelDisplay::Videos {
107                videos, textlist, ..
108            } => {
109                if textlist.items.is_empty() {
110                    vec![(String::from("hover-url"), "no-videos".to_string())]
111                } else {
112                    vec![(
113                        String::from("hover-url"),
114                        format!(
115                            "{}/watch?v={}",
116                            match status.provider {
117                                Provider::YouTube => "https://youtube.com",
118                                Provider::Invidious => &mainconfig.invidious_instance,
119                            },
120                            videos[textlist.selected].id().unwrap_or_default()
121                        ),
122                    )]
123                }
124            }
125            ChannelDisplay::Playlists {
126                playlists,
127                textlist,
128                ..
129            } => {
130                if textlist.items.is_empty() {
131                    vec![(String::from("hover-url"), "no-videos".to_string())]
132                } else {
133                    vec![(
134                        String::from("hover-url"),
135                        format!(
136                            "{}/playlist?list={}",
137                            match status.provider {
138                                Provider::YouTube => "https://youtube.com",
139                                Provider::Invidious => &mainconfig.invidious_instance,
140                            },
141                            playlists[textlist.selected].id().unwrap_or_default()
142                        ),
143                    )]
144                }
145            }
146            _ => Vec::new(),
147        }
148    }
149    /// update the style of the item (colours, etc), ran on ever render
150    fn update_appearance(
151        &mut self,
152        info: &tui_additions::framework::ItemInfo,
153        appearance: &AppearanceConfig,
154    ) {
155        // is runs on every render
156        match self {
157            ChannelDisplay::Main { textlist, grid, .. }
158            | ChannelDisplay::Playlists { textlist, grid, .. }
159            | ChannelDisplay::Videos { textlist, grid, .. } => {
160                textlist.set_border_type(appearance.borders);
161                textlist.set_style(Style::default().fg(appearance.colors.text));
162
163                if info.selected {
164                    textlist
165                        .set_selected_style(Style::default().fg(appearance.colors.text_special));
166                    textlist.set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
167                    grid.set_border_style(Style::default().fg(appearance.colors.outline_selected));
168                } else {
169                    if info.hover {
170                        grid.set_border_style(Style::default().fg(appearance.colors.outline_hover));
171                    } else {
172                        grid.set_border_style(Style::default().fg(appearance.colors.outline));
173                    }
174                    textlist
175                        .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
176                    textlist
177                        .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
178                }
179            }
180            _ => {}
181        }
182    }
183
184    /// handles when select (enter) is pressed, generally loads the hovered item in a
185    /// `SingleItemPage`
186    fn select_at_cursor(&self, framework: &mut FrameworkClean) {
187        match self {
188            Self::None => {}
189            Self::Main {
190                textlist, commands, ..
191            } => {
192                let command_string = commands[textlist.selected].1.clone();
193
194                framework
195                    .data
196                    .state
197                    .get_mut::<Tasks>()
198                    .unwrap()
199                    .priority
200                    .push(Task::Command(apply_envs(command_string)));
201            }
202            Self::Videos {
203                videos, textlist, ..
204            } => {
205                // on select loads that in singleitem
206                if !videos.is_empty() {
207                    framework
208                        .data
209                        .state
210                        .get_mut::<Tasks>()
211                        .unwrap()
212                        .priority
213                        .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
214                            videos[textlist.selected].minivideo().unwrap().id.clone(),
215                        ))));
216                } else {
217                    *framework.data.global.get_mut::<Message>().unwrap() =
218                        Message::Error(String::from("There is nothing to select"));
219                }
220            }
221            Self::Playlists {
222                playlists,
223                textlist,
224                ..
225            } => {
226                if !playlists.is_empty() {
227                    framework
228                        .data
229                        .state
230                        .get_mut::<Tasks>()
231                        .unwrap()
232                        .priority
233                        .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist(
234                            playlists[textlist.selected]
235                                .miniplaylist()
236                                .unwrap()
237                                .id
238                                .clone(),
239                        ))));
240                } else {
241                    *framework.data.global.get_mut::<Message>().unwrap() =
242                        Message::Error(String::from("There is nothing to select"));
243                }
244            }
245        }
246    }
247
248    /// updates the video/playlist preview
249    fn update(&mut self) {
250        match self {
251            Self::Videos {
252                videos: items,
253                textlist,
254                iteminfo,
255                ..
256            }
257            | Self::Playlists {
258                playlists: items,
259                textlist,
260                iteminfo,
261                ..
262            } => {
263                if !items.is_empty()
264                    && items[textlist.selected].id() != iteminfo.item.as_ref().unwrap().id()
265                {
266                    iteminfo.item = Some(items[textlist.selected].clone())
267                }
268            }
269            _ => {}
270        }
271    }
272
273    /// check if self should be able to be selected
274    pub fn selectable(&self) -> bool {
275        !matches!(self, Self::None)
276    }
277}
278
279impl FrameworkItem for ChannelDisplay {
280    fn render(
281        &mut self,
282        frame: &mut ratatui::Frame,
283        framework: &mut tui_additions::framework::FrameworkClean,
284        area: ratatui::layout::Rect,
285        popup_render: bool,
286        info: tui_additions::framework::ItemInfo,
287    ) {
288        if popup_render {
289            return;
290        }
291
292        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
293        self.update_appearance(&info, appearance);
294        let border_style = Style::default().fg(if info.hover {
295            appearance.colors.outline_hover
296        } else if info.selected {
297            appearance.colors.outline_selected
298        } else {
299            appearance.colors.outline
300        });
301
302        // matches itself to render differently depending on the enum variation
303        match self {
304            Self::None => {
305                // the block is created when rendered because its quite simple and should not be a
306                // performance issue
307                let block = Block::default()
308                    .border_type(appearance.borders)
309                    .borders(Borders::ALL)
310                    .border_style(border_style);
311                frame.render_widget(block, area);
312            }
313            Self::Main {
314                grid,
315                textlist,
316                iteminfo,
317                ..
318            } => {
319                let chunks = grid.chunks(area).unwrap()[0].clone();
320                frame.render_widget(grid.clone(), area);
321                iteminfo.render(frame, framework, chunks[0], popup_render, info);
322                textlist.set_height(chunks[1].height);
323                frame.render_widget(textlist.clone(), chunks[1]);
324            }
325            Self::Videos {
326                textlist,
327                iteminfo,
328                grid,
329                ..
330            }
331            | Self::Playlists {
332                textlist,
333                iteminfo,
334                grid,
335                ..
336            } => {
337                let inner = &grid.chunks(area).unwrap()[0];
338
339                frame.render_widget(grid.clone(), area);
340                textlist.set_height(inner[0].height);
341                frame.render_widget(textlist.clone(), inner[0]);
342                iteminfo.render(frame, framework, inner[1], popup_render, info);
343            }
344        }
345    }
346
347    fn select(&mut self, _framework: &mut tui_additions::framework::FrameworkClean) -> bool {
348        self.selectable()
349    }
350
351    fn message(
352        &mut self,
353        framework: &mut FrameworkClean,
354        data: std::collections::HashMap<String, Box<dyn std::any::Any>>,
355    ) -> bool {
356        if !data.contains_key("type") {
357            return false;
358        }
359
360        let updated = match self {
361            Self::None => false,
362            Self::Main { textlist, .. } => data.get("type").is_some_and(|v| {
363                v.downcast_ref::<String>()
364                    .is_some_and(|v| match v.as_str() {
365                        "scrollup" => textlist.up().is_ok(),
366                        "scrolldown" => textlist.down().is_ok(),
367                        _ => false,
368                    })
369            }),
370            Self::Videos {
371                textlist,
372                videos,
373                iteminfo,
374                ..
375            } => data.get("type").is_some_and(|v| {
376                let updated = v
377                    .downcast_ref::<String>()
378                    .is_some_and(|v| match v.as_str() {
379                        "scrollup" => textlist.up().is_ok(),
380                        "scrolldown" => textlist.down().is_ok(),
381                        _ => false,
382                    });
383
384                if updated && !videos.is_empty() {
385                    framework
386                        .data
387                        .state
388                        .get_mut::<Tasks>()
389                        .unwrap()
390                        .priority
391                        .push(Task::RenderAll);
392                    framework
393                        .data
394                        .global
395                        .get_mut::<Status>()
396                        .unwrap()
397                        .render_image = true;
398                    iteminfo.item = Some(videos[textlist.selected].clone());
399                }
400                updated
401            }),
402            Self::Playlists {
403                playlists,
404                textlist,
405                iteminfo,
406                ..
407            } => {
408                let updated = data.get("type").is_some_and(|v| {
409                    v.downcast_ref::<String>()
410                        .is_some_and(|v| match v.as_str() {
411                            "scrollup" => textlist.up().is_ok(),
412                            "scrolldown" => textlist.down().is_ok(),
413                            _ => false,
414                        })
415                });
416
417                if updated && !playlists.is_empty() {
418                    framework
419                        .data
420                        .state
421                        .get_mut::<Tasks>()
422                        .unwrap()
423                        .priority
424                        .push(Task::RenderAll);
425                    framework
426                        .data
427                        .global
428                        .get_mut::<Status>()
429                        .unwrap()
430                        .render_image = true;
431                    iteminfo.item = Some(playlists[textlist.selected].clone());
432                }
433
434                updated
435            }
436        };
437
438        set_envs(
439            self.infalte_item_update(
440                framework.data.global.get::<MainConfig>().unwrap(),
441                framework.data.global.get::<Status>().unwrap(),
442            )
443            .into_iter(),
444            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
445        );
446
447        updated
448    }
449
450    fn key_event(
451        &mut self,
452        framework: &mut tui_additions::framework::FrameworkClean,
453        key: crossterm::event::KeyEvent,
454        _info: tui_additions::framework::ItemInfo,
455    ) -> Result<(), Box<dyn std::error::Error>> {
456        let action = if let Some(action) = framework
457            .data
458            .global
459            .get::<KeyBindingsConfig>()
460            .unwrap()
461            .get(key)
462        {
463            action
464        } else {
465            return Ok(());
466        };
467
468        match self {
469            Self::Videos {
470                videos,
471                textlist,
472                iteminfo,
473                ..
474            } => {
475                let updated = match action {
476                    KeyAction::MoveUp => textlist.up().is_ok(),
477                    KeyAction::MoveDown => textlist.down().is_ok(),
478                    KeyAction::MoveLeft | KeyAction::First => textlist.first().is_ok(),
479                    KeyAction::MoveRight | KeyAction::End => textlist.last().is_ok(),
480                    KeyAction::Select => {
481                        self.select_at_cursor(framework);
482                        return Ok(());
483                    }
484                    _ => false,
485                };
486
487                // only update iteminfo (it requires cloning) if changed and not empty
488                if updated && !videos.is_empty() {
489                    framework
490                        .data
491                        .state
492                        .get_mut::<Tasks>()
493                        .unwrap()
494                        .priority
495                        .push(Task::RenderAll);
496                    framework
497                        .data
498                        .global
499                        .get_mut::<Status>()
500                        .unwrap()
501                        .render_image = true;
502                    iteminfo.item = Some(videos[textlist.selected].clone());
503                    set_envs(
504                        self.infalte_item_update(
505                            framework.data.global.get::<MainConfig>().unwrap(),
506                            framework.data.global.get::<Status>().unwrap(),
507                        )
508                        .into_iter(),
509                        &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
510                    );
511                }
512            }
513            Self::Playlists {
514                playlists,
515                textlist,
516                iteminfo,
517                ..
518            } => {
519                let updated = match action {
520                    KeyAction::MoveUp => textlist.up().is_ok(),
521                    KeyAction::MoveDown => textlist.down().is_ok(),
522                    KeyAction::MoveLeft => textlist.first().is_ok(),
523                    KeyAction::MoveRight => textlist.last().is_ok(),
524                    KeyAction::Select => {
525                        self.select_at_cursor(framework);
526                        return Ok(());
527                    }
528                    _ => false,
529                };
530
531                if updated && !playlists.is_empty() {
532                    framework
533                        .data
534                        .state
535                        .get_mut::<Tasks>()
536                        .unwrap()
537                        .priority
538                        .push(Task::RenderAll);
539                    framework
540                        .data
541                        .global
542                        .get_mut::<Status>()
543                        .unwrap()
544                        .render_image = true;
545                    iteminfo.item = Some(playlists[textlist.selected].clone());
546                }
547            }
548            Self::Main {
549                textlist, commands, ..
550            } => {
551                let updated = match action {
552                    // move the cursor in the textlist, only update the screen if it is changed
553                    KeyAction::MoveUp => textlist.up().is_ok(),
554                    KeyAction::MoveDown => textlist.down().is_ok(),
555                    KeyAction::MoveLeft | KeyAction::First => textlist.first().is_ok(),
556                    KeyAction::MoveRight | KeyAction::End => textlist.last().is_ok(),
557                    KeyAction::Select => {
558                        self.select_at_cursor(framework);
559                        framework
560                            .data
561                            .state
562                            .get_mut::<Tasks>()
563                            .unwrap()
564                            .priority
565                            .push(Task::RenderAll);
566                        return Ok(());
567                    }
568                    _ => false,
569                };
570
571                if updated && !commands.is_empty() {
572                    framework
573                        .data
574                        .state
575                        .get_mut::<Tasks>()
576                        .unwrap()
577                        .priority
578                        .push(Task::RenderAll);
579                    framework
580                        .data
581                        .global
582                        .get_mut::<Status>()
583                        .unwrap()
584                        .render_image = true;
585                }
586            }
587            _ => {}
588        }
589
590        Ok(())
591    }
592
593    fn load_item(
594        &mut self,
595        framework: &mut tui_additions::framework::FrameworkClean,
596        _info: tui_additions::framework::ItemInfo,
597    ) -> Result<(), Box<dyn std::error::Error>> {
598        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
599        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
600        let page = framework.data.state.get::<Page>().unwrap().channeldisplay();
601
602        match page.r#type {
603            ChannelDisplayPageType::Main => {
604                let channel = Item::from_full_channel(
605                    SearchProviderWrapper::channel(&page.id)?,
606                    mainconfig.image_index,
607                );
608                if mainconfig.images.display() {
609                    download_all_images(vec![(&channel).into()]);
610                }
611                let commands = framework
612                    .data
613                    .global
614                    .get::<CommandsConfig>()
615                    .unwrap()
616                    .channel
617                    .clone();
618                *self = Self::Main {
619                    iteminfo: Box::new(ItemInfo::new(Some(channel.clone()))),
620                    channel: Box::new(channel),
621                    grid: Grid::new(
622                        vec![Constraint::Percentage(60), Constraint::Percentage(40)],
623                        vec![Constraint::Percentage(100)],
624                    )?
625                    .border_type(appearance.borders),
626                    textlist: Self::new_textlist_with_map(commands.clone()),
627                    commands,
628                }
629            }
630            ChannelDisplayPageType::Videos => {
631                let videos = SearchProviderWrapper::channel_videos(&page.id)?
632                    .into_iter()
633                    .map(|video| Item::from_common_video(video, mainconfig.image_index))
634                    .collect::<Vec<_>>();
635                if mainconfig.images.display() {
636                    download_all_images(videos.iter().map(|item| item.into()).collect());
637                }
638                *self = Self::Videos {
639                    textlist: TextList::default()
640                        .ascii_only(!mainconfig.allow_unicode)
641                        .border_type(appearance.borders)
642                        .style(Style::default().fg(appearance.colors.text))
643                        .items(&videos)?,
644                    iteminfo: Box::new(ItemInfo::new(videos.first().cloned())),
645                    grid: Grid::new(
646                        vec![Constraint::Percentage(60), Constraint::Percentage(40)],
647                        vec![Constraint::Percentage(100)],
648                    )?
649                    .border_type(appearance.borders),
650                    videos,
651                };
652            }
653            ChannelDisplayPageType::Playlists => {
654                let playlists = SearchProviderWrapper::channel_playlists(&page.id)?
655                    .into_iter()
656                    .map(Item::from_common_playlist)
657                    .collect::<Vec<_>>();
658                if mainconfig.images.display() {
659                    download_all_images(playlists.iter().map(|item| item.into()).collect());
660                }
661                *self = Self::Playlists {
662                    textlist: TextList::default()
663                        .ascii_only(!mainconfig.allow_unicode)
664                        .border_type(appearance.borders)
665                        .style(Style::default().fg(appearance.colors.text))
666                        .items(&playlists)?,
667                    iteminfo: Box::new(ItemInfo::new(playlists.first().cloned())),
668                    grid: Grid::new(
669                        vec![Constraint::Percentage(60), Constraint::Percentage(40)],
670                        vec![Constraint::Percentage(100)],
671                    )?
672                    .border_type(appearance.borders),
673                    playlists,
674                };
675            }
676        }
677
678        set_envs(
679            self.inflate_load(mainconfig, framework.data.global.get::<Status>().unwrap())
680                .into_iter(),
681            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
682        );
683
684        set_envs(
685            self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
686                .into_iter(),
687            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
688        );
689
690        Ok(())
691    }
692
693    fn mouse_event(
694        &mut self,
695        framework: &mut tui_additions::framework::FrameworkClean,
696        x: u16,
697        y: u16,
698        _absolute_x: u16,
699        _absolute_y: u16,
700    ) -> bool {
701        let chunk_index = if matches!(self, Self::Main { .. }) {
702            1
703        } else {
704            0
705        };
706        match self {
707            Self::None => return false,
708            Self::Main { textlist, grid, .. }
709            | Self::Videos { textlist, grid, .. }
710            | Self::Playlists { textlist, grid, .. } => {
711                let chunk = grid
712                    .chunks(
713                        if let Some(prev_frame) =
714                            framework.data.global.get::<Status>().unwrap().prev_frame
715                        {
716                            prev_frame
717                        } else {
718                            return false;
719                        },
720                    )
721                    .unwrap()[0][chunk_index];
722
723                if !chunk.intersects(Rect::new(x, y, 1, 1)) {
724                    return false;
725                }
726
727                let y = (y - chunk.y) as usize + textlist.scroll;
728
729                // clicking on already selected item
730                if y == textlist.selected
731                    || y == textlist.selected + 2
732                    || y == textlist.selected + 1
733                {
734                    self.select_at_cursor(framework);
735                    return true;
736                }
737
738                // clicking on rows after the last item
739                if y > textlist.items.len() + 1 {
740                    let _ = textlist.last();
741                } else if y <= textlist.selected {
742                    textlist.selected = y;
743                } else if y >= textlist.selected + 2 {
744                    textlist.selected = y - 2;
745                }
746
747                self.update();
748
749                // render the new image
750                framework
751                    .data
752                    .global
753                    .get_mut::<Status>()
754                    .unwrap()
755                    .render_image = true;
756            }
757        }
758        set_envs(
759            self.infalte_item_update(
760                framework.data.global.get::<MainConfig>().unwrap(),
761                framework.data.global.get::<Status>().unwrap(),
762            )
763            .into_iter(),
764            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
765        );
766
767        true
768    }
769}