summaryrefslogtreecommitdiffstats
path: root/src/process.rs
blob: cbfc88506d9f36d4c9e49f29ad616da3cb631437 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
mod artifact;
mod results;
#[cfg(test)]
mod tests;
pub(crate) mod thread;

use std::{
	io::ErrorKind,
	process::Command,
	sync::{
		atomic::{AtomicBool, Ordering},
		Arc,
	},
};

use anyhow::{anyhow, Error, Result};
use parking_lot::Mutex;

pub(crate) use self::{artifact::Artifact, results::Results, thread::Thread};
use crate::{
	display::Size,
	events,
	events::{Event, MetaEvent},
	input::StandardEvent,
	module::{self, ExitStatus, ModuleHandler, State},
	runtime::ThreadStatuses,
	search::{self, Action, Searchable},
	todo_file::TodoFile,
	view::{RenderContext, State as ViewState},
};

pub(crate) struct Process<ModuleProvider: module::ModuleProvider> {
	ended: Arc<AtomicBool>,
	exit_status: Arc<Mutex<ExitStatus>>,
	input_state: events::State,
	module_handler: Arc<Mutex<ModuleHandler<ModuleProvider>>>,
	paused: Arc<AtomicBool>,
	render_context: Arc<Mutex<RenderContext>>,
	state: Arc<Mutex<State>>,
	thread_statuses: ThreadStatuses,
	todo_file: Arc<Mutex<TodoFile>>,
	view_state: crate::view::State,
	search_state: search::State,
}

impl<ModuleProvider: module::ModuleProvider> Clone for Process<ModuleProvider> {
	fn clone(&self) -> Self {
		Self {
			ended: Arc::clone(&self.ended),
			exit_status: Arc::clone(&self.exit_status),
			input_state: self.input_state.clone(),
			module_handler: Arc::clone(&self.module_handler),
			paused: Arc::clone(&self.paused),
			render_context: Arc::clone(&self.render_context),
			state: Arc::clone(&self.state),
			thread_statuses: self.thread_statuses.clone(),
			todo_file: Arc::clone(&self.todo_file),
			view_state: self.view_state.clone(),
			search_state: self.search_state.clone(),
		}
	}
}

impl<ModuleProvider: module::ModuleProvider> Process<ModuleProvider> {
	pub(crate) fn new(
		initial_display_size: Size,
		todo_file: Arc<Mutex<TodoFile>>,
		module_handler: ModuleHandler<ModuleProvider>,
		input_state: events::State,
		view_state: crate::view::State,
		search_state: search::State,
		thread_statuses: ThreadStatuses,
	) -> Self {
		Self {
			ended: Arc::new(AtomicBool::from(false)),
			exit_status: Arc::new(Mutex::new(ExitStatus::None)),
			input_state,
			module_handler: Arc::new(Mutex::new(module_handler)),
			paused: Arc::new(AtomicBool::from(false)),
			render_context: Arc::new(Mutex::new(RenderContext::new(
				initial_display_size.width(),
				initial_display_size.height(),
			))),
			search_state,
			state: Arc::new(Mutex::new(State::WindowSizeError)),
			thread_statuses,
			todo_file,
			view_state,
		}
	}

	pub(crate) fn is_ended(&self) -> bool {
		self.ended.load(Ordering::Acquire)
	}

	/// Permanently End the event read thread.
	pub(crate) fn end(&self) {
		self.ended.store(true, Ordering::Release);
	}

	pub(crate) fn state(&self) -> State {
		*self.state.lock()
	}

	pub(crate) fn set_state(&self, state: State) {
		*self.state.lock() = state;
	}

	pub(crate) fn exit_status(&self) -> ExitStatus {
		*self.exit_status.lock()
	}

	pub(crate) fn set_exit_status(&self, exit_status: ExitStatus) {
		*self.exit_status.lock() = exit_status;
	}

	pub(crate) fn should_exit(&self) -> bool {
		self.exit_status() != ExitStatus::None || self.is_ended()
	}

	pub(crate) fn is_exit_status_kill(&self) -> bool {
		self.exit_status() == ExitStatus::Kill
	}

	fn activate(&self, previous_state: State) -> Results {
		let mut module_handler = self.module_handler.lock();
		let mut results = module_handler.activate(self.state(), previous_state);
		// always trigger a resize on activate, for modules that track size
		results.enqueue_resize();
		results
	}

	pub(crate) fn render(&self) {
		let render_context = *self.render_context.lock();
		let mut module_handler = self.module_handler.lock();
		let view_data = module_handler.build_view_data(self.state(), &render_context);
		// TODO It is not possible for this to fail. crate::view::State should be updated to not return an error
		self.view_state.render(view_data);
	}

	pub(crate) fn write_todo_file(&self) -> Result<()> {
		self.todo_file.lock().write_file().map_err(Error::from)
	}

	fn deactivate(&self, state: State) -> Results {
		let mut module_handler = self.module_handler.lock();
		module_handler.deactivate(state)
	}

	pub(crate) fn handle_event(&self) -> Option<Results> {
		self.module_handler
			.lock()
			.handle_event(self.state(), &self.input_state.clone(), &self.view_state.clone())
	}

	fn handle_event_artifact(&self, event: Event) -> Results {
		let mut results = Results::new();
		match event {
			Event::Standard(StandardEvent::Exit) => {
				results.exit_status(ExitStatus::Abort);
			},
			Event::Standard(StandardEvent::Kill) => {
				results.exit_status(ExitStatus::Kill);
			},
			Event::Resize(width, height) => {
				self.view_state.resize(width, height);

				let mut render_context = self.render_context.lock();
				render_context.update(width, height);
				if self.state() != State::WindowSizeError && render_context.is_window_too_small() {
					results.state(State::WindowSizeError);
				}
			},
			_ => {},
		};
		results
	}

	fn handle_state(&self, state: State) -> Results {
		let mut results = Results::new();
		let previous_state = self.state();
		if previous_state != state {
			self.set_state(state);
			results.append(self.deactivate(previous_state));
			results.append(self.activate(previous_state));
		}
		results
	}

	fn handle_error(&self, error: &Error, previous_state: Option<State>) -> Results {
		let mut results = Results::new();
		let return_state = previous_state.unwrap_or_else(|| self.state());
		self.set_state(State::Error);
		results.append(self.activate(return_state));
		let mut module_handler = self.module_handler.lock();
		results.append(module_handler.error(State::Error, error));
		results
	}

	fn handle_exit_status(&self, exit_status: ExitStatus) -> Results {
		self.set_exit_status(exit_status);
		Results::new()
	}

	fn handle_enqueue_resize(&self) -> Results {
		let render_context = self.render_context.lock();
		self.input_state.enqueue_event(Event::Resize(
			render_context.width() as u16,
			render_context.height() as u16,
		));
		Results::new()
	}

	fn handle_external_command(&self, external_command: &(String, Vec<String>)) -> Results {
		let mut results = Results::new();

		match self.run_command(external_command) {
			Ok(meta_event) => {
				self.input_state.enqueue_event(Event::from(meta_event));
			},
			Err(err) => {
				results.error_with_return(
					err.context(format!(
						"Unable to run {} {}",
						external_command.0,
						external_command.1.join(" ")
					)),
					State::List,
				);
			},
		}
		results
	}

	fn run_command(&self, external_command: &(String, Vec<String>)) -> Result<MetaEvent> {
		self.view_state.stop();
		self.input_state.pause();

		self.thread_statuses
			.wait_for_status(crate::view::REFRESH_THREAD_NAME, &crate::runtime::Status::Waiting)?