src/items/videolist.rs

513 lines · 16617 bytes

  1use crossterm::event::KeyCode;
  2use tui::{
  3    layout::{Constraint, Rect},
  4    style::Style,
  5};
  6use tui_additions::{
  7    framework::{FrameworkClean, FrameworkItem},
  8    widgets::{Grid, TextList},
  9};
 10use typemap::Key;
 11
 12use crate::{
 13    config::{AppearanceConfig, MainConfig, Provider},
 14    global::{
 15        functions::set_envs,
 16        structs::{
 17            ChannelDisplayPage, ChannelDisplayPageType, Item, MiniVideoItem, Page, StateEnvs,
 18            Status, Subscriptions, Task, Tasks,
 19        },
 20    },
 21};
 22
 23use super::{ItemInfo, SubSelect};
 24
 25#[derive(Clone)]
 26pub struct VideoList {
 27    pub items: Vec<MiniVideoItem>,
 28    pub selector: TextList,
 29    pub display: ItemInfo,
 30    pub grid: Grid,
 31    /// stores the latest known `self.selector.selected`
 32    /// this allows for the item to "remember" its previous items after refreshes
 33    /// if it is reset to 0 after refreshes, is can be displaying different stuff from channelist
 34    pub previous: usize,
 35    /// current channel id, is None if channellist is on `all feeds`
 36    pub channel_id: Option<String>,
 37}
 38
 39impl Default for VideoList {
 40    fn default() -> Self {
 41        Self {
 42            selector: TextList::default(),
 43            display: ItemInfo::default(),
 44            items: Vec::new(),
 45            grid: Grid::new(
 46                vec![Constraint::Percentage(70), Constraint::Percentage(30)],
 47                vec![Constraint::Percentage(100)],
 48            )
 49            .unwrap(),
 50            previous: 0,
 51            channel_id: None,
 52        }
 53    }
 54}
 55
 56impl VideoList {
 57    fn update_appearance(
 58        &mut self,
 59        info: &tui_additions::framework::ItemInfo,
 60        appearance: &AppearanceConfig,
 61    ) {
 62        if info.selected {
 63            self.grid
 64                .set_border_style(Style::default().fg(appearance.colors.outline_selected));
 65            self.selector
 66                .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
 67        } else if info.hover {
 68            self.grid
 69                .set_border_style(Style::default().fg(appearance.colors.outline_hover));
 70            self.selector
 71                .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
 72        } else {
 73            self.grid
 74                .set_border_style(Style::default().fg(appearance.colors.outline));
 75            self.selector
 76                .set_cursor_style(Style::default().fg(appearance.colors.outline));
 77        }
 78    }
 79
 80    fn update_items(&mut self, subscriptions: &Subscriptions, subselect: usize) {
 81        self.previous = subselect;
 82        if subselect == 0 {
 83            // if channellist is at index 0 (first item), then fetch all feeds
 84            self.channel_id = None;
 85            self.items = subscriptions.get_all_videos();
 86        } else if subselect <= subscriptions.0.len() {
 87            // or else, only fetch the one channel
 88            self.channel_id = Some(subscriptions.0[subselect - 1].channel.id.clone());
 89            self.items = subscriptions.0[subselect - 1].videos.clone();
 90        } else {
 91            // no idea when will this be true, just here to prevent some errors.
 92            self.channel_id = None;
 93            self.items.clear();
 94        }
 95    }
 96
 97    fn select_at_cursor(&self, framework: &mut FrameworkClean) {
 98        // if "all feeds" is selected (channel_id is None)
 99        // - Sync all
100        // - ...
101        //
102        // if "all feeds is not selected" (channel_id is Some(id))
103        // - Sync channel
104        // - View channel
105        // - Unsub
106        // - ...
107        match self.selector.selected {
108            // if "all feeds" and index is 0, sync all feeds
109            0 if self.channel_id.is_none() => framework
110                .data
111                .state
112                .get_mut::<Tasks>()
113                .unwrap()
114                .priority
115                .push(Task::Command("syncall".to_string())),
116            // if not "all feeds" and index is 0, sync only 1 feed
117            0 => framework
118                .data
119                .state
120                .get_mut::<Tasks>()
121                .unwrap()
122                .priority
123                .push(Task::Command(format!(
124                    "sync {}",
125                    self.channel_id.clone().unwrap()
126                ))),
127            // if view channel, load the channel page
128            1 if self.channel_id.is_some() => framework
129                .data
130                .state
131                .get_mut::<Tasks>()
132                .unwrap()
133                .priority
134                .push(Task::LoadPage(Page::ChannelDisplay(ChannelDisplayPage {
135                    id: self.channel_id.clone().unwrap(),
136                    r#type: ChannelDisplayPageType::Main,
137                }))),
138            // unsub
139            2 if self.channel_id.is_some() => framework
140                .data
141                .state
142                .get_mut::<Tasks>()
143                .unwrap()
144                .priority
145                .push(Task::Command(format!(
146                    "unsub {} ;; reload",
147                    self.channel_id.clone().unwrap()
148                ))),
149            // otherwise, load the video
150            i => framework
151                .data
152                .state
153                .get_mut::<Tasks>()
154                .unwrap()
155                .priority
156                .push(Task::LoadPage(Page::SingleItem(
157                    crate::global::structs::SingleItemPage::Video(
158                        self.items[i - if self.channel_id.is_some() { 3 } else { 1 }]
159                            .id
160                            .clone(),
161                    ),
162                ))),
163        }
164    }
165
166    fn set_env(&self, framework: &mut FrameworkClean) {
167        // envs to set: hover-video-url and hover-video-id
168        let id = if let Some(item) = &self.display.item {
169            item.id().unwrap().to_string()
170        } else {
171            "invalid".to_string()
172        };
173        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
174        set_envs(
175            [
176                (
177                    String::from("hover-video-url"),
178                    format!(
179                        "{}watch?v={id}",
180                        match framework.data.global.get::<Status>().unwrap().provider {
181                            Provider::YouTube => "https://youtube.com/",
182                            Provider::Invidious => mainconfig.invidious_instance.as_str(),
183                        }
184                    ),
185                ),
186                (String::from("hover-video-id"), id),
187            ]
188            .into_iter(),
189            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
190        )
191    }
192}
193
194fn get_options(is_channel: bool) -> &'static [&'static str] {
195    // different predefined options to display depending on if "all feeds" is selected
196    if is_channel {
197        &["Sync feed", "View channel", "Remove subscription"]
198    } else {
199        &["Sync all feeds"]
200    }
201}
202
203impl FrameworkItem for VideoList {
204    fn load_item(
205        &mut self,
206        framework: &mut tui_additions::framework::FrameworkClean,
207        _info: tui_additions::framework::ItemInfo,
208    ) -> Result<(), Box<dyn std::error::Error>> {
209        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
210
211        self.grid.set_border_type(appearance.borders);
212        self.selector.set_border_type(appearance.borders);
213
214        // put the items into self.items
215        self.update_items(
216            framework.data.global.get::<Subscriptions>().unwrap(),
217            framework
218                .data
219                .global
220                .get::<Status>()
221                .unwrap()
222                .storage
223                .get::<SubSelect>()
224                .unwrap_or(&SubSelect(self.previous))
225                .0,
226        );
227        // update textlist to display the items in self.items
228        self.selector
229            .set_items(
230                &get_options(self.channel_id.is_some())
231                    .iter()
232                    .map(|s| s.to_string())
233                    .chain(self.items.iter().map(|vid| vid.title.clone()))
234                    .collect::<Vec<_>>(),
235            )
236            .unwrap();
237
238        // tell channellist whether an image is being displayed
239        // if yes, then the page is cleared if channellist cursor is moved
240        framework.data.state.insert::<VidSelect>(VidSelect(
241            self.selector.selected > if self.channel_id.is_some() { 2 } else { 0 },
242        ));
243        Ok(())
244    }
245
246    fn render(
247        &mut self,
248        frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
249        framework: &mut tui_additions::framework::FrameworkClean,
250        area: tui::layout::Rect,
251        popup_render: bool,
252        info: tui_additions::framework::ItemInfo,
253    ) {
254        if popup_render {
255            return;
256        }
257
258        if let Some(subselect) = framework
259            .data
260            .global
261            .get::<Status>()
262            .unwrap()
263            .storage
264            .get::<SubSelect>()
265        {
266            self.update_items(
267                framework.data.global.get::<Subscriptions>().unwrap(),
268                subselect.0,
269            );
270            framework
271                .data
272                .state
273                .insert::<VidSelect>(VidSelect(self.selector.selected > 1));
274            self.selector
275                .set_items(
276                    &get_options(self.channel_id.is_some())
277                        .iter()
278                        .map(|s| s.to_string())
279                        .chain(self.items.iter().map(|vid| vid.title.clone()))
280                        .collect::<Vec<_>>(),
281                )
282                .unwrap();
283            self.selector.scroll = 0;
284            self.selector.selected = 0;
285            self.set_env(framework);
286        }
287
288        let chunks = self.grid.chunks(area).unwrap()[0].clone();
289
290        self.update_appearance(
291            &info,
292            framework.data.global.get::<AppearanceConfig>().unwrap(),
293        );
294        frame.render_widget(self.grid.clone(), area);
295        if framework
296            .data
297            .global
298            .get::<Subscriptions>()
299            .unwrap()
300            .0
301            .is_empty()
302        {
303            return;
304        }
305
306        self.selector.set_height(chunks[1].height);
307        frame.render_widget(self.selector.clone(), chunks[0]);
308
309        if self.channel_id.is_some() {
310            match self.selector.selected {
311                0 => {}
312                1 => {}
313                2 => {}
314                _ => self
315                    .display
316                    .render(frame, framework, chunks[1], popup_render, info),
317            }
318        } else {
319            match self.selector.selected {
320                0 => {}
321                _ => self
322                    .display
323                    .render(frame, framework, chunks[1], popup_render, info),
324            }
325        }
326    }
327
328    fn key_event(
329        &mut self,
330        framework: &mut tui_additions::framework::FrameworkClean,
331        key: crossterm::event::KeyEvent,
332        _info: tui_additions::framework::ItemInfo,
333    ) -> Result<(), Box<dyn std::error::Error>> {
334        let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
335        let previously_selected = self.selector.selected;
336        match key.code {
337            KeyCode::Down if self.selector.down().is_ok() => tasks.priority.push(Task::RenderAll),
338            KeyCode::Up if self.selector.up().is_ok() => tasks.priority.push(Task::RenderAll),
339            KeyCode::Left if self.selector.first().is_ok() => tasks.priority.push(Task::RenderAll),
340            KeyCode::Right if self.selector.last().is_ok() => tasks.priority.push(Task::RenderAll),
341            KeyCode::Enter => {
342                self.select_at_cursor(framework);
343                return Ok(());
344            }
345            _ => return Ok(()),
346        }
347
348        let offset = if self.channel_id.is_some() { 3 } else { 1 };
349        if self.selector.selected != previously_selected {
350            if self.selector.selected < offset {
351                self.display.item = None;
352                if previously_selected >= offset {
353                    tasks.priority.push(Task::ClearPage);
354                }
355            } else {
356                self.display.item = self
357                    .items
358                    .get(self.selector.selected - offset)
359                    .map(|item| Item::MiniVideo(item.clone()));
360            }
361            framework
362                .data
363                .state
364                .insert::<VidSelect>(VidSelect(self.selector.selected > 1));
365            framework
366                .data
367                .global
368                .get_mut::<Status>()
369                .unwrap()
370                .render_image = true;
371
372            self.set_env(framework);
373            return Ok(());
374        }
375
376        if self.selector.selected < offset {
377            return Ok(());
378        }
379
380        match framework
381            .data
382            .global
383            .get::<Subscriptions>()
384            .unwrap()
385            .0
386            .get(self.selector.selected - offset)
387        {
388            Some(item)
389                if item.channel.id
390                    != match &self.display.item {
391                        Some(displayed) => displayed.id().unwrap_or_default(),
392                        None => "",
393                    } => {}
394            Some(_) => {}
395            None => self.display.item = None,
396        };
397
398        Ok(())
399    }
400
401    fn mouse_event(
402        &mut self,
403        framework: &mut FrameworkClean,
404        x: u16,
405        y: u16,
406        _absolute_x: u16,
407        _absolute_y: u16,
408    ) -> bool {
409        let chunk = self
410            .grid
411            .chunks(
412                if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
413                {
414                    prev_frame
415                } else {
416                    return false;
417                },
418            )
419            .unwrap()[0][0];
420
421        if !chunk.intersects(Rect::new(x, y, 1, 1)) {
422            return false;
423        }
424
425        let previously_selected = self.selector.selected;
426        let y = (y - chunk.y) as usize + self.selector.scroll;
427
428        if y == self.selector.selected
429            || y == self.selector.selected + 2
430            || y == self.selector.selected + 1
431        {
432            self.select_at_cursor(framework);
433            return true;
434        }
435
436        // clicking on rows after the last item
437        if y > self.selector.items.len() + 1 {
438            return false;
439        }
440
441        // moving the cursor
442        if y <= self.selector.selected {
443            self.selector.selected = y;
444        }
445
446        if y >= self.selector.selected + 2 {
447            self.selector.selected = y - 2;
448        }
449
450        if self.selector.selected == previously_selected {
451            return false;
452        }
453
454        self.update(framework);
455        self.set_env(framework);
456        // render the new image
457        let status = framework.data.global.get_mut::<Status>().unwrap();
458        status.render_image = true;
459        status
460            .storage
461            .insert::<VidSelect>(VidSelect(self.selector.selected > 1));
462
463        if framework.data.state.get::<VidSelect>().unwrap().0 {
464            framework
465                .data
466                .state
467                .get_mut::<Tasks>()
468                .unwrap()
469                .priority
470                .push(Task::ClearPage);
471        }
472        true
473    }
474}
475
476// The below chunk of code is copied from channellist, which is copied from video list, i have no
477// idea what it does
478impl VideoList {
479    pub fn update(&mut self, framework: &mut FrameworkClean) {
480        let offset = if self.channel_id.is_some() { 3 } else { 1 };
481        if self.selector.selected < offset
482            || self.items.get(self.selector.selected - offset).is_none()
483        {
484            framework
485                .data
486                .global
487                .get_mut::<Status>()
488                .unwrap()
489                .render_image = true;
490            framework
491                .data
492                .state
493                .get_mut::<Tasks>()
494                .unwrap()
495                .priority
496                .push(Task::ClearPage);
497            self.display.item = None;
498            return;
499        }
500
501        self.display.item = Some(Item::MiniVideo(
502            self.items[self.selector.selected - offset].clone(),
503        ));
504    }
505}
506
507#[derive(Clone, Copy)]
508// if image is being displayed
509pub struct VidSelect(pub bool);
510
511impl Key for VidSelect {
512    type Value = Self;
513}