Skip to content

feat: statistics dialog #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
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
832 changes: 699 additions & 133 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,21 @@ version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = "1.0.95"
discord-presence = "1.5.0"
# Locked to 0.7.0 because of https://github.com/hfiguiere/i18n-format/issues/1
gettext-rs = { version = "=0.7.0", features = ["gettext-system"] }
graphene = { package = "graphene-rs", version = "0.20.7" }
gvdb-macros = "0.1.12"
i18n-format = "0.2.0"
include_dir = "0.7.3"
rand = "0.8.5"
rayon = "1.10.0"
refinery = { version = "0.8.14", features = ["rusqlite"] }
rusqlite = { version = "=0.31.0", features = ["bundled", "time"] } # Locked until Refinery is updated
strum = "0.26.2"
strum_macros = "0.26.2"
time = { version = "0.3.37", features = ["parsing", "local-offset"] }
unicode-segmentation = "1.11.0"
unidecode = "0.3.0"

Expand Down
6 changes: 3 additions & 3 deletions data/artwork/icon/dev.bragefuglseth.Keypunch.Source.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions data/resources/icons/scalable/actions/graph-symbolic.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions data/resources/icons/scalable/actions/lightbulb-symbolic.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions data/resources/style-hc.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.line-chart-button > button {
box-shadow: none;
}

.line-chart-button .line-chart-dot {
background-color: currentColor;
}
37 changes: 35 additions & 2 deletions data/resources/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ KpTextView > textview {
font-variant-ligatures: none;
}

