src/items/channeldisplay.rs

388 lines · 14575 bytes

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