ttypo 0.1.3

Terminal-based typing test.
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
pub mod results;

use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use std::fmt;
use std::time::Instant;

/// Returns true if a character is printable ASCII (0x20-0x7E).
pub fn is_typeable(c: char) -> bool {
    c.is_ascii() && !c.is_ascii_control()
}

/// Returns the typeable portion of `text`.
/// When `ascii` is false the full text is returned unchanged.
fn target_text(text: &str, ascii: bool) -> String {
    if ascii {
        text.chars().filter(|c| is_typeable(*c)).collect()
    } else {
        text.to_string()
    }
}

#[derive(Clone)]
pub struct TestEvent {
    pub time: Instant,
    pub key: KeyEvent,
    pub correct: Option<bool>,
}

pub fn is_missed_word_event(event: &TestEvent) -> bool {
    event.correct != Some(true)
}

impl fmt::Debug for TestEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TestEvent")
            .field("time", &String::from("Instant { ... }"))
            .field("key", &self.key)
            .finish()
    }
}

#[derive(Debug, Clone)]
pub struct TestWord {
    pub text: String,
    pub progress: String,
    pub events: Vec<TestEvent>,
}

impl From<String> for TestWord {
    fn from(string: String) -> Self {
        TestWord {
            text: string,
            progress: String::new(),
            events: Vec::new(),
        }
    }
}

impl From<&str> for TestWord {
    fn from(string: &str) -> Self {
        Self::from(string.to_string())
    }
}

/// A line of the original file, used in raw mode for display.
#[derive(Debug, Clone)]
pub struct DisplayLine {
    /// Leading whitespace (tabs expanded to 4 spaces).
    pub indent: String,
    /// Index of the first word on this line in `Test::words`.
    pub word_start: usize,
    /// Number of words on this line (0 for empty/whitespace-only lines).
    pub word_count: usize,
}

#[derive(Debug, Clone)]
pub struct Test {
    pub words: Vec<TestWord>,
    pub current_word: usize,
    pub complete: bool,
    pub backtracking_enabled: bool,
    pub sudden_death_enabled: bool,
    pub backspace_enabled: bool,
    /// Original line layout for raw/file mode (empty = word-wrap mode).
    pub lines: Vec<DisplayLine>,
    /// When true, non-typeable characters are skipped during typing.
    pub ascii: bool,
    pub start_time: Option<Instant>,
    /// Label describing the source of the test contents (language name, filename, or "stdin").
    pub source: String,
}

impl Test {
    pub fn new(
        words: Vec<String>,
        backtracking_enabled: bool,
        sudden_death_enabled: bool,
        backspace_enabled: bool,
        lines: Vec<DisplayLine>,
        ascii: bool,
        source: String,
    ) -> Self {
        let mut test = Self {
            words: words.into_iter().map(TestWord::from).collect(),
            current_word: 0,
            complete: false,
            backtracking_enabled,
            sudden_death_enabled,
            backspace_enabled,
            lines,
            ascii,
            start_time: None,
            source,
        };
        test.skip_non_typeable_words();
        test
    }

    pub fn elapsed_secs(&self) -> f64 {
        self.start_time
            .map(|t| t.elapsed().as_secs_f64())
            .unwrap_or(0.0)
    }

    pub fn live_wpm(&self) -> f64 {
        let elapsed = self.elapsed_secs();
        if elapsed < 0.5 {
            return 0.0;
        }
        let chars_typed: usize = self.words[..self.current_word]
            .iter()
            .map(|w| w.progress.len())
            .sum::<usize>()
            + self.words[self.current_word].progress.len();
        // Standard: 1 word = 5 characters
        (chars_typed as f64 / 5.0) / (elapsed / 60.0)
    }

    pub fn progress(&self) -> (usize, usize) {
        (self.current_word, self.words.len())
    }

    pub fn handle_key(&mut self, key: KeyEvent) {
        if key.kind != KeyEventKind::Press {
            return;
        }

        if self.start_time.is_none() {
            self.start_time = Some(Instant::now());
        }

        let ascii = self.ascii;
        let word = &mut self.words[self.current_word];
        let target = target_text(&word.text, ascii);
        match key.code {
            KeyCode::Char(' ') | KeyCode::Enter => {
                if target.chars().nth(word.progress.len()) == Some(' ') {
                    word.progress.push(' ');
                    word.events.push(TestEvent {
                        time: Instant::now(),
                        correct: Some(true),
                        key,
                    })
                } else if !word.progress.is_empty() || target.is_empty() {
                    let correct = target == word.progress;
                    if self.sudden_death_enabled && !correct {
                        self.reset();
                    } else {
                        word.events.push(TestEvent {
                            time: Instant::now(),
                            correct: Some(correct),
                            key,
                        });
                        self.next_word();
                        self.skip_non_typeable_words();
                    }
                }
            }
            KeyCode::Backspace => {
                if word.progress.is_empty() && self.backtracking_enabled && self.backspace_enabled {
                    self.last_word();
                } else if self.backspace_enabled {
                    word.events.push(TestEvent {
                        time: Instant::now(),
                        correct: Some(!target.starts_with(&word.progress[..])),
                        key,
                    });
                    word.progress.pop();
                }
            }
            // CTRL-BackSpace and CTRL-W
            KeyCode::Char('h') | KeyCode::Char('w')
                if key.modifiers.contains(KeyModifiers::CONTROL) =>
            {
                if self.words[self.current_word].progress.is_empty() {
                    self.last_word();
                }

                let word = &mut self.words[self.current_word];

                word.events.push(TestEvent {
                    time: Instant::now(),
                    correct: None,
                    key,
                });
                word.progress.clear();
            }
            KeyCode::Char(c) => {
                word.progress.push(c);
                let correct = target.starts_with(&word.progress[..]);
                if self.sudden_death_enabled && !correct {
                    self.reset();
                } else {
                    word.events.push(TestEvent {
                        time: Instant::now(),
                        correct: Some(correct),
                        key,
                    });
                    if word.progress == target && self.current_word == self.words.len() - 1 {
                        self.complete = true;
                        self.current_word = 0;
                    }
                }
            }
            _ => {}
        };
    }

