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