-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathev_handler.rs
More file actions
391 lines (360 loc) · 13.5 KB
/
ev_handler.rs
File metadata and controls
391 lines (360 loc) · 13.5 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
//! Provides the [`handle_event`] function
use std::convert::TryInto;
use std::io::Write;
use std::sync::{atomic::AtomicBool, Arc};
#[cfg(feature = "search")]
use parking_lot::{Condvar, Mutex};
use super::utils::display;
use super::{events::Event, utils::term};
#[cfg(feature = "search")]
use crate::search;
use crate::{error::MinusError, input::InputEvent, PagerState};
/// Respond based on the type of event
///
/// It will match the type of event received and based on that, it can take actions like:-
/// - Mutating fields of [`PagerState`]
/// - Handle cleanup and exits
/// - Call search related functions
#[cfg_attr(not(feature = "search"), allow(unused_mut))]
#[allow(clippy::too_many_lines)]
pub fn handle_event(
ev: Event,
mut out: &mut impl Write,
p: &mut PagerState,
is_exited: &Arc<AtomicBool>,
#[cfg(feature = "search")] user_input_active: &Arc<(Mutex<bool>, Condvar)>,
) -> Result<(), MinusError> {
match ev {
Event::SetData(text) => {
p.lines = text;
p.format_lines();
}
Event::UserInput(InputEvent::Exit) => {
p.exit();
is_exited.store(true, std::sync::atomic::Ordering::SeqCst);
term::cleanup(&mut out, &p.exit_strategy, true)?;
}
Event::UserInput(InputEvent::UpdateUpperMark(mut um)) => {
display::draw_for_change(out, p, &mut um)?;
p.upper_mark = um;
}
Event::UserInput(InputEvent::RestorePrompt) => {
// Set the message to None and new messages to false as all messages have been shown
p.message = None;
p.update_displayed_prompt();
}
Event::UserInput(InputEvent::UpdateTermArea(c, r)) => {
p.rows = r;
p.cols = c;
// Readjust the text wrapping for the new number of columns
p.format_lines();
}
Event::UserInput(InputEvent::UpdateLineNumber(l)) => {
p.line_numbers = l;
p.format_lines();
}
#[cfg(feature = "search")]
Event::UserInput(InputEvent::Search(m)) => {
p.search_mode = m;
// Reset search mark so it won't be out of bounds if we have
// less matches in this search than last time
p.search_mark = 0;
// Pause the main user input thread, read search query and then restart the main input thread
let (lock, cvar) = (&user_input_active.0, &user_input_active.1);
let mut active = lock.lock();
*active = false;
drop(active);
// let string = search::fetch_input(&mut out, p.search_mode, p.rows)?;
let search_result = search::fetch_input(&mut out, p)?;
let mut active = lock.lock();
*active = true;
drop(active);
cvar.notify_one();
// If we have incremental search cache directly use it and return
if let Some(incremental_search_result) = search_result.incremental_search_result {
p.search_term = search_result.compiled_regex;
p.upper_mark = incremental_search_result.upper_mark;
p.search_mark = incremental_search_result.search_mark;
p.search_idx = incremental_search_result.search_idx;
p.formatted_lines = incremental_search_result.formatted_lines;
return Ok(());
}
// If we only have compiled regex cached, use that otherwise compile the original
// string query if its not empty
p.search_term = if search_result.compiled_regex.is_some() {
search_result.compiled_regex
} else if !search_result.string.is_empty() {
let compiled_regex = regex::Regex::new(&search_result.string).ok();
if compiled_regex.is_none() {
p.message = Some("Invalid regular expression. Press Enter".to_owned());
p.update_displayed_prompt();
}
compiled_regex
} else {
return Ok(());
};
// Format the lines, this will automatically generate the PagerState.search_idx
p.format_lines();
// Move to next search match after the current upper_mark
let position_of_next_match = search::next_nth_match(&p.search_idx, p.upper_mark, 1);
if let Some(pnm) = position_of_next_match {
p.search_mark = pnm;
p.upper_mark = *p.search_idx.iter().nth(p.search_mark).unwrap();
}
p.update_displayed_prompt();
display::draw_full(&mut out, p)?;
}
#[cfg(feature = "search")]
Event::UserInput(InputEvent::NextMatch | InputEvent::MoveToNextMatch(1))
if p.search_term.is_some() =>
{
// Move to next search match after the current upper_mark
let position_of_next_match = search::next_nth_match(&p.search_idx, p.upper_mark, 1);
if let Some(pnm) = position_of_next_match {
p.search_mark = pnm;
p.upper_mark = *p.search_idx.iter().nth(p.search_mark).unwrap();
}
p.update_displayed_prompt();
}
#[cfg(feature = "search")]
Event::UserInput(InputEvent::PrevMatch | InputEvent::MoveToPrevMatch(1))
if p.search_term.is_some() =>
{
// If no matches, return immediately
if p.search_idx.is_empty() {
return Ok(());
}
// Decrement the s_mark and get the preceding index
p.search_mark = p.search_mark.saturating_sub(1);
if let Some(y) = p.search_idx.iter().nth(p.search_mark) {
// If the index is less than or equal to the upper_mark, then set y to the new upper_mark
if *y < p.upper_mark {
p.upper_mark = *y;
p.update_displayed_prompt();
}
}
}
#[cfg(feature = "search")]
Event::UserInput(InputEvent::MoveToNextMatch(n)) if p.search_term.is_some() => {
// Move to next nth search match after the current upper_mark
let position_of_next_match = search::next_nth_match(&p.search_idx, p.upper_mark, n);
if let Some(pnm) = position_of_next_match {
p.search_mark = pnm;
p.upper_mark = *p.search_idx.iter().nth(p.search_mark).unwrap();
// Ensure there is enough text available after location corresponding to
// position_of_next_match so that we can display a pagefull of data. If not,
// reduce it so that a pagefull of text can be accommodated.
// NOTE: Add 1 to total number of lines to avoid off-by-one errors
while p.upper_mark.saturating_add(p.rows) > p.num_lines().saturating_add(1) {
p.search_mark = p.search_mark.saturating_sub(1);
p.upper_mark = *p.search_idx.iter().nth(p.search_mark).unwrap();
}
}
p.update_displayed_prompt();
}
#[cfg(feature = "search")]
Event::UserInput(InputEvent::MoveToPrevMatch(n)) if p.search_term.is_some() => {
// If no matches, return immediately
if p.search_idx.is_empty() {
return Ok(());
}
// Decrement the s_mark and get the preceding index
p.search_mark = p.search_mark.saturating_sub(n);
if let Some(y) = p.search_idx.iter().nth(p.search_mark) {
// If the index is less than or equal to the upper_mark, then set y to the new upper_mark
if *y < p.upper_mark {
p.upper_mark = *y;
p.update_displayed_prompt();
}
}
}
Event::AppendData(text) => {
let prev_unterminated = p.unterminated;
let prev_fmt_lines_count = p.num_lines();
let append_style = p.append_str(text.as_str());
if !p.running.lock().is_uninitialized() {
display::draw_append_text(
out,
p,
prev_unterminated,
prev_fmt_lines_count,
append_style,
)?;
return Ok(());
}
}
Event::SetPrompt(ref text) | Event::SendMessage(ref text) => {
if let Event::SetPrompt(_) = ev {
p.prompt = text.to_string();
} else {
p.message = Some(text.to_string());
}
p.update_displayed_prompt();
term::move_cursor(&mut out, 0, p.rows.try_into().unwrap(), false)?;
if !p.running.lock().is_uninitialized() {
super::utils::display::write_prompt(
&mut out,
&p.displayed_prompt,
p.rows.try_into().unwrap(),
)?;
}
}
Event::SetLineNumbers(ln) => {
p.line_numbers = ln;
p.format_lines();
}
Event::SetExitStrategy(es) => p.exit_strategy = es,
#[cfg(feature = "static_output")]
Event::SetRunNoOverflow(val) => p.run_no_overflow = val,
#[cfg(feature = "search")]
Event::IncrementalSearchCondition(cb) => p.incremental_search_condition = cb,
Event::SetInputClassifier(clf) => p.input_classifier = clf,
Event::AddExitCallback(cb) => p.exit_callbacks.push(cb),
Event::UserInput(_) => {}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::super::events::Event;
use super::handle_event;
use crate::{ExitStrategy, PagerState};
use std::sync::{atomic::AtomicBool, Arc};
#[cfg(feature = "search")]
use {
once_cell::sync::Lazy,
parking_lot::{Condvar, Mutex},
};
// Tests constants
#[cfg(feature = "search")]
static UIA: Lazy<Arc<(Mutex<bool>, Condvar)>> =
Lazy::new(|| Arc::new((Mutex::new(true), Condvar::new())));
const TEST_STR: &str = "This is some sample text";
// Tests for event emitting functions of Pager
#[test]
fn set_data() {
let mut ps = PagerState::new().unwrap();
let ev = Event::SetData(TEST_STR.to_string());
let mut out = Vec::new();
handle_event(
ev,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert_eq!(ps.formatted_lines, vec![TEST_STR.to_string()]);
}
#[test]
fn append_str() {
let mut ps = PagerState::new().unwrap();
let ev1 = Event::AppendData(format!("{TEST_STR}\n"));
let ev2 = Event::AppendData(TEST_STR.to_string());
let mut out = Vec::new();
handle_event(
ev1,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
handle_event(
ev2,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert_eq!(
ps.formatted_lines,
vec![TEST_STR.to_string(), TEST_STR.to_string()]
);
}
#[test]
fn set_prompt() {
let mut ps = PagerState::new().unwrap();
let ev = Event::SetPrompt(TEST_STR.to_string());
let mut out = Vec::new();
handle_event(
ev,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert_eq!(ps.prompt, TEST_STR.to_string());
}
#[test]
fn send_message() {
let mut ps = PagerState::new().unwrap();
let ev = Event::SendMessage(TEST_STR.to_string());
let mut out = Vec::new();
handle_event(
ev,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert_eq!(ps.message.unwrap(), TEST_STR.to_string());
}
#[test]
#[cfg(feature = "static_output")]
fn set_run_no_overflow() {
let mut ps = PagerState::new().unwrap();
let ev = Event::SetRunNoOverflow(false);
let mut out = Vec::new();
handle_event(
ev,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert!(!ps.run_no_overflow);
}
#[test]
fn set_exit_strategy() {
let mut ps = PagerState::new().unwrap();
let ev = Event::SetExitStrategy(ExitStrategy::PagerQuit);
let mut out = Vec::new();
handle_event(
ev,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert_eq!(ps.exit_strategy, ExitStrategy::PagerQuit);
}
#[test]
fn add_exit_callback() {
let mut ps = PagerState::new().unwrap();
let ev = Event::AddExitCallback(Box::new(|| println!("Hello World")));
let mut out = Vec::new();
handle_event(
ev,
&mut out,
&mut ps,
&Arc::new(AtomicBool::new(false)),
#[cfg(feature = "search")]
&UIA,
)
.unwrap();
assert_eq!(ps.exit_callbacks.len(), 1);
}
}