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