1use std::collections::HashMap;
17use std::path::PathBuf;
18use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use serde::{Deserialize, Serialize};
21
22use crate::model::{Item, ItemKey};
23
24const MAX_BOOST: f32 = 0.5;
31
32const MAX_AGE_DAYS: f64 = 90.0;
34
35#[derive(Debug, Clone, Default, Serialize, Deserialize)]
36struct Entry {
37 count: u32,
39 last_used: u64,
41}
42
43impl Entry {
44 fn recency_weight(&self, now: u64) -> f32 {
46 let age_days = (now.saturating_sub(self.last_used) as f64) / 86_400.0;
47 let weight = if age_days < 1.0 {
49 1.0
50 } else if age_days < 7.0 {
51 0.7
52 } else if age_days < 30.0 {
53 0.4
54 } else if age_days < MAX_AGE_DAYS {
55 0.2
56 } else {
57 0.0
58 };
59 weight as f32
60 }
61
62 fn score(&self, now: u64) -> f32 {
63 let volume = (f64::from(self.count) + 1.0).ln() as f32;
66 volume * self.recency_weight(now)
67 }
68}
69
70#[derive(Debug, Clone, PartialEq)]
73pub struct Usage {
74 pub count: u32,
76 pub age: Duration,
78 pub recency_weight: f32,
81 pub score: f32,
84}
85
86#[derive(Debug, Default)]
88pub struct Frecency {
89 entries: HashMap<ItemKey, Entry>,
90 path: Option<PathBuf>,
91 dirty: bool,
93}
94
95impl Frecency {
96 #[must_use]
100 pub fn load() -> Self {
101 let Some(path) = Self::default_path() else {
102 tracing::warn!("no data directory; frecency will not persist");
103 return Self::default();
104 };
105
106 let entries = match std::fs::read_to_string(&path) {
107 Ok(contents) => serde_json::from_str(&contents).unwrap_or_else(|error| {
108 tracing::warn!(%error, ?path, "discarding unreadable frecency history");
109 HashMap::new()
110 }),
111 Err(error) if error.kind() == std::io::ErrorKind::NotFound => HashMap::new(),
112 Err(error) => {
113 tracing::warn!(%error, ?path, "failed to read frecency history");
114 HashMap::new()
115 }
116 };
117
118 Self {
119 entries,
120 path: Some(path),
121 dirty: false,
122 }
123 }
124
125 fn default_path() -> Option<PathBuf> {
126 dirs::data_dir().map(|dir| dir.join("jump").join("frecency.json"))
127 }
128
129 #[must_use]
136 pub fn is_empty(&self) -> bool {
137 self.entries.is_empty()
138 }
139
140 #[must_use]
147 pub fn explain(&self, key: &ItemKey) -> Option<Usage> {
148 let now = now_secs();
149 self.entries.get(key).map(|usage| Usage {
150 count: usage.count,
151 age: Duration::from_secs(now.saturating_sub(usage.last_used)),
152 recency_weight: usage.recency_weight(now),
153 score: usage.score(now),
154 })
155 }
156
157 pub fn record(&mut self, key: &ItemKey) {
159 let entry = self.entries.entry(key.clone()).or_default();
160 entry.count = entry.count.saturating_add(1);
161 entry.last_used = now_secs();
162 self.dirty = true;
163 }
164
165 pub fn boost(&self, items: &mut [Item]) {
172 if items.is_empty() {
173 return;
174 }
175
176 let now = now_secs();
177
178 let max_usage = items
182 .iter()
183 .filter_map(|item| self.entries.get(&item.key))
184 .map(|usage| usage.score(now))
185 .fold(0.0_f32, f32::max);
186
187 if max_usage <= 0.0 {
188 return;
189 }
190
191 for item in items.iter_mut() {
192 item.score += self
193 .entries
194 .get(&item.key)
195 .map_or(0.0, |usage| usage.score(now) / max_usage)
196 * MAX_BOOST;
197 }
198 }
199
200 pub fn save(&mut self) {
202 if !self.dirty {
203 return;
204 }
205 let Some(path) = self.path.as_ref() else {
206 return;
207 };
208
209 if let Some(parent) = path.parent()
210 && let Err(error) = std::fs::create_dir_all(parent)
211 {
212 tracing::warn!(%error, ?parent, "failed to create data directory");
213 return;
214 }
215
216 let Ok(contents) = serde_json::to_string(&self.entries) else {
217 return;
218 };
219
220 let temporary = path.with_extension("json.tmp");
222 if let Err(error) = std::fs::write(&temporary, contents) {
223 tracing::warn!(%error, ?temporary, "failed to write frecency history");
224 return;
225 }
226 if let Err(error) = std::fs::rename(&temporary, path) {
227 tracing::warn!(%error, ?path, "failed to replace frecency history");
228 return;
229 }
230
231 self.dirty = false;
232 }
233}
234
235fn now_secs() -> u64 {
236 SystemTime::now()
237 .duration_since(UNIX_EPOCH)
238 .map_or(0, |duration| duration.as_secs())
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244 use crate::model::Source;
245
246 fn item(name: &str) -> Item {
247 Item {
248 key: ItemKey(format!("entry:{name}")),
249 id: 0,
250 title: name.to_owned(),
251 subtitle: String::new(),
252 icon: None,
253 category_icon: None,
254 window: None,
255 source: Source::Launcher,
256 autocomplete: None,
257 score: 0.0,
258 }
259 }
260
261 #[test]
262 fn usage_breaks_ties_between_equal_matches() {
263 let mut frecency = Frecency::default();
264 frecency.record(&ItemKey("entry:Firefox".to_owned()));
265 frecency.record(&ItemKey("entry:Firefox".to_owned()));
266
267 let mut items = vec![item("Files"), item("Firefox")];
269 for entry in &mut items {
270 entry.score = 0.6;
271 }
272 frecency.boost(&mut items);
273
274 assert!(
275 items[1].score > items[0].score,
276 "the used entry gains a boost"
277 );
278 }
279
280 #[test]
281 fn usage_cannot_override_a_clearly_better_match() {
282 let mut frecency = Frecency::default();
283 for _ in 0..50 {
284 frecency.record(&ItemKey("entry:Firefox".to_owned()));
285 }
286
287 let mut items = vec![item("Files"), item("Firefox")];
288 items[0].score = 1.0;
290 items[1].score = 0.15;
291 frecency.boost(&mut items);
292
293 assert!(items[0].score > items[1].score);
294 }
295
296 #[test]
297 fn scores_are_untouched_without_history() {
298 let frecency = Frecency::default();
299 let mut items = vec![item("Files"), item("Firefox")];
300 items[0].score = 0.7;
301 items[1].score = 0.3;
302 frecency.boost(&mut items);
303
304 assert!((items[0].score - 0.7).abs() < f32::EPSILON);
305 assert!((items[1].score - 0.3).abs() < f32::EPSILON);
306 }
307
308 #[test]
309 fn stale_usage_stops_contributing() {
310 let usage = Entry {
311 count: 100,
312 last_used: 0,
313 };
314 assert_eq!(usage.score(now_secs()), 0.0);
316 }
317}