8000 fix: single event loop, leaner dependencies, unclipped results graph by jrnxf · Pull Request #29 · jrnxf/thokr · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,648 changes: 323 additions & 1,325 deletions Cargo.lock

Large diffs are not rendered by default.

28 changes: 15 additions & 13 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,23 @@ repository = "https://github.com/thatvegandev/thokr.git"
homepage = "https://github.com/thatvegandev/thokr"
license = "MIT"
authors = ["Colby Thomas <thatvegandev@gmail.com>"]
edition = "2021"
edition = "2024"
rust-version = "1.88"
exclude = [".github", "*.log", "Dockerfile", "plans"]
keywords = ["tui", "terminal", "typing"]

[dependencies]
ratatui = "0.30.1"
serde = { version = "1.0", features = ["derive"] }
clap = { version = "4", features = ["derive"] }
serde_json = "1.0.79"
rand = "0.8.5"
itertools = "0.10.3"
unicode-width = "0.1.9"
webbrowser = "0.7.1"
strum_macros = "0 8000 .24.0"
include_dir = "0.7.2"
directories = "4.0"
chrono = "0.4"
cgisf_lib = "0.1.3"
chrono = { version = "0.4.45", default-features = false, features = ["clock"] }
clap = { version = "4.6", features = ["derive"] }
directories = "6.0"
rand = "0.8.5"
ratatui = { version = "0.30.2", default-features = false, features = ["crossterm", "layout-cache"] }

[dev-dependencies]
insta = "1.49"

[profile.release]
lto = true
codegen-units = 1
strip = true
68 changes: 68 additions & 0 deletions src/bench.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! A timing harness, not a correctness test:
//! `cargo test --release -- --ignored --nocapture bench`
//!
//! Frames go through the real crossterm backend into a sink, so the numbers
//! cover handling the key, rendering, diffing against the last frame and
//! encoding the escape codes, but not the terminal emulator itself.

use crate::{App, Cli};
use clap::Parser;
use ratatui::{Terminal, TerminalOptions, Viewport, backend::CrosstermBackend, layout::Rect};
use std::{io, time::Instant};

const PROMPT: &str = "the quick brown fox jumps over the lazy dog while seven wizards quietly judge a boxing match near the old stone bridge";
const RUNS: usize = 300;

fn median(mut samples: Vec<f64>) -> f64 {
samples.sort_by(f64::total_cmp);
samples[samples.len() / 2]
}

#[test]
#[ignore = "timing harness"]
fn bench_key_and_frame() {
for (width, height) in [(100, 30), (40, 20)] {
let mut terminal = Terminal::with_options(
CrosstermBackend::new(io::sink()),
TerminalOptions {
viewport: Viewport::Fixed(Rect::new(0, 0, width, height)),
},
)
.unwrap();
let mut app = App::new(Cli::parse_from(["thokr", "-p", PROMPT]));
let keys = PROMPT.chars().count() - 1;

// type all but the last char, drawing a frame after every key
let mut samples = Vec::new();
for _ in 0..RUNS {
app.restart();
terminal.draw(|frame| app.draw(frame)).unwrap();
let start = Instant::now();
for c in PROMPT.chars().take(keys) {
app.thok.write(c);
terminal.draw(|frame| app.draw(frame)).unwrap();
}
samples.push(start.elapsed().as_nanos() as f64 / keys as f64);
}
println!(
"key + frame {width}x{height}: {:.2} us",
median(samples) / 1000.0
);

// finish the test, then redraw the results screen
app.thok.write('e');
app.thok.calc_results();
let mut samples = Vec::new();
for _ in 0..RUNS {
let start = Instant::now();
for _ in 0..20 {
terminal.draw(|frame| app.draw(frame)).unwrap();
}
samples.push(start.elapsed().as_nanos() as f64 / 20.0);
}
println!(
"results frame {width}x{height}: {:.2} us",
median(samples) / 1000.0
);
}
}
160 changes: 160 additions & 0 deletions src/history.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
//! The results history: one CSV row per finished test, appended to `log.csv`
//! in the platform's config folder. People keep these files across versions,
//! so the columns and their formats must not change.

use crate::thok::Thok;
use chrono::{Local, NaiveDateTime};
use directories::ProjectDirs;
use std::{
fs::{self, OpenOptions},
io::{self, Write},
path::{Path, PathBuf},
};

