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