src/items/channeldisplay.rs

559 lines · 20188 bytes

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