app: read the history a page at a time and open clips on demand

Every launch parsed all 313 timelines, raw responses and all, which put
2.1 GB of JSON on the heap at startup.

The list now holds `Summary` rows: `history::summaries` parses a file,
keeps the champion, queue, scoreline, LP change and event count, then
drops the timeline. Files are listed by write time, and `poll` reads the
next 20 when the list is scrolled near its end or when the filtered rows
do not fill the screen. Selecting a row hands its id to the review
screen, which reads that one timeline on a thread.

Peak memory over 313 recordings: 165 MB.
This commit is contained in:
vhaudiquet committed 2026-11-16 23:48:58 +01:00
1 parent 4efc2f3968
commit 6584b2f92f
7 files changed
+315 -83

No files matched your search

+4
View File
@@ -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, 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, 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`). 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 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 (`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 TODO opened. The review screen uses it. If clip-accurate seeking turns out to be worse than
+128 -22
View File
@@ -1,12 +1,13 @@
//! App state, the frame hook and the screen dispatch. //! App state, the frame hook and the screen dispatch.
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, TryRecvError, channel}; use std::sync::mpsc::{Receiver, TryRecvError, channel};
use std::time::Duration; use std::time::Duration;
use rune::tok::type_; use rune::tok::type_;
use rune::{Cx, El, Key, KeyEvent, Tx, col, el, row, text}; 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::ipc::{self, Daemon};
use crate::os; use crate::os;
use crate::portraits; use crate::portraits;
@@ -92,6 +93,16 @@ pub struct AudioDevice {
pub is_default: bool, 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<PathBuf>,
next: usize,
games: Vec<Summary>,
}
/// A message banner shown above the screen until dismissed. /// A message banner shown above the screen until dismissed.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Notice { pub struct Notice {
@@ -110,9 +121,16 @@ pub struct App {
pub form: screens::settings::Form, pub form: screens::settings::Form,
pub encoders: Encoders, pub encoders: Encoders,
pub devices: AudioDevices, pub devices: AudioDevices,
pub games: Vec<Timeline>, /// One row per recording on disk, a page at a time.
pub games_rx: Option<Receiver<Vec<Timeline>>>, pub games: Vec<Summary>,
/// Every timeline file, most recent first: `games` holds the first `games_next` of them.
pub games_paths: Vec<PathBuf>,
pub games_rx: Option<Receiver<GamesPage>>,
pub games_loaded: bool, 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<Receiver<Option<Timeline>>>,
pub filter: Option<QueueCategory>, pub filter: Option<QueueCategory>,
pub review: screens::review::Review, pub review: screens::review::Review,
pub portraits: Option<portraits::Portraits>, pub portraits: Option<portraits::Portraits>,
@@ -155,8 +173,11 @@ impl App {
encoders: Encoders::default(), encoders: Encoders::default(),
devices: AudioDevices::default(), devices: AudioDevices::default(),
games: Vec::new(), games: Vec::new(),
games_paths: Vec::new(),
games_rx: None, games_rx: None,
games_loaded: false, games_loaded: false,
games_next: 0,
review_rx: None,
filter: None, filter: None,
review: screens::review::Review::default(), review: screens::review::Review::default(),
portraits: None, portraits: None,
@@ -192,7 +213,10 @@ impl App {
current_game_id: None, current_game_id: None,
client_connected: true, client_connected: true,
}; };
self.games = history::sample(); self.games = history::sample()
.iter()
.map(|game| game.summary())
.collect();
self.games_loaded = true; self.games_loaded = true;
self.devices = AudioDevices { self.devices = AudioDevices {
input_devices: vec![AudioDevice { input_devices: vec![AudioDevice {
@@ -360,23 +384,58 @@ impl App {
self.processes_rx = Some(rx); 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) { pub fn refresh_games(&mut self) {
if self.games_rx.is_some() { if self.games_rx.is_some() {
return; return;
} }
let (tx, rx) = channel(); let (tx, rx) = channel();
std::thread::spawn(move || { std::thread::spawn(move || {
let games = history::load_all(); let paths = history::timeline_paths();
let _ = tx.send(games); 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); 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. /// The game the review screen is showing, if any.
pub fn reviewed(&self) -> Option<&Timeline> { pub fn reviewed(&self) -> Option<&Timeline> {
let id = self.review.game.as_deref()?; self.review.game.as_ref()
self.games.iter().find(|game| game.recording_id == id)
} }
} }
@@ -579,8 +638,17 @@ impl App {
if let Some(rx) = &self.games_rx { if let Some(rx) = &self.games_rx {
match rx.try_recv() { match rx.try_recv() {
Ok(games) => { Ok(page) => {
self.games = games; 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_loaded = true;
self.games_rx = None; self.games_rx = None;
changed = true; 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(); let mut tray_events = Vec::new();
if let Some(rx) = &self.tray_events { if let Some(rx) = &self.tray_events {
while let Ok(event) = rx.try_recv() { while let Ok(event) = rx.try_recv() {
@@ -906,15 +1011,22 @@ pub fn demo_review(app: &mut App) {
app.pending_review = false; app.pending_review = false;
let live = std::env::args().any(|arg| arg == "--live"); let live = std::env::args().any(|arg| arg == "--live");
if live { if live {
let index = app let row = app
.games .games
.iter() .iter()
.position(|game| !game.events.is_empty()) .find(|game| game.event_count > 0)
.unwrap_or(0); .map(|game| game.recording_id.clone());
screens::review::open(app, index); if let Some(id) = row {
screens::review::open(app, &id);
}
return; 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()); app.review.error = Some("Sample recording: no clip on disk.".to_string());
// Snapshot hook: draw a real clip when one is handed in. // Snapshot hook: draw a real clip when one is handed in.
if let Ok(path) = std::env::var("LR_DEMO_VIDEO") { 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.player = Some(player);
app.review.error = None; 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;
}
} }
+117 -36
View File
@@ -130,64 +130,123 @@ pub fn timeline_dir() -> PathBuf {
daemon::recordings_dir().join("timelines") daemon::recordings_dir().join("timelines")
} }
/// Every timeline on disk, newest first. Files that fail to parse are skipped. /// Timeline files on disk, most recently written first.
/// Every timeline on disk, newest first. The raw API responses make each file large (hundreds ///
/// of kilobytes), so the files are parsed in parallel. /// The name is a recording id, so the write time is the only cheap order there is. A
pub fn load_all() -> Vec<Timeline> { /// 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<PathBuf> {
let dir = timeline_dir(); let dir = timeline_dir();
let Ok(entries) = std::fs::read_dir(&dir) else { let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new(); return Vec::new();
}; };
let paths: Vec<PathBuf> = entries let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
.flatten() .flatten()
.map(|entry| entry.path()) .map(|entry| entry.path())
.filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json")) .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(); .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); /// The rows for a page of timelines.
let parsed = std::sync::Mutex::new(Vec::with_capacity(paths.len())); ///
let threads = std::thread::available_parallelism() /// Each file is parsed whole, because the champion, the scoreline and the queue only exist
.map(|count| count.get()) /// inside the raw responses, and the [`Timeline`] is dropped as soon as its [`Summary`] is
.unwrap_or(4) /// built. Only the summaries are kept, so the events and the raw JSON do not pile up.
.clamp(1, 8); pub fn summaries(paths: &[PathBuf]) -> Vec<Summary> {
paths.iter().filter_map(|path| summary_of(path)).collect()
std::thread::scope(|scope| { }
for _ in 0..threads {
scope.spawn(|| { fn summary_of(path: &Path) -> Option<Summary> {
loop { let text = std::fs::read_to_string(path).ok()?;
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::<Timeline>(&text) { match serde_json::from_str::<Timeline>(&text) {
Ok(timeline) => parsed.lock().unwrap().push(timeline), Ok(timeline) => Some(timeline.summary()),
Err(e) => eprintln!("skipping {}: {e}", path.display()), 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<Utc>,
pub duration_secs: i64,
champion: Option<String>,
summoner: Option<String>,
queue_label: String,
category: QueueCategory,
outcome: Outcome,
stats: Option<Stats>,
lp: Option<LpChange>,
pub event_count: usize,
}
impl Summary {
pub fn champion(&self) -> Option<String> {
self.champion.clone()
}
pub fn summoner(&self) -> Option<String> {
self.summoner.clone()
}
pub fn queue_label(&self) -> &str {
&self.queue_label
}
pub fn category(&self) -> QueueCategory {
self.category
} }
});
let mut out = parsed.into_inner().unwrap(); pub fn outcome(&self) -> Outcome {
out.sort_by_key(|timeline| std::cmp::Reverse(timeline.start_time)); self.outcome
out }
pub fn stats(&self) -> Option<Stats> {
self.stats
}
pub fn lp_change(&self) -> Option<LpChange> {
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<Timeline> { pub fn load(recording_id: &str) -> Option<Timeline> {
let path = timeline_dir().join(format!("{recording_id}.json")); let path = timeline_dir().join(format!("{recording_id}.json"));
let text = std::fs::read_to_string(path).ok()?; let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&text).ok() serde_json::from_str(&text).ok()
} }
// ---------------------------------------------------------------------------
// Extractors, from types/timeline.ts
// ---------------------------------------------------------------------------
impl Timeline { impl Timeline {
fn end_stats(&self) -> Option<&Value> { fn end_stats(&self) -> Option<&Value> {
self.raw_end_game_stats.as_ref() self.raw_end_game_stats.as_ref()
@@ -586,7 +645,29 @@ mod tests {
assert_eq!(lp.tier, "EMERALD"); assert_eq!(lp.tier, "EMERALD");
assert_eq!(lp.league_points, 74); 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] #[test]
fn a_video_is_found_by_its_timestamp_prefix() { fn a_video_is_found_by_its_timestamp_prefix() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4())); let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
+5 -2
View File
@@ -22,7 +22,7 @@ use rune::AppSpec;
fn main() { fn main() {
if std::env::args().any(|arg| arg == "--games") { if std::env::args().any(|arg| arg == "--games") {
println!("{} timelines", crate::history::load_all().len()); println!("{} timelines", crate::history::timeline_paths().len());
return; return;
} }
if std::env::args().any(|arg| arg == "--probe") { if std::env::args().any(|arg| arg == "--probe") {
@@ -79,7 +79,10 @@ fn main() {
}), }),
("many", |app| { ("many", |app| {
app.screen = app::Screen::History; 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; app.games_loaded = true;
}), }),
], ],
+20 -8
View File
@@ -8,7 +8,7 @@ use rune::{Color, El, col, el, row, text};
use crate::app::App; use crate::app::App;
use crate::format; use crate::format;
use crate::history::{Outcome, QueueCategory, Timeline}; use crate::history::{Outcome, QueueCategory, Summary};
use crate::screens::review; use crate::screens::review;
use crate::ui::{self, Paint, body, heading}; 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 { pub fn view(app: &App, p: Paint) -> El {
let filtered: Vec<(usize, &Timeline)> = app let filtered: Vec<&Summary> = app
.games .games
.iter() .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(); .collect();
// The scroll bar gets its own strip at the end, clear of the cards. // 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.", "Pick another queue above.",
)); ));
} else { } else {
for (index, game) in filtered { for (index, game) in filtered.iter().enumerate() {
list = list.child(game_card(app, p, game, index)); 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), .color(p.t.text),
) )
.child( .child(
text(format!("{} recordings", app.games.len())) text(count_label(app))
.key("count") .key("count")
.font(body(11.5)) .font(body(11.5))
.color(p.muted()), .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 { fn empty(p: Paint, title: &str, detail: &str) -> El {
col() col()
.key("empty") .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 outcome = game.outcome();
let ink = outcome_color(p, outcome); let ink = outcome_color(p, outcome);
let id = game.recording_id.clone();
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into()); let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
let duration = game.duration_secs.max(0) as f64; let duration = game.duration_secs.max(0) as f64;
let lp = game.lp_change(); 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) .shadow(8.0, 24.0, p.t.shadow_soft)
.hover(p.t.hover) .hover(p.t.hover)
.press(p.t.press) .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( .child(
col().key("card").w_full().child(banner).child( col().key("card").w_full().child(banner).child(
row() row()
+35 -15
View File
@@ -8,12 +8,15 @@ use rune::{El, Player, SurfaceFit, Tx, col, el, row, text};
use crate::app::{App, Screen}; use crate::app::{App, Screen};
use crate::format; use crate::format;
use crate::highlight::{self, Highlight}; use crate::highlight::{self, Highlight};
use crate::history::{Outcome, Timeline}; use crate::history::{self, Outcome, Timeline};
use crate::ui::{self, Paint, body, heading}; use crate::ui::{self, Paint, body, heading};
#[derive(Default)] #[derive(Default)]
pub struct Review { pub struct Review {
pub game: Option<String>, /// The opened recording, once its file has been read.
pub game: Option<Timeline>,
/// Set while that file is on its way to the screen.
pub loading: bool,
pub player: Option<Player>, pub player: Option<Player>,
pub time: f64, pub time: f64,
pub duration: f64, pub duration: f64,
@@ -45,30 +48,41 @@ impl Review {
} }
} }
/// Open a game in the review screen and load its clip. /// Open a recording in the review screen.
pub fn open(app: &mut App, index: usize) { ///
/// 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); leave(app);
app.screen = Screen::Review; app.screen = Screen::Review;
app.review.loading = true;
let Some(game) = app.games.get(index) else { let id = recording_id.to_string();
return; let (tx, rx) = std::sync::mpsc::channel();
}; std::thread::spawn(move || {
// Keep the recording id, not the row number: a new recording can re-sort the list. let _ = tx.send(history::load(&id));
app.review.game = Some(game.recording_id.clone()); });
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 path = game.video_path();
let highlights = highlight::compute( let highlights = highlight::compute(
game, &game,
game.summoner().as_deref(), game.summoner().as_deref(),
highlight::Options::default(), highlight::Options::default(),
); );
let duration = game.duration_secs.max(0) as f64;
app.review.highlights = highlights; 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 { let Some(path) = path else {
app.review.error = Some(format!( app.review.error = Some(format!(
"No video file found for this recording ({}).", "No video file found for this recording ({}).",
game.video_file.as_deref().unwrap_or("unnamed") video_file.as_deref().unwrap_or("unnamed")
)); ));
return; return;
}; };
@@ -82,6 +96,8 @@ pub fn open(app: &mut App, index: usize) {
/// Leave the review screen and stop playback. /// Leave the review screen and stop playback.
pub fn leave(app: &mut App) { pub fn leave(app: &mut App) {
app.review_rx = None;
app.review.loading = false;
app.review.player = None; app.review.player = None;
app.review.game = None; app.review.game = None;
app.review.highlights.clear(); app.review.highlights.clear();
@@ -91,7 +107,6 @@ pub fn leave(app: &mut App) {
app.review.export_note = None; app.review.export_note = None;
app.review.export = None; app.review.export = None;
} }
/// Called from `poll` while the review screen is up. /// Called from `poll` while the review screen is up.
pub fn tick(app: &mut App, tx: &mut Tx) -> bool { pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
let mut changed = false; 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 { pub fn view(app: &App, p: Paint) -> El {
let Some(game) = app.reviewed() else { let Some(game) = app.reviewed() else {
let message = if app.review.loading {
"Opening the recording…"
} else {
"No game selected."
};
return col() return col()
.key("review") .key("review")
.padding(space::S6) .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 outcome = game.outcome();
let ink = match outcome { let ink = match outcome {
+6
View File
@@ -646,6 +646,12 @@ impl ScrollBar {
last: std::rc::Rc::new(std::cell::Cell::new(rune::ScrollPos::default())), 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. /// 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 { pub fn follow(&self, key: &'static str, viewport: El) -> El {