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