src/global/structs/tasks.rs
301 lines · 9501 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 }
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 }
145
146 if self.reload {
147 // same as in loadpage
148 clear_envs(&mut framework.data.state.get_mut::<StateEnvs>().unwrap().0);
149 set_envs(
150 framework
151 .data
152 .global
153 .get::<MainConfig>()
154 .unwrap()
155 .env
156 .clone()
157 .into_iter(),
158 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
159 );
160
161 // reload simply runs `.load()` on all items
162 *framework.data.global.get_mut::<Message>().unwrap() =
163 Message::Message(String::from("Reloading page..."));
164 Self::render_force_clear(framework, terminal)?;
165 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
166 {
167 Message::Error(e.to_string())
168 } else {
169 Message::None
170 };
171 let status = framework.data.global.get_mut::<Status>().unwrap();
172 status.provider_updated = true;
173 status.render_image = true;
174 self.render = RenderTask::All;
175 }
176
177 match self.render {
178 RenderTask::All => {
179 Self::render(framework, terminal)?;
180 }
181 RenderTask::Only(_locations) => {
182 // need to file an issue to tui-rs suggesting this as a feature
183 unimplemented!("tui-rs does not support partial re-rendering");
184 }
185 RenderTask::None => {}
186 }
187
188 if framework
189 .data
190 .global
191 .get::<Status>()
192 .unwrap()
193 .provider_updated
194 {
195 update_provider(&mut framework.data);
196 }
197
198 Ok(())
199 }
200
201 /// the render task runs this function
202 pub fn render(
203 framework: &mut Framework,
204 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
205 ) -> Result<(), Box<dyn Error>> {
206 terminal.draw(|frame| {
207 Self::render_with_frame(framework, frame);
208 })?;
209
210 Ok(())
211 }
212
213 /// this function force clears the terminal before rendering, removing sixels and halfblock images
214 pub fn render_force_clear(
215 framework: &mut Framework,
216 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
217 ) -> Result<(), Box<dyn Error>> {
218 terminal.clear()?;
219 terminal.draw(|frame| {
220 Self::render_with_frame(framework, frame);
221 })?;
222
223 Ok(())
224 }
225
226 /// this function renders onto the given frame
227 pub fn render_with_frame(
228 framework: &mut Framework,
229 frame: &mut Frame<CrosstermBackend<Stdout>>,
230 ) {
231 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
232 let area = frame.size();
233
234 framework
235 .data
236 .global
237 .get_mut::<Status>()
238 .unwrap()
239 .prev_frame = Some(area);
240
241 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
242 if area.width < min_dimentions.width || area.height < min_dimentions.height {
243 let paragraph = Paragraph::new(format!(
244 "{}Current: {} x {}\nRequired: {} x {}",
245 "\n".repeat(area.height as usize / 2 - 1),
246 area.width,
247 area.height,
248 min_dimentions.width,
249 min_dimentions.height
250 ))
251 .alignment(Alignment::Center)
252 .style(
253 Style::default().fg(framework
254 .data
255 .global
256 .get::<AppearanceConfig>()
257 .unwrap()
258 .colors
259 .text_error),
260 );
261 frame.render_widget(paragraph, area);
262 return;
263 }
264
265 framework.render(frame);
266 }
267}
268
269/// a single task
270#[derive(Clone, PartialEq, Eq, Debug)]
271pub enum RenderTask {
272 All,
273 None,
274 Only(Vec<(usize, usize)>),
275}
276
277/// priority will get executed first, last will get executed after priority queue finished
278#[derive(Clone, Default)]
279pub struct Tasks {
280 pub priority: TaskQueue,
281 pub last: TaskQueue,
282}
283
284impl Tasks {
285 // clears and returns the `priority` task queue, if it is already cleared then returns the `last` task queue
286 pub fn pop(&mut self) -> Option<TaskQueue> {
287 if !self.priority.is_empty() {
288 return Some(mem::take(&mut self.priority));
289 }
290
291 if !self.last.is_empty() {
292 return Some(mem::take(&mut self.last));
293 }
294
295 None
296 }
297}
298
299impl Key for Tasks {
300 type Value = Self;
301}