diff --git a/app/README.md b/app/README.md index fd26ec0..970d443 100644 --- a/app/README.md +++ b/app/README.md @@ -78,6 +78,10 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti 4. Match history: done. Cards read `GameHistory.vue`'s fields (result, champion portrait, queue, KDA, CS/m, gold/m, LP change) from the raw API responses in each timeline, with the queue filters. Portraits come from Data Dragon and are cached on disk (`src/portraits.rs`). + The list holds rows, not timelines: `history::summaries` parses each file, keeps a + `Summary`, and drops the timeline with its events and raw responses, 20 rows at a time as + the list scrolls. Opening a row reads that one timeline again, on a thread, and the review + screen fills in when it arrives. Peak over 313 recordings: 165 MB, down from 2.1 GB. 5. Video: not libmpv. Rune ships a `Player` with a native surface and frame seeking (`Player::file`, `seek`, `duration`), which removes the OpenGL and wgpu interop question the TODO opened. The review screen uses it. If clip-accurate seeking turns out to be worse than diff --git a/app/src/app.rs b/app/src/app.rs index 29956fa..916de00 100644 --- a/app/src/app.rs +++ b/app/src/app.rs @@ -1,12 +1,13 @@ //! App state, the frame hook and the screen dispatch. +use std::path::PathBuf; use std::sync::mpsc::{Receiver, TryRecvError, channel}; use std::time::Duration; use rune::tok::type_; use rune::{Cx, El, Key, KeyEvent, Tx, col, el, row, text}; -use crate::history::{self, QueueCategory, Timeline}; +use crate::history::{self, QueueCategory, Summary, Timeline}; use crate::ipc::{self, Daemon}; use crate::os; use crate::portraits; @@ -92,6 +93,16 @@ pub struct AudioDevice { pub is_default: bool, } +/// How many rows the history reads at a time. +const GAMES_PAGE: usize = 20; + +/// One page of history rows, with the file list when it is the first page. +pub struct GamesPage { + paths: Vec, + next: usize, + games: Vec, +} + /// A message banner shown above the screen until dismissed. #[derive(Debug, Clone)] pub struct Notice { @@ -110,9 +121,16 @@ pub struct App { pub form: screens::settings::Form, pub encoders: Encoders, pub devices: AudioDevices, - pub games: Vec, - pub games_rx: Option>>, + /// One row per recording on disk, a page at a time. + pub games: Vec, + /// Every timeline file, most recent first: `games` holds the first `games_next` of them. + pub games_paths: Vec, + pub games_rx: Option>, pub games_loaded: bool, + /// How many of `games_paths` have been turned into rows. + pub games_next: usize, + /// The timeline the review is waiting for, once a row is opened. + pub review_rx: Option>>, pub filter: Option, pub review: screens::review::Review, pub portraits: Option, @@ -155,8 +173,11 @@ impl App { encoders: Encoders::default(), devices: AudioDevices::default(), games: Vec::new(), + games_paths: Vec::new(), games_rx: None, games_loaded: false, + games_next: 0, + review_rx: None, filter: None, review: screens::review::Review::default(), portraits: None, @@ -192,7 +213,10 @@ impl App { current_game_id: None, client_connected: true, }; - self.games = history::sample(); + self.games = history::sample() + .iter() + .map(|game| game.summary()) + .collect(); self.games_loaded = true; self.devices = AudioDevices { input_devices: vec![AudioDevice { @@ -360,23 +384,58 @@ impl App { self.processes_rx = Some(rx); } - /// Read the timelines on a thread of their own; `poll` picks the list up. + /// List the timelines on disk and read the first page of rows on a thread of their own. + /// `poll` picks them up. pub fn refresh_games(&mut self) { if self.games_rx.is_some() { return; } let (tx, rx) = channel(); std::thread::spawn(move || { - let games = history::load_all(); - let _ = tx.send(games); + let paths = history::timeline_paths(); + let end = paths.len().min(GAMES_PAGE); + let games = history::summaries(&paths[..end]); + let _ = tx.send(GamesPage { + paths, + next: end, + games, + }); }); self.games_rx = Some(rx); } + /// Read the next page of rows, if the list has one and none is already on its way. + /// + /// Called from `poll` while the history list is scrolled near its end, and while the + /// filtered list is shorter than the screen. + pub fn load_more_games(&mut self) { + if self.games_rx.is_some() || self.games_next >= self.games_paths.len() { + return; + } + let start = self.games_next; + let end = (start + GAMES_PAGE).min(self.games_paths.len()); + let page = self.games_paths[start..end].to_vec(); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let games = history::summaries(&page); + let _ = tx.send(GamesPage { + paths: Vec::new(), + next: end, + games, + }); + }); + self.games_next = end; + self.games_rx = Some(rx); + } + + /// Whether more rows are waiting to be read. + pub fn more_games(&self) -> bool { + self.games_next < self.games_paths.len() + } + /// The game the review screen is showing, if any. pub fn reviewed(&self) -> Option<&Timeline> { - let id = self.review.game.as_deref()?; - self.games.iter().find(|game| game.recording_id == id) + self.review.game.as_ref() } } @@ -579,8 +638,17 @@ impl App { if let Some(rx) = &self.games_rx { match rx.try_recv() { - Ok(games) => { - self.games = games; + Ok(page) => { + if !page.paths.is_empty() { + self.games = page.games; + self.games_paths = page.paths; + } else { + self.games.extend(page.games); + } + // Pages arrive in write-time order; the list reads by start time. + self.games + .sort_by_key(|game| std::cmp::Reverse(game.start_time)); + self.games_next = page.next; self.games_loaded = true; self.games_rx = None; changed = true; @@ -593,6 +661,43 @@ impl App { } } + if let Some(rx) = &self.review_rx { + match rx.try_recv() { + Ok(None) => { + self.review_rx = None; + self.review.loading = false; + self.review.error = Some("That recording's timeline could not be read.".into()); + changed = true; + } + Ok(Some(game)) => { + self.review_rx = None; + self.review.loading = false; + screens::review::show(self, game); + changed = true; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => { + self.review_rx = None; + self.review.loading = false; + } + } + } + + // The history reads its rows a page at a time. Fetch the next page when the list is + // scrolled near its end, or when what it shows does not fill the screen: a filter can + // leave three rows on a page of twenty. + if self.screen == Screen::History + && self.games_loaded + && self.more_games() + && self.games_rx.is_none() + { + // Nothing has reported where the viewport is until a frame has laid it out. + let at = self.scroll.position(); + let room_left = at.max[1] - (at.offset[1] + at.viewport[1]); + if at.viewport[1] > 0.0 && room_left < 400.0 { + self.load_more_games(); + } + } let mut tray_events = Vec::new(); if let Some(rx) = &self.tray_events { while let Ok(event) = rx.try_recv() { @@ -906,15 +1011,22 @@ pub fn demo_review(app: &mut App) { app.pending_review = false; let live = std::env::args().any(|arg| arg == "--live"); if live { - let index = app + let row = app .games .iter() - .position(|game| !game.events.is_empty()) - .unwrap_or(0); - screens::review::open(app, index); + .find(|game| game.event_count > 0) + .map(|game| game.recording_id.clone()); + if let Some(id) = row { + screens::review::open(app, &id); + } return; } - app.review.game = app.games.first().map(|game| game.recording_id.clone()); + + let mut sample = crate::history::sample(); + if sample.is_empty() { + return; + } + screens::review::show(app, sample.remove(0)); app.review.error = Some("Sample recording: no clip on disk.".to_string()); // Snapshot hook: draw a real clip when one is handed in. if let Ok(path) = std::env::var("LR_DEMO_VIDEO") { @@ -923,10 +1035,4 @@ pub fn demo_review(app: &mut App) { app.review.player = Some(player); app.review.error = None; } - - if let Some(game) = app.games.first() { - app.review.highlights = - crate::highlight::compute(game, game.summoner().as_deref(), Default::default()); - app.review.duration = game.duration_secs.max(0) as f64; - } } diff --git a/app/src/history.rs b/app/src/history.rs index 7c55c6b..1cbc68b 100644 --- a/app/src/history.rs +++ b/app/src/history.rs @@ -130,64 +130,123 @@ pub fn timeline_dir() -> PathBuf { daemon::recordings_dir().join("timelines") } -/// Every timeline on disk, newest first. Files that fail to parse are skipped. -/// Every timeline on disk, newest first. The raw API responses make each file large (hundreds -/// of kilobytes), so the files are parsed in parallel. -pub fn load_all() -> Vec { +/// Timeline files on disk, most recently written first. +/// +/// The name is a recording id, so the write time is the only cheap order there is. A +/// recording is written when its game ends, which matches when it started closely enough for +/// a list that gets re-sorted by `start_time` as pages arrive. +pub fn timeline_paths() -> Vec { let dir = timeline_dir(); let Ok(entries) = std::fs::read_dir(&dir) else { return Vec::new(); }; - let paths: Vec = entries + let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries .flatten() .map(|entry| entry.path()) .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json")) + .filter_map(|path| { + let written = std::fs::metadata(&path).ok()?.modified().ok()?; + Some((written, path)) + }) .collect(); + found.sort_by_key(|(written, _)| std::cmp::Reverse(*written)); + found.into_iter().map(|(_, path)| path).collect() +} - let next = std::sync::atomic::AtomicUsize::new(0); - let parsed = std::sync::Mutex::new(Vec::with_capacity(paths.len())); - let threads = std::thread::available_parallelism() - .map(|count| count.get()) - .unwrap_or(4) - .clamp(1, 8); - - std::thread::scope(|scope| { - for _ in 0..threads { - scope.spawn(|| { - loop { - let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let Some(path) = paths.get(index) else { - break; - }; - let Ok(text) = std::fs::read_to_string(path) else { - continue; - }; - match serde_json::from_str::(&text) { - Ok(timeline) => parsed.lock().unwrap().push(timeline), - Err(e) => eprintln!("skipping {}: {e}", path.display()), - } - } - }); +/// The rows for a page of timelines. +/// +/// Each file is parsed whole, because the champion, the scoreline and the queue only exist +/// inside the raw responses, and the [`Timeline`] is dropped as soon as its [`Summary`] is +/// built. Only the summaries are kept, so the events and the raw JSON do not pile up. +pub fn summaries(paths: &[PathBuf]) -> Vec { + paths.iter().filter_map(|path| summary_of(path)).collect() +} + +fn summary_of(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + match serde_json::from_str::(&text) { + Ok(timeline) => Some(timeline.summary()), + Err(e) => { + eprintln!("skipping {}: {e}", path.display()); + None } - }); + } +} + +/// What the match history list needs from a recording. +/// +/// The list shows 309 rows of this at a time and the events and raw responses of the timeline +/// stay on disk until a row is opened, so this carries only the values they were read for. +#[derive(Debug, Clone)] +pub struct Summary { + pub recording_id: String, + pub start_time: DateTime, + pub duration_secs: i64, + champion: Option, + summoner: Option, + queue_label: String, + category: QueueCategory, + outcome: Outcome, + stats: Option, + lp: Option, + pub event_count: usize, +} + +impl Summary { + pub fn champion(&self) -> Option { + self.champion.clone() + } + + pub fn summoner(&self) -> Option { + self.summoner.clone() + } + + pub fn queue_label(&self) -> &str { + &self.queue_label + } - let mut out = parsed.into_inner().unwrap(); - out.sort_by_key(|timeline| std::cmp::Reverse(timeline.start_time)); - out + pub fn category(&self) -> QueueCategory { + self.category + } + + pub fn outcome(&self) -> Outcome { + self.outcome + } + + pub fn stats(&self) -> Option { + self.stats + } + + pub fn lp_change(&self) -> Option { + self.lp.clone() + } +} + +impl Timeline { + /// The list row for this recording, computed before the timeline is dropped. + pub fn summary(&self) -> Summary { + Summary { + recording_id: self.recording_id.clone(), + start_time: self.start_time, + duration_secs: self.duration_secs, + champion: self.champion(), + summoner: self.summoner(), + queue_label: self.queue_label(), + category: self.category(), + outcome: self.outcome(), + stats: self.stats(), + lp: self.lp_change(), + event_count: self.events.len(), + } + } } -/// One timeline by recording id. -#[allow(dead_code)] pub fn load(recording_id: &str) -> Option { let path = timeline_dir().join(format!("{recording_id}.json")); let text = std::fs::read_to_string(path).ok()?; serde_json::from_str(&text).ok() } -// --------------------------------------------------------------------------- -// Extractors, from types/timeline.ts -// --------------------------------------------------------------------------- - impl Timeline { fn end_stats(&self) -> Option<&Value> { self.raw_end_game_stats.as_ref() @@ -586,7 +645,29 @@ mod tests { assert_eq!(lp.tier, "EMERALD"); assert_eq!(lp.league_points, 74); } + #[test] + fn a_summary_keeps_what_the_row_shows() { + let summary = parsed().summary(); + assert_eq!(summary.recording_id, "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c"); + assert_eq!(summary.champion().as_deref(), Some("Kai'Sa")); + assert_eq!(summary.queue_label(), "Ranked Solo"); + assert_eq!(summary.outcome(), Outcome::Victory); + assert_eq!(summary.event_count, 2); + assert_eq!(summary.stats().unwrap().kills, 9); + assert_eq!(summary.lp_change().unwrap().delta, 21); + } + #[test] + fn pages_read_summaries_from_disk() { + let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("game.json"); + std::fs::write(&path, TIMELINE).unwrap(); + let rows = summaries(&[path, dir.join("missing.json")]); + assert_eq!(rows.len(), 1, "a file that cannot be read is skipped"); + assert_eq!(rows[0].champion().as_deref(), Some("Kai'Sa")); + let _ = std::fs::remove_dir_all(dir); + } #[test] fn a_video_is_found_by_its_timestamp_prefix() { let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4())); diff --git a/app/src/main.rs b/app/src/main.rs index 5d8dc1b..84ea737 100644 --- a/app/src/main.rs +++ b/app/src/main.rs @@ -22,7 +22,7 @@ use rune::AppSpec; fn main() { if std::env::args().any(|arg| arg == "--games") { - println!("{} timelines", crate::history::load_all().len()); + println!("{} timelines", crate::history::timeline_paths().len()); return; } if std::env::args().any(|arg| arg == "--probe") { @@ -79,7 +79,10 @@ fn main() { }), ("many", |app| { app.screen = app::Screen::History; - app.games = (0..30).flat_map(|_| crate::history::sample()).collect(); + app.games = (0..30) + .flat_map(|_| crate::history::sample()) + .map(|game| game.summary()) + .collect(); app.games_loaded = true; }), ], diff --git a/app/src/screens/history.rs b/app/src/screens/history.rs index 451c3ce..ba221e0 100644 --- a/app/src/screens/history.rs +++ b/app/src/screens/history.rs @@ -8,7 +8,7 @@ use rune::{Color, El, col, el, row, text}; use crate::app::App; use crate::format; -use crate::history::{Outcome, QueueCategory, Timeline}; +use crate::history::{Outcome, QueueCategory, Summary}; use crate::screens::review; use crate::ui::{self, Paint, body, heading}; @@ -34,11 +34,10 @@ fn outcome_color(p: Paint, outcome: Outcome) -> Color { } pub fn view(app: &App, p: Paint) -> El { - let filtered: Vec<(usize, &Timeline)> = app + let filtered: Vec<&Summary> = app .games .iter() - .enumerate() - .filter(|(_, g)| app.filter.is_none_or(|f| g.category() == f)) + .filter(|g| app.filter.is_none_or(|f| g.category() == f)) .collect(); // The scroll bar gets its own strip at the end, clear of the cards. @@ -64,7 +63,7 @@ pub fn view(app: &App, p: Paint) -> El { "Pick another queue above.", )); } else { - for (index, game) in filtered { + for (index, game) in filtered.iter().enumerate() { list = list.child(game_card(app, p, game, index)); } } @@ -104,7 +103,7 @@ pub fn view(app: &App, p: Paint) -> El { .color(p.t.text), ) .child( - text(format!("{} recordings", app.games.len())) + text(count_label(app)) .key("count") .font(body(11.5)) .color(p.muted()), @@ -127,6 +126,18 @@ pub fn view(app: &App, p: Paint) -> El { ) } +/// The line under the title: how many recordings there are, and how many have been read. +/// +/// The list reads a page at a time, so the two differ while it is filling up. +fn count_label(app: &App) -> String { + let total = app.games_paths.len().max(app.games.len()); + if app.more_games() { + format!("{} recordings · {} loaded", total, app.games.len()) + } else { + format!("{total} recordings") + } +} + fn empty(p: Paint, title: &str, detail: &str) -> El { col() .key("empty") @@ -148,9 +159,10 @@ fn empty(p: Paint, title: &str, detail: &str) -> El { ) } -fn game_card(app: &App, p: Paint, game: &Timeline, index: usize) -> El { +fn game_card(app: &App, p: Paint, game: &Summary, index: usize) -> El { let outcome = game.outcome(); let ink = outcome_color(p, outcome); + let id = game.recording_id.clone(); let champion = game.champion().unwrap_or_else(|| "Unknown champion".into()); let duration = game.duration_secs.max(0) as f64; let lp = game.lp_change(); @@ -223,7 +235,7 @@ fn game_card(app: &App, p: Paint, game: &Timeline, index: usize) -> El { .shadow(8.0, 24.0, p.t.shadow_soft) .hover(p.t.hover) .press(p.t.press) - .on_press(move |app: &mut App| review::open(app, index)) + .on_press(move |app: &mut App| review::open(app, &id)) .child( col().key("card").w_full().child(banner).child( row() diff --git a/app/src/screens/review.rs b/app/src/screens/review.rs index cfd2e7c..4a20f3e 100644 --- a/app/src/screens/review.rs +++ b/app/src/screens/review.rs @@ -8,12 +8,15 @@ use rune::{El, Player, SurfaceFit, Tx, col, el, row, text}; use crate::app::{App, Screen}; use crate::format; use crate::highlight::{self, Highlight}; -use crate::history::{Outcome, Timeline}; +use crate::history::{self, Outcome, Timeline}; use crate::ui::{self, Paint, body, heading}; #[derive(Default)] pub struct Review { - pub game: Option, + /// The opened recording, once its file has been read. + pub game: Option, + /// Set while that file is on its way to the screen. + pub loading: bool, pub player: Option, pub time: f64, pub duration: f64, @@ -45,30 +48,41 @@ impl Review { } } -/// Open a game in the review screen and load its clip. -pub fn open(app: &mut App, index: usize) { +/// Open a recording in the review screen. +/// +/// Only the id travels here: the timeline with its events and raw responses is a large file +/// and stays on disk until a row is opened. It is read on a thread, and `poll` hands it to +/// [`show`] when it arrives. +pub fn open(app: &mut App, recording_id: &str) { leave(app); app.screen = Screen::Review; + app.review.loading = true; - let Some(game) = app.games.get(index) else { - return; - }; - // Keep the recording id, not the row number: a new recording can re-sort the list. - app.review.game = Some(game.recording_id.clone()); + let id = recording_id.to_string(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(history::load(&id)); + }); + app.review_rx = Some(rx); +} + +/// Fill the review screen with a timeline that has been read, and load its clip. +pub fn show(app: &mut App, game: Timeline) { let path = game.video_path(); let highlights = highlight::compute( - game, + &game, game.summoner().as_deref(), highlight::Options::default(), ); - let duration = game.duration_secs.max(0) as f64; app.review.highlights = highlights; - app.review.duration = duration; + app.review.duration = game.duration_secs.max(0) as f64; + let video_file = game.video_file.clone(); + app.review.game = Some(game); let Some(path) = path else { app.review.error = Some(format!( "No video file found for this recording ({}).", - game.video_file.as_deref().unwrap_or("unnamed") + video_file.as_deref().unwrap_or("unnamed") )); return; }; @@ -82,6 +96,8 @@ pub fn open(app: &mut App, index: usize) { /// Leave the review screen and stop playback. pub fn leave(app: &mut App) { + app.review_rx = None; + app.review.loading = false; app.review.player = None; app.review.game = None; app.review.highlights.clear(); @@ -91,7 +107,6 @@ pub fn leave(app: &mut App) { app.review.export_note = None; app.review.export = None; } - /// Called from `poll` while the review screen is up. pub fn tick(app: &mut App, tx: &mut Tx) -> bool { let mut changed = false; @@ -138,10 +153,15 @@ pub fn tick(app: &mut App, tx: &mut Tx) -> bool { pub fn view(app: &App, p: Paint) -> El { let Some(game) = app.reviewed() else { + let message = if app.review.loading { + "Opening the recording…" + } else { + "No game selected." + }; return col() .key("review") .padding(space::S6) - .child(text("No game selected.").font(body(13.0)).color(p.muted())); + .child(text(message).font(body(13.0)).color(p.muted())); }; let outcome = game.outcome(); let ink = match outcome { diff --git a/app/src/ui.rs b/app/src/ui.rs index 33d5cdb..b6c2769 100644 --- a/app/src/ui.rs +++ b/app/src/ui.rs @@ -646,6 +646,12 @@ impl ScrollBar { last: std::rc::Rc::new(std::cell::Cell::new(rune::ScrollPos::default())), } } + /// Where the viewport is scrolled to, as of the last frame that reported it. + /// + /// A screen can read this to load more rows as the end of a long list comes into view. + pub fn position(&self) -> rune::ScrollPos { + self.last.get() + } /// Make this viewport's scrolling move the thumb, and its key one a drag can scroll to. pub fn follow(&self, key: &'static str, viewport: El) -> El {