-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathinit.rs
More file actions
363 lines (322 loc) · 12.3 KB
/
Copy pathinit.rs
File metadata and controls
363 lines (322 loc) · 12.3 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//! Contains functions that initialize minus
//!
//! This module provides two main functions:-
//! * The [`init_core`] function which is responsible for setting the initial state of the
//! Pager, do environment checks and initializing various core functions on either async
//! tasks or native threads depending on the feature set
//!
//! * The [`start_reactor`] function displays the displays the output and also polls
//! the [`Receiver`] held inside the [`Pager`] for events. Whenever a event is
//! detected, it reacts to it accordingly.
use crate::{
Pager, PagerState,
error::MinusError,
hooks::Hook,
input::InputEvent,
minus_core::{
RunMode,
commands::Command,
ev_handler::handle_event,
utils::{display::draw_full, term},
},
};
use crossbeam_channel::{Receiver, Sender, TrySendError};
use crossterm::event;
use std::{
io::Write,
panic,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
#[cfg(not(test))]
use std::io::stdout;
#[cfg(feature = "search")]
use parking_lot::Condvar;
use parking_lot::Mutex;
use super::{CommandQueue, RUNMODE, utils::display::draw_for_change};
/// The main entry point of minus
///
/// This is called by both [`dynamic_paging`](crate::dynamic_paging) and
/// [`page_all`](crate::page_all) functions.
///
/// It first receives all events present inside the [`Pager`]'s receiver
/// and creates the initial state that to be stored inside the [`PagerState`]
///
/// Then it checks if the minus is running in static mode and does some checks:-
/// * If standard output is not a terminal screen, that is if it is a file or block
/// device, minus will write all the data at once to the stdout and quit
///
/// * If the size of the data is less than the available number of rows in the terminal
/// then it displays everything on the main stdout screen at once and quits. This
/// behaviour can be turned off if [`Pager::set_run_no_overflow`] is called
/// by the main application
// Sorry... this behaviour would have been cool to have in async mode, just think about it!!! Many
// implementations were proposed but none were perfect
// It is because implementing this especially with line wrapping and terminal scrolling
// is a a nightmare because terminals are really naughty and more when you have to fight with it
// using your library... your only weapon
// So we just don't take any more proposals about this. It is really frustating to
// to thoroughly test each implementation and fix out all rough edges around it
/// Next it initializes the runtime and calls [`start_reactor`] and a [`event reader`] which is
/// selected based on the enabled feature set:-
///
/// # Errors
///
/// Setting/cleaning up the terminal can fail and IO to/from the terminal can
/// fail.
///
/// [`event reader`]: event_reader
#[allow(clippy::module_name_repetitions)]
#[allow(clippy::too_many_lines)]
pub fn init_core(pager: Pager, rm: RunMode) -> std::result::Result<(), MinusError> {
#[cfg(not(test))]
let mut out = stdout();
#[cfg(test)]
let mut out = Vec::new();
// Is the event reader running
#[cfg(feature = "search")]
let input_thread_running = Arc::new((Mutex::new(true), Condvar::new()));
assert_eq!(
*super::RUNMODE.lock(),
RunMode::Uninitialized,
"Failed to set the RUNMODE. This is caused probably because another instance of minus is already running"
);
#[allow(unused_mut)]
let mut ps = crate::state::PagerState::generate_initial_state(&pager.rx)?;
*super::RUNMODE.lock() = rm;
ps.run_hooks(Hook::PrePagerStart);
// Static mode checks
#[cfg(all(feature = "static_output", not(test)))]
if *RUNMODE.lock() == RunMode::Static {
use {super::utils::display::write_raw_lines, crossterm::tty::IsTty};
// If stdout is not a tty, write everything and quit
if !out.is_tty() {
write_raw_lines(&mut out, &[ps.screen.orig_text], None)?;
*RUNMODE.lock() = RunMode::Uninitialized;
return Ok(());
}
// If number of lines of text is less than available rows, write everything and quit
// unless run_no_overflow is set to true
if ps.screen.formatted_lines_count() <= ps.rows && !ps.run_no_overflow {
write_raw_lines(&mut out, &ps.screen.formatted_lines, Some("\r"))?;
ps.exit();
*RUNMODE.lock() = RunMode::Uninitialized;
return Ok(());
}
}
// Setup terminal, adjust line wraps and get rows
#[cfg(not(test))]
term::setup(&mut out)?;
// Has the user quit
let is_exited = Arc::new(AtomicBool::new(false));
let is_exited2 = is_exited.clone();
{
let panic_hook = panic::take_hook();
panic::set_hook(Box::new(move |pinfo| {
is_exited2.store(true, std::sync::atomic::Ordering::SeqCst);
// HACK: In test we don't care about the cleanup code so just use a separate buffer
// for panic handler.
#[cfg(test)]
let mut out2 = Vec::new();
#[cfg(not(test))]
let mut out2 = stdout();
// While silently ignoring error is considered a bad practice, we are forced to do it here
// as we cannot use the ? and panicking here will (probably?) cause an immediate abort
drop(term::cleanup(&mut out2, true));
panic_hook(pinfo);
}));
}
let ps_mutex = Arc::new(Mutex::new(ps));
let evtx = pager.tx;
let rx = pager.rx;
let p1 = ps_mutex.clone();
#[cfg(feature = "search")]
let input_thread_running2 = input_thread_running.clone();
std::thread::scope(|s| -> crate::Result {
let is_exited3 = is_exited.clone();
let is_exited4 = is_exited.clone();
#[cfg(test)]
let mut out2 = Vec::new();
#[cfg(not(test))]
let mut out2 = stdout();
let t1 = s.spawn(move || {
let res = event_reader(
&evtx,
&p1,
#[cfg(feature = "search")]
&input_thread_running2,
&is_exited3,
);
if res.is_err() {
is_exited3.store(true, std::sync::atomic::Ordering::SeqCst);
}
res
});
let t2 = s.spawn(move || {
let res = start_reactor(
&rx,
&ps_mutex,
&mut out2,
#[cfg(feature = "search")]
&input_thread_running,
&is_exited4,
);
if res.is_err() {
is_exited4.store(true, std::sync::atomic::Ordering::SeqCst);
}
res
});
let r1 = t1.join().unwrap();
let r2 = t2.join().unwrap();
if r1.is_err() || r2.is_err() {
*RUNMODE.lock() = RunMode::Uninitialized;
term::cleanup(&mut out, true)?;
}
r1?;
r2?;
Ok(())
})
}
/// Continuously displays the output and reacts to events
///
/// This function displays the output continuously while also checking for user inputs.
///
/// Whenever a event like a user input or instruction from the main application is detected
/// it will call [`handle_event`] to take required action for the event.
/// Then it will be do some checks if it is really necessory to redraw the screen
/// and redraw if it event requires it to do so.
///
/// For example if all rows in a terminal aren't filled and a
/// [`AppendData`](super::commands::Command::AppendData) event occurs, it is absolutely necessary to
/// update the screen immediately; while if all rows are filled, we can omit to redraw the screen.
#[allow(clippy::too_many_lines)]
fn start_reactor(
rx: &Receiver<Command>,
ps: &Arc<Mutex<PagerState>>,
mut out_lock: impl Write,
#[cfg(feature = "search")] input_thread_running: &Arc<(Mutex<bool>, Condvar)>,
is_exited: &Arc<AtomicBool>,
) -> Result<(), MinusError> {
let mut command_queue = CommandQueue::new();
{
let mut p = ps.lock();
draw_full(&mut out_lock, &mut p)?;
p.run_hooks(Hook::PostPagerStart);
if p.follow_output {
draw_for_change(&mut out_lock, &mut p, &mut (usize::MAX - 1))?;
}
}
let run_mode = *RUNMODE.lock();
match run_mode {
#[cfg(feature = "dynamic_output")]
RunMode::Dynamic => loop {
if is_exited.load(Ordering::SeqCst) {
term::cleanup(&mut out_lock, true)?;
ps.lock().run_hooks(Hook::PostPagerExit);
let mut rm = RUNMODE.lock();
*rm = RunMode::Uninitialized;
drop(rm);
break;
}
let next_command = if command_queue.is_empty() {
rx.recv()
} else {
Ok(command_queue.pop_front().unwrap())
};
let mut p = ps.lock();
if let Ok(Command::Io(ic)) = next_command {
use crate::minus_core::ev_handler::handle_io_command;
handle_io_command(
ic,
&mut out_lock,
&mut p,
&mut command_queue,
#[cfg(feature = "search")]
input_thread_running,
)?;
} else if let Ok(command) = next_command {
handle_event(command, &mut p, &mut command_queue, is_exited);
}
},
#[cfg(feature = "static_output")]
RunMode::Static => {
loop {
if is_exited.load(Ordering::SeqCst) {
// Cleanup the screen
//
// This is not needed in dynamic paging because this is already handled by handle_event
term::cleanup(&mut out_lock, true)?;
ps.lock().run_hooks(Hook::PostPagerExit);
let mut rm = RUNMODE.lock();
*rm = RunMode::Uninitialized;
drop(rm);
break;
}
let next_command = if command_queue.is_empty() {
rx.recv()
} else {
Ok(command_queue.pop_front().unwrap())
};
let mut p = ps.lock();
if let Ok(Command::Io(ic)) = next_command {
use crate::minus_core::ev_handler::handle_io_command;
handle_io_command(
ic,
&mut out_lock,
&mut p,
&mut command_queue,
#[cfg(feature = "search")]
input_thread_running,
)?;
} else if let Ok(command) = next_command {
handle_event(command, &mut p, &mut command_queue, is_exited);
}
}
}
RunMode::Uninitialized => panic!(
"Static variable RUNMODE set to uninitialized.\
This is most likely a bug. Please open an issue to the developers"
),
}
Ok(())
}
fn event_reader(
evtx: &Sender<Command>,
ps: &Arc<Mutex<PagerState>>,
#[cfg(feature = "search")] user_input_active: &Arc<(Mutex<bool>, Condvar)>,
is_exited: &Arc<AtomicBool>,
) -> Result<(), MinusError> {
loop {
if is_exited.load(Ordering::SeqCst) {
break;
}
#[cfg(feature = "search")]
{
let (lock, cvar) = (&user_input_active.0, &user_input_active.1);
cvar.wait_while(&mut lock.lock(), |pending| !*pending);
}
if event::poll(std::time::Duration::from_millis(100))
.map_err(|e| MinusError::HandleEvent(e.into()))?
{
let ev = event::read().map_err(|e| MinusError::HandleEvent(e.into()))?;
let mut guard = ps.lock();
// Get the events
let input = guard.input_register.classify_input(ev, &guard);
if let Some(iev) = input {
if !matches!(iev, InputEvent::Number(_)) {
guard.prefix_num.clear();
guard.format_prompt();
}
if let Err(TrySendError::Disconnected(_)) = evtx.try_send(Command::UserInput(iev)) {
break;
}
} else {
guard.prefix_num.clear();
guard.format_prompt();
}
}
}
Result::<(), MinusError>::Ok(())
}