src/global/structs/tasks.rs

261 lines · 8073 bytes

  1use crate::{
  2    config::{AppearanceConfig, MinDimentions},
  3    global::functions::run_command,
  4};
  5
  6use super::{message::Message, page::Page, status::Status};
  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
 74    pub fn is_empty(&self) -> bool {
 75        self == &Self::default()
 76    }
 77
 78    // runs all tasks in a task queue
 79    pub fn run(
 80        self,
 81        framework: &mut Framework,
 82        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
 83    ) -> Result<(), Box<dyn Error>> {
 84        // if there is any commands, run them first as they may modify data, which is rendered
 85        // later in this function
 86        for command in self.commands.iter() {
 87            run_command(
 88                &command.split_whitespace().collect::<Vec<_>>(),
 89                framework,
 90                terminal,
 91            );
 92        }
 93
 94        if self.clear_all {
 95            terminal.clear()?;
 96        }
 97
 98        if self.lazy_rendered {
 99            framework
100                .data
101                .global
102                .get_mut::<Status>()
103                .unwrap()
104                .render_image = false;
105        }
106
107        // save state in history, then replace all items by whats in the new page and run `.load()` on them
108        if let Some(page) = self.load_page {
109            *framework.data.global.get_mut::<Message>().unwrap() =
110                Message::Message(page.load_msg(framework));
111            framework.push_history();
112            framework.cursor = CursorState::default();
113
114            let page_config = page.to_page_config(framework);
115            *framework.data.state.get_mut::<MinDimentions>().unwrap() =
116                MinDimentions::new(page_config.min_width(), page_config.min_height());
117
118            let state = page_config.to_state(framework);
119            framework.set_state(state);
120            framework.data.global.get_mut::<Status>().unwrap().reset();
121            *framework.data.state.get_mut::<Page>().unwrap() = page;
122            Self::render_force_clear(framework, terminal)?;
123            *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
124
125            *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
126            {
127                Message::Error(format!("{}", e))
128            } else {
129                Message::None
130            };
131            Self::render(framework, terminal)?;
132        }
133
134        if self.reload {
135            // reload simply runs `.load()` on all items
136            *framework.data.global.get_mut::<Message>().unwrap() =
137                Message::Message(String::from("Reloading page..."));
138            Self::render_force_clear(framework, terminal)?;
139            *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
140            {
141                Message::Error(format!("{}", e))
142            } else {
143                Message::None
144            };
145            Self::render(framework, terminal)?;
146        }
147
148        match self.render {
149            RenderTask::All => {
150                Self::render(framework, terminal)?;
151            }
152            RenderTask::Only(_locations) => {
153                // need to file an issue to tui-rs suggesting this as a feature
154                unimplemented!("tui-rs does not support partial re-rendering");
155            }
156            RenderTask::None => {}
157        }
158
159        Ok(())
160    }
161
162    // the render task runs this function
163    pub fn render(
164        framework: &mut Framework,
165        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
166    ) -> Result<(), Box<dyn Error>> {
167        terminal.draw(|frame| {
168            Self::render_with_frame(framework, frame);
169        })?;
170
171        Ok(())
172    }
173
174    // this function force clears the terminal before rendering, removing sixels and halfblock images
175    pub fn render_force_clear(
176        framework: &mut Framework,
177        terminal: &mut Terminal<CrosstermBackend<Stdout>>,
178    ) -> Result<(), Box<dyn Error>> {
179        terminal.clear()?;
180        terminal.draw(|frame| {
181            Self::render_with_frame(framework, frame);
182        })?;
183
184        Ok(())
185    }
186
187    pub fn render_with_frame(
188        framework: &mut Framework,
189        frame: &mut Frame<CrosstermBackend<Stdout>>,
190    ) {
191        let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
192        let area = frame.size();
193
194        framework
195            .data
196            .global
197            .get_mut::<Status>()
198            .unwrap()
199            .prev_frame = Some(area);
200
201        // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
202        if area.width < min_dimentions.width || area.height < min_dimentions.height {
203            let paragraph = Paragraph::new(format!(
204                "{}Current: {} x {}\nRequired: {} x {}",
205                "\n".repeat(area.height as usize / 2 - 1),
206                area.width,
207                area.height,
208                min_dimentions.width,
209                min_dimentions.height
210            ))
211            .alignment(Alignment::Center)
212            .style(
213                Style::default().fg(framework
214                    .data
215                    .global
216                    .get::<AppearanceConfig>()
217                    .unwrap()
218                    .colors
219                    .text_error),
220            );
221            frame.render_widget(paragraph, area);
222            return;
223        }
224
225        framework.render(frame);
226    }
227}
228
229/// a single task
230#[derive(Clone, PartialEq, Eq, Debug)]
231pub enum RenderTask {
232    All,
233    None,
234    Only(Vec<(usize, usize)>),
235}
236
237/// priority will get executed first, last will get executed after priority queue finished
238#[derive(Clone, Default)]
239pub struct Tasks {
240    pub priority: TaskQueue,
241    pub last: TaskQueue,
242}
243
244impl Tasks {
245    // clears and returns the `priority` task queue, if it is already cleared then returns the `last` task queue
246    pub fn pop(&mut self) -> Option<TaskQueue> {
247        if !self.priority.is_empty() {
248            return Some(mem::take(&mut self.priority));
249        }
250
251        if !self.last.is_empty() {
252            return Some(mem::take(&mut self.last));
253        }
254
255        None
256    }
257}
258
259impl Key for Tasks {
260    type Value = Self;
261}