src/global/structs/tasks.rs
237 lines · 7393 bytes
1use crate::config::{AppearanceConfig, MinDimentions};
2
3use super::{message::Message, page::Page, status::Status};
4use std::{error::Error, io::Stdout, mem};
5use tui::{
6 backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal,
7};
8use tui_additions::framework::{CursorState, Framework};
9use typemap::Key;
10
11/// tasks to be put on taskqueues
12#[derive(Clone)]
13pub enum Task {
14 RenderAll,
15 Reload,
16 RenderOnly(usize, usize),
17 LoadPage(Page),
18 ClearPage,
19 LazyRendered,
20}
21
22/// multiple tasks joined together, with duplicates removed
23#[derive(Clone, PartialEq, Eq)]
24pub struct TaskQueue {
25 pub render: RenderTask,
26 pub reload: bool,
27 pub load_page: Option<Page>,
28 pub clear_all: bool,
29 pub lazy_rendered: bool,
30}
31
32impl Default for TaskQueue {
33 fn default() -> Self {
34 Self {
35 render: RenderTask::None,
36 reload: false,
37 load_page: None,
38 clear_all: false,
39 lazy_rendered: false,
40 }
41 }
42}
43
44impl TaskQueue {
45 // add task to queue
46 pub fn push(&mut self, task: Task) {
47 match task {
48 Task::RenderAll => self.render = RenderTask::All,
49 Task::Reload => self.reload = true,
50 Task::RenderOnly(x, y) => match &mut self.render {
51 RenderTask::Only(renders) => {
52 if !renders.contains(&(x, y)) {
53 renders.push((x, y));
54 println!("{:?}", self.render);
55 }
56 }
57 RenderTask::None => self.render = RenderTask::Only(vec![(x, y)]),
58 _ => {}
59 },
60 Task::LoadPage(page) => self.load_page = Some(page),
61 Task::ClearPage => self.clear_all = true,
62 Task::LazyRendered => self.lazy_rendered = true,
63 // _ => {}
64 }
65 }
66
67 pub fn is_empty(&self) -> bool {
68 self == &Self::default()
69 }
70
71 // runs all tasks in a task queue
72 pub fn run(
73 self,
74 framework: &mut Framework,
75 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
76 ) -> Result<(), Box<dyn Error>> {
77 if self.clear_all {
78 terminal.clear()?;
79 }
80
81 if self.lazy_rendered {
82 framework
83 .data
84 .global
85 .get_mut::<Status>()
86 .unwrap()
87 .render_image = false;
88 }
89
90 // save state in history, then replace all items by whats in the new page and run `.load()` on them
91 if let Some(page) = self.load_page {
92 *framework.data.global.get_mut::<Message>().unwrap() =
93 Message::Message(page.load_msg(framework));
94 framework.push_history();
95 framework.cursor = CursorState::default();
96
97 let page_config = page.to_page_config(framework);
98 *framework.data.state.get_mut::<MinDimentions>().unwrap() =
99 MinDimentions::new(page_config.min_width(), page_config.min_height());
100
101 let state = page_config.to_state(framework);
102 framework.set_state(state);
103 framework.data.global.get_mut::<Status>().unwrap().reset();
104 *framework.data.state.get_mut::<Page>().unwrap() = page;
105 Self::render_force_clear(framework, terminal)?;
106 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
107
108 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
109 {
110 Message::Error(format!("{}", e))
111 } else {
112 Message::None
113 };
114 Self::render(framework, terminal)?;
115 }
116
117 if self.reload {
118 // reload simply runs `.load()` on all items
119 *framework.data.global.get_mut::<Message>().unwrap() =
120 Message::Message(String::from("Reloading page..."));
121 Self::render_force_clear(framework, terminal)?;
122 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
123 {
124 Message::Error(format!("{}", e))
125 } else {
126 Message::None
127 };
128 Self::render(framework, terminal)?;
129 }
130
131 match self.render {
132 RenderTask::All => {
133 Self::render(framework, terminal)?;
134 }
135 RenderTask::Only(_locations) => {
136 // need to file an issue to tui-rs suggesting this as a feature
137 unimplemented!("tui-rs does not support partial re-rendering");
138 }
139 RenderTask::None => {}
140 }
141
142 Ok(())
143 }
144
145 // the render task runs this function
146 pub fn render(
147 framework: &mut Framework,
148 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
149 ) -> Result<(), Box<dyn Error>> {
150 terminal.draw(|frame| {
151 Self::render_with_frame(framework, frame);
152 })?;
153
154 Ok(())
155 }
156
157 // this function force clears the terminal before rendering, removing sixels and halfblock images
158 pub fn render_force_clear(
159 framework: &mut Framework,
160 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
161 ) -> Result<(), Box<dyn Error>> {
162 terminal.clear()?;
163 terminal.draw(|frame| {
164 Self::render_with_frame(framework, frame);
165 })?;
166
167 Ok(())
168 }
169
170 pub fn render_with_frame(
171 framework: &mut Framework,
172 frame: &mut Frame<CrosstermBackend<Stdout>>,
173 ) {
174 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
175 let area = frame.size();
176
177 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
178 if area.width < min_dimentions.width || area.height < min_dimentions.height {
179 let paragraph = Paragraph::new(format!(
180 "{}Current: {} x {}\nRequired: {} x {}",
181 "\n".repeat(area.height as usize / 2 - 1),
182 area.width,
183 area.height,
184 min_dimentions.width,
185 min_dimentions.height
186 ))
187 .alignment(Alignment::Center)
188 .style(
189 Style::default().fg(framework
190 .data
191 .global
192 .get::<AppearanceConfig>()
193 .unwrap()
194 .colors
195 .text_error),
196 );
197 frame.render_widget(paragraph, area);
198 return;
199 }
200
201 framework.render(frame);
202 }
203}
204
205/// a single task
206#[derive(Clone, PartialEq, Eq, Debug)]
207pub enum RenderTask {
208 All,
209 None,
210 Only(Vec<(usize, usize)>),
211}
212
213/// priority will get executed first, last will get executed after priority queue finished
214#[derive(Clone, Default)]
215pub struct Tasks {
216 pub priority: TaskQueue,
217 pub last: TaskQueue,
218}
219
220impl Tasks {
221 // clears and returns the `priority` task queue, if it is already cleared then returns the `last` task queue
222 pub fn pop(&mut self) -> Option<TaskQueue> {
223 if !self.priority.is_empty() {
224 return Some(mem::take(&mut self.priority));
225 }
226
227 if !self.last.is_empty() {
228 return Some(mem::take(&mut self.last));
229 }
230
231 None
232 }
233}
234
235impl Key for Tasks {
236 type Value = Self;
237}