src/items/channeldisplay.rs
696 lines · 25021 bytes
1use super::ItemInfo;
2use crate::{
3 config::*,
4 global::{functions::*, structs::*},
5};
6use invidious::ClientSyncTrait;
7use ratatui::{
8 layout::{Constraint, Rect},
9 style::Style,
10 widgets::{Block, Borders},
11};
12use tui_additions::{
13 framework::{FrameworkClean, FrameworkItem},
14 widgets::{Grid, TextList},
15};
16
17/// the 4 pages that a channel has (including the default "blank" page when loading)
18#[derive(Clone)]
19pub enum ChannelDisplay {
20 /// a blank item, will turn into one of the other variants when `.load()` depending on the page
21 None,
22 /// main channel display page
23 Main {
24 channel: Box<Item>,
25 iteminfo: Box<ItemInfo>,
26 grid: Grid,
27 textlist: TextList,
28 commands: Vec<(String, String)>,
29 },
30 /// latest videos
31 Videos {
32 videos: Vec<Item>,
33 textlist: TextList,
34 iteminfo: Box<ItemInfo>,
35 grid: Grid,
36 },
37 /// created playlists
38 Playlists {
39 playlists: Vec<Item>,
40 textlist: TextList,
41 iteminfo: Box<ItemInfo>,
42 grid: Grid,
43 },
44}
45
46impl Default for ChannelDisplay {
47 fn default() -> Self {
48 Self::None
49 }
50}
51
52impl ChannelDisplay {
53 pub fn new_textlist_with_map(commands: Vec<(String, String)>) -> TextList {
54 TextList::default()
55 .items(
56 &commands
57 .iter()
58 .map(|command| &command.0)
59 .collect::<Vec<_>>(),
60 )
61 .unwrap()
62 }
63
64 fn inflate_load(&self, mainconfig: &MainConfig, status: &Status) -> Vec<(String, String)> {
65 match self {
66 Self::Main { channel, .. } => {
67 vec![
68 (
69 String::from("url"),
70 match status.provider {
71 Provider::Invidious => format!(
72 "{}/channel/{}{}",
73 mainconfig.invidious_instance,
74 channel.id().unwrap_or_default(),
75 match self {
76 Self::None | Self::Main { .. } => "",
77 Self::Videos { .. } => "videos",
78 Self::Playlists { .. } => "playlists",
79 }
80 ),
81 Provider::YouTube => format!("'https://youtu.be/{}'", channel.id().unwrap_or_default()),
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 key_event(
351 &mut self,
352 framework: &mut tui_additions::framework::FrameworkClean,
353 key: crossterm::event::KeyEvent,
354 _info: tui_additions::framework::ItemInfo,
355 ) -> Result<(), Box<dyn std::error::Error>> {
356 let action = if let Some(action) = framework
357 .data
358 .global
359 .get::<KeyBindingsConfig>()
360 .unwrap()
361 .get(key)
362 {
363 action
364 } else {
365 return Ok(());
366 };
367
368 match self {
369 Self::Videos {
370 videos,
371 textlist,
372 iteminfo,
373 ..
374 } => {
375 let updated = match action {
376 KeyAction::MoveUp => textlist.up().is_ok(),
377 KeyAction::MoveDown => textlist.down().is_ok(),
378 KeyAction::MoveLeft | KeyAction::First => textlist.first().is_ok(),
379 KeyAction::MoveRight | KeyAction::End => textlist.last().is_ok(),
380 KeyAction::Select => {
381 self.select_at_cursor(framework);
382 return Ok(());
383 }
384 _ => false,
385 };
386
387 // only update iteminfo (it requires cloning) if changed and not empty
388 if updated && !videos.is_empty() {
389 framework
390 .data
391 .state
392 .get_mut::<Tasks>()
393 .unwrap()
394 .priority
395 .push(Task::RenderAll);
396 framework
397 .data
398 .global
399 .get_mut::<Status>()
400 .unwrap()
401 .render_image = true;
402 iteminfo.item = Some(videos[textlist.selected].clone());
403 set_envs(
404 self.infalte_item_update(
405 framework.data.global.get::<MainConfig>().unwrap(),
406 framework.data.global.get::<Status>().unwrap(),
407 )
408 .into_iter(),
409 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
410 );
411 }
412 }
413 Self::Playlists {
414 playlists,
415 textlist,
416 iteminfo,
417 ..
418 } => {
419 let updated = match action {
420 KeyAction::MoveUp => textlist.up().is_ok(),
421 KeyAction::MoveDown => textlist.down().is_ok(),
422 KeyAction::MoveLeft => textlist.first().is_ok(),
423 KeyAction::MoveRight => textlist.last().is_ok(),
424 KeyAction::Select => {
425 self.select_at_cursor(framework);
426 return Ok(());
427 }
428 _ => false,
429 };
430
431 if updated && !playlists.is_empty() {
432 framework
433 .data
434 .state
435 .get_mut::<Tasks>()
436 .unwrap()
437 .priority
438 .push(Task::RenderAll);
439 framework
440 .data
441 .global
442 .get_mut::<Status>()
443 .unwrap()
444 .render_image = true;
445 iteminfo.item = Some(playlists[textlist.selected].clone());
446 }
447 }
448 Self::Main {
449 textlist, commands, ..
450 } => {
451 let updated = match action {
452 // move the cursor in the textlist, only update the screen if it is changed
453 KeyAction::MoveUp => textlist.up().is_ok(),
454 KeyAction::MoveDown => textlist.down().is_ok(),
455 KeyAction::MoveLeft | KeyAction::First => textlist.first().is_ok(),
456 KeyAction::MoveRight | KeyAction::End => textlist.last().is_ok(),
457 KeyAction::Select => {
458 self.select_at_cursor(framework);
459 framework
460 .data
461 .state
462 .get_mut::<Tasks>()
463 .unwrap()
464 .priority
465 .push(Task::RenderAll);
466 return Ok(());
467 }
468 _ => false,
469 };
470
471 if updated && !commands.is_empty() {
472 framework
473 .data
474 .state
475 .get_mut::<Tasks>()
476 .unwrap()
477 .priority
478 .push(Task::RenderAll);
479 framework
480 .data
481 .global
482 .get_mut::<Status>()
483 .unwrap()
484 .render_image = true;
485 }
486 }
487 _ => {}
488 }
489
490 Ok(())
491 }
492
493 fn load_item(
494 &mut self,
495 framework: &mut tui_additions::framework::FrameworkClean,
496 _info: tui_additions::framework::ItemInfo,
497 ) -> Result<(), Box<dyn std::error::Error>> {
498 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
499 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
500 let page = framework.data.state.get::<Page>().unwrap().channeldisplay();
501
502 match page.r#type {
503 ChannelDisplayPageType::Main => {
504 let channel = Item::from_full_channel(
505 framework
506 .data
507 .global
508 .get::<InvidiousClient>()
509 .unwrap()
510 .0
511 .channel(&page.id, None)?,
512 mainconfig.image_index,
513 );
514 if mainconfig.images.display() {
515 download_all_images(vec![(&channel).into()]);
516 }
517 let commands = framework
518 .data
519 .global
520 .get::<CommandsConfig>()
521 .unwrap()
522 .channel
523 .clone();
524 *self = Self::Main {
525 iteminfo: Box::new(ItemInfo::new(Some(channel.clone()))),
526 channel: Box::new(channel),
527 grid: Grid::new(
528 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
529 vec![Constraint::Percentage(100)],
530 )?
531 .border_type(appearance.borders),
532 textlist: Self::new_textlist_with_map(commands.clone()),
533 commands,
534 }
535 }
536 ChannelDisplayPageType::Videos => {
537 let videos = framework
538 .data
539 .global
540 .get::<InvidiousClient>()
541 .unwrap()
542 .0
543 .channel_videos(&page.id, None)?
544 .videos
545 .into_iter()
546 .map(|video| Item::from_common_video(video, mainconfig.image_index))
547 .collect::<Vec<_>>();
548 if mainconfig.images.display() {
549 download_all_images(videos.iter().map(|item| item.into()).collect());
550 }
551 *self = Self::Videos {
552 textlist: TextList::default()
553 .ascii_only(!mainconfig.allow_unicode)
554 .border_type(appearance.borders)
555 .style(Style::default().fg(appearance.colors.text))
556 .items(&videos)?,
557 iteminfo: Box::new(ItemInfo::new(videos.first().cloned())),
558 grid: Grid::new(
559 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
560 vec![Constraint::Percentage(100)],
561 )?
562 .border_type(appearance.borders),
563 videos,
564 };
565 }
566 ChannelDisplayPageType::Playlists => {
567 let playlists = framework
568 .data
569 .global
570 .get::<InvidiousClient>()
571 .unwrap()
572 .0
573 .channel_playlists(&page.id, None)?
574 .playlists
575 .into_iter()
576 .map(Item::from_common_playlist)
577 .collect::<Vec<_>>();
578 if mainconfig.images.display() {
579 download_all_images(playlists.iter().map(|item| item.into()).collect());
580 }
581 *self = Self::Playlists {
582 textlist: TextList::default()
583 .ascii_only(!mainconfig.allow_unicode)
584 .border_type(appearance.borders)
585 .style(Style::default().fg(appearance.colors.text))
586 .items(&playlists)?,
587 iteminfo: Box::new(ItemInfo::new(playlists.first().cloned())),
588 grid: Grid::new(
589 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
590 vec![Constraint::Percentage(100)],
591 )?
592 .border_type(appearance.borders),
593 playlists,
594 };
595 }
596 }
597
598 set_envs(
599 self
600 .inflate_load(
601 mainconfig,
602 framework.data.global.get::<Status>().unwrap(),
603 )
604 .into_iter(),
605 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
606 );
607
608 set_envs(
609 self.infalte_item_update(mainconfig, framework.data.global.get::<Status>().unwrap())
610 .into_iter(),
611 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
612 );
613
614 Ok(())
615 }
616
617 fn mouse_event(
618 &mut self,
619 framework: &mut tui_additions::framework::FrameworkClean,
620 x: u16,
621 y: u16,
622 _absolute_x: u16,
623 _absolute_y: u16,
624 ) -> bool {
625 let chunk_index = if matches!(self, Self::Main { .. }) {
626 1
627 } else {
628 0
629 };
630 match self {
631 Self::None => return false,
632 Self::Main { textlist, grid, .. }
633 | Self::Videos { textlist, grid, .. }
634 | Self::Playlists { textlist, grid, .. } => {
635 let chunk = grid
636 .chunks(
637 if let Some(prev_frame) =
638 framework.data.global.get::<Status>().unwrap().prev_frame
639 {
640 prev_frame
641 } else {
642 return false;
643 },
644 )
645 .unwrap()[0][chunk_index];
646
647 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
648 return false;
649 }
650
651 let y = (y - chunk.y) as usize + textlist.scroll;
652
653 // clicking on already selected item
654 if y == textlist.selected
655 || y == textlist.selected + 2
656 || y == textlist.selected + 1
657 {
658 self.select_at_cursor(framework);
659 return true;
660 }
661
662 // clicking on rows after the last item
663 if y > textlist.items.len() + 1 {
664 return false;
665 }
666
667 // moving the cursor
668 if y <= textlist.selected {
669 textlist.selected = y;
670 } else if y >= textlist.selected + 2 {
671 textlist.selected = y - 2;
672 }
673
674 self.update();
675
676 // render the new image
677 framework
678 .data
679 .global
680 .get_mut::<Status>()
681 .unwrap()
682 .render_image = true;
683 }
684 }
685 set_envs(
686 self.infalte_item_update(
687 framework.data.global.get::<MainConfig>().unwrap(),
688 framework.data.global.get::<Status>().unwrap(),
689 )
690 .into_iter(),
691 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
692 );
693
694 true
695 }
696}