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