diff --git a/app/README.md b/app/README.md index ab3bd33..a450638 100644 --- a/app/README.md +++ b/app/README.md @@ -23,7 +23,10 @@ Headless renders, for looking at a screen without a window: ```sh cargo run -- --snap history.png --scene history cargo run -- --snap settings.png --scene settings -cargo run -- --snap recording.png --scene recording +cargo run -- --snap recording.png --scene recording # the settings tab +cargo run -- --snap recording-live.png --scene recording-live # a game being recorded +cargo run -- --snap recording-live-delete.png --scene recording-live-delete +cargo run -- --snap recording-idle.png --scene recording-idle cargo run -- --snap audio.png --scene audio cargo run -- --snap review.png --scene review cargo run -- --snap clips.png --scene clips @@ -70,7 +73,7 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti | `src/export.rs` | ffmpeg clip export, the clips folder it fills and its miniatures | | `src/os.rs` | Run key, toasts, tray icon and menu | | `src/ui.rs` | Colours, cards, switches, sliders, buttons | -| `src/screens/` | Settings, match history, clips, game review | +| `src/screens/` | Settings, match history, clips, game review, the recording in progress | ## Where this stands against TODO.txt @@ -110,6 +113,23 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti 10. Parity: `tauri-app` is still in the tree. Delete it once the items above are verified on a machine with a live League Client. +### The recording screen + +While the daemon records, the app opens on the game it is recording and can stop it. The +daemon's protocol answers about the daemon only — recording or not, and which game id — so the +screen reads the game where it is: `/liveclientdata/allgamedata` on `https://127.0.0.1:2999`, +the endpoint the daemon itself polls for its events, which needs no login. It is read once a +second on a thread of its own, together with the timeline the recorder opened for this game +(the champion, the queue and the summoner it fetched at the start) and the clip being written +in the recordings folder. Without the game's answer the screen still shows what it has, and +says it is waiting. + +Stopping over the protocol is not the stop the recorder gives a game that ends by itself: the +recorder writes the video into a new timeline and leaves the open one behind, which would show +in Match history as a game that never happened, next to one with no champion. The app closes +the open timeline into the one holding the video (`history::close_stopped`), and "Stop and +delete" removes the clip and both. + ### Known gaps - Item images are not drawn. Champion portraits download from Data Dragon on first sight and are diff --git a/app/src/app.rs b/app/src/app.rs index 28d8cf2..1d934da 100644 --- a/app/src/app.rs +++ b/app/src/app.rs @@ -27,6 +27,7 @@ pub enum Screen { Clips, Clip, Review, + Recording, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -118,6 +119,9 @@ pub struct Notice { pub struct App { pub screen: Screen, + /// Whether the screens show `history::sample` rather than the disk: a snapshot run, which + /// never starts the daemon and has nothing live to read. + pub sample: bool, /// The screens behind this one, oldest first: the back arrow returns through them. pub behind: Vec, pub settings_tab: SettingsTab, @@ -160,6 +164,8 @@ pub struct App { pub clips_menu_open: Option, /// The clip the delete dialog is about, by its `id@start` key. pub confirm_clip_delete: Option, + /// The game being recorded: what the recording screen has read of it. + pub recording: screens::recording::State, pub review: screens::review::Review, pub portraits: Option, /// The icons of the processes the audio sources name, decoded from their executables. @@ -173,6 +179,7 @@ pub struct App { pub clips_scroll: ui::ScrollBar, pub highlights_scroll: ui::ScrollBar, pub events_scroll: ui::ScrollBar, + pub recording_scroll: ui::ScrollBar, pub notice: Option, /// ffmpeg being downloaded on the first run, and the whole percent it last reported. pub ffmpeg_rx: Option>, @@ -194,6 +201,7 @@ impl App { // `--live` renders headless but talks to the daemon and reads the real recordings. let live = std::env::args().any(|arg| arg == "--live"); let mut app = Self { + sample: headless && !live, screen: Screen::History, behind: Vec::new(), settings_tab: SettingsTab::Quick, @@ -222,6 +230,7 @@ impl App { thumbs_rx: None, clips_menu_open: None, confirm_clip_delete: None, + recording: screens::recording::State::default(), review: screens::review::Review::default(), portraits: None, icons: None, @@ -232,6 +241,7 @@ impl App { clips_scroll: ui::ScrollBar::new(), highlights_scroll: ui::ScrollBar::new(), events_scroll: ui::ScrollBar::new(), + recording_scroll: ui::ScrollBar::new(), notice: None, ffmpeg_rx: None, ffmpeg_pct: None, @@ -574,6 +584,14 @@ impl App { } } + /// The container the recorder writes new recordings in, as the settings say. + pub fn container(&self) -> String { + self.settings + .as_ref() + .map(|settings| settings.output.container.clone()) + .unwrap_or_else(|| self.form.draft.output.container.clone()) + } + /// The folders a recording's clip may be in: the configured output folder first, then the /// default one, where timelines and the clips folder live. pub fn video_roots(&self) -> Vec { @@ -793,9 +811,23 @@ impl App { self.refresh_games(); // A stop can take a moment to write the timeline; read it again shortly. tx.wake_after(Duration::from_millis(1500)); + if self.screen == Screen::Recording { + self.jump(Screen::History); + } + self.recording.forget(); } self.tray_recording = self.status.is_recording; } + // The screen a game opens: what is being recorded, until it stops. A recording that is + // already running when the app starts is the first thing it shows too. + if self.status.is_recording && !was_recording { + self.recording.begin(); + if first { + self.jump(Screen::Recording); + } else { + self.go(Screen::Recording); + } + } true } } @@ -873,11 +905,13 @@ impl App { (ipc::Request::StartRecording, Err(e)) => { self.notify_error(format!("Cannot start recording: {e}")) } - (ipc::Request::StopRecording, Ok(_)) => { - self.notify("Recording stopped"); - self.refresh_games(); + (ipc::Request::StopRecording, Ok(data)) => { + screens::recording::stopped(self, &data); } (ipc::Request::StopRecording, Err(e)) => { + // The stop never happened, so nothing was written: a "stop and delete" that + // failed must not turn into a plain stop later. + self.recording.deleting = false; self.notify_error(format!("Cannot stop recording: {e}")) } (ipc::Request::Logs, Ok(data)) => { @@ -1081,6 +1115,11 @@ impl App { if self.screen == Screen::Review { changed |= screens::review::tick(self, tx); } + // The recording screen reads the game and the disk; it only does it while it shows, + // and reads them again on the way back in. + if self.screen == Screen::Recording { + changed |= screens::recording::tick(self, t); + } changed |= screens::clip::tick(self, tx); changed } @@ -1133,6 +1172,10 @@ pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool { app.confirm_delete = None; true } + (Key::Escape, _) if app.recording.confirm_delete => { + app.recording.confirm_delete = false; + true + } (Key::Escape, _) if app.confirm_clip_delete.is_some() => { app.confirm_clip_delete = None; true @@ -1224,6 +1267,7 @@ fn back_label(screen: Screen) -> &'static str { Screen::Clip => "← Clip", Screen::Review => "← Game", Screen::Settings => "← Settings", + Screen::Recording => "← Recording", } } @@ -1246,6 +1290,20 @@ fn titlebar(p: Paint, app: &App, insets: ChromeInsets) -> El { // On the settings screen the title bar has nothing to offer: refreshing and opening // settings again would only repeat what the screen already does. if app.screen != Screen::Settings { + // A game being recorded is one click away, whatever screen the viewer wandered to. + if app.status.is_recording && app.screen != Screen::Recording { + actions = actions.child(ui::button( + p, + "open-recording", + "Recording", + false, + |app: &mut App| { + app.menu_open = None; + app.clips_menu_open = None; + app.jump(Screen::Recording); + }, + )); + } if !matches!(app.screen, Screen::Clips | Screen::Clip) { actions = actions.child(ui::button( p, @@ -1348,6 +1406,7 @@ pub fn view(app: &App, cx: &mut Cx) -> El { Screen::Clips => screens::clips::view(app, p, &mut overlays), Screen::Clip => screens::clip::view(app, p), Screen::Review => screens::review::view(app, p), + Screen::Recording => screens::recording::view(app, p), }; let mut main = col().key("main").grow(1.0).min_h(0.0).w_full().fill(p.t.bg); if let Some(banner) = &app.notice { @@ -1373,6 +1432,11 @@ pub fn view(app: &App, cx: &mut Cx) -> El { .child(app.events_scroll.thumb(p, "events-thumb", "event-scroller")), Screen::Review => window, Screen::Clips => window.child(app.clips_scroll.thumb(p, "clips-thumb", "clips-scroller")), + Screen::Recording => window.child(app.recording_scroll.thumb( + p, + "recording-thumb", + "recording-scroller", + )), Screen::Settings => window.child(app.scroll.thumb(p, "scroll-thumb", "scroller")), Screen::History => window.child(app.scroll.thumb(p, "scroll-thumb", "list-scroller")), // A clip fills its screen with a player, not a list: the history or settings thumb would @@ -1388,6 +1452,9 @@ pub fn view(app: &App, cx: &mut Cx) -> El { if app.confirm_clip_delete.is_some() { screens::clips::delete_dialog(app, p, &mut overlays); } + if app.recording.confirm_delete { + screens::recording::confirm_dialog(app, p, &mut overlays); + } rune_kit::root(content, overlays) } diff --git a/app/src/history.rs b/app/src/history.rs index ef42e69..9857979 100644 --- a/app/src/history.rs +++ b/app/src/history.rs @@ -147,8 +147,11 @@ pub fn timeline_dir() -> PathBuf { /// 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 { + paths_in(&timeline_dir()) +} + +fn paths_in(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new(); }; let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries @@ -176,7 +179,10 @@ pub fn summaries(paths: &[PathBuf]) -> Vec { 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()), + // A game the recorder is still writing has no end yet: it is the recording screen's, + // and Match history is what has been recorded. + Ok(timeline) if timeline.end_time.is_some() => Some(timeline.summary()), + Ok(_) => None, Err(e) => { eprintln!("skipping {}: {e}", path.display()); None @@ -300,6 +306,197 @@ fn delete_in(recording_id: &str, video: Option<&Path>, recordings: &Path) -> Res Ok(()) } +/// The timeline a recording is being written into: the newest file with no end yet. +/// +/// The recorder opens a timeline when a game starts and writes its end when it stops, so a +/// file without `end_time` is a game that is still going. The game id picks it out when the +/// client reported one; the newest open file is the answer otherwise. +/// The timeline a recording is being written into: the newest file with no end yet. +/// +/// The recorder opens a timeline when a game starts and writes its end when it stops, so a +/// file without `end_time` is a game that is still going. The game id picks it out when the +/// client reported one; the newest open file is the answer otherwise. +pub fn open_timeline(game_id: Option) -> Option<(PathBuf, Timeline)> { + open_in(&timeline_dir(), game_id) +} + +fn open_in(dir: &Path, game_id: Option) -> Option<(PathBuf, Timeline)> { + let mut newest = None; + // The file being written is the newest. One left open by an earlier stop can only be + // older than everything written since, so a few of the newest is enough. + for path in paths_in(dir).into_iter().take(4) { + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let Ok(timeline) = serde_json::from_str::(&text) else { + continue; + }; + if timeline.end_time.is_some() { + continue; + } + if game_id.is_none() || timeline.game_id == game_id { + return Some((path, timeline)); + } + if newest.is_none() { + newest = Some((path, timeline)); + } + } + newest +} + +/// The clip a recording is writing into `dir`, with the bytes on disk so far. +/// +/// The recorder names the file when it starts and only reports it when it stops, so the file +/// is found rather than asked for: the newest one of the container the settings name that was +/// written since the recording began. `None` until it exists, and in a folder the recorder +/// writes nothing to. +pub fn writing_file(dir: &Path, container: &str, since: DateTime) -> Option<(PathBuf, u64)> { + let since: std::time::SystemTime = (since - chrono::Duration::minutes(2)).into(); + let entries = std::fs::read_dir(dir).ok()?; + let mut newest: Option<(std::time::SystemTime, PathBuf, u64)> = None; + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_file() { + continue; + } + let ours = path + .extension() + .and_then(|e| e.to_str()) + .is_some_and(|e| e.eq_ignore_ascii_case(container)); + if !ours { + continue; + } + let Ok(meta) = entry.metadata() else { + continue; + }; + let Ok(written) = meta.modified() else { + continue; + }; + if written < since { + continue; + } + if newest.as_ref().is_none_or(|(at, _, _)| written > *at) { + newest = Some((written, path, meta.len())); + } + } + newest.map(|(_, path, bytes)| (path, bytes)) +} + +/// Finish the timeline the recorder left open for a game the app stopped. +/// +/// A game the recorder ends by itself is finalized: one timeline with the game, the video and +/// the end. Stopped over the protocol it writes the video into a new timeline and leaves the +/// open one behind, so Match history would show two rows for one game: a game that never +/// happened, and one with a video but no champion or queue. What the open timeline knows +/// moves to the one holding the video, and the leftover is deleted. +/// +/// `discard` is the app's "stop and delete": the video goes with both timelines, so a game +/// stopped that way leaves nothing behind at all. +pub fn close_stopped(open: Option<&Path>, video: &Path, discard: bool) -> Result<(), String> { + close_stopped_in(&timeline_dir(), open, video, discard) +} + +fn close_stopped_in( + dir: &Path, + open: Option<&Path>, + video: &Path, + discard: bool, +) -> Result<(), String> { + let held = timeline_for_video(dir, video); + if discard { + let mut failed = None; + let files = [ + held.map(|(path, _)| path), + Some(video.to_path_buf()), + open.map(Path::to_path_buf), + ]; + for path in files.into_iter().flatten() { + if let Err(e) = remove(&path) { + failed.get_or_insert(e); + } + } + return failed.map_or(Ok(()), Err); + } + let (Some(open), Some((held, mut finished))) = (open, held) else { + return Ok(()); + }; + if held == open { + // The recorder finished this timeline itself: there is nothing to move. + return Ok(()); + } + let text = std::fs::read_to_string(open) + .map_err(|e| format!("could not read {}: {e}", open.display()))?; + let game: Value = serde_json::from_str(&text) + .map_err(|e| format!("{} is not a timeline: {e}", open.display()))?; + // A file left open by some other game is not this one's to finish: merging two recordings + // would name one game with another's video. + let wanted = finished.get("game_id").and_then(Value::as_u64); + let offered = game.get("game_id").and_then(Value::as_u64); + if wanted.is_some() && offered.is_some() && wanted != offered { + return Ok(()); + } + // The fields the recorder fills in when a game starts, which only the open timeline + // holds: everything a row names the game by. + for key in [ + "game_id", + "raw_session", + "raw_summoner", + "raw_champion_select", + "raw_rune_page", + "raw_live_client_data", + ] { + if finished.get(key).is_none_or(Value::is_null) + && let Some(value) = game.get(key) + { + finished[key] = value.clone(); + } + } + let json = serde_json::to_string_pretty(&finished) + .map_err(|e| format!("could not write {}: {e}", held.display()))?; + std::fs::write(&held, json).map_err(|e| format!("could not write {}: {e}", held.display()))?; + remove(open) +} + +/// The timeline holding `video`, with its JSON, as the recorder writes it when it stops. +/// +/// The clip's file name ties the two together: the recorder stores it in the timeline it +/// wrote for that clip. +fn timeline_for_video(dir: &Path, video: &Path) -> Option<(PathBuf, Value)> { + let name = video.file_name()?.to_str()?; + let entries = std::fs::read_dir(dir).ok()?; + for entry in entries.flatten() { + let path = entry.path(); + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + let Ok(text) = std::fs::read_to_string(&path) else { + continue; + }; + let Ok(value) = serde_json::from_str::(&text) else { + continue; + }; + let stored = value.get("video_file").and_then(Value::as_str).or_else(|| { + value + .get("video_path") + .and_then(Value::as_str) + .and_then(|path| Path::new(path).file_name()) + .and_then(|name| name.to_str()) + }); + if stored == Some(name) { + return Some((path, value)); + } + } + None +} + +/// Remove a file, saying which one could not go. +fn remove(path: &Path) -> Result<(), String> { + if !path.exists() { + return Ok(()); + } + std::fs::remove_file(path).map_err(|e| format!("could not delete {}: {e}", path.display())) +} + impl Timeline { fn end_stats(&self) -> Option<&Value> { self.raw_end_game_stats.as_ref() @@ -825,4 +1022,147 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + + /// A timeline the recorder opened for a game, without an end yet. + fn open_game(game_id: u64, champion: &str) -> String { + serde_json::json!({ + "recording_id": uuid::Uuid::new_v4().to_string(), + "start_time": "2026-03-27T16:42:52Z", + "end_time": null, + "duration_secs": 0, + "events": [], + "game_id": game_id, + "raw_session": {"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}}, + "raw_summoner": {"gameName": "Demo", "tagLine": "EUW"}, + "raw_live_client_data": {"activePlayer": {"championName": champion}}, + "video_file": null + }) + .to_string() + } + + fn write_timeline(dir: &Path, name: &str, json: &str) -> PathBuf { + let path = dir.join(format!("{name}.json")); + std::fs::write(&path, json).unwrap(); + path + } + + fn temp_dir() -> PathBuf { + let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn the_game_being_recorded_is_the_timeline_without_an_end() { + let dir = temp_dir(); + write_timeline(&dir, "finished", TIMELINE); + // Written last, so it is the newest: the game the recorder is writing. + let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa")); + assert_eq!( + open_in(&dir, Some(70)).map(|(path, _)| path), + Some(open.clone()) + ); + // The game id of a game that is not open falls back to the newest open file. + assert_eq!(open_in(&dir, Some(99)).map(|(path, _)| path), Some(open)); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_game_still_being_recorded_is_not_in_the_history() { + let dir = temp_dir(); + let finished = write_timeline(&dir, "finished", TIMELINE); + let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa")); + let rows = summaries(&[finished, open]); + assert_eq!(rows.len(), 1, "only the game that ended has a row"); + assert_eq!(rows[0].recording_id, parsed().recording_id); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_stop_from_the_app_moves_the_game_onto_its_video() { + let dir = temp_dir(); + let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa")); + // What the recorder writes when it stops over the protocol: the video, and no game. + let stopped = write_timeline( + &dir, + "stopped", + &serde_json::json!({ + "recording_id": uuid::Uuid::new_v4().to_string(), + "start_time": "2026-03-27T16:42:52Z", + "end_time": "2026-03-27T16:55:00Z", + "duration_secs": 728, + "events": [], + "game_id": 70, + "video_file": "2026-03-27_16-42-52_7000000.mp4", + "video_path": "C:/clips/2026-03-27_16-42-52_7000000.mp4" + }) + .to_string(), + ); + let video = Path::new("C:/clips/2026-03-27_16-42-52_7000000.mp4"); + + close_stopped_in(&dir, Some(&open), video, false).unwrap(); + + assert!(!open.exists(), "the leftover timeline is deleted"); + let merged: Value = + serde_json::from_str(&std::fs::read_to_string(&stopped).unwrap()).unwrap(); + let game = Timeline { + raw_session: merged.get("raw_session").cloned(), + raw_summoner: merged.get("raw_summoner").cloned(), + ..parsed() + }; + assert_eq!(game.champion().as_deref(), Some("Kai'Sa")); + assert_eq!(game.summoner().as_deref(), Some("Demo#EUW")); + assert_eq!(game.queue_label(), "Ranked Solo"); + // What the recorder wrote stays: the video and the end. + assert_eq!(merged["duration_secs"], 728); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn stopping_and_deleting_takes_the_video_with_both_timelines() { + let dir = temp_dir(); + let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa")); + let stopped = write_timeline( + &dir, + "stopped", + &serde_json::json!({ + "recording_id": uuid::Uuid::new_v4().to_string(), + "start_time": "2026-03-27T16:42:52Z", + "end_time": "2026-03-27T16:55:00Z", + "duration_secs": 728, + "events": [], + "game_id": 70, + "video_file": "game.mp4" + }) + .to_string(), + ); + let clips = temp_dir(); + let video = clips.join("game.mp4"); + std::fs::write(&video, b"x").unwrap(); + + close_stopped_in(&dir, Some(&open), &video, true).unwrap(); + + assert!(!open.exists()); + assert!(!stopped.exists()); + assert!(!video.exists(), "the clip goes with it"); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(clips); + } + + #[test] + fn the_clip_being_written_is_the_newest_of_its_container() { + let dir = temp_dir(); + std::fs::write(dir.join("notes.txt"), b"n").unwrap(); + std::fs::write(dir.join("old.mp4"), b"old").unwrap(); + std::fs::write(dir.join("new.mp4"), b"newer!").unwrap(); + let since = Utc::now() - chrono::Duration::minutes(1); + let (path, bytes) = writing_file(&dir, "mp4", since).unwrap(); + assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("new.mp4")); + assert_eq!(bytes, 6); + // Nothing was written since a folder scan later than every file: there is nothing to + // name until the recorder starts. + let later = Utc::now() + chrono::Duration::minutes(5); + assert!(writing_file(&dir, "mp4", later).is_none()); + let _ = std::fs::remove_dir_all(dir); + } } diff --git a/app/src/main.rs b/app/src/main.rs index 5cb484a..7de9570 100644 --- a/app/src/main.rs +++ b/app/src/main.rs @@ -42,6 +42,17 @@ fn attach_console() {} use rune::AppSpec; +/// `--scene recording-live`: the daemon recording, with the sample game on the screen. +fn demo_recording(app: &mut app::App) { + app.status = app::Status { + status: "recording".into(), + is_recording: true, + current_game_id: Some(7_000_000), + client_connected: true, + }; + screens::recording::demo(app); +} + fn main() { attach_console(); if std::env::args().any(|arg| arg == "--games") { @@ -82,6 +93,16 @@ fn main() { rune::App::new(AppSpec { scenes: &[ ("history", |_app: &mut app::App| {}), + ("recording-live", |app| { + demo_recording(app); + app.jump(app::Screen::Recording); + }), + ("recording-live-delete", |app| { + demo_recording(app); + app.jump(app::Screen::Recording); + app.recording.confirm_delete = true; + }), + ("recording-idle", |app| app.jump(app::Screen::Recording)), ("settings", |app| app.jump(app::Screen::Settings)), ("recording", |app| { app.jump(app::Screen::Settings); diff --git a/app/src/screens/mod.rs b/app/src/screens/mod.rs index 15dbd84..9468d17 100644 --- a/app/src/screens/mod.rs +++ b/app/src/screens/mod.rs @@ -1,7 +1,9 @@ -//! The screens: settings, match history, the clips grid, one open clip and the game review. +//! The screens: settings, match history, the clips grid, one open clip, the game review and +//! the recording in progress. pub mod clip; pub mod clips; pub mod history; +pub mod recording; pub mod review; pub mod settings; diff --git a/app/src/screens/recording.rs b/app/src/screens/recording.rs new file mode 100644 index 0000000..45d59e9 --- /dev/null +++ b/app/src/screens/recording.rs @@ -0,0 +1,1063 @@ +//! Recording: the game the daemon is recording, and the way to stop it. +//! +//! The daemon's protocol says whether it is recording and which game it is on, and nothing +//! about the game itself. The screen reads the rest where it is: the game's own live data, +//! at the loopback endpoint the daemon polls for its events, and the timeline the recorder +//! opened for this game, which holds the champion, the queue and the summoner it fetched at +//! the start. + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; +use std::time::Duration; + +use chrono::{DateTime, Utc}; +use rune::tok::{TextStyle, radius, space}; +use rune::{El, col, el, row, text}; +use serde_json::Value; +use ureq::tls::TlsConfig; + +use crate::app::{App, Screen}; +use crate::format; +use crate::history::{self, Timeline}; +use crate::settings::Settings; +use crate::ui::{self, Paint, body, heading}; + +/// The game's own data for the game it is running. +/// +/// Served by the game client on the loopback address, with a certificate it made for itself: +/// there is no name to verify and nothing on the network in between, so verification is off. +/// The daemon polls the events of the same server, and this is what it does not pass on. +const LIVE_URL: &str = "https://127.0.0.1:2999/liveclientdata/allgamedata"; + +/// How often the screen asks the game and the disk, in seconds. +const REFRESH: f64 = 1.0; + +/// A figure the screen reads off: monospaced, so the clocks do not jiggle as they count. +fn mono(size: f32) -> TextStyle { + TextStyle::new(size, 500.0).mono() +} + +/// What the screen knows of the recording it is showing. +#[derive(Default)] +pub struct State { + /// The game's live data, as last read. + pub live: Option, + /// The timeline the recorder is filling in: what it learned about the game at the start. + pub open: Option, + /// The clip being written, with the bytes on disk so far. + pub file: Option<(PathBuf, u64)>, + /// Why the live data could not be read, when it could not. + pub error: Option, + /// When the recording began, as the status flip or the timeline said. + pub started: Option>, + /// The read on its way to `poll`, and when the last one went out. + rx: Option>, + at: f64, + /// The whole second the clocks last showed, so a frame redraws when it ticks and not + /// before. + second: u64, + /// The "stop and delete" confirmation is open. + pub confirm_delete: bool, + /// The stop on its way is a stop and delete. + pub deleting: bool, +} + +impl State { + /// The daemon started recording: the last game's readings go, and the clock starts. + pub fn begin(&mut self) { + *self = State { + started: Some(Utc::now()), + ..State::default() + }; + } + + /// The recording ended: forget what the screen read of it. + /// + /// A stop the app asked for keeps `deleting`: the daemon's status can reach the app before + /// the answer to the stop, and the answer is what deletes anything. + pub fn forget(&mut self) { + *self = State { + deleting: self.deleting, + ..State::default() + }; + } + + /// When the recording began: the recorder's own start once its timeline is on disk. + pub fn started_at(&self) -> Option> { + self.open + .as_ref() + .map(|timeline| timeline.start_time) + .or(self.started) + } + + /// How long the recorder has been recording, in seconds. + pub fn elapsed(&self) -> f64 { + self.started_at() + .map(|at| Utc::now().signed_duration_since(at).num_seconds().max(0) as f64) + .unwrap_or(0.0) + } + + /// The champion being recorded: the game's own answer first, then the recorder's. + pub fn champion(&self) -> Option { + self.live + .as_ref() + .and_then(Live::mine) + .map(|player| player.champion.clone()) + .filter(|name| !name.is_empty()) + .or_else(|| self.open.as_ref().and_then(Timeline::champion)) + } +} + +/// What one read of the game and the disk answered. +struct Snapshot { + live: Result, + open: Option, + file: Option<(PathBuf, u64)>, +} + +// --------------------------------------------------------------------------- +// Reading +// --------------------------------------------------------------------------- + +/// Read the game and the disk on a thread; `tick` takes the answer. +fn snapshot(game_id: Option, dir: &Path, container: &str, since: DateTime) -> Snapshot { + let open = history::open_timeline(game_id).map(|(_, timeline)| timeline); + let file = history::writing_file(dir, container, since); + let live = fetch().and_then(|value| { + Live::parse(&value).ok_or_else(|| "the game has not reached the map yet".to_string()) + }); + Snapshot { live, open, file } +} + +/// The game's live data, as the game client serves it. +/// +/// What goes wrong here is what a game that is still loading looks like: the endpoint answers +/// with nothing, or refuses until the map is up. The screen says so in those words; the +/// transport's own message goes to the shell, where a run from one can see it. +fn fetch() -> Result { + let answer = ureq::get(LIVE_URL) + .config() + .tls_config(TlsConfig::builder().disable_verification(true).build()) + .timeout_global(Some(Duration::from_secs(2))) + .build() + .call(); + let mut response = match answer { + Ok(response) => response, + Err(e) => { + eprintln!("live data: {e}"); + return Err("the game is not answering yet".to_string()); + } + }; + let mut text = String::new(); + if let Err(e) = response.body_mut().as_reader().read_to_string(&mut text) { + eprintln!("live data: {e}"); + return Err("the game's answer did not read".to_string()); + } + serde_json::from_str(&text).map_err(|e| { + eprintln!("live data: {e}"); + "the game's answer did not read".to_string() + }) +} + +/// One player in the game being recorded. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Player { + pub name: String, + pub champion: String, + pub level: u32, + pub kills: u32, + pub deaths: u32, + pub assists: u32, + pub creep_score: u32, + pub vision: f64, + /// On the blue side. + pub order: bool, + pub dead: bool, + pub respawn: f64, +} + +/// A count the game reports, in the range the screen draws. +fn count(value: Option<&Value>) -> u32 { + value + .and_then(Value::as_u64) + .map_or(0, |n| n.min(u64::from(u32::MAX)) as u32) +} + +/// One game as its client reports it while it runs. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Live { + /// How long the game has been running, in seconds. + pub game_time: f64, + /// Everyone in it, both sides. + pub players: Vec, + /// Which of them is being recorded. + pub me: Option, + /// The recorded player's gold, which the game reports apart from the scores. + pub gold: u64, +} + +impl Live { + /// Read `/liveclientdata/allgamedata`. + pub fn parse(value: &Value) -> Option { + let game = value.get("gameData")?; + let game_time = game.get("gameTime").and_then(Value::as_f64)?; + let mut players = Vec::new(); + for player in value.get("allPlayers")?.as_array()? { + let champion = player + .get("championName") + .and_then(Value::as_str) + .unwrap_or_default(); + // A slot with no champion has not picked yet, or is not in this game at all. + if champion.is_empty() { + continue; + } + let score = |key: &str| count(player.pointer(&format!("/scores/{key}"))); + players.push(Player { + name: name_of(player), + champion: champion.to_string(), + level: count(player.get("level")), + kills: score("kills"), + deaths: score("deaths"), + assists: score("assists"), + creep_score: score("creepScore"), + vision: player + .pointer("/scores/wardScore") + .and_then(Value::as_f64) + .unwrap_or(0.0), + order: player.get("team").and_then(Value::as_str) == Some("ORDER"), + dead: player + .get("isDead") + .and_then(Value::as_bool) + .unwrap_or(false), + respawn: player + .get("respawnTimer") + .and_then(Value::as_f64) + .unwrap_or(0.0), + }); + } + let active = value.get("activePlayer"); + let champion = active + .and_then(|active| active.get("championName")) + .and_then(Value::as_str) + .filter(|name| !name.is_empty()); + let summoner = active + .and_then(|active| active.get("summonerName")) + .and_then(Value::as_str); + // The active player's own row is the one for the champion, and failing that for the + // name: the game names the player being watched in both places. + let me = champion + .and_then(|name| players.iter().position(|player| player.champion == name)) + .or_else(|| { + summoner.and_then(|name| players.iter().position(|player| player.name == name)) + }); + Some(Live { + game_time, + players, + me, + gold: active + .and_then(|active| active.get("currentGold")) + .and_then(Value::as_f64) + .unwrap_or(0.0) + .max(0.0) as u64, + }) + } + + /// The player being recorded, once the game says which one it is. + pub fn mine(&self) -> Option<&Player> { + self.me.and_then(|at| self.players.get(at)) + } +} + +/// A player's name, as the game writes it: `Name#TAG` when it has a tag. +fn name_of(player: &Value) -> String { + if let Some(name) = player.get("riotId").and_then(Value::as_str) + && !name.is_empty() + { + return name.to_string(); + } + let game_name = player + .get("riotIdGameName") + .or_else(|| player.get("summonerName")) + .and_then(Value::as_str) + .unwrap_or_default(); + let tag = player + .get("riotIdTagLine") + .and_then(Value::as_str) + .unwrap_or_default(); + if tag.is_empty() { + game_name.to_string() + } else { + format!("{game_name}#{tag}") + } +} + +// --------------------------------------------------------------------------- +// Polling +// --------------------------------------------------------------------------- + +/// Take the read that landed and start the next one, while the game runs. +/// +/// Returns whether the view has something new to draw: the clock on screen ticks with the +/// frames the app wakes for anyway, so a running recording always redraws. +pub fn tick(app: &mut App, t: f64) -> bool { + let mut changed = false; + if let Some(rx) = app.recording.rx.as_ref() { + match rx.try_recv() { + Ok(snapshot) => { + app.recording.rx = None; + app.recording.live = snapshot.live.as_ref().ok().cloned(); + app.recording.error = snapshot.live.err(); + app.recording.open = snapshot.open; + app.recording.file = snapshot.file; + changed = true; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => app.recording.rx = None, + } + } + // Nothing to read when nothing runs: the screen is only here on the way back from a game. + // A snapshot writes the sample game, and there is nothing behind it to ask. + if !app.status.is_recording || app.sample { + return changed; + } + // The clocks tick once a second: the rest of the screen only changes when a read lands. + let second = app.recording.elapsed().floor() as u64; + if second != app.recording.second { + app.recording.second = second; + changed = true; + } + if app.recording.rx.is_none() && t - app.recording.at >= REFRESH { + app.recording.at = t; + let game_id = app.status.current_game_id; + let since = app.recording.started_at().unwrap_or_else(Utc::now); + let dir = app.output_dir(); + let container = app.container(); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let _ = tx.send(snapshot(game_id, &dir, &container, since)); + }); + app.recording.rx = Some(rx); + } + changed +} + +/// The daemon answered a stop: close what the app's own stop left open, then leave the screen. +/// +/// The answer carries the clip the recorder wrote. A game the recorder ends by itself is one +/// timeline; stopped over the protocol it writes the video into a second one and leaves the +/// open one behind, which [`history::close_stopped`] tidies up, and which also deletes both +/// when the stop was the app's "stop and delete". +pub fn stopped(app: &mut App, data: &Value) { + let deleting = std::mem::take(&mut app.recording.deleting); + app.recording.confirm_delete = false; + let video = data.get("path").and_then(Value::as_str).map(PathBuf::from); + match video { + Some(video) => { + let open = history::open_timeline(app.status.current_game_id).map(|(path, _)| path); + match history::close_stopped(open.as_deref(), &video, deleting) { + Ok(()) if deleting => app.notify("Recording deleted"), + Ok(()) => app.notify("Recording stopped"), + // The recording is over whatever the tidying up made of it, and the row on + // screen is read from disk again below. + Err(e) => app.notify_error(e), + } + } + None => app.notify("Recording stopped"), + } + app.recording.forget(); + app.refresh_games(); + if app.screen == Screen::Recording { + app.jump(Screen::History); + } +} + +/// The dialog's "Yes": stop, and delete what the stop writes. +pub fn delete_confirmed(app: &mut App) { + app.recording.confirm_delete = false; + app.recording.deleting = true; + app.daemon.stop_recording(); +} + +// --------------------------------------------------------------------------- +// The screen +// --------------------------------------------------------------------------- + +pub fn view(app: &App, p: Paint) -> El { + let mut screen = col() + .key("recording") + .w_full() + .padding(space::S6) + .gap(space::S3) + .child(header(app, p)); + if !app.status.is_recording { + screen = screen.child( + col() + .key("idle") + .w_full() + .py(96.0) + .center() + .gap(6.0) + .child( + text("Nothing is being recorded") + .key("idle-title") + .font(heading(15.0)) + .color(p.t.text), + ) + .child( + text("The recorder starts on its own when a game begins.") + .key("idle-detail") + .font(body(12.0)) + .color(p.muted()), + ), + ); + } else { + screen = screen.child(hero(app, p)).child( + row() + .key("halves") + .w_full() + .gap(space::S3) + .child( + col() + .key("teams") + .grow(1.0) + .min_w(0.0) + .gap(space::S3) + .child(team(app, p, true)) + .child(team(app, p, false)), + ) + .child( + col() + .key("side") + .w(320.0) + .min_w(260.0) + .child(details(app, p)), + ), + ); + } + // A short window scrolls the screen rather than cutting the side column off. + app.recording_scroll.follow( + "recording-scroller", + col() + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(rune::ScrollSpec { + stick_bottom: false, + }) + .child(screen), + ) +} + +fn header(app: &App, p: Paint) -> El { + let mut title = row().key("title-line").gap(space::S2).center_y().child( + text("Recording") + .key("title") + .font(heading(20.0)) + .color(p.t.text), + ); + if app.status.is_recording { + title = title.child(ui::dot(p.danger)); + } + let subtitle = match (&app.recording.open, app.status.is_recording) { + (_, false) => "Nothing is being recorded".to_string(), + (Some(timeline), true) => match timeline.summoner() { + Some(summoner) => format!("{} · {summoner}", timeline.queue_label()), + None => timeline.queue_label(), + }, + (None, true) => "Waiting for the game".to_string(), + }; + let mut actions = row().key("actions").gap(space::S2).center_y(); + if app.status.is_recording { + actions = actions + .child(ui::button( + p, + "stop-recording", + "Stop recording", + true, + |app: &mut App| app.daemon.stop_recording(), + )) + .child(ui::button_danger( + p, + "stop-delete", + "Stop and delete", + |app: &mut App| app.recording.confirm_delete = true, + )); + } + row() + .key("head") + .w_full() + .justify_between() + .center_y() + .child( + col().key("title-block").gap(2.0).child(title).child( + text(subtitle) + .key("subtitle") + .font(body(11.5)) + .color(p.muted()), + ), + ) + .child(actions) +} + +/// The game on screen now: who is being recorded, the clocks, and the scoreline. +fn hero(app: &App, p: Paint) -> El { + let state = &app.recording; + let live = state.live.as_ref(); + let me = live.and_then(Live::mine); + let champion = state.champion(); + let game_time = live + .map(|live| live.game_time) + .unwrap_or_else(|| state.elapsed()); + let started = state + .started_at() + .map(|at| format!("Started {}", format::game_start(at))) + .unwrap_or_else(|| "Starting".to_string()); + let queue = state + .open + .as_ref() + .map(Timeline::queue_label) + .unwrap_or_else(|| "—".to_string()); + let summoner = state.open.as_ref().and_then(Timeline::summoner); + + let mut scores = row().key("scores").w_full().gap(30.0).center_y(); + if let Some(player) = me { + scores = scores + .child(stat( + p, + &format!("{}/{}/{}", player.kills, player.deaths, player.assists), + "K / D / A", + )) + .child(stat(p, &player.creep_score.to_string(), "CS")) + .child(stat( + p, + &format::number(live.map_or(0, |live| live.gold)), + "Gold", + )) + .child(stat(p, &format!("{:.0}", player.vision), "Vision")) + .child(stat(p, &player.level.to_string(), "Level")); + } else { + let detail = state + .error + .clone() + .unwrap_or_else(|| "The game has not reported a scoreline yet.".into()); + scores = scores.child( + col() + .key("waiting") + .gap(1.0) + .child( + text("Waiting for the game's live data") + .key("waiting-title") + .font(body(12.0)) + .color(p.muted()), + ) + .child( + text(detail) + .key("waiting-detail") + .font(body(11.0)) + .color(p.muted()) + .shrink() + .truncate(), + ), + ); + } + + el().key("hero") + .w_full() + .radius(radius::LG) + .fill(p.t.card) + .border(p.hair, p.t.card_border) + .shadow(1.0, 2.0, p.t.shadow) + .shadow(8.0, 24.0, p.t.shadow_soft) + .child( + col() + .key("hero-body") + .w_full() + .child( + row() + .key("hero-head") + .w_full() + .gap(space::S3) + .px(space::S6) + .py(space::S3) + .center_y() + .child(ui::champion_portrait(app, p, champion.as_deref(), 56.0)) + .child( + col() + .key("who") + .grow(1.0) + .min_w(0.0) + .gap(2.0) + .child( + text(champion.unwrap_or_else(|| "Recording".into())) + .key("champion") + .font(heading(18.0)) + .color(p.t.text) + .shrink() + .truncate(), + ) + .child( + text(match &summoner { + Some(summoner) => format!("{queue} · {summoner}"), + None => queue.clone(), + }) + .key("queue") + .font(body(11.5)) + .color(p.muted()) + .shrink() + .truncate(), + ) + .child( + text(started) + .key("started") + .font(body(11.0)) + .color(p.muted()), + ), + ) + .child(clock(p, game_time, "Game time")) + .child(clock(p, state.elapsed(), "Recorded")), + ) + .child( + el().key("hero-sep") + .w_full() + .h(p.hair) + .fill(p.t.separator) + .a11y_hidden(), + ) + .child( + row() + .key("hero-scores") + .w_full() + .px(space::S6) + .py(space::S2) + .center_y() + .child(scores), + ), + ) +} + +/// One of the two clocks: the value over what it counts. +fn clock(p: Paint, secs: f64, label: &str) -> El { + col() + .key(format!("clock-{label}")) + .gap(0.0) + .items_end() + .child( + text(format::clock(secs)) + .key("value") + .font(mono(20.0)) + .color(p.t.text), + ) + .child(text(label).key("label").font(body(10.5)).color(p.muted())) +} + +fn stat(p: Paint, value: &str, label: &str) -> El { + col() + .key(format!("stat-{label}")) + .gap(0.0) + .child(text(value).key("value").font(mono(14.0)).color(p.t.text)) + .child(text(label).key("label").font(body(10.5)).color(p.muted())) +} + +/// One side of the game, champion by champion. +fn team(app: &App, p: Paint, order: bool) -> El { + let mut rows = Vec::new(); + if let Some(live) = &app.recording.live { + let mut players: Vec<&Player> = live + .players + .iter() + .filter(|player| player.order == order) + .collect(); + if !order { + players.reverse(); + } + for player in players { + rows.push(player_row(app, p, player)); + } + } + if rows.is_empty() { + rows.push( + text("Waiting for the game's players…") + .key("no-players") + .font(body(11.5)) + .color(p.muted()) + .padding(space::S2), + ); + } + ui::card(p, Some(if order { "Blue team" } else { "Red team" }), rows) +} + +fn player_row(app: &App, p: Paint, player: &Player) -> El { + let mut trailing = row().key("score").gap(space::S2).center_y().child( + text(format!( + "{}/{}/{}", + player.kills, player.deaths, player.assists + )) + .key("kda") + .font(mono(11.5)) + .color(p.t.text), + ); + if player.dead { + trailing = trailing.child( + text(format!("{}s", player.respawn.ceil().max(0.0) as u64)) + .key("respawn") + .font(mono(11.5)) + .color(p.danger), + ); + } + row() + .key(format!("player-{}", player.champion)) + .w_full() + .h(30.0) + .px(space::S2) + .gap(space::S2) + .center_y() + .child(ui::champion_portrait(app, p, Some(&player.champion), 20.0)) + .child( + text(&player.name) + .key("name") + .font(body(11.5)) + .color(if player.dead { p.muted() } else { p.t.text }) + .grow(1.0) + .min_w(0.0) + .shrink() + .truncate(), + ) + .child(col().key("kda-col").w(58.0).items_end().child(trailing)) + .child( + col().key("cs-col").w(44.0).items_end().child( + text(player.creep_score.to_string()) + .key("cs") + .font(mono(11.5)) + .color(p.muted()), + ), + ) + .child( + col().key("level-col").w(30.0).items_end().child( + text(player.level.to_string()) + .key("level") + .font(mono(11.5)) + .color(p.muted()), + ), + ) +} + +/// What is being written, and how it is being written. +fn details(app: &App, p: Paint) -> El { + let state = &app.recording; + let settings = app.settings.as_ref(); + let file = state.file.as_ref().and_then(|(path, bytes)| { + path.file_name() + .and_then(|name| name.to_str()) + .map(|name| (name.to_string(), *bytes)) + }); + let rows = vec![ + detail_row(p, "recorded", "Recorded", format::clock(state.elapsed())), + detail_row( + p, + "started", + "Started", + state + .started_at() + .map(format::game_start) + .unwrap_or_else(|| "—".to_string()), + ), + detail_row( + p, + "file", + "File", + file.as_ref() + .map(|(name, _)| name.clone()) + .unwrap_or_else(|| "not written yet".to_string()), + ), + detail_row( + p, + "size", + "On disk", + file.as_ref() + .map(|(_, bytes)| format::bytes(*bytes)) + .unwrap_or_else(|| "—".to_string()), + ), + detail_row( + p, + "quality", + "Quality", + match settings { + Some(settings) => format!( + "{} · {} fps", + settings.video.quality.label(), + settings.video.frame_rate + ), + None => "—".to_string(), + }, + ), + detail_row( + p, + "encoder", + "Encoder", + settings + .map(|settings| settings.video.encoder_preset.label().to_string()) + .unwrap_or_else(|| "—".to_string()), + ), + detail_row(p, "audio", "Audio", audio_label(settings)), + detail_row( + p, + "folder", + "Folder", + app.output_dir().display().to_string(), + ), + ]; + ui::card(p, Some("This recording"), rows) +} + +/// A label on the left, its value on the right, in a row of the details card. +fn detail_row(p: Paint, key: &str, label: &str, value: String) -> El { + row() + .key(format!("detail-{key}")) + .w_full() + .h(30.0) + .px(space::S2) + .gap(space::S2) + .center_y() + .justify_between() + .label(format!("{label}: {value}")) + .child( + text(label) + .key("label") + .font(body(11.5)) + .color(p.muted()) + .a11y_hidden(), + ) + .child( + text(value) + .key("value") + .font(mono(11.5)) + .color(p.t.text) + .shrink() + .truncate() + .a11y_hidden(), + ) +} + +/// What the video carries, in the order the recorder lays the tracks down. +fn audio_label(settings: Option<&Settings>) -> String { + let Some(settings) = settings else { + return "—".to_string(); + }; + if !settings.audio.enabled { + return "No sound".to_string(); + } + let mut parts = Vec::new(); + if settings.audio.capture_game { + parts.push("Game".to_string()); + } + if settings.audio.capture_mic { + parts.push("Microphone".to_string()); + } + for source in &settings.audio.capture_apps { + if source.enabled { + parts.push(source.name.clone()); + } + } + if parts.is_empty() { + "Nothing".to_string() + } else { + parts.join(", ") + } +} + +/// The confirmation "Stop and delete" opens: stopping is the point of no return. +pub fn confirm_dialog(app: &App, p: Paint, layer: &mut Vec) { + let panel = col() + .key("stop-delete-dialog") + .role("dialog") + .label("Stop and delete this recording") + .w(380.0) + .padding(space::S6) + .gap(space::S3) + .radius(radius::LG) + .fill(p.t.card) + .border(p.hair, p.t.card_border) + .shadow(4.0, 12.0, p.t.shadow) + .shadow(24.0, 48.0, p.t.shadow_soft) + .modal(true, |app: &mut App| app.recording.confirm_delete = false) + .child( + text("Stop recording and delete it?") + .key("stop-delete-question") + .font(heading(15.0)) + .color(p.t.text), + ) + .child( + text("The video and its timeline are removed from disk. Nothing of this game is kept.") + .key("stop-delete-note") + .font(body(12.0)) + .color(p.muted()), + ) + .child( + row() + .key("stop-delete-actions") + .w_full() + .gap(space::S2) + .justify_end() + .child(ui::button( + p, + "stop-delete-no", + "No", + false, + |app: &mut App| { + app.recording.confirm_delete = false; + }, + )) + .child(ui::button_danger( + p, + "stop-delete-yes", + "Stop and delete", + delete_confirmed, + )), + ); + + layer.push( + el().key("stop-delete-scrim") + .absolute(0.0, 0.0) + .w_full() + .h_full() + .fill(rune::Color::BLACK.alpha(if app.dark { 0.55 } else { 0.28 })) + .a11y_hidden(), + ); + layer.push( + el().key("stop-delete-layer") + .absolute(0.0, 0.0) + .w_full() + .h_full() + .padding(16.0) + .center() + .child(panel), + ); +} + +/// A recording for `--scene recording-live`: twelve minutes in, one team ahead, a file on disk. +pub fn demo(app: &mut App) { + let mut live = Live { + game_time: 754.0, + gold: 12_840, + ..Live::default() + }; + let mut add = |name: &str, + champion: &str, + level: u32, + (kills, deaths, assists): (u32, u32, u32), + cs: u32, + order: bool| { + live.players.push(Player { + name: name.to_string(), + champion: champion.to_string(), + level, + kills, + deaths, + assists, + creep_score: cs, + vision: 18.0, + order, + dead: false, + respawn: 0.0, + }); + }; + add("Demo#EUW", "Kai'Sa", 11, (9, 3, 7), 214, true); + add("Nautilus Main", "Nautilus", 9, (2, 5, 14), 42, true); + add("Mid Lane", "Azir", 12, (6, 2, 9), 231, true); + add("Jungle Diff", "Sejuani", 10, (3, 3, 12), 138, true); + add("Top Lane", "Camille", 11, (7, 4, 5), 189, true); + add("Enemy ADC", "Jinx", 10, (5, 6, 4), 205, false); + add("Enemy Support", "Thresh", 8, (1, 8, 10), 34, false); + add("Enemy Mid", "Zed", 11, (4, 5, 6), 198, false); + add("Enemy Jungle", "Lee Sin", 9, (2, 7, 8), 121, false); + add("Enemy Top", "Renekton", 10, (5, 5, 3), 176, false); + live.me = Some(0); + app.recording.live = Some(live); + app.recording.started = Some(Utc::now() - chrono::Duration::seconds(766)); + app.recording.file = Some(( + PathBuf::from(r"C:\Users\you\Videos\League\2026-11-22_20-31-08_7000000.mp4"), + 1_288_000_000, + )); + if let Some(mut sample) = crate::history::sample().into_iter().next() { + sample.start_time = Utc::now() - chrono::Duration::seconds(766); + sample.end_time = None; + sample.video_file = None; + sample.video_path = None; + app.recording.open = Some(sample); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const ALL_GAME_DATA: &str = r#"{ + "activePlayer": { + "championName": "Kai'Sa", + "currentGold": 12840.5, + "level": 11, + "summonerName": "Demo" + }, + "allPlayers": [ + { + "championName": "Kai'Sa", + "riotId": "Demo#EUW", + "riotIdGameName": "Demo", + "riotIdTagLine": "EUW", + "level": 11, + "team": "ORDER", + "isDead": false, + "respawnTimer": 0.0, + "scores": {"kills": 9, "deaths": 3, "assists": 7, "creepScore": 214, "wardScore": 18.0} + }, + { + "championName": "Zed", + "summonerName": "Enemy Mid", + "level": 12, + "team": "CHAOS", + "isDead": true, + "respawnTimer": 7.4, + "scores": {"kills": 4, "deaths": 5, "assists": 6, "creepScore": 198} + }, + { + "championName": "", + "team": "CHAOS", + "scores": {} + } + ], + "gameData": {"gameMode": "CLASSIC", "gameTime": 754.2} + }"#; + + #[test] + fn the_game_reports_who_is_playing_and_how_it_is_going() { + let value: Value = serde_json::from_str(ALL_GAME_DATA).unwrap(); + let live = Live::parse(&value).unwrap(); + assert!((live.game_time - 754.2).abs() < 1e-9); + // The empty slot is not a player. + assert_eq!(live.players.len(), 2); + assert_eq!(live.gold, 12_840); + + let me = live.mine().unwrap(); + assert_eq!(me.champion, "Kai'Sa"); + assert_eq!(me.name, "Demo#EUW"); + assert_eq!((me.kills, me.deaths, me.assists), (9, 3, 7)); + assert_eq!(me.creep_score, 214); + assert_eq!(me.vision, 18.0); + assert!(me.order && !me.dead); + + // A name without a tag is read without one, and a dead player says when they are back. + let enemy = &live.players[1]; + assert_eq!(enemy.name, "Enemy Mid"); + assert!(!enemy.order); + assert!(enemy.dead); + assert!((enemy.respawn - 7.4).abs() < 1e-9); + } + + #[test] + fn a_game_that_is_not_on_the_map_reports_nothing() { + // The game answers with an error document until the map has loaded. + let value = serde_json::json!({"errorCode": "RESOURCE_NOT_FOUND"}); + assert!(Live::parse(&value).is_none()); + } +}