    fn last_word(&mut self) {
        if self.current_word != 0 {
            self.current_word -= 1;
        }
    }

    fn next_word(&mut self) {
        if self.current_word == self.words.len() - 1 {
            self.complete = true;
            self.current_word = 0;
        } else {
            self.current_word += 1;
        }
    }

    fn reset(&mut self) {
        self.words.iter_mut().for_each(|word: &mut TestWord| {
            word.progress.clear();
            word.events.clear();
        });
        self.current_word = 0;
        self.complete = false;
        self.start_time = None;
        self.skip_non_typeable_words();
    }

    fn skip_non_typeable_words(&mut self) {
        if !self.ascii || self.complete {
            return;
        }
        loop {
            let t = target_text(&self.words[self.current_word].text, true);
            if !t.is_empty() {
                break;
            }
            self.next_word();
            if self.complete {
                break;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::KeyEventState;

    fn make_test(words: &[&str], lines: Vec<DisplayLine>, ascii: bool) -> Test {
        Test::new(
            words.iter().map(|s| s.to_string()).collect(),
            true,
            false,
            true,
            lines,
            ascii,
            String::new(),
        )
    }

    fn press(c: char) -> KeyEvent {
        KeyEvent {
            code: KeyCode::Char(c),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }
    }

    fn press_space() -> KeyEvent {
        KeyEvent {
            code: KeyCode::Char(' '),
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        }
    }

    #[test]
    fn new_preserves_lines() {
        let lines = vec![
            DisplayLine {
                indent: String::new(),
                word_start: 0,
                word_count: 2,
            },
            DisplayLine {
                indent: String::new(),
                word_start: 2,
                word_count: 2,
            },
        ];
        let test = make_test(&["a", "b", "c", "d"], lines.clone(), false);
        assert_eq!(test.lines.len(), 2);
        assert_eq!(test.lines[0].word_start, 0);
        assert_eq!(test.lines[1].word_start, 2);
        assert_eq!(test.words.len(), 4);
    }

    #[test]
    fn reset_preserves_lines() {
        let lines = vec![
            DisplayLine {
                indent: String::new(),
                word_start: 0,
                word_count: 1,
            },
            DisplayLine {
                indent: String::new(),
                word_start: 1,
                word_count: 2,
            },
        ];
        let mut test = make_test(&["a", "b", "c"], lines, false);
        test.words[0].progress = "a".to_string();
        test.current_word = 1;
        test.words[1].progress = "x".to_string();

        test.reset();

        assert_eq!(test.current_word, 0);
        assert!(!test.complete);
        assert!(test.words.iter().all(|w| w.progress.is_empty()));
        assert_eq!(test.lines.len(), 2);
    }

    #[test]
    fn target_text_without_ascii() {
        assert_eq!(target_text("caf\u{00e9}", false), "caf\u{00e9}");
    }

    #[test]
    fn target_text_with_ascii() {
        assert_eq!(target_text("caf\u{00e9}", true), "caf");
        assert_eq!(target_text("hello\u{2014}world", true), "helloworld");
        assert_eq!(target_text("\u{201c}quoted\u{201d}", true), "quoted");
    }

    #[test]
    fn ascii_skips_unicode_in_typing() {
        let mut test = make_test(&["caf\u{00e9}"], Vec::new(), true);
        for c in "caf".chars() {
            test.handle_key(press(c));
        }
        assert!(test.complete);
    }

    #[test]
    fn ascii_space_advances_past_unicode_word() {
        let mut test = make_test(&["caf\u{00e9}", "ok"], Vec::new(), true);
        for c in "caf".chars() {
            test.handle_key(press(c));
        }
        test.handle_key(press_space());
        assert_eq!(test.current_word, 1);
    }

    #[test]
    fn ascii_auto_skips_all_unicode_word() {
        let test = make_test(&["\u{2014}\u{2014}", "ok"], Vec::new(), true);
        // entirely non-typeable word is auto-skipped at construction
        assert_eq!(test.current_word, 1);
    }

    #[test]
    fn ascii_auto_skips_chain_of_unicode_words() {
        let test = make_test(&["\u{2014}", "\u{00e9}\u{00e9}", "ok"], Vec::new(), true);
        // both non-typeable words skipped at construction
        assert_eq!(test.current_word, 2);
    }

    #[test]
    fn ascii_auto_skips_after_space() {
        let mut test = make_test(&["hi", "\u{2014}", "ok"], Vec::new(), true);
        for c in "hi".chars() {
            test.handle_key(press(c));
        }
        test.handle_key(press_space());
        // skipped past the non-typeable word to "ok"
        assert_eq!(test.current_word, 2);
    }

    #[test]
    fn ascii_all_non_typeable_completes() {
        let test = make_test(&["\u{2014}", "\u{00e9}"], Vec::new(), true);
        assert!(test.complete);
    }

    #[test]
    fn without_ascii_unicode_must_be_typed() {
        let mut test = make_test(&["caf\u{00e9}"], Vec::new(), false);
        for c in "caf".chars() {
            test.handle_key(press(c));
        }
        assert!(!test.complete);
    }

    #[test]
    fn without_ascii_no_auto_skip() {
        let test = make_test(&["\u{2014}", "ok"], Vec::new(), false);
        // without ascii, no auto-skipping
        assert_eq!(test.current_word, 0);
    }
}