src/global/structs/tasks.rs

302 lines · 9587 bytes

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