src/items/channeldisplay.rs

770 lines · 27914 bytes

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