src/items/channeldisplay.rs

571 lines · 20808 bytes

  1use super::ItemInfo;
  2use crate::{
  3    config::*,
  4    global::{functions::*, structs::*},
  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 { channel: Item, iteminfo: ItemInfo },
 23    /// latest videos
 24    Videos {
 25        videos: Vec<Item>,
 26        textlist: TextList,
 27        iteminfo: ItemInfo,
 28        grid: Grid,
 29    },
 30    /// created playlists
 31    Playlists {
 32        playlists: Vec<Item>,
 33        textlist: TextList,
 34        iteminfo: ItemInfo,
 35        grid: Grid,
 36    },
 37}
 38
 39impl Default for ChannelDisplay {
 40    fn default() -> Self {
 41        Self::None
 42    }
 43}
 44
 45impl ChannelDisplay {
 46    fn infalte_item_update(
 47        &self,
 48        mainconfig: &MainConfig,
 49        status: &Status,
 50    ) -> Vec<(String, String)> {
 51        match self {
 52            ChannelDisplay::Videos {
 53                videos, textlist, ..
 54            } => {
 55                if textlist.items.is_empty() {
 56                    vec![(String::from("hover-url"), "no-videos".to_string())]
 57                } else {
 58                    vec![(
 59                        String::from("hover-url"),
 60                        format!(
 61                            "{}/watch?v={}",
 62                            match status.provider {
 63                                Provider::YouTube => "https://youtube.com",
 64                                Provider::Invidious => &mainconfig.invidious_instance,
 65                            },
 66                            videos[textlist.selected].id().unwrap_or_default()
 67                        ),
 68                    )]
 69                }
 70            }
 71            ChannelDisplay::Playlists {
 72                playlists,
 73                textlist,
 74                ..
 75            } => {
 76                if textlist.items.is_empty() {
 77                    vec![(String::from("hover-url"), "no-videos".to_string())]
 78                } else {
 79                    vec![(
 80                        String::from("hover-url"),
 81                        format!(
 82                            "{}/playlist?list={}",
 83                            match status.provider {
 84                                Provider::YouTube => "https://youtube.com",
 85                                Provider::Invidious => &mainconfig.invidious_instance,
 86                            },
 87                            playlists[textlist.selected].id().unwrap_or_default()
 88                        ),
 89                    )]
 90                }
 91            }
 92            _ => Vec::new(),
 93        }
 94    }
 95    /// update the style of the item (colours, etc), ran on ever render
 96    fn update_appearance(
 97        &mut self,
 98        info: &tui_additions::framework::ItemInfo,
 99        appearance: &AppearanceConfig,
100    ) {
101        // is runs on every render
102        match self {
103            ChannelDisplay::Videos { textlist, grid, .. } => {
104                if info.selected {
105                    textlist
106                        .set_selected_style(Style::default().fg(appearance.colors.text_special));
107                    textlist.set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
108                    grid.set_border_style(Style::default().fg(appearance.colors.outline_selected));
109                } else {
110                    if info.hover {
111                        grid.set_border_style(Style::default().fg(appearance.colors.outline_hover));
112                    } else {
113                        grid.set_border_style(Style::default().fg(appearance.colors.outline));
114                    }
115                    textlist
116                        .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
117                    textlist
118                        .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
119                }
120            }
121            ChannelDisplay::Playlists { textlist, grid, .. } => {
122                if info.selected {
123                    textlist
124                        .set_selected_style(Style::default().fg(appearance.colors.text_special));
125                    textlist.set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
126                    grid.set_border_style(Style::default().fg(appearance.colors.outline_selected));
127                } else {
128                    if info.hover {
129                        grid.set_border_style(Style::default().fg(appearance.colors.outline_hover));
130                    } else {
131                        grid.set_border_style(Style::default().fg(appearance.colors.outline));
132                    }
133                    textlist
134                        .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
135                    textlist
136                        .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
137                }
138            }
139            _ => {}
140        }
141    }
142
143    /// handles when select (enter) is pressed, generally loads the hovered item in a
144    /// `SingleItemPage`
145    fn select_at_cursor(&self, framework: &mut FrameworkClean) {
146        match self {
147            Self::None | Self::Main { .. } => {}
148            Self::Videos {
149                videos, textlist, ..
150            } => {
151                // on select loads that in singleitem
152                if !videos.is_empty() {
153                    framework
154                        .data
155                        .state
156                        .get_mut::<Tasks>()
157                        .unwrap()
158                        .priority
159                        .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Video(
160                            videos[textlist.selected].minivideo().unwrap().id.clone(),
161                        ))));
162                } else {
163                    *framework.data.global.get_mut::<Message>().unwrap() =
164                        Message::Error(String::from("There is nothing to select"));
165                }
166            }
167            Self::Playlists {
168                playlists,
169                textlist,
170                ..
171            } => {
172                if !playlists.is_empty() {
173                    framework
174                        .data
175                        .state
176                        .get_mut::<Tasks>()
177                        .unwrap()
178                        .priority
179                        .push(Task::LoadPage(Page::SingleItem(SingleItemPage::Playlist(
180                            playlists[textlist.selected]
181                                .miniplaylist()
182                                .unwrap()
183                                .id
184                                .clone(),
185                        ))));
186                } else {
187                    *framework.data.global.get_mut::<Message>().unwrap() =
188                        Message::Error(String::from("There is nothing to select"));
189                }
190            }
191        }
192    }
193
194    /// updates the video/playlist preview
195    fn update(&mut self) {
196        match self {
197            Self::Videos {
198                videos: items,
199                textlist,
200                iteminfo,
201                ..
202            }
203            | Self::Playlists {
204                playlists: items,
205                textlist,
206                iteminfo,
207                ..
208            } => {
209                if !items.is_empty()
210                    && items[textlist.selected].id() != iteminfo.item.as_ref().unwrap().id()
211                {
212                    iteminfo.item = Some(items[textlist.selected].clone())
213                }
214            }
215            _ => {}
216        }
217    }
218
219    /// check if self should be able to be selected
220    pub fn selectable(&self) -> bool {
221        !(matches!(self, Self::Main { .. }) || matches!(self, Self::None))
222    }
223}
224
225impl FrameworkItem for ChannelDisplay {
226    fn render(
227        &mut self,
228        frame: &mut ratatui::Frame<ratatui::backend::CrosstermBackend<std::io::Stdout>>,
229        framework: &mut tui_additions::framework::FrameworkClean,
230        area: ratatui::layout::Rect,
231        popup_render: bool,
232        info: tui_additions::framework::ItemInfo,
233    ) {
234        if popup_render {
235            return;
236        }
237
238        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
239        self.update_appearance(&info, appearance);
240        let border_style = Style::default().fg(if info.hover {
241            appearance.colors.outline_hover
242        } else if info.selected {
243            appearance.colors.outline_selected
244        } else {
245            appearance.colors.outline
246        });
247
248        // matches itself to render differently depending on the enum variation
249        match self {
250            Self::None => {
251                // the block is created when rendered because its quite simple and should not be a
252                // performance issue
253                let block = Block::default()
254                    .border_type(appearance.borders)
255                    .borders(Borders::ALL)
256                    .border_style(border_style);
257                frame.render_widget(block, area);
258            }
259            Self::Main { iteminfo, .. } => {
260                let block = Block::default()
261                    .border_type(appearance.borders)
262                    .borders(Borders::ALL)
263                    .border_style(border_style);
264                let inner = block.inner(area);
265
266                frame.render_widget(block, area);
267                iteminfo.render(frame, framework, inner, popup_render, info);
268            }
269            Self::Videos {
270                textlist,
271                iteminfo,
272                grid,
273                ..
274            }
275            | Self::Playlists {
276                textlist,
277                iteminfo,
278                grid,
279                ..
280            } => {
281                let inner = &grid.chunks(area).unwrap()[0];
282
283                frame.render_widget(grid.clone(), area);
284                textlist.set_height(inner[0].height);
285                frame.render_widget(textlist.clone(), inner[0]);
286                iteminfo.render(frame, framework, inner[1], popup_render, info);
287            }
288        }
289    }
290
291    fn select(&mut self, _framework: &mut tui_additions::framework::FrameworkClean) -> bool {
292        self.selectable()
293    }
294
295    fn key_event(
296        &mut self,
297        framework: &mut tui_additions::framework::FrameworkClean,
298        key: crossterm::event::KeyEvent,
299        _info: tui_additions::framework::ItemInfo,
300    ) -> Result<(), Box<dyn std::error::Error>> {
301        let action = if let Some(action) = framework
302            .data
303            .global
304            .get::<KeyBindingsConfig>()
305            .unwrap()
306            .get(key)
307        {
308            action
309        } else {
310            return Ok(());
311        };
312
313        match self {
314            Self::Videos {
315                videos,
316                textlist,
317                iteminfo,
318                ..
319            } => {
320                let updated = match action {
321                    KeyAction::MoveUp => textlist.up().is_ok(),
322                    KeyAction::MoveDown => textlist.down().is_ok(),
323                    KeyAction::MoveLeft | KeyAction::First => textlist.first().is_ok(),
324                    KeyAction::MoveRight | KeyAction::End => textlist.last().is_ok(),
325                    KeyAction::Select => {
326                        self.select_at_cursor(framework);
327                        return Ok(());
328                    }
329                    _ => false,
330                };
331
332                // only update iteminfo (it requires cloning) if changed and not empty
333                if updated && !videos.is_empty() {
334                    framework
335                        .data
336                        .state
337                        .get_mut::<Tasks>()
338                        .unwrap()
339                        .priority
340                        .push(Task::RenderAll);
341                    framework
342                        .data
343                        .global
344                        .get_mut::<Status>()
345                        .unwrap()
346                        .render_image = true;
347                    iteminfo.item = Some(videos[textlist.selected].clone());
348                    set_envs(
349                        self.infalte_item_update(
350                            framework.data.global.get::<MainConfig>().unwrap(),
351                            framework.data.global.get::<Status>().unwrap(),
352                        )
353                        .into_iter(),
354                        &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
355                    );
356                }
357            }
358            Self::Playlists {
359                playlists,
360                textlist,
361                iteminfo,
362                ..
363            } => {
364                let updated = match action {
365                    KeyAction::MoveUp => textlist.up().is_ok(),
366                    KeyAction::MoveDown => textlist.down().is_ok(),
367                    KeyAction::MoveLeft => textlist.first().is_ok(),
368                    KeyAction::MoveRight => textlist.last().is_ok(),
369                    KeyAction::Select => {
370                        self.select_at_cursor(framework);
371                        return Ok(());
372                    }
373                    _ => false,
374                };
375
376                if updated && !playlists.is_empty() {
377                    framework
378                        .data
379                        .state
380                        .get_mut::<Tasks>()
381                        .unwrap()
382                        .priority
383                        .push(Task::RenderAll);
384                    framework
385                        .data
386                        .global
387                        .get_mut::<Status>()
388                        .unwrap()
389                        .render_image = true;
390                    iteminfo.item = Some(playlists[textlist.selected].clone());
391                }
392            }
393            _ => {}
394        }
395
396        Ok(())
397    }
398
399    fn load_item(
400        &mut self,
401        framework: &mut tui_additions::framework::FrameworkClean,
402        _info: tui_additions::framework::ItemInfo,
403    ) -> Result<(), Box<dyn std::error::Error>> {
404        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
405        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
406        let page = framework.data.state.get::<Page>().unwrap().channeldisplay();
407
408        match page.r#type {
409            ChannelDisplayPageType::Main => {
410                let channel = Item::from_full_channel(
411                    framework
412                        .data
413                        .global
414                        .get::<InvidiousClient>()
415                        .unwrap()
416                        .0
417                        .channel(&page.id, None)?,
418                    mainconfig.image_index,
419                );
420                if mainconfig.images.display() {
421                    download_all_images(vec![(&channel).into()]);
422                }
423                *self = Self::Main {
424                    iteminfo: ItemInfo::new(Some(channel.clone())),
425                    channel,
426                }
427            }
428            ChannelDisplayPageType::Videos => {
429                let videos = framework
430                    .data
431                    .global
432                    .get::<InvidiousClient>()
433                    .unwrap()
434                    .0
435                    .channel_videos(&page.id, None)?
436                    .videos
437                    .into_iter()
438                    .map(|video| Item::from_channel_video(video, mainconfig.image_index))
439                    .collect::<Vec<_>>();
440                if mainconfig.images.display() {
441                    download_all_images(videos.iter().map(|item| item.into()).collect());
442                }
443                *self = Self::Videos {
444                    textlist: TextList::default()
445                        .ascii_only(!mainconfig.allow_unicode)
446                        .border_type(appearance.borders)
447                        .style(Style::default().fg(appearance.colors.text))
448                        .items(&videos)?,
449                    iteminfo: ItemInfo::new(videos.first().cloned()),
450                    grid: Grid::new(
451                        vec![Constraint::Percentage(60), Constraint::Percentage(40)],
452                        vec![Constraint::Percentage(100)],
453                    )?
454                    .border_type(appearance.borders),
455                    videos,
456                };
457            }
458            ChannelDisplayPageType::Playlists => {
459                let playlists = framework
460                    .data
461                    .global
462                    .get::<InvidiousClient>()
463                    .unwrap()
464                    .0
465                    .channel_playlists(&page.id, None)?
466                    .playlists
467                    .into_iter()
468                    .map(Item::from_channel_playlist)
469                    .collect::<Vec<_>>();
470                if mainconfig.images.display() {
471                    download_all_images(playlists.iter().map(|item| item.into()).collect());
472                }
473                *self = Self::Playlists {
474                    textlist: TextList::default()
475                        .ascii_only(!mainconfig.allow_unicode)
476                        .border_type(appearance.borders)
477                        .style(Style::default().fg(appearance.colors.text))
478                        .items(&playlists)?,
479                    iteminfo: ItemInfo::new(playlists.first().cloned()),
480                    grid: Grid::new(
481                        vec![Constraint::Percentage(60), Constraint::Percentage(40)],
482                        vec![Constraint::Percentage(100)],
483                    )?
484                    .border_type(appearance.borders),
485                    playlists,
486                };
487            }
488        }
489
490        set_envs(
491            self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
492                .into_iter(),
493            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
494        );
495
496        Ok(())
497    }
498
499    fn mouse_event(
500        &mut self,
501        framework: &mut tui_additions::framework::FrameworkClean,
502        x: u16,
503        y: u16,
504        _absolute_x: u16,
505        _absolute_y: u16,
506    ) -> bool {
507        match self {
508            Self::None | Self::Main { .. } => return false,
509            Self::Videos { textlist, grid, .. } | Self::Playlists { textlist, grid, .. } => {
510                let chunk = grid
511                    .chunks(
512                        if let Some(prev_frame) =
513                            framework.data.global.get::<Status>().unwrap().prev_frame
514                        {
515                            prev_frame
516                        } else {
517                            return false;
518                        },
519                    )
520                    .unwrap()[0][0];
521
522                if !chunk.intersects(Rect::new(x, y, 1, 1)) {
523                    return false;
524                }
525
526                let y = (y - chunk.y) as usize + textlist.scroll;
527
528                // clicking on already selected item
529                if y == textlist.selected
530                    || y == textlist.selected + 2
531                    || y == textlist.selected + 1
532                {
533                    self.select_at_cursor(framework);
534                    return true;
535                }
536
537                // clicking on rows after the last item
538                if y > textlist.items.len() + 1 {
539                    return false;
540                }
541
542                // moving the cursor
543                if y <= textlist.selected {
544                    textlist.selected = y;
545                } else if y >= textlist.selected + 2 {
546                    textlist.selected = y - 2;
547                }
548
549                self.update();
550
551                // render the new image
552                framework
553                    .data
554                    .global
555                    .get_mut::<Status>()
556                    .unwrap()
557                    .render_image = true;
558            }
559        }
560        set_envs(
561            self.infalte_item_update(
562                framework.data.global.get::<MainConfig>().unwrap(),
563                framework.data.global.get::<Status>().unwrap(),
564            )
565            .into_iter(),
566            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
567        );
568
569        true
570    }
571}