src/app/app.rs

9aedf4a98dfbe60cee47b4e673a37437e309f462
youtube-tui/src/app/app.rs history · blame · raw

411 lines · 12840 bytes

  1use std::{
  2    collections::LinkedList,
  3    sync::{Arc, Mutex},
  4};
  5
  6use crate::{
  7    app::pages::main_menu::*,
  8    structs::{AppHistory, Item, Page, Row, SearchSettings, WatchHistory},
  9    traits::{ItemTrait, PageTrait},
 10};
 11use crossterm::event::KeyCode;
 12use invidious::blocking::Client;
 13use tui::{
 14    backend::Backend,
 15    layout::{Constraint, Direction, Layout},
 16    style::{Color, Style},
 17    widgets::{Block, Paragraph, Wrap},
 18    Frame,
 19};
 20
 21use super::{
 22    config::{Action, Config},
 23    pages::{channel::Channel, item_info::ItemInfo, search::Search},
 24};
 25
 26#[derive(Clone)]
 27pub struct App {
 28    pub config: Config,
 29    pub page: Page,
 30    pub state: Vec<Row>, // Item
 31    pub selectable: Vec<Vec<(usize, usize)>>,
 32    pub hover: Option<(usize, usize)>, // x, y
 33    pub selected: Option<(usize, usize)>,
 34    pub client: Client,
 35    pub message: Option<String>,
 36    pub load: bool,
 37    pub render: bool,
 38    pub popup_focus: bool,
 39    pub history: Vec<AppHistory>,
 40    pub watch_history: WatchHistory,
 41    pub search_settings: SearchSettings,
 42    pub search_text: String,
 43    pub page_no: usize,
 44}
 45
 46pub struct AppNoState {
 47    pub config: Config,
 48    pub page: Page,
 49    pub selectable: Vec<Vec<(usize, usize)>>,
 50    pub hover: Option<(usize, usize)>, // x, y
 51    pub selected: Option<(usize, usize)>,
 52    pub client: Client,
 53    pub message: Option<String>,
 54    pub load: bool,
 55    pub render: bool,
 56    pub popup_focus: bool,
 57    pub history: Vec<AppHistory>,
 58    pub watch_history: WatchHistory,
 59    pub search_settings: SearchSettings,
 60    pub search_text: String,
 61    pub page_no: usize,
 62}
 63
 64impl AppNoState {
 65    pub fn split(app: App) -> (Self, Vec<Row>) {
 66        let out = Self {
 67            config: app.config,
 68            page: app.page,
 69            selectable: app.selectable,
 70            hover: app.hover,
 71            selected: app.selected,
 72            client: app.client,
 73            message: app.message,
 74            load: app.load,
 75            render: app.render,
 76            popup_focus: app.popup_focus,
 77            history: app.history,
 78            watch_history: app.watch_history,
 79            search_settings: app.search_settings,
 80            search_text: app.search_text,
 81            page_no: app.page_no,
 82        };
 83        (out, app.state)
 84    }
 85
 86    pub fn join(app: Self, state: Vec<Row>) -> App {
 87        App {
 88            config: app.config,
 89            page: app.page,
 90            selectable: app.selectable,
 91            hover: app.hover,
 92            selected: app.selected,
 93            client: app.client,
 94            message: app.message,
 95            load: app.load,
 96            render: app.render,
 97            popup_focus: app.popup_focus,
 98            history: app.history,
 99            watch_history: app.watch_history,
100            search_settings: app.search_settings,
101            search_text: app.search_text,
102            page_no: app.page_no,
103            state,
104        }
105    }
106}
107
108impl Default for App {
109    fn default() -> Self {
110        let config = Config::load().unwrap();
111        let state = config.layouts.main_menu.clone().into();
112        let selectable = App::selectable(&state);
113        Self {
114            page: Page::default(),
115            state,
116            selectable,
117            client: Client::new(config.main.server_url.clone()),
118            selected: None,
119            hover: None,
120            message: None,
121            load: true,
122            render: true,
123            popup_focus: false,
124            history: Vec::new(),
125            config,
126            watch_history: WatchHistory::load(),
127            search_settings: SearchSettings::default(),
128            search_text: String::new(),
129            page_no: 1,
130        }
131    }
132}
133
134impl App {
135    pub fn selectable(state: &Vec<Row>) -> Vec<Vec<(usize, usize)>> {
136        let mut selectable = Vec::new();
137
138        for (y, row) in state.iter().enumerate() {
139            let mut row_vec = Vec::new();
140            for (x, row_item) in row.items.iter().enumerate() {
141                if match &row_item.item {
142                    Item::Global(item) => item.selectable(),
143                    Item::MainMenu(item) => item.selectable(),
144                    Item::ItemInfo(item) => item.selectable(),
145                    Item::Search(item) => item.selectable(),
146                    Item::Channel(item) => item.selectable(),
147                } {
148                    row_vec.push((x, y));
149                }
150            }
151            if row_vec.len() != 0 {
152                selectable.push(row_vec);
153            }
154        }
155
156        selectable
157    }
158
159    pub fn key_input(mut self, key: KeyCode) -> App {
160        let action = self.config.keybindings.0.get(&key);
161
162        if let Some((x, y)) = self.selected {
163            if action != Some(&Action::Deselect) {
164                let mut item = self.state[y].items[x].item.clone();
165                let updated;
166                (updated, self) = item.key_input(key, self);
167                if updated {
168                    self.state[y].items[x].item = item;
169                }
170
171                return self;
172            }
173        }
174
175        let action = match action {
176            Some(action) => *action,
177            None => return self,
178        };
179
180        match action {
181            Action::Select => {
182                if self.hover.is_some() && self.selected.is_none() {
183                    let (mut x, mut y) = self.hover.unwrap();
184                    (x, y) = self.selectable[y][x];
185
186                    let select;
187                    (self, select) = self.state[y]
188                        .items
189                        .iter()
190                        .nth(x)
191                        .clone()
192                        .unwrap()
193                        .item
194                        .clone()
195                        .select(self);
196                    if select {
197                        self.selected = Some((x, y));
198                    }
199
200                    return self;
201                }
202            }
203            Action::Deselect => {
204                if self.selected.is_some() {
205                    self.selected = None;
206                    self.popup_focus = false;
207                    return self;
208                }
209            }
210
211            _ => {}
212        }
213
214        match &mut self.hover {
215            Some((x, y)) => match action {
216                Action::Up => {
217                    if *y > 0 {
218                        let temp_y = *y - 1;
219                        if *x > self.selectable[temp_y].len() {
220                            let temp_x = self.selectable[temp_y].len();
221                            if temp_x > self.selectable[*y].len() - 1 {
222                                *x = self.selectable[*y].len() - 1;
223                            }
224                        }
225                        *y -= 1;
226                        if *x > self.selectable[*y].len() - 1 {
227                            *x = self.selectable[*y].len() - 1;
228                        }
229                    }
230                }
231                Action::Down => {
232                    if *y < self.selectable.len() - 1 {
233                        *y += 1;
234                        if *x > self.selectable[*y].len() - 1 {
235                            *x = self.selectable[*y].len() - 1;
236                        }
237                    }
238                }
239
240                Action::Left => {
241                    if *x > 0 {
242                        *x -= 1;
243                    }
244                }
245
246                Action::Right => {
247                    if *x < self.selectable[*y].len() - 1 {
248                        *x += 1;
249                    }
250                }
251
252                _ => {}
253            },
254            None => match action {
255                Action::Up => {
256                    self.hover = Some((0, 0));
257                }
258                Action::Down => {
259                    self.hover = Some((0, self.selectable.len() - 1));
260                }
261                Action::Left => {
262                    self.hover = Some((0, 0));
263                }
264                Action::Right => {
265                    self.hover = Some((0, self.selectable.len() - 1));
266                }
267                _ => {}
268            },
269        }
270
271        self
272    }
273
274    pub fn render<B: Backend>(mut self, frame: &mut Frame<B>) -> Self {
275        let size = frame.size();
276        let mut popups = Vec::new();
277
278        let min = self.page.min(&self.config);
279
280        if size.width < min.0 || size.height < min.1 {
281            let paragraph = Paragraph::new(format!(
282                "Window too small. Minimum size for this page is {} x {}. Current size is {} x {}",
283                min.0, min.1, size.width, size.height
284            ))
285            .block(Block::default())
286            .style(Style::default().fg(Color::Red))
287            .wrap(Wrap { trim: true });
288            frame.render_widget(paragraph, size);
289            return self;
290        }
291
292        let hover_selected = if let Some((x, y)) = self.hover {
293            Some(self.selectable[y][x])
294        } else {
295            None
296        };
297
298        let vertical_chunks = Layout::default()
299            .direction(Direction::Vertical)
300            .constraints(
301                self.state
302                    .iter()
303                    .map(|row| row.height)
304                    .collect::<Vec<Constraint>>(),
305            )
306            .split(size);
307
308        let (mut app, mut state) = AppNoState::split(self);
309
310        for (y, (row, row_chunk)) in state
311            .iter_mut()
312            .zip(vertical_chunks.clone().iter_mut())
313            .enumerate()
314        {
315            let mut constraints = LinkedList::new();
316            let mut length = match row.centered {
317                true => Some(0),
318                false => None,
319            };
320            for item in row.items.iter() {
321                constraints.push_back(item.constraint);
322                if let Some(length_value) = length {
323                    length = Some(match item.constraint {
324                        Constraint::Length(l) | Constraint::Max(l) | Constraint::Min(l) => {
325                            l + length_value
326                        }
327                        Constraint::Percentage(p) => length_value + size.width * p / 100,
328                        _ => unreachable!(),
329                    })
330                }
331            }
332
333            if let Some(i) = length {
334                let extra_constraint = Constraint::Length((size.width - i) / 2);
335                constraints.push_front(extra_constraint);
336            } else {
337                constraints.push_front(Constraint::Length(0));
338            }
339
340            constraints.push_back(Constraint::Length(0));
341
342            let mut chunks = Layout::default()
343                .direction(Direction::Horizontal)
344                .constraints(constraints.into_iter().collect::<Vec<Constraint>>())
345                .split(*row_chunk)
346                .into_iter();
347
348            frame.render_widget(Block::default(), chunks.next().unwrap());
349
350            for (x, (chunk, item)) in chunks
351                .zip(row.items.iter_mut().map(|i| &mut i.item))
352                .enumerate()
353            {
354                let selected = app.selected == Some((x, y));
355
356                let hover = hover_selected == Some((x, y));
357                let popup_focus = app.popup_focus;
358
359                let hold = item.render_item(frame, chunk, app, selected, hover, popup_focus, false);
360
361                app = hold.1;
362
363                if hold.0 {
364                    popups.push((item, selected, hover, chunk));
365                }
366            }
367        }
368
369        for (item, selected, hover, chunk) in popups {
370            let hold = item.render_item(frame, chunk, app, selected, hover, true, true);
371            app = hold.1;
372        }
373
374        self = AppNoState::join(app, state);
375        self
376    }
377
378    pub fn pop(mut self) -> (App, bool) {
379        if self.history.len() == 0 {
380            self.message = Some(String::from("This is the beginning of history"));
381            return (self, false);
382        }
383
384        let app_history = self.history.pop().unwrap();
385
386        self = Self {
387            state: app_history.state,
388            selectable: app_history.selectable,
389            selected: app_history.selected,
390            hover: app_history.hover,
391            message: app_history.message,
392            page: app_history.page,
393            client: app_history.client,
394            load: app_history.load,
395            render: app_history.render,
396            history: self.history.clone(),
397            config: self.config,
398            watch_history: self.watch_history,
399            search_settings: self.search_settings,
400            popup_focus: app_history.popup_focus,
401            search_text: app_history.search_text,
402            page_no: app_history.page_no,
403        };
404
405        (self, true)
406    }
407
408    pub fn home(&mut self) {
409        *self = App::default();
410    }
411}