src/global/structs/tasks.rs
302 lines · 9556 bytes
1use crate::{
2 config::*,
3 global::{functions::*, structs::*},
4};
5
6use std::{error::Error, io::Stdout, mem};
7use tui::{
8 backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal,
9};
10use tui_additions::framework::{CursorState, Framework};
11use typemap::Key;
12
13/// tasks to be put on taskqueues
14#[derive(Clone)]
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)]
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 println!("{:?}", self.render);
60 }
61 }
62 RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]),
63 _ => {}
64 },
65 Task::LoadPage(page) => self.load_page = Some(page),
66 Task::ClearPage => self.clear_all = true,
67 Task::LazyRendered => self.lazy_rendered = true,
68 Task::Command(s) => self.commands.push(s),
69 }
70 }
71
72 pub fn is_empty(&self) -> bool {
73 self == &Self::default()
74 }
75
76 /// runs all tasks in a task queue
77 pub fn run(
78 mut self,
79 framework: &mut Framework,
80 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
81 ) -> Result<(), Box<dyn Error>> {
82 // if there is any commands, run them first as they may modify data, which is rendered
83 // later in this function
84 for command in self.commands.iter() {
85 run_command(command, framework, terminal);
86 }
87
88 if self.clear_all {
89 terminal.clear()?;
90 }
91
92 if self.lazy_rendered {
93 framework
94 .data
95 .global
96 .get_mut::<Status>()
97 .unwrap()
98 .render_image = false;
99 }
100
101 // save state in history, then replace all items by whats in the new page and run `.load()` on them
102 if let Some(page) = self.load_page {
103 *framework.data.global.get_mut::<Message>().unwrap() =
104 Message::Message(page.load_msg(framework));
105 framework.push_history();
106
107 // clear all envs modified by the previous state (keeping ones that are there when the
108 // program launches), then add the envs set in main config
109 clear_envs(&mut framework.data.state.get_mut::<StateEnvs>().unwrap().0);
110 set_envs(
111 framework
112 .data
113 .global
114 .get::<MainConfig>()
115 .unwrap()
116 .env
117 .clone()
118 .into_iter(),
119 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
120 );
121 // reset cursor position
122 framework.cursor = CursorState::default();
123
124 let page_config = page.to_page_config(framework);
125 *framework.data.state.get_mut::<MinDimentions>().unwrap() =
126 MinDimentions::new(page_config.min_width(), page_config.min_height());
127
128 let state = page_config.to_state(framework);
129 framework.set_state(state);
130 framework.data.global.get_mut::<Status>().unwrap().reset();
131 *framework.data.state.get_mut::<Page>().unwrap() = page;
132 Self::render_force_clear(framework, terminal)?;
133 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
134
135 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
136 {
137 Message::Error(e.to_string())
138 } else {
139 Message::None
140 };
141 let status = framework.data.global.get_mut::<Status>().unwrap();
142 status.provider_updated = true;
143 status.render_image = true;
144 self.render = RenderTask::All;
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}