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