-
Notifications
You must be signed in to change notification settings - Fork 11
/
runner.rs
632 lines (548 loc) · 21 KB
/
runner.rs
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Test runner module. Controles the test flow, checks input, and returns results.
//!
//! This is the main module that is orchestrating the flow of the test.
//! It prints the expected input as placeholder, then it reads user input and reacts to it.
//! When program is started `Normal` mode is turned on.
//! To go to `Editing` mode user needs to press `e`.
//! To go to `Normal` mode from `Editing` mode, and effectively pause the test, press `<Esc>`.
//!
//! When a test is started it checks the user input
//! and prints it to indicate valid characters and mistakes.
//! After the `duration` (amount of seconds) specified in config has passed the test is finished.
//! And test statistics are returned from the runner.
use anyhow::{Context, Result};
use crossterm::event::{self, Event, KeyCode};
use mockall::automock;
use std::time::{Duration, Instant};
use tui::{
backend::Backend,
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Style},
text::Text,
widgets::{Paragraph, Widget, Wrap},
Frame, Terminal,
};
use crate::config::Config;
use crate::expected_input::ExpectedInputInterface;
/// To switch from Normal to Editing press `e`.
/// To switch from Editing to Normal press `<Esc>`.
enum InputMode {
Normal,
Editing,
}
/// Struct that runs and controlles the test.
pub struct Runner {
input: String,
input_mode: InputMode,
config: Config,
expected_input: Box<dyn ExpectedInputInterface>,
raw_mistakes_count: u64,
raw_valid_characters_count: u64,
}
/// Struct holding the test results.
#[derive(Debug)]
pub struct Stats {
pub wpm: f64,
pub raw_accuracy: f64,
pub raw_valid_characters_count: u64,
pub raw_mistakes_count: u64,
pub raw_typed_characters_count: u64,
pub accuracy: f64,
pub valid_characters_count: u64,
pub typed_characters_count: u64,
pub mistakes_count: u64,
}
impl Runner {
/// Create new test runner instance
pub fn new(config: Config, expected_input: impl ExpectedInputInterface + 'static) -> Self {
Self {
input: String::new(),
input_mode: InputMode::Normal,
config,
expected_input: Box::new(expected_input),
raw_mistakes_count: 0,
raw_valid_characters_count: 0,
}
}
/// Method that runs the test.
///
/// It renders the application using the `tui` crate and reacts to user input.
pub fn run<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<Stats> {
let mut start_time = Instant::now();
let mut pause_time = Instant::now();
let mut is_started = false;
let tick_rate = Duration::from_secs(1);
let mut last_tick = Instant::now();
loop {
if let InputMode::Editing = self.input_mode {
if is_started && start_time.elapsed() >= self.config.duration {
return Ok(self.get_stats());
}
}
terminal
.draw(|f: &mut Frame<B>| {
let mut frame_wrapper = FrameWrapper::new(f);
self.render(&mut frame_wrapper, start_time.elapsed().as_secs());
})
.context("Unable to draw in terminal")?;
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
if event::poll(timeout).context("Unable to poll for event")? {
if let Event::Key(key) = event::read().context("Unable to read event")? {
match self.input_mode {
InputMode::Normal => match key.code {
KeyCode::Char('e') => {
start_time = if is_started {
start_time + pause_time.elapsed()
} else {
Instant::now()
};
is_started = true;
self.input_mode = InputMode::Editing;
}
KeyCode::Char('q') => {
// todo return canceled test error and handle it in main
return Ok(Stats {
wpm: 0.0,
raw_accuracy: 0.0,
raw_valid_characters_count: 0,
raw_mistakes_count: 0,
raw_typed_characters_count: 0,
accuracy: 0.0,
valid_characters_count: 0,
mistakes_count: 0,
typed_characters_count: 0,
});
}
_ => {}
},
InputMode::Editing => match key.code {
KeyCode::Char(c) => {
self.input.push(c);
let expected_input = self
.expected_input
.get_string(self.input.len())
.chars()
.collect::<Vec<char>>();
let is_correct =
self.input.chars().last() == expected_input.last().copied();
if !is_correct {
self.raw_mistakes_count += 1;
} else {
self.raw_valid_characters_count += 1;
}
}
KeyCode::Backspace => {
self.input.pop();
}
KeyCode::Esc => {
pause_time = Instant::now();
self.input_mode = InputMode::Normal;
}
_ => {}
},
}
}
}
if last_tick.elapsed() >= tick_rate {
last_tick = Instant::now();
}
}
}
/// Render a frame with each visual elements of the program in terminal.
///
/// There are two areas being rendered,
/// input area - where user input and expected input is displayed,
/// and info arae - where help message and time remaining is rendered.
fn render(&mut self, frame: &mut impl FrameWrapperInterface, time_elapsed: u64) {
let areas = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1), Constraint::Length(1)].as_ref())
.split(frame.size());
let input_area = areas[0];
let info_area = areas[1];
let frame_width = frame.size().width as usize;
let input_len = self.input.len();
let current_line_index = (input_len / frame_width) as u16;
let input_current_line_len = input_len % frame_width;
let expected_input_str = self
.expected_input
.get_string((current_line_index as usize + 2) * frame_width);
let (expected_input_current_line, expected_input_following_lines) =
expected_input_str.split_at(((current_line_index as usize) + 1) * frame_width);
let (expected_input_current_line_already_typed, expected_input_current_line_rest) =
expected_input_current_line.split_at(input_len);
let expected_input_str = expected_input_current_line_already_typed.to_string()
+ expected_input_current_line_rest
+ expected_input_following_lines;
self.print_input(frame, expected_input_str, input_area, frame_width);
self.print_block_of_text(
frame,
expected_input_current_line_rest.to_string(),
Rect {
x: input_area.x + input_current_line_len as u16,
y: input_area.y + current_line_index,
width: frame_width as u16 - input_current_line_len as u16,
height: 1,
},
Color::Gray,
false,
false,
);
self.print_block_of_text(
frame,
expected_input_following_lines.to_string(),
Rect {
x: input_area.x,
y: input_area.y + current_line_index + 1,
height: input_area.height - current_line_index - 1,
width: input_area.width,
},
Color::DarkGray,
true,
false,
);
self.move_cursor(
frame,
input_area,
input_current_line_len,
current_line_index,
);
let time_left = self
.config
.duration
.checked_sub(Duration::from_secs(time_elapsed))
.unwrap_or(Duration::from_secs(0));
let label = match time_left.as_secs() {
1 => "second",
_ => "seconds",
};
let time_left_message = match self.input_mode {
InputMode::Normal => String::new(),
InputMode::Editing => format!("{} {label} left", time_left.as_secs()),
};
self.print_block_of_text(
frame,
time_left_message,
info_area,
Color::Yellow,
true,
false,
);
let help_message = match self.input_mode {
InputMode::Normal => "press 'e' to start the test, press 'q' to quit",
InputMode::Editing => "press 'Esc' to pause the test",
};
self.print_block_of_text(
frame,
help_message.to_string(),
info_area,
Color::Yellow,
true,
true,
)
}
/// Iterate over characters in user input
/// and print them using different colors indicating if they are valid or wrong.
fn print_input(
&mut self,
frame: &mut impl FrameWrapperInterface,
expected_input: String,
input_area: Rect,
frame_width: usize,
) {
for ((input_char_index, input_char), (_, expected_input_char)) in
self.input.char_indices().zip(expected_input.char_indices())
{
let input = Paragraph::new(expected_input_char.to_string()).style(
match input_char == expected_input_char {
true => Style::default().fg(Color::Green),
false => Style::default().bg(Color::Red).fg(Color::Gray),
},
);
frame.render_widget(
input,
Rect {
x: (input_area.x + input_char_index as u16) % frame_width as u16,
y: input_area.y + input_char_index as u16 / frame_width as u16,
width: 1,
height: 1,
},
);
}
}
/// Used for rendering text within given area and adjusted with given color.
fn print_block_of_text(
&self,
frame: &mut impl FrameWrapperInterface,
text_str: String,
area: Rect,
color: Color,
wrap: bool,
align_right: bool,
) {
let mut text = Text::from(text_str);
text.patch_style(Style::default().fg(color));
let mut paragraph = Paragraph::new(text);
if wrap {
paragraph = paragraph.wrap(Wrap { trim: false });
}
if align_right {
paragraph = paragraph.alignment(Alignment::Right);
}
frame.render_widget(paragraph, area);
}
/// Move the user cursor to place after the end of user input.
fn move_cursor(
&self,
frame: &mut impl FrameWrapperInterface,
area: Rect,
input_current_line_len: usize,
current_line_index: u16,
) {
match self.input_mode {
InputMode::Normal =>
// Don't do anything, because `Frame` already hid the cursor
{}
InputMode::Editing => frame.set_cursor(
area.x + input_current_line_len as u16,
area.y + current_line_index,
),
}
}
/// Calculate the statistics of the test and return them.
///
/// WPM is number of valid characters that are in the input after the test has finished
/// divided by 5, to get the "number of words typed", and divided by the duration of the test
/// normalized to 60 seconds.
/// This way WPM is only counted in valid characters, so each mistake that wasn't corrected is
/// not taken into consideration when calculating it.
///
/// `raw_valid_characters_count` is number of times when valid character was pressed.
/// `raw_mistakes_count is number` of times when invalid character was pressed.
/// `raw_typed_characters_count` is number of key presses that happened in `Edting` mode during
/// the test.
/// `raw_accuracy` is ratio of `raw_valid_characters_count` to `raw_typed_characters_count`.
///
/// `valid_characters_count`is number of valid characters in the input after the test has
/// finished, so if any corrections where made, it will consider the state of the input after
/// them.
/// `mistakes_count` is number of invalid characters in the input after the test has finished.
/// `typed_characters_count` is number of characters in the input after the test has finished.
/// `accuracy` is ratio of `valid_characters_count` to `typed_characters_count`.
///
fn get_stats(&self) -> Stats {
let typed_characters = self.input.chars();
let typed_characters_count = typed_characters.clone().count();
let expected_input_str = self.expected_input.get_string(typed_characters_count);
let expected_characters = expected_input_str.chars();
let mistakes_count = typed_characters
.clone()
.zip(expected_characters.clone())
.filter(|(input_char, expected_input_char)| input_char != expected_input_char)
.count() as u64;
let valid_characters_count = typed_characters_count as u64 - mistakes_count;
Stats {
wpm: valid_characters_count as f64 / 5.0 * 60.0 / self.config.duration.as_secs() as f64,
raw_accuracy: (self.raw_valid_characters_count) as f64
/ (self.raw_valid_characters_count + self.raw_mistakes_count) as f64
* 100.0,
raw_valid_characters_count: self.raw_valid_characters_count,
raw_mistakes_count: self.raw_mistakes_count,
raw_typed_characters_count: self.raw_valid_characters_count + self.raw_mistakes_count,
accuracy: (typed_characters_count - mistakes_count as usize) as f64
/ typed_characters_count as f64
* 100.0,
valid_characters_count,
mistakes_count,
typed_characters_count: typed_characters_count as u64,
}
}
}
/// Used for generating mocks using `mockall` crate
#[automock]
trait FrameWrapperInterface {
fn render_widget<W: Widget + 'static>(&mut self, widget: W, area: Rect);
fn set_cursor(&mut self, x: u16, y: u16);
fn size(&self) -> Rect;
}
/// Used for generating mocks using `mockall` crate
pub struct FrameWrapper<'a, 'b, B: Backend> {
frame: &'a mut Frame<'b, B>,
}
impl<'a, 'b, B: Backend> FrameWrapper<'a, 'b, B> {
pub fn new(frame: &'a mut Frame<'b, B>) -> Self {
FrameWrapper { frame }
}
}
impl<'a, 'b, B: Backend> FrameWrapperInterface for FrameWrapper<'a, 'b, B> {
fn render_widget<T: Widget + 'static>(&mut self, widget: T, area: Rect) {
self.frame.render_widget(widget, area);
}
fn set_cursor(&mut self, x: u16, y: u16) {
self.frame.set_cursor(x, y);
}
fn size(&self) -> Rect {
self.frame.size()
}
}
#[cfg(test)]
mod test {
use mockall::predicate;
use crate::expected_input::MockExpectedInputInterface;
use super::*;
#[test]
fn should_render_single_line_input() {
let config = Config::default();
let mut expected_input = MockExpectedInputInterface::default();
expected_input
.expect_get_string()
.with(predicate::eq(2 * 50))
.return_const("foobarbaaz".repeat(10));
let mut runner = Runner::new(config, expected_input);
runner.input_mode = InputMode::Editing;
runner.input = "foo".to_string();
let mut frame = MockFrameWrapperInterface::default();
frame.expect_size().times(2).return_const(Rect {
x: 39,
y: 1,
width: 50,
height: 1,
});
frame
.expect_render_widget::<Paragraph>()
.times(7)
.return_const(());
frame
.expect_set_cursor()
.with(predicate::eq(42), predicate::eq(1))
.times(1)
.return_const(());
runner.render(&mut frame, 0);
}
#[test]
fn should_render_multi_line_input() {
let config = Config::default();
let mut expected_input = MockExpectedInputInterface::default();
expected_input
.expect_get_string()
.with(predicate::eq(4 * 3))
.return_const("foobarbazqux".to_string());
let mut runner = Runner::new(config, expected_input);
runner.input_mode = InputMode::Editing;
runner.input = "foobar".to_string();
let mut frame = MockFrameWrapperInterface::default();
frame.expect_size().times(2).return_const(Rect {
x: 0,
y: 0,
width: 4,
height: 3,
});
frame
.expect_render_widget::<Paragraph>()
.times(10)
.return_const(());
frame
.expect_set_cursor()
.with(predicate::eq(2), predicate::eq(1))
.times(1)
.return_const(());
runner.render(&mut frame, 0);
}
#[test]
fn should_print_input() {
let config = Config::default();
let expected_input = MockExpectedInputInterface::default();
let mut runner = Runner::new(config, expected_input);
runner.input = "foo".to_string();
let mut frame = MockFrameWrapperInterface::default();
frame
.expect_render_widget::<Paragraph>()
.times(3)
.return_const(());
runner.print_input(
&mut frame,
"foo".to_string(),
Rect {
x: 0,
y: 0,
width: 50,
height: 1,
},
50,
);
}
#[test]
fn should_print_block_of_text() {
let config = Config::default();
let expected_input = MockExpectedInputInterface::default();
let runner = Runner::new(config, expected_input);
let mut frame = MockFrameWrapperInterface::default();
frame
.expect_render_widget::<Paragraph>()
.withf(|_widget: &Paragraph<'_>, area| {
*area
== Rect {
x: 0,
y: 0,
width: 50,
height: 1,
}
})
.times(1)
.return_const(());
runner.print_block_of_text(
&mut frame,
"foo".to_string(),
Rect {
x: 0,
y: 0,
width: 50,
height: 1,
},
Color::Gray,
false,
false,
);
}
#[test]
fn should_not_move_cursor_in_normal_mode() {
let config = Config::default();
let expected_input = MockExpectedInputInterface::default();
let runner = Runner::new(config, expected_input);
let mut frame = MockFrameWrapperInterface::default();
frame.expect_set_cursor().times(0).return_const(());
let area = Rect {
x: 40,
y: 11,
width: 50,
height: 1,
};
let input_current_line_len = 2;
let current_line_index = 16;
runner.move_cursor(&mut frame, area, input_current_line_len, current_line_index)
}
#[test]
fn should_move_cursor_in_editing_mode() {
let config = Config::default();
let expected_input = MockExpectedInputInterface::default();
let mut runner = Runner::new(config, expected_input);
runner.input_mode = InputMode::Editing;
let mut frame = MockFrameWrapperInterface::default();
frame
.expect_set_cursor()
.with(predicate::eq(42), predicate::eq(27))
.times(1)
.return_const(());
let area = Rect {
x: 40,
y: 11,
width: 50,
height: 1,
};
let input_current_line_len = 2;
let current_line_index = 16;
runner.move_cursor(&mut frame, area, input_current_line_len, current_line_index)
}
}