src/global/structs/tasks.rs

396 lines · 12290 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, fmt::Debug, io::Stdout, mem, sync::Arc};
 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    Custom(TaskFunction),
 24}
 25
 26#[derive(Clone)]
 27pub struct TaskFunction(Arc<dyn Fn(&mut tui_additions::framework::Framework)>);
 28
 29impl TaskFunction {
 30    pub fn new(f: Arc<dyn Fn(&mut tui_additions::framework::Framework)>) -> Self {
 31        Self(f)
 32    }
 33}
 34
 35impl PartialEq for TaskFunction {
 36    fn eq(&self, _other: &Self) -> bool {
 37        false
 38    }
 39}
 40
 41impl Debug for TaskFunction {
 42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 43        f.write_str("[task function]")
 44    }
 45}
 46
 47impl TaskFunction {
 48    pub fn run(self, framework: &mut tui_additions::framework::Framework) {
 49        self.0(framework);
 50    }
 51}
 52
 53impl Eq for TaskFunction {}
 54
 55/// multiple tasks joined together, with duplicates removed
 56#[derive(Clone, PartialEq, Eq, Debug)]
 57pub struct TaskQueue {
 58    pub render: RenderTask,
 59    pub reload: bool,
 60    pub load_page: Option<Page>,
 61    pub clear_all: bool,
 62    pub lazy_rendered: bool,
 63    pub reload_render: bool,
 64    pub commands: Vec<String>,
 65    pub custom_functions: Vec<TaskFunction>,
 66}
 67
 68impl Default for TaskQueue {
 69    fn default() -> Self {
 70        Self {
 71            render: RenderTask::None,
 72            reload: false,
 73            load_page: None,
 74            clear_all: false,
 75            lazy_rendered: false,
 76            reload_render: true,
 77            commands: Vec::new(),
 78            custom_functions: Vec::new(),
 79        }
 80    }
 81}
 82
 83impl TaskQueue {
 84    /// add task to queue
 85    pub fn push(&mut self, task: Task) {
 86        match task {
 87            Task::RenderAll => self.render = RenderTask::All,
 88            Task::Reload => self.reload = true,
 89            Task::RenderOnly(x, y) => match &mut self.render {
 90                RenderTask::Only(renders) => {
 91                    if !renders.contains(&(x, y)) {
 92                        renders.push((x, y));
 93                    }
 94                }
 95                RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]),
 96                _ => {}
 97            },
 98            Task::LoadPage(page) => self.load_page = Some(page),
 99            Task::ClearPage => self.clear_all = true,
100            Task::LazyRendered => self.lazy_rendered = true,
101            Task::Command(s) => self.commands.push(s),
102            Task::Custom(f) => self.custom_functions.push(f),
103        }
104    }
105
106    pub fn is_empty(&self) -> bool {
107        self == &Self::default()
108    }
109
110    /// runs all tasks in a task queue
111    pub fn run(
112        mut self,
113        framework: &mut Framework,
114        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
115    ) -> Result<(), Box<dyn Error>> {
116        // if there is any commands, run them first as they may modify data, which is rendered
117        // later in this function
118        for command in self.commands.iter() {
119            run_command(command, framework, terminal);
120        }
121
122        if self.clear_all {
123            terminal.clear()?;
124        }
125
126        if self.lazy_rendered {
127            framework
128                .data
129                .global
130                .get_mut::<Status>()
131                .unwrap()
132                .render_image = false;
133        }
134
135        // save state in history, then replace all items by whats in the new page and run `.load()` on them
136        if let Some(page) = self.load_page {
137            *framework.data.global.get_mut::<Message>().unwrap() =
138                Message::Message(page.load_msg(framework));
139            framework.push_history();
140
141            // clear all envs modified by the previous state (keeping ones that are there when the
142            // program launches), then add the envs set in main config
143            clear_envs(&mut framework.data.state.get_mut::<StateEnvs>().unwrap().0);
144            set_envs(
145                framework
146                    .data
147                    .global
148                    .get::<MainConfig>()
149                    .unwrap()
150                    .env
151                    .clone()
152                    .into_iter(),
153                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
154            );
155            // reset cursor position
156            framework.cursor = CursorState::default();
157
158            let page_config = page.to_page_config(framework);
159            *framework.data.state.get_mut::<MinDimentions>().unwrap() =
160                MinDimentions::new(page_config.min_width(), page_config.min_height());
161
162            let state = page_config.to_state(framework);
163            framework.set_state(state);
164            framework.data.global.get_mut::<Status>().unwrap().reset();
165            *framework.data.state.get_mut::<Page>().unwrap() = page;
166            Self::render_force_clear(framework, terminal)?;
167            *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
168
169            *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
170            {
171                Message::Error(e.to_string())
172            } else {
173                Message::None
174            };
175            let status = framework.data.global.get_mut::<Status>().unwrap();
176            status.provider_updated = true;
177            status.render_image = true;
178            self.render = RenderTask::All;
179            run_command(&page_config.command, framework, terminal);
180        }
181
182        if self.reload {
183            // same as in loadpage
184            clear_envs(&mut framework.data.state.get_mut::<StateEnvs>().unwrap().0);
185            set_envs(
186                framework
187                    .data
188                    .global
189                    .get::<MainConfig>()
190                    .unwrap()
191                    .env
192                    .clone()
193                    .into_iter(),
194                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
195            );
196
197            // reload simply runs `.load()` on all items
198            if self.reload_render {
199                *framework.data.global.get_mut::<Message>().unwrap() =
200                    Message::Message(String::from("Reloading page..."));
201                Self::render_force_clear(framework, terminal)?;
202                *framework.data.global.get_mut::<Message>().unwrap() =
203                    if let Err(e) = framework.load() {
204                        Message::Error(e.to_string())
205                    } else {
206                        Message::None
207                    };
208                self.render = RenderTask::All;
209            }
210
211            let status = framework.data.global.get_mut::<Status>().unwrap();
212            status.provider_updated = true;
213            status.render_image = true;
214        }
215
216        match self.render {
217            RenderTask::All => Self::render(framework, terminal)?,
218            RenderTask::Only(locations) => Self::render_onlys(framework, terminal, locations)?,
219            RenderTask::None => {}
220        }
221
222        for custom in self.custom_functions {
223            custom.run(framework)
224        }
225
226        if framework
227            .data
228            .global
229            .get::<Status>()
230            .unwrap()
231            .provider_updated
232        {
233            update_provider(&mut framework.data);
234        }
235
236        Ok(())
237    }
238
239    /// the render task runs this function
240    pub fn render(
241        framework: &mut Framework,
242        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
243    ) -> Result<(), Box<dyn Error>> {
244        terminal.draw(|frame| {
245            Self::render_with_frame(framework, frame);
246        })?;
247
248        Ok(())
249    }
250
251    /// this function force clears the terminal before rendering, removing sixels and halfblock images
252    pub fn render_force_clear(
253        framework: &mut Framework,
254        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
255    ) -> Result<(), Box<dyn Error>> {
256        terminal.clear()?;
257        terminal.draw(|frame| {
258            Self::render_with_frame(framework, frame);
259        })?;
260
261        Ok(())
262    }
263
264    pub fn render_onlys(
265        framework: &mut Framework,
266        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
267        locations: Vec<(usize, usize)>,
268    ) -> Result<(), Box<dyn Error>> {
269        Self::render_onlys_with_frame(framework, &mut terminal.get_frame(), locations);
270        terminal.flush()?;
271        Ok(())
272    }
273
274    pub fn render_onlys_with_frame(
275        framework: &mut Framework,
276        frame: &mut Frame,
277        locations: Vec<(usize, usize)>,
278    ) {
279        framework.render_only_multiple(frame, &locations);
280    }
281
282    /// this function renders onto the given frame
283    pub fn render_with_frame(framework: &mut Framework, frame: &mut Frame) {
284        let area = frame.area();
285
286        framework
287            .data
288            .global
289            .get_mut::<Status>()
290            .unwrap()
291            .prev_frame = Some(area);
292
293        if Self::protective_screen(framework, frame) {
294            return;
295        }
296
297        framework.render(frame);
298    }
299
300    // pub fn render_filter(
301    //     framework: &mut Framework,
302    //     terminal: &mut Terminal<CrosstermBackend<Stdout>>,
303    //     filter: impl Fn(&Box<dyn FrameworkItem>) -> bool,
304    // ) -> Result<(), Box<dyn Error>> {
305    //     Self::render_filter_with_frame(framework, &mut terminal.get_frame(), filter);
306    //     terminal.flush()?;
307    //     Ok(())
308    // }
309    //
310    // pub fn render_filter_with_frame(
311    //     framework: &mut Framework,
312    //     frame: &mut Frame<CrosstermBackend<Stdout>>,
313    //     filter: impl Fn(&Box<dyn FrameworkItem>) -> bool,
314    // ) {
315    //     let area = frame.size();
316    //
317    //     framework
318    //         .data
319    //         .global
320    //         .get_mut::<Status>()
321    //         .unwrap()
322    //         .prev_frame = Some(area);
323    //
324    //     if Self::protective_screen(framework, frame) {
325    //         return;
326    //     }
327    //
328    //     framework.render_filter(frame, filter);
329    // }
330
331    /// this function renders onto the given frame
332    pub fn protective_screen(framework: &mut Framework, frame: &mut Frame) -> bool {
333        let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
334        let area = frame.area();
335
336        // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
337        if area.width < min_dimentions.width || area.height < min_dimentions.height {
338            let paragraph = Paragraph::new(format!(
339                "{}Current: {} x {}\nRequired: {} x {}",
340                "\n".repeat(area.height as usize / 2 - 1),
341                area.width,
342                area.height,
343                min_dimentions.width,
344                min_dimentions.height
345            ))
346            .alignment(Alignment::Center)
347            .style(
348                Style::default().fg(framework
349                    .data
350                    .global
351                    .get::<AppearanceConfig>()
352                    .unwrap()
353                    .colors
354                    .text_error),
355            );
356            frame.render_widget(paragraph, area);
357            true
358        } else {
359            false
360        }
361    }
362}
363
364/// a single task
365#[derive(Clone, PartialEq, Eq, Debug)]
366pub enum RenderTask {
367    All,
368    None,
369    Only(Vec<(usize, usize)>),
370}
371
372/// priority will get executed first, last will get executed after priority queue finished
373#[derive(Clone, Default)]
374pub struct Tasks {
375    pub priority: TaskQueue,
376    pub last: TaskQueue,
377}
378
379impl Tasks {
380    // clears and returns the `priority` task queue, if it is already cleared then returns the `last` task queue
381    pub fn pop(&mut self) -> Option<TaskQueue> {
382        if !self.priority.is_empty() {
383            return Some(mem::take(&mut self.priority));
384        }
385
386        if !self.last.is_empty() {
387            return Some(mem::take(&mut self.last));
388        }
389
390        None
391    }
392}
393
394impl Key for Tasks {
395    type Value = Self;
396}