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