const HEADER: &str = "date,num_words,num_secs,elapsed_secs,wpm,accuracy,std_dev";

/// Where the log lives; `None` when the system has no home directory.
pub fn path() -> Option<PathBuf> {
ProjectDirs::from("", "", "thokr").map(|dirs| dirs.config_dir().join("log.csv"))
}

/// Appends the results of a finished test to the log.
pub fn append(thok: &Thok) -> io::Result<()> {
match path() {
Some(path) => append_row(&path, &row(Local::now().naive_local(), thok)),
None => Ok(()),
}
}

fn row(finished_at: NaiveDateTime, thok: &Thok) -> String {
format!(
"{},{},{},{:.2},{},{},{:.2}",
finished_at.format("%c"),
thok.number_of_words,
thok.number_of_secs
.map_or_else(String::new, |secs| format!("{secs:.2}")),
thok.elapsed_secs,
thok.wpm, // already a whole number
thok.accuracy, // already a whole number
thok.std_dev,
)
}

/// Appends `row` to the file at `path`. A file that does not exist yet is
/// created, along with its folder, and starts with the header.
fn append_row(path: &Path, row: &str) -> io::Result<()> {
if let Some(folder) = path.parent() {
fs::create_dir_all(folder)?;
}
let is_new = !path.exists();
let mut file = OpenOptions::new().append(true).create(true).open(path)?;
if is_new {
writeln!(file, "{HEADER}")?;
}
writeln!(file, "{row}")
}

#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDate;

/// A log as thokr 0.5.0 wrote it: a word test, then a timed test.
const OLD_LOG: &str = "\
date,num_words,num_secs,elapsed_secs,wpm,accuracy,std_dev
Mon Oct 12 10:19:27 2026,15,,3.42,64,95,1.70
Mon Oct 12 10:19:44 2026,15,3.00,2.99,72,100,0.00
";

fn finished_thok(number_of_secs: Option<f64>) -> Thok {
let mut thok = Thok::new("the quick brown fox".to_string(), 4, number_of_secs);
thok.elapsed_secs = 5.2549;
thok.wpm = 36.0;
thok.accuracy = 95.0;
thok.std_dev = 1.0198;
thok
}

fn date() -> NaiveDateTime {
NaiveDate::from_ymd_opt(2026, 10, 5)
.unwrap()
.and_hms_opt(9, 7, 3)
.unwrap()
}

/// Reads a row back column by column, the way a spreadsheet or a script would.
fn parse(row: &str) -> (NaiveDateTime, usize, Option<f64>, f64, u32, u32, f64) {
let columns: Vec<&str> = row.split(',').collect();
assert_eq!(columns.len(), HEADER.split(',').count(), "{row}");
(
NaiveDateTime::parse_from_str(columns[0], "%c").unwrap(),
columns[1].parse().unwrap(),
(!columns[2].is_empty()).then(|| columns[2].parse().unwrap()),
columns[3].parse().unwrap(),
columns[4].parse().unwrap(),
columns[5].parse().unwrap(),
columns[6].parse().unwrap(),
)
}

#[test]
fn row_keeps_the_format_of_existing_logs() {
assert_eq!(
row(date(), &finished_thok(None)),
"Mon Oct 5 09:07:03 2026,4,,5.25,36,95,1.02"
);
assert_eq!(
row(date(), &finished_thok(Some(30.0))),
"Mon Oct 5 09:07:03 2026,4,30.00,5.25,36,95,1.02"
);
}

#[test]
fn old_and_new_rows_parse_the_same_way() {
let mut rows = OLD_LOG.lines();
assert_eq!(rows.next(), Some(HEADER));
let word_test = parse(rows.next().unwrap());
assert_eq!((word_test.1, word_test.2, word_test.4), (15, None, 64));
let timed_test = parse(rows.next().unwrap());
assert_eq!((timed_test.2, timed_test.3), (Some(3.0), 2.99));

let new = parse(&row(date(), &finished_thok(Some(30.0))));
assert_eq!(new, (date(), 4, Some(30.0), 5.25, 36, 95, 1.02));
}

