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