src/global/structs/tasks.rs

354 lines · 11191 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 => Self::render(framework, terminal)?,
180            RenderTask::Only(locations) => Self::render_onlys(framework, terminal, locations)?,
181            RenderTask::None => {}
182        }
183
184        if framework
185            .data
186            .global
187            .get::<Status>()
188            .unwrap()
189            .provider_updated
190        {
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    pub fn render_onlys(
223        framework: &mut Framework,
224        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
225        locations: Vec<(usize, usize)>,
226    ) -> Result<(), Box<dyn Error>> {
227        Self::render_onlys_with_frame(framework, &mut terminal.get_frame(), locations);
228        terminal.flush()?;
229        Ok(())
230    }
231
232    pub fn render_onlys_with_frame(
233        framework: &mut Framework,
234        frame: &mut Frame,
235        locations: Vec<(usize, usize)>,
236    ) {
237        framework.render_only_multiple(frame, &locations);
238    }
239
240    /// this function renders onto the given frame
241    pub fn render_with_frame(framework: &mut Framework, frame: &mut Frame) {
242        let area = frame.area();
243
244        framework
245            .data
246            .global
247            .get_mut::<Status>()
248            .unwrap()
249            .prev_frame = Some(area);
250
251        if Self::protective_screen(framework, frame) {
252            return;
253        }
254
255        framework.render(frame);
256    }
257
258    // pub fn render_filter(
259    //     framework: &mut Framework,
260    //     terminal: &mut Terminal<CrosstermBackend<Stdout>>,
261    //     filter: impl Fn(&Box<dyn FrameworkItem>) -> bool,
262    // ) -> Result<(), Box<dyn Error>> {
263    //     Self::render_filter_with_frame(framework, &mut terminal.get_frame(), filter);
264    //     terminal.flush()?;
265    //     Ok(())
266    // }
267    //
268    // pub fn render_filter_with_frame(
269    //     framework: &mut Framework,
270    //     frame: &mut Frame<CrosstermBackend<Stdout>>,
271    //     filter: impl Fn(&Box<dyn FrameworkItem>) -> bool,
272    // ) {
273    //     let area = frame.size();
274    //
275    //     framework
276    //         .data
277    //         .global
278    //         .get_mut::<Status>()
279    //         .unwrap()
280    //         .prev_frame = Some(area);
281    //
282    //     if Self::protective_screen(framework, frame) {
283    //         return;
284    //     }
285    //
286    //     framework.render_filter(frame, filter);
287    // }
288
289    /// this function renders onto the given frame
290    pub fn protective_screen(framework: &mut Framework, frame: &mut Frame) -> bool {
291        let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
292        let area = frame.area();
293
294        // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
295        if area.width < min_dimentions.width || area.height < min_dimentions.height {
296            let paragraph = Paragraph::new(format!(
297                "{}Current: {} x {}\nRequired: {} x {}",
298                "\n".repeat(area.height as usize / 2 - 1),
299                area.width,
300                area.height,
301                min_dimentions.width,
302                min_dimentions.height
303            ))
304            .alignment(Alignment::Center)
305            .style(
306                Style::default().fg(framework
307                    .data
308                    .global
309                    .get::<AppearanceConfig>()
310                    .unwrap()
311                    .colors
312                    .text_error),
313            );
314            frame.render_widget(paragraph, area);
315            true
316        } else {
317            false
318        }
319    }
320}
321
322/// a single task
323#[derive(Clone, PartialEq, Eq, Debug)]
324pub enum RenderTask {
325    All,
326    None,
327    Only(Vec<(usize, usize)>),
328}
329
330/// priority will get executed first, last will get executed after priority queue finished
331#[derive(Clone, Default)]
332pub struct Tasks {
333    pub priority: TaskQueue,
334    pub last: TaskQueue,
335}
336
337impl Tasks {
338    // clears and returns the `priority` task queue, if it is already cleared then returns the `last` task queue
339    pub fn pop(&mut self) -> Option<TaskQueue> {
340        if !self.priority.is_empty() {
341            return Some(mem::take(&mut self.priority));
342        }
343
344        if !self.last.is_empty() {
345            return Some(mem::take(&mut self.last));
346        }
347
348        None
349    }
350}
351
352impl Key for Tasks {
353    type Value = Self;
354}