KpResultsView .key-number {
font-size: 3.5rem;
.key-number {
font-size: 3.2rem;
font-weight: 700;
}

Expand Down Expand Up @@ -49,3 +49,36 @@ window.hide-controls headerbar.test .end {
border-radius: 9999px;
}

.group-header {
padding: 6px 0px;
}

.wpm-legend {
border-bottom: 2px solid var(--accent-bg-color);
}

.accuracy-legend {
border-bottom: 2px dashed currentColor;
opacity: calc(var(--dim-opacity) - 0.2);
}

.line-chart-dot {
border-radius: 50%;
background-color: var(--accent-bg-color);
transition: transform 200ms;
}

.line-chart-button > button {
background: transparent;
padding: 0px;
}

.line-chart-button > button:hover .line-chart-dot,
.line-chart-button > button:checked .line-chart-dot {
transform: scale(2);
}

.line-chart-button {
--popover-bg-color: var(--accent-bg-color);
--popover-fg-color: var(--light-1);
}
277 changes: 277 additions & 0 deletions src/database.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@
use crate::typing_test_utils::*;
use anyhow::Result;
use gettextrs::gettext;
use i18n_format::i18n_fmt;
use rusqlite::Connection;
use std::fs;
use std::path::PathBuf;
use std::sync::LazyLock;
use time::{Date, Duration, Month, OffsetDateTime, Time};

pub struct ChartItem {
pub title: String,
pub time_index: usize,
pub wpm: f64,
pub accuracy: f64,
}

pub struct PeriodSummary {
pub wpm: f64,
pub accuracy: f64,
pub finish_rate: f64,
pub practice_time: String, // TODO: store this as a time::Duration instead
}

pub const DATABASE: LazyLock<TypingStatsDb> = LazyLock::new(|| {
let path = gtk::glib::user_data_dir().join("keypunch");

TypingStatsDb::setup(path).unwrap()
});

refinery::embed_migrations!("./src/migrations");

pub struct TypingStatsDb(Connection);

impl TypingStatsDb {
pub fn setup(location: PathBuf) -> Result<TypingStatsDb> {
fs::create_dir_all(&location)?;

let mut conn = Connection::open(&location.join("statistics.sqlite")).unwrap();
migrations::runner().run(&mut conn).unwrap();

Ok(TypingStatsDb(conn))
}

pub fn push_summary(&self, summary: &TestSummary) -> Result<()> {
let (test_type, language, duration) = match summary.config {
TestConfig::Finite => ("Custom", None, None),
TestConfig::Generated {
difficulty,
language,
duration,
..
} => {
let difficulty = match difficulty {
GeneratedTestDifficulty::Simple => "Simple",
GeneratedTestDifficulty::Advanced => "Advanced",
};
(
difficulty,
Some(language.to_string()),
Some(duration.to_string()),
)
}
};

self.0.execute(
"
INSERT INTO tests (
timestamp,
finished,
test_type,
language,
duration,
real_duration,
wpm,
accuracy
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(
summary.start_timestamp,
summary.finished,
test_type,
language,
duration,
summary.real_duration.as_secs(),
summary.wpm,
summary.accuracy,
),
)?;
Ok(())
}

// Returns the average WPM and accuracy at a given date
pub fn average_from_period(
&self,
start: OffsetDateTime,
end: OffsetDateTime,
) -> rusqlite::Result<(f64, f64)> {
self.0.query_row(
"SELECT AVG(wpm), AVG(accuracy)
FROM tests
WHERE finished = TRUE
AND UNIXEPOCH(timestamp) BETWEEN ? AND ?
AND test_type IN ('Simple', 'Advanced')",
(start.unix_timestamp(), end.unix_timestamp()),
|row| Ok((row.get(0)?, row.get(1)?)),
)
}

pub fn get_past_month(&self) -> Option<Vec<ChartItem>> {
let now = OffsetDateTime::now_local().unwrap_or(OffsetDateTime::now_utc());
let today_start = now.replace_time(Time::MIDNIGHT);
let today_end = now.replace_time(Time::MAX);

let mut month_data: Vec<ChartItem> = (0..30)
.filter_map(|n| {
let start = today_start - Duration::days(29 - n);
let end = today_end - Duration::days(29 - n);

if let Ok((wpm, accuracy)) = DATABASE.average_from_period(start, end) {
Some(ChartItem {
title: formatted_date(start.date()),
time_index: n as usize,
wpm,
accuracy,
})
} else {
None
}
})
.collect();

let &ChartItem {
time_index: time_offset,
..
} = month_data.get(0)?;

for item in month_data.iter_mut() {
item.time_index -= time_offset;
}

Some(month_data)
}

pub fn get_past_year(&self) -> Option<Vec<ChartItem>> {
let now = OffsetDateTime::now_local().unwrap_or(OffsetDateTime::now_utc());

let mut month_data: Vec<ChartItem> = (0..12)
.filter_map(|n| {
let mut start = now.replace_day(1).unwrap().replace_time(Time::MIDNIGHT);

for _ in 0..(11 - n) {
let prev_month_length = start.month().previous().length(start.year());
start -= Duration::days(prev_month_length as i64)
}

let month_length = start.month().length(start.year());
let end = start
.replace_day(month_length)
.unwrap()
.replace_time(Time::MAX);

if let Ok((wpm, accuracy)) = DATABASE.average_from_period(start, end) {
Some(ChartItem {
title: formatted_month(start.date()),
time_index: n as usize,
wpm,
accuracy,
})
} else {
None
}
})
.collect();

let &ChartItem {
time_index: time_offset,
..
} = month_data.get(0)?;

for item in month_data.iter_mut() {
item.time_index -= time_offset;
}

Some(month_data)
}

pub fn last_month_summary(&self) -> Option<PeriodSummary> {
let now = OffsetDateTime::now_local().unwrap_or(OffsetDateTime::now_utc());

let start = now.replace_time(Time::MIDNIGHT) - Duration::days(27);
let (wpm, accuracy) = self.average_from_period(start, now).ok()?;

let (finish_rate, practice_time) = self
.0
.query_row(
"SELECT SUM(finished), COUNT(*), SUM(real_duration)
FROM tests
WHERE UNIXEPOCH(timestamp) BETWEEN ? AND ?
AND test_type IN ('Simple', 'Advanced')",
(start.unix_timestamp(), now.unix_timestamp()),
|row| Ok((row.get::<_, f64>(0)? / row.get::<_, f64>(1)?, row.get::<_, i64>(2)?)),
)
.ok()?;

Some(PeriodSummary {
wpm,
accuracy,
finish_rate,
practice_time: human_readable_duration_short(Duration::seconds(practice_time))
})
}
}

// TODO: move i18n stuff into separate file

fn formatted_date(date: Date) -> String {
let day = date.day();

match date.month() {
// Translators: This is a date. The {} is replaced with a number.
Month::January => i18n_fmt! { i18n_fmt("January {}", day) },
Month::February => i18n_fmt! { i18n_fmt("February {}", day) },
Month::March => i18n_fmt! { i18n_fmt("March {}", day) },
Month::April => i18n_fmt! { i18n_fmt("April {}", day) },
Month::May => i18n_fmt! { i18n_fmt("May {}", day) },
Month::June => i18n_fmt! { i18n_fmt("June {}", day) },
Month::July => i18n_fmt! { i18n_fmt("July {}", day) },
Month::August => i18n_fmt! { i18n_fmt("August {}", day) },
Month::September => i18n_fmt! { i18n_fmt("September {}", day) },
Month::October => i18n_fmt! { i18n_fmt("October {}", day) },
Month::November => i18n_fmt! { i18n_fmt("November {}", day) },
Month::December => i18n_fmt! { i18n_fmt("December {}", day) },
}
}

fn formatted_month(date: Date) -> String {
let year = date.year();

match date.month() {
// Translators: This is a month label for the "monthly" view in the statistics dialog.
// The {} is replaced with a year.
Month::January => i18n_fmt! { i18n_fmt("January {}", year) },
Month::February => i18n_fmt! { i18n_fmt("February {}", year) },
Month::March => i18n_fmt! { i18n_fmt("March {}", year) },
Month::April => i18n_fmt! { i18n_fmt("April {}", year) },
Month::May => i18n_fmt! { i18n_fmt("May {}", year) },
Month::June => i18n_fmt! { i18n_fmt("June {}", year) },
Month::July => i18n_fmt! { i18n_fmt("July {}", year) },
Month::August => i18n_fmt! { i18n_fmt("August {}", year) },
Month::September => i18n_fmt! { i18n_fmt("September {}", year) },
Month::October => i18n_fmt! { i18n_fmt("October {}", year) },
Month::November => i18n_fmt! { i18n_fmt("November {}", year) },
Month::December => i18n_fmt! { i18n_fmt("December {}", year) },
}
}

pub fn human_readable_duration_short(duration: Duration) -> String {
let total_secs = duration.as_seconds_f32().floor() as u32;

let minutes = total_secs / 60;
let secs = total_secs % 60;

if minutes > 0 && secs > 0 {
// Translators: The `{}` blocks will be replaced with the number of minutes
// and seconds. Do not translate them!
i18n_fmt! { i18n_fmt("{}m {}s", minutes, secs) }
} else if minutes > 0 {
// Translators: The `{}` block will be replaced with the number of minutes.
// Do not translate it!
i18n_fmt! { i18n_nfmt("{} m", "{} m", minutes as u32, minutes) }
} else {
// Translators: The `{}` block will be replaced with the number of seconds.
// Do not translate it!
i18n_fmt! { i18n_nfmt("{} s", "{} s", secs as u32, secs) }
}
}
File renamed without changes.
Loading