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