minus 5.6.1

An asynchronous data feedable terminal paging library for Rust
Documentation
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! 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::{self, AppendStyle};
use super::CommandQueue;
use super::{commands::Command, utils::term};
#[cfg(feature = "search")]
use crate::search;
use crate::{error::MinusError, input::InputEvent, PagerState};

/// Respond based on the type of command
///
/// 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: Command,
    mut out: &mut impl Write,
    p: &mut PagerState,
    command_queue: &mut CommandQueue,
    is_exited: &Arc<AtomicBool>,
    #[cfg(feature = "search")] user_input_active: &Arc<(Mutex<bool>, Condvar)>,
) -> Result<(), MinusError> {
    match ev {
        Command::SetData(text) => {
            p.screen.orig_text = text;
            p.format_lines();
            p.screen.line_count = p.screen.orig_text.lines().count();
            if !p.running.lock().is_uninitialized() {
                display::draw_full(&mut out, p)?;
            }
        }
        Command::UserInput(InputEvent::Exit) => {
            p.exit();
            is_exited.store(true, std::sync::atomic::Ordering::SeqCst);
            term::cleanup(&mut out, &p.exit_strategy, true)?;
        }
        Command::UserInput(InputEvent::UpdateUpperMark(mut um)) => {
            let line_count = p.screen.formatted_lines_count();
            // Reduce one row for prompt/messages
            let writable_rows = p.rows.saturating_sub(1);
            // Calculate the lower_mark by adding either the rows or line_count depending
            // on the minimality
            let lower_mark = p.upper_mark.saturating_add(writable_rows.min(line_count));
            // If the lower_bound is greater than the available line count, we set it to such a value
            // so that the last page can be displayed entirely, i.e never scroll past the last line
            if lower_mark > line_count {
                p.upper_mark = line_count.saturating_sub(writable_rows);
            }

            display::draw_for_change(out, p, &mut um)?;
            p.upper_mark = um;
        }
        Command::UserInput(InputEvent::UpdateLeftMark(lm)) if !p.screen.line_wrapping => {
            if lm.saturating_add(p.cols) > p.screen.get_max_line_length() && lm > p.left_mark {
                return Ok(());
            }
            p.left_mark = lm;
            display::draw_full(out, p)?;
        }
        Command::UserInput(InputEvent::RestorePrompt) => {
            // Set the message to None and new messages to false as all messages have been shown
            p.message = None;
            command_queue.push_back_unchecked(Command::FormatRedrawPrompt);
        }
        Command::UserInput(InputEvent::UpdateTermArea(c, r)) => {
            p.rows = r;
            p.cols = c;
            // Readjust the text wrapping for the new number of columns
            command_queue.push_back(Command::FormatRedrawDisplay);
        }
        Command::UserInput(InputEvent::UpdateLineNumber(l)) => {
            p.line_numbers = l;
            command_queue.push_back(Command::FormatRedrawDisplay);
        }
        #[cfg(feature = "search")]
        Command::UserInput(InputEvent::Search(m)) => {
            p.search_mode = m;
            p.search_state.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_state.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();

            command_queue.push_back_unchecked(Command::FormatRedrawPrompt);
            // If we have incremental search cache directly use it and return
            if let Some(incremental_search_result) = search_result.incremental_search_result {
                p.search_state.search_term = search_result.compiled_regex;
                p.upper_mark = incremental_search_result.upper_mark;
                p.search_state.search_mark = incremental_search_result.search_mark;
                p.search_state.search_idx = incremental_search_result.search_idx;
                p.screen.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_state.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() {
                    command_queue.push_back_unchecked(Command::SendMessage(
                        "Invalid regular expression. Press Enter".to_string(),
                    ));
                    return Ok(());
                }
                compiled_regex
            } else {
                return Ok(());
            };

            // Format the lines, this will automatically generate the PagerState.search_idx
            p.format_lines();
        }
        #[cfg(feature = "search")]
        Command::UserInput(InputEvent::NextMatch | InputEvent::MoveToNextMatch(1))
            if p.search_state.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_state.search_idx, p.upper_mark, 1);
            if let Some(pnm) = position_of_next_match {
                p.search_state.search_mark = pnm;
                let upper_mark = *p
                    .search_state
                    .search_idx
                    .iter()
                    .nth(p.search_state.search_mark)
                    .unwrap();
                command_queue.push_back_unchecked(Command::UserInput(InputEvent::UpdateUpperMark(
                    upper_mark,
                )));
                command_queue.push_back_unchecked(Command::FormatRedrawPrompt);
            }
        }
        #[cfg(feature = "search")]
        Command::UserInput(InputEvent::PrevMatch | InputEvent::MoveToPrevMatch(1))
            if p.search_state.search_term.is_some() =>
        {
            // If no matches, return immediately
            if p.search_state.search_idx.is_empty() {
                return Ok(());
            }
            // Decrement the s_mark and get the preceding index
            p.search_state.search_mark = p.search_state.search_mark.saturating_sub(1);
            if let Some(y) = p
                .search_state
                .search_idx
                .iter()
                .nth(p.search_state.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;
                    command_queue.push_back_unchecked(Command::FormatRedrawPrompt);
                    command_queue.push_back_unchecked(Command::UserInput(
                        InputEvent::UpdateUpperMark(p.upper_mark),
                    ));
                }
            }
        }
        #[cfg(feature = "search")]
        Command::UserInput(InputEvent::MoveToNextMatch(n))
            if p.search_state.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_state.search_idx, p.upper_mark, n);
            if let Some(pnm) = position_of_next_match {
                p.search_state.search_mark = pnm;
                let upper_mark = *p
                    .search_state
                    .search_idx
                    .iter()
                    .nth(p.search_state.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.screen.formatted_lines_count().saturating_add(1)
                {
                    p.search_state.search_mark = p.search_state.search_mark.saturating_sub(1);
                    p.upper_mark = *p
                        .search_state
                        .search_idx
                        .iter()
                        .nth(p.search_state.search_mark)
                        .unwrap();
                }
                command_queue.push_back_unchecked(Command::UserInput(InputEvent::UpdateUpperMark(
                    upper_mark,
                )));
                command_queue.push_back_unchecked(Command::FormatRedrawPrompt);
            }
        }
        #[cfg(feature = "search")]
        Command::UserInput(InputEvent::MoveToPrevMatch(n))
            if p.search_state.search_term.is_some() =>
        {
            // If no matches, return immediately
            if p.search_state.search_idx.is_empty() {
                return Ok(());
            }
            // Decrement the s_mark and get the preceding index
            p.search_state.search_mark = p.search_state.search_mark.saturating_sub(n);
            if let Some(y) = p
                .search_state
                .search_idx
                .iter()
                .nth(p.search_state.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 {
                    let upper_mark = *y;
                    command_queue.push_back_unchecked(Command::UserInput(
                        InputEvent::UpdateUpperMark(upper_mark),
                    ));
                    command_queue.push_back_unchecked(Command::FormatRedrawPrompt);
                }
            }
        }

        Command::UserInput(InputEvent::HorizontalScroll(val)) => {
            p.screen.line_wrapping = val;
            command_queue.push_back_unchecked(Command::FormatRedrawDisplay);
        }

        Command::FormatRedrawDisplay => {
            p.format_lines();
            display::draw_full(&mut out, p)?;
        }
        Command::AppendData(text) => {
            let prev_unterminated = p.screen.unterminated;
            let prev_fmt_lines_count = p.screen.formatted_lines_count();
            let is_running = !p.running.lock().is_uninitialized();
            let rows = p.rows;
            let append_style = p.append_str(text.as_str());

            if is_running {
                if append_style == AppendStyle::FullRedraw {
                    return display::draw_full(out, p);
                }
                display::draw_append_text(
                    out,
                    rows,
                    prev_unterminated,
                    prev_fmt_lines_count,
                    &append_style,
                )?;

                if p.follow_output {
                    command_queue.push_back_unchecked(Command::UserInput(
                        InputEvent::UpdateUpperMark(p.screen.formatted_lines_count()),
                    ));
                }
            }
        }

        Command::SetPrompt(ref text) | Command::SendMessage(ref text) => {
            if let Command::SetPrompt(_) = ev {
                p.prompt = text.to_string();
            } else {
                p.message = Some(text.to_string());
            }
            p.format_prompt();
            if !p.running.lock().is_uninitialized() {
                display::write_prompt(out, &p.displayed_prompt, p.rows.try_into().unwrap())?;
            }
        }
        Command::SetLineNumbers(ln) => {
            p.line_numbers = ln;
            p.format_lines();
            if !p.running.lock().is_uninitialized() {
                display::write_prompt(out, &p.displayed_prompt, p.rows.try_into().unwrap())?;
            }
        }
        Command::FormatRedrawPrompt => {
            p.format_prompt();
            display::write_prompt(out, &p.displayed_prompt, p.rows.try_into().unwrap())?;
        }
        Command::SetExitStrategy(es) => p.exit_strategy = es,
        Command::LineWrapping(lw) => {
            p.screen.line_wrapping = lw;
            p.format_lines();
        }
        #[cfg(feature = "static_output")]
        Command::SetRunNoOverflow(val) => p.run_no_overflow = val,
        #[cfg(feature = "search")]
        Command::IncrementalSearchCondition(cb) => p.search_state.incremental_search_condition = cb,
        Command::SetInputClassifier(clf) => p.input_classifier = clf,
        Command::AddExitCallback(cb) => p.exit_callbacks.push(cb),
        Command::ShowPrompt(show) => p.show_prompt = show,
        Command::FollowOutput(follow_output)
        | Command::UserInput(InputEvent::FollowOutput(follow_output)) => {
            p.follow_output = follow_output;
            command_queue.push_back(Command::UserInput(InputEvent::UpdateUpperMark(
                p.screen.formatted_lines_count(),
            )));
            command_queue.push_back(Command::FormatRedrawPrompt);
        }
        Command::UserInput(_) => {}
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::super::commands::Command;
    use super::handle_event;
    use crate::{minus_core::CommandQueue, ExitStrategy, PagerState, RunMode};
    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]
    #[cfg(any(feature = "dynamic_output", feature = "static_output"))]
    fn set_data() {
        let mut ps = PagerState::new().unwrap();
        let ev = Command::SetData(TEST_STR.to_string());
        let mut out = Vec::new();
        #[cfg(feature = "dynamic_output")]
        {
            *crate::minus_core::RUNMODE.lock() = RunMode::Dynamic;
        }
        #[cfg(feature = "static_output")]
        {
            *crate::minus_core::RUNMODE.lock() = RunMode::Static;
        }
        let mut command_queue = CommandQueue::new_zero();

        handle_event(
            ev,
            &mut out,
            &mut ps,
            &mut command_queue,
            &Arc::new(AtomicBool::new(false)),
            #[cfg(feature = "search")]
            &UIA,
        )
        .unwrap();
        assert_eq!(ps.screen.formatted_lines, vec![TEST_STR.to_string()]);
    }

    #[test]
    fn append_str() {
        let mut ps = PagerState::new().unwrap();
        let ev1 = Command::AppendData(format!("{TEST_STR}\n"));
        let ev2 = Command::AppendData(TEST_STR.to_string());
        let mut out = Vec::new();
        let mut command_queue = CommandQueue::new_zero();

        handle_event(
            ev1,
            &mut out,
            &mut ps,
            &mut command_queue,
            &Arc::new(AtomicBool::new(false)),
            #[cfg(feature = "search")]
            &UIA,
        )
        .unwrap();
        handle_event(
            ev2,
            &mut out,
            &mut ps,
            &mut command_queue,
            &Arc::new(AtomicBool::new(false)),
            #[cfg(feature = "search")]
            &UIA,
        )
        .unwrap();
        assert_eq!(
            ps.screen.formatted_lines,
            vec![TEST_STR.to_string(), TEST_STR.to_string()]
        );
    }

    #[test]
    #[cfg(any(feature = "dynamic_output", feature = "static_output"))]
    fn set_prompt() {
        let mut ps = PagerState::new().unwrap();
        let ev = Command::SetPrompt(TEST_STR.to_string());
        let mut out = Vec::new();
        let mut command_queue = CommandQueue::new_zero();
        #[cfg(feature = "dynamic_output")]
        {
            *crate::minus_core::RUNMODE.lock() = RunMode::Dynamic;
        }
        #[cfg(feature = "static_output")]
        {
            *crate::minus_core::RUNMODE.lock() = RunMode::Static;
        }

        handle_event(
            ev,
            &mut out,
            &mut ps,
            &mut command_queue,
            &Arc::new(AtomicBool::new(false)),
            #[cfg(feature = "search")]
            &UIA,
        )
        .unwrap();
        assert_eq!(ps.prompt, TEST_STR.to_string());
    }

    #[test]
    #[cfg(any(feature = "dynamic_output", feature = "static_output"))]
    fn send_message() {
        let mut ps = PagerState::new().unwrap();
        #[cfg(feature = "dynamic_output")]
        {
            *crate::minus_core::RUNMODE.lock() = RunMode::Dynamic;
        }
        #[cfg(feature = "static_output")]
        {
            *crate::minus_core::RUNMODE.lock() = RunMode::Static;
        }
        let ev = Command::SendMessage(TEST_STR.to_string());
        let mut out = Vec::new();
        let mut command_queue = CommandQueue::new_zero();

        handle_event(
            ev,
            &mut out,
            &mut ps,
            &mut command_queue,
            &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 = Command::SetRunNoOverflow(false);
        let mut out = Vec::new();
        let mut command_queue = CommandQueue::new_zero();

        handle_event(
            ev,
            &mut out,
            &mut ps,
            &mut command_queue,
            &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 = Command::SetExitStrategy(ExitStrategy::PagerQuit);
        let mut out = Vec::new();
        let mut command_queue = CommandQueue::new_zero();

        handle_event(
            ev,
            &mut out,
            &mut ps,
            &mut command_queue,
            &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 = Command::AddExitCallback(Box::new(|| println!("Hello World")));
        let mut out = Vec::new();
        let mut command_queue = CommandQueue::new_zero();

        handle_event(
            ev,
            &mut out,
            &mut ps,
            &mut command_queue,
            &Arc::new(AtomicBool::new(false)),
            #[cfg(feature = "search")]
            &UIA,
        )
        .unwrap();
        assert_eq!(ps.exit_callbacks.len(), 1);
    }
}