src/global/structs/tasks.rs

297 lines · 9634 bytes

  1use crate::{
  2    config::{AppearanceConfig, MainConfig, MinDimentions},
  3    global::functions::{clear_envs, run_command, set_envs, update_provider},
  4};
  5
  6use super::{message::Message, page::Page, status::Status, StateEnvs};
  7use std::{error::Error, io::Stdout, mem};
  8use tui::{
  9    backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal,
 10};
 11use tui_additions::framework::{CursorState, Framework};
 12use typemap::Key;
 13
 14/// tasks to be put on taskqueues
 15#[derive(Clone)]
 16pub enum Task {
 17    RenderAll,
 18    Reload,
 19    RenderOnly(usize, usize),
 20    LoadPage(Page),
 21    ClearPage,
 22    LazyRendered,
 23    Command(String),
 24}
 25
 26/// multiple tasks joined together, with duplicates removed
 27#[derive(Clone, PartialEq, Eq)]
 28pub struct TaskQueue {
 29    pub render: RenderTask,
 30    pub reload: bool,
 31    pub load_page: Option<Page>,
 32    pub clear_all: bool,
 33    pub lazy_rendered: bool,
 34    pub commands: Vec<String>,
 35}
 36
 37impl Default for TaskQueue {
 38    fn default() -> Self {
 39        Self {
 40            render: RenderTask::None,
 41            reload: false,
 42            load_page: None,
 43            clear_all: false,
 44            lazy_rendered: false,
 45            commands: Vec::new(),
 46        }
 47    }
 48}
 49
 50impl TaskQueue {
 51    /// add task to queue
 52    pub fn push(&mut self, task: Task) {
 53        match task {
 54            Task::RenderAll => self.render = RenderTask::All,
 55            Task::Reload => self.reload = true,
 56            Task::RenderOnly(x, y) => match &mut self.render {
 57                RenderTask::Only(renders) => {
 58                    if !renders.contains(&(x, y)) {
 59                        renders.push((x, y));
 60                        println!("{:?}", self.render);
 61                    }
 62                }
 63                RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]),
 64                _ => {}
 65            },
 66            Task::LoadPage(page) => self.load_page = Some(page),
 67            Task::ClearPage => self.clear_all = true,
 68            Task::LazyRendered => self.lazy_rendered = true,
 69            Task::Command(s) => self.commands.push(s),
 70        }
 71    }
 72
 73    pub fn is_empty(&self) -> bool {
 74        self == &Self::default()
 75    }
 76
 77    /// runs all tasks in a task queue
 78    pub fn run(
 79        mut self,
 80        framework: &mut Framework,
 81        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
 82    ) -> Result<(), Box<dyn Error>> {
 83        // if there is any commands, run them first as they may modify data, which is rendered
 84        // later in this function
 85        for command in self.commands.iter() {
 86            run_command(command, framework, terminal);
 87        }
 88
 89        if self.clear_all {
 90            terminal.clear()?;
 91        }
 92
 93        if self.lazy_rendered {
 94            framework
 95                .data
 96                .global
 97                .get_mut::<Status>()
 98                .unwrap()
 99                .render_image = false;
100        }
101
102        // save state in history, then replace all items by whats in the new page and run `.load()` on them
103        if let Some(page) = self.load_page {
104            *framework.data.global.get_mut::<Message>().unwrap() =
105                Message::Message(page.load_msg(framework));
106            framework.push_history();
107
108            // clear all envs modified by the previous state (keeping ones that are there when the
109            // program launches), then add the envs set in main config
110            clear_envs(&mut framework.data.state.get_mut::<StateEnvs>().unwrap().0);
111            set_envs(
112                framework
113                    .data
114                    .global
115                    .get::<MainConfig>()
116                    .unwrap()
117                    .env
118                    .clone()
119                    .into_iter(),
120                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
121            );
122            // reset cursor position
123            framework.cursor = CursorState::default();
124
125            let page_config = page.to_page_config(framework);
126            *framework.data.state.get_mut::<MinDimentions>().unwrap() =
127                MinDimentions::new(page_config.min_width(), page_config.min_height());
128
129            let state = page_config.to_state(framework);
130            framework.set_state(state);
131            framework.data.global.get_mut::<Status>().unwrap().reset();
132            *framework.data.state.get_mut::<Page>().unwrap() = page;
133            Self::render_force_clear(framework, terminal)?;
134            *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
135
136            *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
137            {
138                Message::Error(e.to_string())
139            } else {
140                Message::None
141            };
142            let status = framework.data.global.get_mut::<Status>().unwrap();
143            status.provider_updated = true;
144            status.render_image = true;
145            self.render = RenderTask::All;
146        }
147
148        if self.reload {
149            // same as in loadpage
150            clear_envs(&mut framework.data.state.get_mut::<StateEnvs>().unwrap().0);
151            set_envs(
152                framework
153                    .data
154                    .global
155                    .get::<MainConfig>()
156                    .unwrap()
157                    .env
158                    .clone()
159                    .into_iter(),
160                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
161            );
162
163            // reload simply runs `.load()` on all items
164            *framework.data.global.get_mut::<Message>().unwrap() =
165                Message::Message(String::from("Reloading page..."));
166            Self::render_force_clear(framework, terminal)?;
167            *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
168            {
169                Message::Error(e.to_string())
170            } else {
171                Message::None
172            };
173            let status = framework.data.global.get_mut::<Status>().unwrap();
174            status.provider_updated = true;
175            status.render_image = true;
176            self.render = RenderTask::All;
177        }
178
179        match self.render {
180            RenderTask::All => {
181                Self::render(framework, terminal)?;
182            }
183            RenderTask::Only(_locations) => {
184                // need to file an issue to tui-rs suggesting this as a feature
185                unimplemented!("tui-rs does not support partial re-rendering");
186            }
187            RenderTask::None => {}
188        }
189
190        if framework.data.global.get::<Status>().unwrap().provider_updated {
191            update_provider(&mut framework.data);
192        }
193
194        Ok(())
195    }
196
197    /// the render task runs this function
198    pub fn render(
199        framework: &mut Framework,
200        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
201    ) -> Result<(), Box<dyn Error>> {
202        terminal.draw(|frame| {
203            Self::render_with_frame(framework, frame);
204        })?;
205
206        Ok(())
207    }
208
209    /// this function force clears the terminal before rendering, removing sixels and halfblock images
210    pub fn render_force_clear(
211        framework: &mut Framework,
212        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
213    ) -> Result<(), Box<dyn Error>> {
214        terminal.clear()?;
215        terminal.draw(|frame| {
216            Self::render_with_frame(framework, frame);
217        })?;
218
219        Ok(())
220    }
221
222    /// this function renders onto the given frame
223    pub fn render_with_frame(
224        framework: &mut Framework,
225        frame: &mut Frame<CrosstermBackend<Stdout>>,
226    ) {
227        let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
228        let area = frame.size();
229
230        framework
231            .data
232            .global
233            .get_mut::<Status>()
234            .unwrap()
235            .prev_frame = Some(area);
236
237        // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
238        if area.width < min_dimentions.width || area.height < min_dimentions.height {
239            let paragraph = Paragraph::new(format!(
240                "{}Current: {} x {}\nRequired: {} x {}",
241                "\n".repeat(area.height as usize / 2 - 1),
242                area.width,
243                area.height,
244                min_dimentions.width,
245                min_dimentions.height
246            ))
247            .alignment(Alignment::Center)
248            .style(
249                Style::default().fg(framework
250                    .data
251                    .global
252                    .get::<AppearanceConfig>()
253                    .unwrap()
254                    .colors
255                    .text_error),
256            );
257            frame.render_widget(paragraph, area);
258            return;
259        }
260
261        framework.render(frame);
262    }
263}
264
265/// a single task
266#[derive(Clone, PartialEq, Eq, Debug)]
267pub enum RenderTask {
268    All,
269    None,
270    Only(Vec<(usize, usize)>),
271}
272
273/// priority will get executed first, last will get executed after priority queue finished
274#[derive(Clone, Default)]
275pub struct Tasks {
276    pub priority: TaskQueue,
277    pub last: TaskQueue,
278}
279
280impl Tasks {
281    // clears and returns the `priority` task queue, if it is already cleared then returns the `last` task queue
282    pub fn pop(&mut self) -> Option<TaskQueue> {
283        if !self.priority.is_empty() {
284            return Some(mem::take(&mut self.priority));
285        }
286
287        if !self.last.is_empty() {
288            return Some(mem::take(&mut self.last));
289        }
290
291        None
292    }
293}
294
295impl Key for Tasks {
296    type Value = Self;
297}