#[test]
fn append_adds_to_an_existing_log_and_starts_a_new_one_with_the_header() {
let folder = std::env::temp_dir().join(format!("thokr-test-{}", std::process::id()));
let new_row = row(date(), &finished_thok(None));

// a log from an older version is appended to, not rewritten
let existing = folder.join("existing").join("log.csv");
fs::create_dir_all(existing.parent().unwrap()).unwrap();
fs::write(&existing, OLD_LOG).unwrap();
append_row(&existing, &new_row).unwrap();
assert_eq!(
fs::read_to_string(&existing).unwrap(),
format!("{OLD_LOG}{new_row}\n")
);

// a first run creates the folder and the file, header first
let fresh = folder.join("fresh").join("thokr").join("log.csv");
append_row(&fresh, &new_row).unwrap();
append_row(&fresh, &new_row).unwrap();
assert_eq!(
fs::read_to_string(&fresh).unwrap(),
format!("{HEADER}\n{new_row}\n{new_row}\n")
);

fs::remove_dir_all(&folder).unwrap();
}

#[test]
fn append_reports_a_log_that_cannot_be_written() {
// a folder cannot be created underneath a regular file
let blocker = std::env::temp_dir().join(format!("thokr-test-file-{}", std::process::id()));
fs::write(&blocker, "").unwrap();
assert!(append_row(&blocker.join("thokr").join("log.csv"), "row").is_err());
fs::remove_file(&blocker).unwrap();
}
}
100 changes: 100 additions & 0 deletions src/lang.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
use cgisf_lib::cgisf;
use clap::ValueEnum;
use rand::{Rng, seq::SliceRandom};

// A word list is compiled into the binary as text, one word per line.
#[derive(Debug, Copy, Clone, ValueEnum)]
pub enum Language {
English,
English1k,
English10k,
}

impl Language {
fn words(self) -> &'static str {
match self {
Self::English => include_str!("lang/english.txt"),
Self::English1k => include_str!("lang/english1k.txt"),
Self::English10k => include_str!("lang/english10k.txt"),
}
}

/// `count` different words in random order, joined by spaces. A list
/// shorter than `count` gives every word it has.
pub fn random_words(self, count: usize) -> String {
let words: Vec<&str> = self.words().lines().collect();
let picked: Vec<&str> = words
.choose_multiple(&mut rand::thread_rng(), count)
.copied()
.collect();
picked.join(" ")
}
}

/// `count` random sentences joined by spaces, and how many words they hold.
pub fn random_sentences(count: usize) -> (String, usize) {
let mut rng = rand::thread_rng();
let mut text = String::new();
for _ in 0..count {
text.push_str(&cgisf(
rng.gen_range(1..3),
rng.gen_range(1..3),
rng.gen_range(1..5),
rng.gen_bool(0.5),
rng.gen_range(1..3),
rng.gen_bool(0.5),
));
}
// every sentence ends with a space, so the spaces count the words
let word_count = text.matches(' ').count();
text.pop();
(text, word_count)
}

#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;

#[test]
fn word_lists_hold_one_word_per_line() {
for (language, size) in [
(Language::English, 200),
(Language::English1k, 999),
(Language::English10k, 9954),
] {
let words: Vec<&str> = language.words().lines().collect();
assert_eq!(words.len(), size, "{language:?}");
assert!(
words.iter().all(|w| !w.is_empty() && !w.contains(' ')),
"{language:?} has a blank line or a space"
);
}
}

#[test]
fn random_words_are_distinct_words_of_the_list() {
let list: HashSet<&str> = Language::English.words().lines().collect();
let prompt = Language::English.random_words(15);
let words: Vec<&str> = prompt.split(' ').collect();
assert_eq!(words.len(), 15);
assert_eq!(words.iter().collect::<HashSet<_>>().len(), 15);
assert!(words.iter().all(|w| list.contains(w)));
}

#[test]
fn random_words_stop_at_the_size_of_the_list() {
let prompt = Language::English.random_words(500);
assert_eq!(prompt.split(' ').count(), 200);
assert_eq!(Language::English.random_words(0), "");
}

#[test]
fn random_sentences_count_their_words() {
let (text, word_count) = random_sentences(3);
assert_eq!(text.split(' ').count(), word_count);
assert_eq!(text.matches('.').count(), 3);
assert!(text.ends_with('.'));
assert_eq!(random_sentences(0), (String::new(), 0));
}
}
Loading
Loading
0