use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use crate::model::{Item, ItemKey};
const MAX_BOOST: f32 = 0.5;
const MAX_AGE_DAYS: f64 = 90.0;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Entry {
count: u32,
last_used: u64,
}
impl Entry {
fn recency_weight(&self, now: u64) -> f32 {
let age_days = (now.saturating_sub(self.last_used) as f64) / 86_400.0;
let weight = if age_days < 1.0 {
1.0
} else if age_days < 7.0 {
0.7
} else if age_days < 30.0 {
0.4
} else if age_days < MAX_AGE_DAYS {
0.2
} else {
0.0
};
weight as f32
}
fn score(&self, now: u64) -> f32 {
let volume = (f64::from(self.count) + 1.0).ln() as f32;
volume * self.recency_weight(now)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Usage {
pub count: u32,
pub age: Duration,
pub recency_weight: f32,
pub score: f32,
}
#[derive(Debug, Default)]
pub struct Frecency {
entries: HashMap<ItemKey, Entry>,
path: Option<PathBuf>,
dirty: bool,
}
impl Frecency {
#[must_use]
pub fn load() -> Self {
let Some(path) = Self::default_path() else {
tracing::warn!("no data directory; frecency will not persist");
return Self::default();
};
let entries = match std::fs::read_to_string(&path) {
Ok(contents) => serde_json::from_str(&contents).unwrap_or_else(|error| {
tracing::warn!(%error, ?path, "discarding unreadable frecency history");
HashMap::new()
}),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => HashMap::new(),
Err(error) => {
tracing::warn!(%error, ?path, "failed to read frecency history");
HashMap::new()
}
};
Self {
entries,
path: Some(path),
dirty: false,
}
}
fn default_path() -> Option<PathBuf> {
dirs::data_dir().map(|dir| dir.join("jump").join("frecency.json"))
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn explain(&self, key: &ItemKey) -> Option<Usage> {
let now = now_secs();
self.entries.get(key).map(|usage| Usage {
count: usage.count,
age: Duration::from_secs(now.saturating_sub(usage.last_used)),
recency_weight: usage.recency_weight(now),
score: usage.score(now),
})
}
pub fn record(&mut self, key: &ItemKey) {
let entry = self.entries.entry(key.clone()).or_default();
entry.count = entry.count.saturating_add(1);
entry.last_used = now_secs();
self.dirty = true;
}
pub fn boost(&self, items: &mut [Item]) {
if items.is_empty() {
return;
}
let now = now_secs();
let max_usage = items
.iter()
.filter_map(|item| self.entries.get(&item.key))
.map(|usage| usage.score(now))
.fold(0.0_f32, f32::max);
if max_usage <= 0.0 {
return;
}
for item in items.iter_mut() {
item.score += self
.entries
.get(&item.key)
.map_or(0.0, |usage| usage.score(now) / max_usage)
* MAX_BOOST;
}
}
pub fn save(&mut self) {
if !self.dirty {
return;
}
let Some(path) = self.path.as_ref() else {
return;
};
if let Some(parent) = path.parent()
&& let Err(error) = std::fs::create_dir_all(parent)
{
tracing::warn!(%error, ?parent, "failed to create data directory");
return;
}
let Ok(contents) = serde_json::to_string(&self.entries) else {
return;
};
let temporary = path.with_extension("json.tmp");
if let Err(error) = std::fs::write(&temporary, contents) {
tracing::warn!(%error, ?temporary, "failed to write frecency history");
return;
}
if let Err(error) = std::fs::rename(&temporary, path) {
tracing::warn!(%error, ?path, "failed to replace frecency history");
return;
}
self.dirty = false;
}
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_secs())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::Source;
fn item(name: &str) -> Item {
Item {
key: ItemKey(format!("entry:{name}")),
id: 0,
title: name.to_owned(),
subtitle: String::new(),
icon: None,
category_icon: None,
window: None,
source: Source::Launcher,
autocomplete: None,
score: 0.0,
}
}
#[test]
fn usage_breaks_ties_between_equal_matches() {
let mut frecency = Frecency::default();
frecency.record(&ItemKey("entry:Firefox".to_owned()));
frecency.record(&ItemKey("entry:Firefox".to_owned()));
let mut items = vec![item("Files"), item("Firefox")];
for entry in &mut items {
entry.score = 0.6;
}
frecency.boost(&mut items);
assert!(
items[1].score > items[0].score,
"the used entry gains a boost"
);
}
#[test]
fn usage_cannot_override_a_clearly_better_match() {
let mut frecency = Frecency::default();
for _ in 0..50 {
frecency.record(&ItemKey("entry:Firefox".to_owned()));
}
let mut items = vec![item("Files"), item("Firefox")];
items[0].score = 1.0;
items[1].score = 0.15;
frecency.boost(&mut items);
assert!(items[0].score > items[1].score);
}
#[test]
fn scores_are_untouched_without_history() {
let frecency = Frecency::default();
let mut items = vec![item("Files"), item("Firefox")];
items[0].score = 0.7;
items[1].score = 0.3;
frecency.boost(&mut items);
assert!((items[0].score - 0.7).abs() < f32::EPSILON);
assert!((items[1].score - 0.3).abs() < f32::EPSILON);
}
#[test]
fn stale_usage_stops_contributing() {
let usage = Entry {
count: 100,
last_used: 0,
};
assert_eq!(usage.score(now_secs()), 0.0);
}
}