Files
leaguerecorder/app/src/app.rs
T
vhaudiquet 9e4349fe42 app: find a clip in the folder it was recorded to
History lists a timeline from the default recordings folder, where
the daemon writes them, but review looked for its clip only there as
well. A recording made into the folder chosen in settings therefore
appeared in history with no video. The app now searches the
configured folder first and the default one after it, and uses the
path stored with the timeline when the recorder wrote one, so a clip
stays playable after the setting moves and an older timeline still
plays.

Settings are read back after a save because the daemon resolves the
chosen folder to an absolute path. The two Open folder buttons open
the configured folder instead of the default one.
2026-11-23 18:24:22 +01:00

1396 lines
48 KiB
Rust

//! 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::export::{self, Clip};
use crate::history::{self, QueueCategory, Summary, Timeline};
use crate::ipc::{self, Daemon};
use crate::os;
use crate::portraits;
use crate::process;
use crate::screens;
use crate::settings::{AudioSource, AudioSourceType, Settings};
use crate::ui::{self, Paint, body, heading};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen {
Settings,
History,
Clips,
Clip,
Review,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingsTab {
Quick,
Recording,
Audio,
Advanced,
}
/// `GetStatusResponse`.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct Status {
#[serde(default)]
pub status: String,
#[serde(default)]
pub is_recording: bool,
#[serde(default)]
pub current_game_id: Option<u64>,
#[serde(default)]
pub client_connected: bool,
}
impl Status {
pub fn label(&self) -> String {
match self.status.as_str() {
"idle" => "Idle".to_string(),
"monitoring" => "Monitoring".to_string(),
"recording" => "Recording".to_string(),
"error" => "Error".to_string(),
"shutting_down" => "Shutting down".to_string(),
"" => "Unknown".to_string(),
other => other.to_string(),
}
}
}
/// `GetEncodersResponse`.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct Encoders {
#[serde(default)]
pub available: Vec<EncoderInfo>,
#[serde(default)]
pub current: String,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct EncoderInfo {
pub id: String,
#[serde(default)]
pub is_hardware: bool,
#[serde(default)]
pub available: bool,
}
/// `GetAudioDevicesResponse`.
#[derive(Debug, Clone, Default, serde::Deserialize)]
pub struct AudioDevices {
#[serde(default)]
pub input_devices: Vec<AudioDevice>,
#[serde(default)]
pub output_devices: Vec<AudioDevice>,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub struct AudioDevice {
pub id: String,
pub name: String,
#[serde(default)]
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.
#[derive(Debug, Clone)]
pub struct Notice {
pub text: String,
pub error: bool,
}
pub struct App {
pub screen: Screen,
pub settings_tab: SettingsTab,
pub dark: bool,
pub daemon: Daemon,
pub connected: bool,
pub status: Status,
pub settings: Option<Settings>,
pub form: screens::settings::Form,
pub encoders: Encoders,
pub devices: AudioDevices,
/// One row per recording on disk, a page at a time.
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,
/// 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>,
/// The row the delete dialog is about, once its menu has asked to delete it.
pub confirm_delete: Option<String>,
/// The card whose actions menu is open, if any. The card's position, not its recording:
/// demo data repeats ids across rows, and a menu opens for one card alone.
pub menu_open: Option<usize>,
/// Every clip the user exported, newest first. Read when the screen opens.
pub clips: Vec<Clip>,
pub clips_loaded: bool,
/// The open clip: its view, with the title being set and its player.
pub clip: Option<screens::clip::ClipView>,
/// A clip waiting for the clipboard: its file. Handled off the handler, in poll.
pub share_clip: Option<PathBuf>,
/// The clips' miniatures, decoded off the render path and cached by file.
pub thumbs: Option<rune::ImageCache>,
/// A miniature on its way: the clip's name and the file that holds it.
pub thumbs_rx: Option<Receiver<(String, PathBuf)>>,
/// The clip card whose actions menu is open, if any: its position, like the history's.
pub clips_menu_open: Option<usize>,
/// The clip the delete dialog is about, by its `id@start` key.
pub confirm_clip_delete: Option<String>,
pub review: screens::review::Review,
pub portraits: Option<portraits::Portraits>,
/// The icons of the processes the audio sources name, decoded from their executables.
pub icons: Option<rune::ImageCache>,
/// Which of those processes are running, refreshed while the audio tab is open.
pub processes: process::Processes,
pub processes_rx: Option<Receiver<process::Processes>>,
/// When the process table was last read, in the clock `poll` gets.
pub processes_at: f64,
pub scroll: ui::ScrollBar,
pub clips_scroll: ui::ScrollBar,
pub highlights_scroll: ui::ScrollBar,
pub events_scroll: ui::ScrollBar,
pub notice: Option<Notice>,
/// ffmpeg being downloaded on the first run, and the whole percent it last reported.
pub ffmpeg_rx: Option<Receiver<export::FetchEvent>>,
pub ffmpeg_pct: Option<u64>,
pub autostart: bool,
pub logs: String,
pub pending_review: bool,
pub last_status: f64,
pub tray_events: Option<Receiver<rune::TrayEvent>>,
pub tray: Option<rune::Tray>,
pub tray_recording: bool,
pub waker: Option<rune::Waker>,
}
impl App {
pub fn new() -> Self {
let autostart = os::autostart_enabled();
let headless = headless();
// `--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 {
screen: Screen::History,
settings_tab: SettingsTab::Quick,
dark: true,
daemon: Daemon::start(headless && !live),
connected: false,
status: Status::default(),
settings: None,
form: screens::settings::Form::empty(),
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,
confirm_delete: None,
menu_open: None,
clips: Vec::new(),
clips_loaded: false,
clip: None,
share_clip: None,
thumbs: None,
thumbs_rx: None,
clips_menu_open: None,
confirm_clip_delete: None,
review: screens::review::Review::default(),
portraits: None,
icons: None,
processes: process::Processes::new(),
processes_rx: None,
processes_at: 0.0,
scroll: ui::ScrollBar::new(),
clips_scroll: ui::ScrollBar::new(),
highlights_scroll: ui::ScrollBar::new(),
events_scroll: ui::ScrollBar::new(),
notice: None,
ffmpeg_rx: None,
ffmpeg_pct: None,
autostart,
logs: String::new(),
pending_review: false,
last_status: -10.0,
tray_events: None,
tray: None,
tray_recording: false,
waker: None,
};
if headless && !live {
app.demo();
}
// Clip export runs on ffmpeg. Fetch it now, on the run that follows an install, so the
// first export does not sit behind a download. A hidden start (the login item) leaves it
// to the export itself.
let hidden = std::env::args().any(|arg| arg == "--hidden");
if !headless && !hidden && export::missing() && !export::fetching() {
let (tx, rx) = channel();
std::thread::spawn(move || {
let _ = export::fetch(move |event| {
let _ = tx.send(event);
});
});
app.ffmpeg_rx = Some(rx);
}
app
}
/// State for `--scene` snapshots: sample history, a connected daemon, default settings.
/// A demo clip like one the export writes: a name, an export time, a size.
pub fn demo_clip(name: String, hours_ago: i64, bytes: u64) -> Clip {
Clip {
name,
path: PathBuf::new(),
thumb: None,
exported: Some(
std::time::SystemTime::now()
- chrono::Duration::hours(hours_ago)
.to_std()
.unwrap_or_default(),
),
bytes,
}
}
pub fn demo(&mut self) {
self.connected = true;
self.status = Status {
status: "monitoring".to_string(),
is_recording: false,
current_game_id: None,
client_connected: true,
};
let sample = history::sample();
self.games = sample.iter().map(|game| game.summary()).collect();
self.games_loaded = true;
let id = |game: &Timeline| game.recording_id.clone();
self.clips = vec![
Self::demo_clip(format!("{}-clip", id(&sample[0])), 3, 22_000_000),
Self::demo_clip("baron-steal".into(), 5, 9_400_000),
Self::demo_clip(format!("{}-clip", id(&sample[1])), 26, 15_800_000),
Self::demo_clip("pentakill".into(), 74, 31_200_000),
];
// Like the folder listing: a miniature already on disk and as new as its clip shows
// at once, and the thumbnail pass only cuts what is missing.
for clip in &mut self.clips {
clip.thumb = export::thumb_of(clip);
}
self.clips_loaded = true;
self.devices = AudioDevices {
input_devices: vec![AudioDevice {
id: "mic-1".into(),
name: "Microphone (USB Audio)".into(),
is_default: true,
}],
output_devices: vec![
AudioDevice {
id: "out-1".into(),
name: "Speakers (Realtek)".into(),
is_default: true,
},
AudioDevice {
id: "out-2".into(),
name: "Headphones (USB Audio)".into(),
is_default: false,
},
],
};
self.encoders = Encoders {
available: vec![EncoderInfo {
id: "jim_nvenc".into(),
available: true,
is_hardware: true,
}],
current: "jim_nvenc".into(),
};
let mut settings = Settings::default();
settings.audio.capture_apps = vec![
AudioSource {
id: "discord".into(),
name: "Discord".into(),
source_type: AudioSourceType::Application,
device: "Discord.exe".into(),
volume: Some(80),
enabled: true,
},
AudioSource {
id: "spotify".into(),
name: "Spotify".into(),
source_type: AudioSourceType::Application,
device: "Spotify.exe".into(),
volume: Some(35),
enabled: true,
},
];
self.form.apply(&settings);
// The sample sources read as a running process and one that is not, so a snapshot
// shows both states of the chip.
self.processes = settings
.audio
.capture_apps
.iter()
.map(|source| {
let running = source.device.eq_ignore_ascii_case("Discord.exe");
(
process::normalize(&source.device),
process::Found {
running,
path: None,
},
)
})
.collect();
self.settings = Some(settings);
}
pub fn notify_error(&mut self, text: impl Into<String>) {
self.notice = Some(Notice {
text: text.into(),
error: true,
});
}
pub fn notify(&mut self, text: impl Into<String>) {
self.notice = Some(Notice {
text: text.into(),
error: false,
});
}
/// Whether the notice on screen belongs to the download. It is updated in place; a notice
/// the app is showing for something else is not replaced by the progress.
fn ffmpeg_banner_showing(&self) -> bool {
match &self.notice {
None => true,
Some(notice) => notice.text.starts_with("Downloading ffmpeg"),
}
}
pub fn refresh_settings(&self) {
self.daemon.get_settings();
}
/// The encoders this machine can run, as the daemon found them, hardware first.
pub fn runnable_encoders(&self) -> Vec<&'static str> {
let mut found: Vec<(&'static str, bool)> = self
.encoders
.available
.iter()
.filter(|encoder| encoder.available)
.filter_map(|encoder| {
let label = crate::settings::EncoderPreset::encoder_name(&encoder.id)?;
Some((label, encoder.is_hardware))
})
.collect();
// Hardware first: it is the choice most people want, and the fallback below uses the
// first entry.
found.sort_by_key(|(_, hardware)| !hardware);
found.into_iter().map(|(label, _)| label).collect()
}
/// Point the draft at an encoder this machine has when the stored one is missing.
///
/// A config written elsewhere can name NVENC on a card that has none. The daemon's encoder
/// list is this machine's own answer, so the draft follows it, and saving keeps it.
fn settle_encoder(&mut self) {
if !self.form.loaded || self.form.dirty {
return;
}
let runnable = self.runnable_encoders();
let Some(pick) = runnable.first() else {
return;
};
let current = self.form.draft.video.encoder_preset.label();
if runnable.contains(&current) {
return;
}
self.form.draft.video.encoder_preset = self.form.draft.video.encoder_preset.with_kind(pick);
self.form.dirty = true;
self.notify(format!(
"{current} is not on this machine; recording will use {pick}"
));
}
/// The process names the audio sources refer to, plus whatever is being typed into the
/// add dialog.
fn watch_names(&self) -> Vec<String> {
let mut names: Vec<String> = self
.form
.draft
.audio
.capture_apps
.iter()
.filter(|source| source.source_type == AudioSourceType::Application)
.map(|source| source.device.clone())
.collect();
if self.form.add_open {
let typed = self.form.source_device.text.trim();
if !typed.is_empty() {
names.push(typed.to_string());
}
}
names.sort();
names.dedup();
names
}
/// Look at the process table on a thread of its own; `poll` picks the answer up.
pub fn refresh_processes(&mut self) {
if self.processes_rx.is_some() {
return;
}
let names = self.watch_names();
if names.is_empty() {
self.processes.clear();
return;
}
let (tx, rx) = channel();
std::thread::spawn(move || {
let _ = tx.send(process::snapshot(names));
});
self.processes_rx = Some(rx);
}
/// Where the daemon writes new recordings, as the settings it holds say.
///
/// The draft stands in until the daemon has answered, so a first launch points at the
/// default folder the daemon would use anyway.
pub fn output_dir(&self) -> PathBuf {
let path = self
.settings
.as_ref()
.map(|settings| settings.output.path.as_str())
.unwrap_or(self.form.draft.output.path.as_str());
if path.is_empty() {
crate::daemon::recordings_dir()
} else {
PathBuf::from(path)
}
}
/// 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<PathBuf> {
let default = crate::daemon::recordings_dir();
let output = self.output_dir();
if output == default {
vec![output]
} else {
vec![output, default]
}
}
/// 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 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 clips folder into the grid. A directory read, quick enough for the UI thread.
/// The miniatures are ffmpeg work, so their pass runs on a thread of its own and `poll`
/// picks each one up as it lands.
pub fn refresh_clips(&mut self) {
self.clips = export::list_clips();
self.clips_loaded = true;
self.spawn_thumbs();
}
/// Cut every missing miniature, one clip at a time, on a thread of its own; `poll` picks
/// each one up as it lands. One pass at a time: the next refresh starts another.
pub fn spawn_thumbs(&mut self) {
if self.thumbs_rx.is_some() {
return;
}
let clips = self.clips.clone();
let (tx, rx) = channel();
std::thread::spawn(move || {
for clip in &clips {
if export::thumb_of(clip).is_some() {
continue;
}
let Some(source) = export::source_of(clip) else {
continue;
};
let thumb = export::thumb_path(clip);
let cut = export::make_thumb(&source, &thumb);
if cut && tx.send((clip.name.clone(), thumb)).is_err() {
break;
}
}
});
self.thumbs_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()
}
/// Drop a recording out of the list once it has been deleted from disk, and drop a page
/// of rows already on its way: it may still hold the deleted file.
pub fn forget_game(&mut self, recording_id: &str) {
self.games.retain(|game| game.recording_id != recording_id);
if let Some(at) = self
.games_paths
.iter()
.position(|path| path.file_stem().and_then(|s| s.to_str()) == Some(recording_id))
{
self.games_paths.remove(at);
if at < self.games_next {
self.games_next -= 1;
}
}
self.games_rx = None;
}
/// The game the review screen is showing, if any.
pub fn reviewed(&self) -> Option<&Timeline> {
self.review.game.as_ref()
}
}
// ---------------------------------------------------------------------------
// Runtime hooks
// ---------------------------------------------------------------------------
thread_local! {
/// The main window's handle, kept where `poll` and the tray can reach it. `WindowHandle`
/// is not `Send`, so it cannot travel with the tray callback.
static WINDOW: std::cell::RefCell<Option<rune::WindowHandle>> =
const { std::cell::RefCell::new(None) };
}
pub fn remember_window(handle: &rune::WindowHandle) {
WINDOW.with(|slot| *slot.borrow_mut() = Some(handle.clone()));
}
fn show_window() {
WINDOW.with(|slot| {
if let Some(handle) = slot.borrow().as_ref() {
handle.open();
}
});
}
fn hide_window() {
WINDOW.with(|slot| {
if let Some(handle) = slot.borrow().as_ref() {
handle.hide();
}
});
}
/// `AppSpec::setup`: keep the waker and put the tray icon up.
pub fn setup(app: &mut App, waker: rune::Waker) {
app.waker = Some(waker.clone());
app.portraits = Some(portraits::Portraits::new(waker.clone()));
app.icons = Some(rune::ImageCache::new(waker.clone()));
app.thumbs = Some(rune::ImageCache::new(waker.clone()));
app.daemon.set_waker(waker.clone());
app.refresh_settings();
app.refresh_games();
app.daemon.get_status();
app.daemon.get_encoders();
app.daemon.get_audio_devices();
if headless() {
return;
}
let (tx, rx) = channel::<rune::TrayEvent>();
let spec = rune::TraySpec::new(os::APP_ID, os::APP_NAME, os::tray_icon())
.tooltip("League Recorder")
.menu(os::tray_menu(false));
let wake = waker.clone();
match rune::Tray::new(spec, move |event| {
let _ = tx.send(event);
wake();
}) {
Ok(tray) => {
app.tray = Some(tray);
app.tray_events = Some(rx);
}
Err(e) => eprintln!("tray icon unavailable: {e}"),
}
}
impl App {
fn apply_status(&mut self, status: Status, tx: &mut Tx) -> bool {
let was_recording = self.status.is_recording;
let first = self.status.status.is_empty();
self.status = status;
self.connected = true;
if first {
self.refresh_settings();
}
if self.status.is_recording != was_recording {
if let Some(tray) = &self.tray {
tray.set_menu(os::tray_menu(self.status.is_recording));
}
if self.status.is_recording {
os::notify(
"recording-started",
"Recording started",
"League Recorder is recording this game.",
);
} else if was_recording {
os::notify(
"recording-stopped",
"Recording stopped",
"Your clip is in Match history.",
);
self.refresh_games();
// A stop can take a moment to write the timeline; read it again shortly.
tx.wake_after(Duration::from_millis(1500));
}
self.tray_recording = self.status.is_recording;
}
true
}
}
impl App {
fn handle_poll(&mut self, t: f64, tx: &mut Tx) -> bool {
let mut changed = false;
for event in self.daemon.drain() {
changed = true;
match (event.request, event.result) {
(ipc::Request::EnsureRunning, Err(e)) => {
self.connected = false;
self.notify_error(e);
}
(ipc::Request::Settings | ipc::Request::ResetSettings, Ok(data)) => {
match crate::settings::from_response(&data) {
Ok(settings) => {
self.form.apply(&settings);
self.settings = Some(settings);
self.settle_encoder();
}
Err(e) => self.notify_error(e),
}
}
// The daemon answers a save with `{"success": true}`. Read the settings back:
// it may have resolved the recordings folder to an absolute path.
(ipc::Request::SaveSettings, Ok(_)) => {
self.settings = Some(self.form.settings());
self.form.saving = false;
self.form.dirty = false;
self.form.loaded = true;
self.notify("Settings saved");
self.daemon.get_settings();
}
(ipc::Request::SaveSettings, Err(e)) => {
self.form.saving = false;
self.notify_error(format!("Settings were not saved: {e}"))
}
(ipc::Request::ResetSettings, Err(e)) => {
self.notify_error(format!("Settings were not reset: {e}"))
}
(ipc::Request::Status, Ok(data)) => match serde_json::from_value::<Status>(data) {
Ok(status) => changed |= self.apply_status(status, tx),
Err(e) => {
self.connected = false;
self.notify_error(format!("Status did not parse: {e}"));
}
},
(ipc::Request::Status, Err(e)) if self.connected => {
self.connected = false;
self.notify_error(format!("Lost the record-daemon: {e}"));
self.refresh_games();
}
(ipc::Request::Encoders, Ok(data)) => {
if let Ok(list) = serde_json::from_value(data) {
self.encoders = list;
self.settle_encoder();
}
}
(ipc::Request::AudioDevices, Ok(data)) => {
if let Ok(list) = serde_json::from_value(data) {
self.devices = list;
}
}
(
ipc::Request::AddAudioSource
| ipc::Request::RemoveAudioSource
| ipc::Request::UpdateAudioSource,
Ok(_),
) => {
self.refresh_settings();
}
(ipc::Request::StartRecording, Ok(_)) => self.notify("Recording started"),
(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, Err(e)) => {
self.notify_error(format!("Cannot stop recording: {e}"))
}
(ipc::Request::Logs, Ok(data)) => {
self.logs = data.as_str().unwrap_or_default().to_string();
}
(_, Err(e)) => self.notify_error(e),
_ => {}
}
}
if let Some(rx) = &self.processes_rx {
match rx.try_recv() {
Ok(processes) => {
self.processes = processes;
self.processes_rx = None;
changed = true;
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => self.processes_rx = None,
}
}
if let Some(rx) = &self.games_rx {
match rx.try_recv() {
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;
if self.pending_review {
demo_review(self);
}
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => self.games_rx = None,
}
}
if let Some(rx) = &self.thumbs_rx {
let mut landed = false;
loop {
match rx.try_recv() {
Ok((name, thumb)) => {
if let Some(clip) = self.clips.iter_mut().find(|clip| clip.name == name) {
clip.thumb = Some(thumb);
landed = true;
}
}
Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => {
self.thumbs_rx = None;
break;
}
}
}
changed |= landed;
}
// The clips grid reads the clips folder, so it loads once it is on screen, not at launch.
if self.screen == Screen::Clips && !self.clips_loaded {
self.refresh_clips();
changed = true;
}
// Taken out of the field so the notice helpers below can borrow the app.
if let Some(rx) = self.ffmpeg_rx.take() {
let mut finished = false;
while let Ok(event) = rx.try_recv() {
match event {
export::FetchEvent::Bytes { done, total } => {
let pct = (done * 100).checked_div(total).unwrap_or(0);
if self.ffmpeg_pct != Some(pct) {
self.ffmpeg_pct = Some(pct);
if self.ffmpeg_banner_showing() {
self.notify(format!("Downloading ffmpeg for clip exports: {pct}%"));
}
}
}
export::FetchEvent::Unpacking => {
if self.ffmpeg_banner_showing() {
self.notify("Unpacking ffmpeg…");
}
}
export::FetchEvent::Finished(result) => {
finished = true;
match result {
Ok(()) => {
if self.ffmpeg_banner_showing() {
self.notify("ffmpeg is ready: clip export works now");
}
}
Err(e) => self.notify_error(e),
}
}
}
changed = true;
}
if !finished {
self.ffmpeg_rx = Some(rx);
}
}
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() {
tray_events.push(event);
}
}
for event in tray_events {
changed = true;
match event {
rune::TrayEvent::Activate { .. } => show_window(),
rune::TrayEvent::Menu(id) if id == "show" => show_window(),
rune::TrayEvent::Menu(id) if id == "hide" => hide_window(),
rune::TrayEvent::Menu(id) if id == "record" => {
if self.status.is_recording {
self.daemon.stop_recording();
} else {
self.daemon.start_recording();
}
}
rune::TrayEvent::Menu(id) if id == "quit" => tx.quit(),
_ => {}
}
}
if t - self.last_status >= 1.0 {
self.last_status = t;
self.daemon.get_status();
}
// The audio tab says whether each process is up, so it reads the process table again
// every couple of seconds while it is on screen.
if self.screen == Screen::Settings
&& (self.settings_tab == SettingsTab::Audio || self.form.add_open)
&& t - self.processes_at >= 2.0
{
self.processes_at = t;
self.refresh_processes();
}
// Keep the clock running so the status stays live even when nothing draws.
tx.wake_after(Duration::from_millis(1000));
// The clip view plays its file; leaving the screen behind stops it with the view.
if self.screen != Screen::Clip && self.clip.take().is_some() {
changed = true;
}
if self.screen == Screen::Review {
changed |= screens::review::tick(self, tx);
}
changed |= screens::clip::tick(self, tx);
changed
}
}
// ---------------------------------------------------------------------------
// Frame and input
// ---------------------------------------------------------------------------
pub fn poll(app: &mut App, t: f64, tx: &mut Tx) -> bool {
// Snapshot hook: pause the demo clip when its clock passes `LR_DEMO_PAUSE_AT` seconds.
if let Some(at) = std::env::var("LR_DEMO_PAUSE_AT")
.ok()
.and_then(|v| v.parse::<f64>().ok())
&& let Some(player) = &app.review.player
&& player.is_playing()
&& player.time() >= at
{
app.review.playback();
}
app.handle_poll(t, tx)
}
pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool {
let command = event.mods.ctrl || event.mods.cmd;
match (&event.key, command) {
(Key::Text(t), false) if t == "1" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None;
app.clips_menu_open = None;
app.screen = Screen::History;
true
}
(Key::Text(t), false) if t == "2" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None;
app.clips_menu_open = None;
app.screen = Screen::Settings;
true
}
(Key::Text(t), false) if t == "3" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None;
app.clips_menu_open = None;
app.screen = Screen::Clips;
true
}
(Key::Escape, _) if app.form.add_open => {
app.form.close_add();
true
}
(Key::Escape, _) if app.confirm_delete.is_some() => {
app.confirm_delete = None;
true
}
(Key::Escape, _) if app.confirm_clip_delete.is_some() => {
app.confirm_clip_delete = None;
true
}
(Key::Escape, _) if app.clips_menu_open.is_some() => {
app.clips_menu_open = None;
true
}
(Key::Escape, _) if app.screen == Screen::Clip => {
app.menu_open = None;
app.screen = Screen::Clips;
true
}
(Key::Escape, _) if app.screen == Screen::Clips => {
app.menu_open = None;
app.screen = Screen::History;
true
}
(Key::Escape, _) if app.screen == Screen::Review => {
screens::review::leave(app);
app.screen = Screen::History;
true
}
(Key::Escape, _) if app.screen == Screen::Settings => {
app.menu_open = None;
app.screen = Screen::History;
true
}
(Key::Text(t), true) if t.eq_ignore_ascii_case("r") => {
app.refresh_games();
app.daemon.get_status();
true
}
_ => false,
}
}
fn status_color(p: Paint, app: &App) -> (rune::Color, String) {
if !app.connected {
return (p.muted(), "Daemon offline".to_string());
}
if app.status.is_recording {
return (p.danger, "Recording".to_string());
}
if app.status.client_connected {
return (
p.success,
format!("{} · client connected", app.status.label()),
);
}
(p.muted(), app.status.label())
}
/// The thin bar under the screens: daemon state on the left, the encoder on the right.
fn statusbar(p: Paint, app: &App) -> El {
let (dot_color, status) = status_color(p, app);
// The draft carries the encoder this machine settled on, which is what a save keeps.
let name = app
.settings
.as_ref()
.map(|_| app.form.draft.video.encoder_preset.label().to_string())
.or_else(|| {
crate::settings::EncoderPreset::encoder_name(&app.encoders.current).map(str::to_string)
});
let recording = match (name, app.settings.as_ref().map(|s| s.video.frame_rate)) {
(Some(name), Some(fps)) => Some(format!("{name} · {fps} fps")),
(Some(name), None) => Some(name),
_ => None,
};
let mut bar = row()
.key("statusbar")
.h(30.0)
.w_full()
.px(14.0)
.gap(8.0)
.center_y()
.fill(p.chrome)
.border_sides([p.hair, 0.0, 0.0, 0.0], p.t.separator)
.child(ui::dot(dot_color))
.child(
text(status)
.key("status-text")
.font(body(11.5))
.color(p.muted()),
)
.child(el().grow(1.0));
if let Some(note) = recording {
bar = bar.child(
text(note)
.key("encoder-note")
.font(body(11.0))
.color(p.muted()),
);
}
bar
}
fn titlebar(p: Paint, app: &App) -> El {
// Leaving a screen is on the left, where a window's back arrow lives; the app's own
// actions stay on the right.
let mut leading = row().key("leading").gap(8.0).center_y();
if matches!(
app.screen,
Screen::Settings | Screen::Clips | Screen::Clip | Screen::Review
) {
let from_clip = app.screen == Screen::Clip;
leading = leading.child(ui::button(
p,
"back",
if from_clip {
"← Clips"
} else {
"← Match history"
},
false,
|app: &mut App| {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.screen = if app.screen == Screen::Clip {
Screen::Clips
} else {
Screen::History
};
},
));
}
let leading = leading.child(
text("League Recorder")
.key("title")
.font(heading(13.0))
.color(p.t.text),
);
let mut actions = row().key("actions").gap(8.0).center_y();
// 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 {
if !matches!(app.screen, Screen::Clips | Screen::Clip) {
actions = actions.child(ui::button(
p,
"open-clips",
"Clips",
false,
|app: &mut App| {
app.menu_open = None;
app.clips_menu_open = None;
screens::review::leave(app);
app.screen = Screen::Clips;
},
));
}
actions = actions
.child(ui::button(
p,
"refresh",
"Refresh",
false,
|app: &mut App| {
app.refresh_games();
app.daemon.get_status();
if app.screen == Screen::Clips {
app.clips_loaded = false;
app.refresh_clips();
}
},
))
.child(ui::button(
p,
"open-settings",
"Settings",
false,
|app: &mut App| {
app.menu_open = None;
screens::review::leave(app);
app.screen = Screen::Settings;
},
));
}
row()
.key("titlebar")
.h(48.0)
.w_full()
.px(16.0)
.gap(8.0)
.center_y()
.justify_between()
.window_drag()
.fill(p.chrome)
.border_sides([0.0, 0.0, p.hair, 0.0], p.t.separator)
.child(leading)
.child(actions)
}
fn notice(p: Paint, notice: &Notice) -> El {
row()
.key("notice")
.w_full()
.h(36.0)
.px(16.0)
.gap(8.0)
.center_y()
.fill(if notice.error {
p.danger.alpha(0.16)
} else {
p.success.alpha(0.16)
})
.on_press(|app: &mut App| app.notice = None)
.child(ui::dot(if notice.error { p.danger } else { p.success }))
.child(
text(notice.text.clone())
.key("notice-text")
.font(body(12.0))
.color(if notice.error { p.danger } else { p.success })
.grow(1.0)
.shrink()
.truncate(),
)
.child(
text("Dismiss")
.key("dismiss")
.font(type_::LABEL)
.color(p.muted()),
)
}
pub fn view(app: &App, cx: &mut Cx<App>) -> El {
let p = Paint::new(app.dark, cx.env().scale);
// Menus and dialogs cover the whole window, title bar and status bar included: the
// history row menus, the add-application form and the delete confirmation.
let mut overlays = Vec::new();
let content = match app.screen {
Screen::Settings => screens::settings::view(app, p),
Screen::History => screens::history::view(app, p, &mut overlays),
Screen::Clips => screens::clips::view(app, p, &mut overlays),
Screen::Clip => screens::clip::view(app, p),
Screen::Review => screens::review::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 {
main = main.child(notice(p, banner));
}
main = main.child(content);
let window = col()
.key("window")
.w_full()
.h_full()
.fill(p.t.bg)
.child(titlebar(p, app))
.child(main)
.child(statusbar(p, app));
let content = match app.screen {
// The two bars belong to the details column and nothing else: leaving them up once the
// column closes floats them over the clip, where they scroll nothing.
Screen::Review if app.review.show_details && app.reviewed().is_some() => window
.child(
app.highlights_scroll
.thumb(p, "highlights-thumb", "highlight-scroller"),
)
.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")),
_ => window.child(app.scroll.thumb(
p,
"scroll-thumb",
if app.screen == Screen::Settings {
"scroller"
} else {
"list-scroller"
},
)),
};
if app.screen == Screen::Settings && app.form.add_open {
screens::settings::add_dialog(app, p, &mut overlays);
}
if app.confirm_delete.is_some() {
screens::history::delete_dialog(app, p, &mut overlays);
}
if app.confirm_clip_delete.is_some() {
screens::clips::delete_dialog(app, p, &mut overlays);
}
rune_kit::root(content, overlays)
}
/// Whether this is a headless run (`--snap out.png`, `--tree`, …) rather than a window.
pub fn headless() -> bool {
const TOOLING: [&str; 8] = [
"--snap",
"--tree",
"--script",
"--trace",
"--strip",
"--video",
"--html",
"--desktop",
];
std::env::args()
.skip(1)
.any(|arg| TOOLING.contains(&arg.split('=').next().unwrap_or("")))
}
/// Put the first sample game on the review screen, for `--scene review`.
pub fn demo_review(app: &mut App) {
app.screen = Screen::Review;
if app.games.is_empty() {
// Opened before the history finished loading: `poll` opens it once it has.
app.pending_review = true;
return;
}
app.pending_review = false;
let live = std::env::args().any(|arg| arg == "--live");
if live {
let row = app
.games
.iter()
.find(|game| game.event_count > 0)
.map(|game| game.recording_id.clone());
if let Some(id) = row {
screens::review::open(app, &id);
}
return;
}
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, with as many audio tracks as
// `LR_DEMO_TRACKS` names.
if let Ok(path) = std::env::var("LR_DEMO_VIDEO") {
let player = rune::Player::file(&path);
player.set_looping(false);
app.review.player = Some(player);
app.review.error = None;
if std::env::var("LR_DEMO_PLAY").is_ok()
&& let Some(player) = &app.review.player
{
player.play();
}
if let Ok(tracks) = std::env::var("LR_DEMO_TRACKS") {
if let Some(game) = app.review.game.as_mut() {
game.audio_tracks = tracks
.split(',')
.map(|name| name.trim().to_string())
.collect();
}
app.review.open_sound(&path);
}
}
}