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