src/items/channeldisplay.rs
553 lines · 19975 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 download_all_images(vec![(&channel).into()]);
409 *self = Self::Main {
410 iteminfo: ItemInfo::new(Some(channel.clone())),
411 channel,
412 }
413 }
414 ChannelDisplayPageType::Videos => {
415 let videos = framework
416 .data
417 .global
418 .get::<InvidiousClient>()
419 .unwrap()
420 .0
421 .channel_videos(&page.id, None)?
422 .videos
423 .into_iter()
424 .map(|video| Item::from_channel_video(video, mainconfig.image_index))
425 .collect::<Vec<_>>();
426 download_all_images(videos.iter().map(|item| item.into()).collect());
427 *self = Self::Videos {
428 textlist: TextList::default()
429 .ascii_only(!mainconfig.allow_unicode)
430 .border_type(appearance.borders)
431 .style(Style::default().fg(appearance.colors.text))
432 .items(&videos)?,
433 iteminfo: ItemInfo::new(videos.first().cloned()),
434 grid: Grid::new(
435 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
436 vec![Constraint::Percentage(100)],
437 )?
438 .border_type(appearance.borders),
439 videos,
440 };
441 }
442 ChannelDisplayPageType::Playlists => {
443 let playlists = framework
444 .data
445 .global
446 .get::<InvidiousClient>()
447 .unwrap()
448 .0
449 .channel_playlists(&page.id, None)?
450 .playlists
451 .into_iter()
452 .map(Item::from_channel_playlist)
453 .collect::<Vec<_>>();
454 download_all_images(playlists.iter().map(|item| item.into()).collect());
455 *self = Self::Playlists {
456 textlist: TextList::default()
457 .ascii_only(!mainconfig.allow_unicode)
458 .border_type(appearance.borders)
459 .style(Style::default().fg(appearance.colors.text))
460 .items(&playlists)?,
461 iteminfo: ItemInfo::new(playlists.first().cloned()),
462 grid: Grid::new(
463 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
464 vec![Constraint::Percentage(100)],
465 )?
466 .border_type(appearance.borders),
467 playlists,
468 };
469 }
470 }
471
472 set_envs(
473 self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
474 .into_iter(),
475 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
476 );
477
478 Ok(())
479 }
480
481 fn mouse_event(
482 &mut self,
483 framework: &mut tui_additions::framework::FrameworkClean,
484 x: u16,
485 y: u16,
486 _absolute_x: u16,
487 _absolute_y: u16,
488 ) -> bool {
489 match self {
490 Self::None | Self::Main { .. } => return false,
491 Self::Videos { textlist, grid, .. } | Self::Playlists { textlist, grid, .. } => {
492 let chunk = grid
493 .chunks(
494 if let Some(prev_frame) =
495 framework.data.global.get::<Status>().unwrap().prev_frame
496 {
497 prev_frame
498 } else {
499 return false;
500 },
501 )
502 .unwrap()[0][0];
503
504 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
505 return false;
506 }
507
508 let y = (y - chunk.y) as usize + textlist.scroll;
509
510 // clicking on already selected item
511 if y == textlist.selected
512 || y == textlist.selected + 2
513 || y == textlist.selected + 1
514 {
515 self.select_at_cursor(framework);
516 return true;
517 }
518
519 // clicking on rows after the last item
520 if y > textlist.items.len() + 1 {
521 return false;
522 }
523
524 // moving the cursor
525 if y <= textlist.selected {
526 textlist.selected = y;
527 } else if y >= textlist.selected + 2 {
528 textlist.selected = y - 2;
529 }
530
531 self.update();
532
533 // render the new image
534 framework
535 .data
536 .global
537 .get_mut::<Status>()
538 .unwrap()
539 .render_image = true;
540 }
541 }
542 set_envs(
543 self.infalte_item_update(
544 framework.data.global.get::<MainConfig>().unwrap(),
545 framework.data.global.get::<Status>().unwrap(),
546 )
547 .into_iter(),
548 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
549 );
550
551 true
552 }
553}