src/items/channeldisplay.rs

559 lines · 20241 bytes

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