src/items/channeldisplay.rs

773 lines · 27928 bytes

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