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