src/items/channeldisplay.rs

572 lines · 20785 bytes

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