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