src/run.rs

301 lines · 12605 bytes

  1use crossterm::event::{self, Event, MouseButton, MouseEventKind};
  2use std::{error::Error, io::Stdout};
  3use tui::{backend::CrosstermBackend, Terminal};
  4use tui_additions::{
  5    framework::{Framework, FrameworkDirection},
  6    widgets::TextField,
  7};
  8
  9use crate::{
 10    config::{CommandBindings, KeyBindingsConfig, MainConfig},
 11    global::{
 12        functions::{
 13            apply_envs, clear_envs, command_capture, run_command, set_envs, update_provider,
 14        },
 15        structs::{KeyAction, Message, Page, StateEnvs, Status, Task, Tasks},
 16    },
 17};
 18
 19/// the main event loop of the program
 20pub fn run(
 21    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
 22    framework: &mut Framework,
 23) -> Result<(), Box<dyn Error>> {
 24    loop {
 25        // repeat forever until all tasks are ran (and Tasks is cleared)
 26        if let Some(tasks) = framework.data.state.get_mut::<Tasks>().unwrap().pop() {
 27            tasks.run(framework, terminal)?;
 28            continue;
 29        }
 30
 31        // exits the function is `.exit` is true - a way for items/commands to exit the program
 32        if framework.data.global.get::<Status>().unwrap().exit {
 33            break;
 34        }
 35        *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
 36
 37        match event::read()? {
 38            Event::Mouse(mouse)
 39                if framework
 40                    .data
 41                    .global
 42                    .get::<MainConfig>()
 43                    .unwrap()
 44                    .mouse_support =>
 45            {
 46                if mouse.kind != MouseEventKind::Down(MouseButton::Left) {
 47                    continue;
 48                }
 49
 50                *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
 51
 52                let status = framework.data.global.get_mut::<Status>().unwrap();
 53                status.command_capture = None;
 54
 55                // check if the search filter popup is clicked
 56                let mut searchfilter_clicked = false;
 57                if status.search_filter_opened {
 58                    let (mut frameworkclean, state) = framework.split_clean();
 59                    for row in state.0.iter_mut() {
 60                        for item in row.items.iter_mut() {
 61                            match item.item.r#type() {
 62                                "youtube_tui::items::searchfilters::SearchFilter" => {
 63                                    if item.item.mouse_event(
 64                                        &mut frameworkclean,
 65                                        0,
 66                                        0,
 67                                        mouse.column,
 68                                        mouse.row,
 69                                    ) {
 70                                        searchfilter_clicked = true;
 71                                        break;
 72                                    }
 73                                }
 74                                _ => {}
 75                            }
 76                        }
 77
 78                        if searchfilter_clicked {
 79                            break;
 80                        }
 81                    }
 82                }
 83
 84                let updated = if searchfilter_clicked {
 85                    true
 86                } else {
 87                    framework.mouse_event(mouse.column, mouse.row)
 88                };
 89
 90                if updated {
 91                    framework
 92                        .data
 93                        .state
 94                        .get_mut::<Tasks>()
 95                        .unwrap()
 96                        .priority
 97                        .push(Task::RenderAll);
 98                }
 99            }
100            Event::Key(key) => {
101                // check if key binds to any commands
102                let command_to_run = framework
103                    .data
104                    .global
105                    .get::<CommandBindings>()
106                    .unwrap()
107                    .get_command(&key, framework.data.state.get::<Page>().unwrap());
108                if !command_to_run.is_empty() {
109                    run_command(&apply_envs(command_to_run), framework, terminal);
110                    framework
111                        .data
112                        .state
113                        .get_mut::<Tasks>()
114                        .unwrap()
115                        .priority
116                        .push(Task::RenderAll);
117                }
118
119                // 1. get the corresponding action
120                // 2. check if action is deselect, if yes, deselect
121                // 3. check is anything is selected, if yes, run `.key_event()` with the key
122                // 4. if nothing is selected, do stuff like moving the cursor or exiting
123
124                let action = framework
125                    .data
126                    .global
127                    .get::<KeyBindingsConfig>()
128                    .unwrap()
129                    .get(key);
130
131                if action == Some(KeyAction::Deselect) {
132                    let _ = framework.deselect();
133                    framework
134                        .data
135                        .state
136                        .get_mut::<Tasks>()
137                        .unwrap()
138                        .priority
139                        .push(Task::RenderAll);
140                    framework
141                        .data
142                        .global
143                        .get_mut::<Status>()
144                        .unwrap()
145                        .command_capture = None;
146                    continue;
147                }
148
149                // if something is selected, pass the key input into that item
150                // if nothing is selected, the following big chunk of code handles to movement of
151                // cursor and stuff
152                if framework.is_selected() {
153                    if let Err(e) = framework.key_input(key) {
154                        *framework.data.global.get_mut::<Message>().unwrap() =
155                            Message::Error(format!("{}", e));
156                    };
157                    continue;
158                }
159
160                // the first part check for if the keys should be captured for entering commands
161                if framework
162                    .data
163                    .global
164                    .get::<Status>()
165                    .unwrap()
166                    .command_capture
167                    .is_some()
168                    // the second part runs the command, and see if the returned boolean
169                    // `is_updated` is true, if so update the screen
170                    && command_capture(&mut framework.split_clean().0, key)
171                {
172                    framework
173                        .data
174                        .state
175                        .get_mut::<Tasks>()
176                        .unwrap()
177                        .priority
178                        .push(Task::RenderAll);
179                    continue;
180                }
181
182                if let Some(action) = action {
183                    let mut render = true;
184                    match action {
185                        KeyAction::StartCommandCapture => {
186                            framework
187                                .data
188                                .global
189                                .get_mut::<Status>()
190                                .unwrap()
191                                .command_capture = Some(TextField::default());
192                        }
193                        KeyAction::Exit => break,
194                        KeyAction::MoveUp => framework.r#move(FrameworkDirection::Up)?,
195                        KeyAction::MoveDown => framework.r#move(FrameworkDirection::Down)?,
196                        KeyAction::MoveLeft => framework.r#move(FrameworkDirection::Left)?,
197                        KeyAction::MoveRight => framework.r#move(FrameworkDirection::Right)?,
198                        KeyAction::Reload => framework
199                            .data
200                            .state
201                            .get_mut::<Tasks>()
202                            .unwrap()
203                            .priority
204                            .push(Task::Reload),
205                        KeyAction::Back => {
206                            if !framework.history.is_empty() {
207                                clear_envs(
208                                    &mut framework.data.state.get::<StateEnvs>().unwrap().0.clone(),
209                                );
210                            }
211                            if framework.revert_last_history().is_err() {
212                                *framework.data.global.get_mut::<Message>().unwrap() =
213                                    Message::Error(String::from(
214                                        "This is already the beginning of history",
215                                    ))
216                            } else {
217                                let status = framework.data.global.get_mut::<Status>().unwrap();
218                                status.render_image = true;
219
220                                update_provider(&mut framework.data);
221                                framework
222                                    .data
223                                    .state
224                                    .get_mut::<Tasks>()
225                                    .unwrap()
226                                    .priority
227                                    .push(Task::ClearPage);
228                                let state_envs =
229                                    framework.data.state.get_mut::<StateEnvs>().unwrap();
230                                set_envs(state_envs.clone().0.into_iter(), &mut state_envs.0);
231                            }
232                        }
233                        KeyAction::FirstHistory => {
234                            if framework.revert_history(0).is_err() {
235                                *framework.data.global.get_mut::<Message>().unwrap() =
236                                    Message::Error(String::from(
237                                        "This is already the beginning of history",
238                                    ))
239                            } else {
240                                let status = framework.data.global.get_mut::<Status>().unwrap();
241                                status.render_image = true;
242
243                                update_provider(&mut framework.data);
244                                framework
245                                    .data
246                                    .state
247                                    .get_mut::<Tasks>()
248                                    .unwrap()
249                                    .priority
250                                    .push(Task::ClearPage);
251                            }
252                        }
253                        KeyAction::ClearHistory => {
254                            if framework.history.is_empty() {
255                                *framework.data.global.get_mut::<Message>().unwrap() =
256                                    Message::Error(String::from(
257                                        "This is already the beginning of history",
258                                    ))
259                            } else {
260                                framework.clear_history();
261                                *framework.data.global.get_mut::<Message>().unwrap() =
262                                    Message::Success(String::from("History cleared!"))
263                            }
264                        }
265                        KeyAction::Select => {
266                            let _ = framework.select();
267                        }
268                        _ => render = false,
269                    }
270                    if render {
271                        framework
272                            .data
273                            .state
274                            .get_mut::<Tasks>()
275                            .unwrap()
276                            .priority
277                            .push(Task::RenderAll);
278                    }
279                }
280            }
281            // always render if there is a screen resize event
282            Event::Resize(_, _) => {
283                framework
284                    .data
285                    .state
286                    .get_mut::<Tasks>()
287                    .unwrap()
288                    .priority
289                    .push(Task::RenderAll);
290                framework
291                    .data
292                    .global
293                    .get_mut::<Status>()
294                    .unwrap()
295                    .render_image = true;
296            }
297            _ => {}
298        }
299    }
300    Ok(())
301}