Files
leaguerecorder/app/src/app.rs
T
vhaudiquet 01a92f1edf app: clear the clippy warnings and the vendored ones
Our crate is warning-free under `cargo clippy --all-targets`. The two
vendored crates warned about an unreachable expression and a qualified
path; both are silenced at their crate root so a normal build prints
nothing.
2026-11-15 23:09:15 +01:00

768 lines
23 KiB
Rust

//! App state, the frame hook and the screen dispatch.
use std::sync::mpsc::{Receiver, TryRecvError, channel};
use std::time::Duration;
use rune::tok::{radius, type_};
use rune::{Cx, El, Key, KeyEvent, Tx, col, el, row, text};
use crate::history::{self, QueueCategory, Timeline};
use crate::ipc::{self, Daemon};
use crate::os;
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,
Review,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingsTab {
General,
Recording,
Audio,
Daemon,
}
/// `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,
pub name: 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,
}
/// 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,
pub games: Vec<Timeline>,
pub games_rx: Option<Receiver<Vec<Timeline>>>,
pub games_loaded: bool,
pub filter: Option<QueueCategory>,
pub review: screens::review::Review,
pub notice: Option<Notice>,
pub autostart: bool,
pub logs: String,
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::General,
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_rx: None,
games_loaded: false,
filter: None,
review: screens::review::Review::default(),
notice: None,
autostart,
logs: String::new(),
last_status: -10.0,
tray_events: None,
tray: None,
tray_recording: false,
waker: None,
};
if headless && !live {
app.demo();
}
app
}
/// State for `--scene` snapshots: sample history, a connected daemon, default settings.
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,
};
self.games = history::sample();
self.games_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(),
name: "NVIDIA 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);
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,
});
}
pub fn refresh_settings(&self) {
self.daemon.get_settings();
}
/// Read the timelines on a thread of their own; `poll` picks the list up.
pub fn refresh_games(&mut self) {
if self.games_rx.is_some() {
return;
}
let (tx, rx) = channel();
std::thread::spawn(move || {
let _ = tx.send(history::load_all());
});
self.games_rx = Some(rx);
}
/// The game the review screen is showing, if any.
pub fn reviewed(&self) -> Option<&Timeline> {
let id = self.review.game.as_deref()?;
self.games.iter().find(|game| game.recording_id == id)
}
}
// ---------------------------------------------------------------------------
// 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.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::SaveSettings
| ipc::Request::ResetSettings,
Ok(data),
) => match crate::settings::from_response(&data) {
Ok(settings) => {
self.form.apply(&settings);
self.settings = Some(settings);
}
Err(e) => self.notify_error(e),
},
(ipc::Request::SaveSettings, Err(e)) => {
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;
}
}
(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.games_rx {
match rx.try_recv() {
Ok(games) => {
self.games = games;
self.games_loaded = true;
self.games_rx = None;
changed = true;
}
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => self.games_rx = None,
}
}
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();
}
// Keep the clock running so the status stays live even when nothing draws.
tx.wake_after(Duration::from_millis(1000));
if self.screen == Screen::Review {
changed |= screens::review::tick(self, tx);
}
changed
}
}
// ---------------------------------------------------------------------------
// Frame and input
// ---------------------------------------------------------------------------
pub fn poll(app: &mut App, t: f64, tx: &mut Tx) -> bool {
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" => {
app.screen = Screen::History;
true
}
(Key::Text(t), false) if t == "2" => {
app.screen = Screen::Settings;
true
}
(Key::Escape, _) if app.screen == Screen::Review => {
screens::review::leave(app);
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())
}
fn nav(p: Paint, label: &str, key: &str, active: bool, to: Screen) -> El {
el().key(key)
.role("tab")
.label(label)
.checked(active)
.focusable(true)
.w_full()
.h(32.0)
.px(10.0)
.center_y()
.radius(radius::MD)
.fill(if active {
p.t.indicator.alpha(0.5)
} else {
rune::Color::TRANSPARENT
})
.hover(p.t.hover)
.press(p.t.press)
.on_press(move |app: &mut App| {
if to != Screen::Review {
screens::review::leave(app);
}
app.screen = to;
})
.child(
text(label)
.key("label")
.font(type_::BODY)
.color(if active { p.t.text } else { p.t.text_secondary })
.a11y_hidden(),
)
}
fn sidebar(p: Paint, app: &App) -> El {
let (dot_color, status) = status_color(p, app);
col()
.key("sidebar")
.w(196.0)
.h_full()
.padding(10.0)
.gap(4.0)
.fill(p.t.bg)
.border_sides([0.0, p.hair, 0.0, 0.0], p.t.separator)
.child(nav(
p,
"Match history",
"nav-history",
app.screen != Screen::Settings,
Screen::History,
))
.child(nav(
p,
"Settings",
"nav-settings",
app.screen == Screen::Settings,
Screen::Settings,
))
.child(el().grow(1.0))
.child(
row()
.key("connection")
.gap(7.0)
.center_y()
.padding(6.0)
.child(ui::dot(dot_color))
.child(
text(status)
.key("status-text")
.font(body(11.5))
.color(p.muted()),
),
)
}
fn titlebar(p: Paint, app: &App) -> El {
let recording = app.status.is_recording;
let label = if recording {
"Stop recording"
} else {
"Start recording"
};
row()
.key("titlebar")
.h(48.0)
.w_full()
.px(16.0)
.gap(8.0)
.center_y()
.justify_between()
.window_drag()
.child(
row()
.key("brand")
.gap(8.0)
.center_y()
.child(el().key("mark").size(18.0, 18.0).radius(5.0).fill(p.accent))
.child(
text("League Recorder")
.key("title")
.font(heading(13.0))
.color(p.t.text),
),
)
.child(
row()
.key("actions")
.gap(8.0)
.center_y()
.child(ui::button(
p,
"record-toggle",
label,
!recording,
|app: &mut App| {
if app.status.is_recording {
app.daemon.stop_recording();
} else {
app.daemon.start_recording();
}
},
))
.child(ui::button(
p,
"refresh",
"Refresh",
false,
|app: &mut App| {
app.refresh_games();
app.daemon.get_status();
},
)),
)
}
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);
let content = match app.screen {
Screen::Settings => screens::settings::view(app, p),
Screen::History => screens::history::view(app, p),
Screen::Review => screens::review::view(app, p),
};
let mut main = col().key("main").grow(1.0).min_h(0.0).h_full().fill(p.t.bg);
if let Some(banner) = &app.notice {
main = main.child(notice(p, banner));
}
main = main.child(content);
col()
.key("window")
.w_full()
.h_full()
.fill(p.t.bg)
.child(titlebar(p, app))
.child(
row()
.key("body")
.grow(1.0)
.min_h(0.0)
.w_full()
.child(sidebar(p, app))
.child(main),
)
}
/// 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;
app.review.game = app.games.first().map(|game| game.recording_id.clone());
app.review.error = Some("Sample recording: no clip on disk.".to_string());
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;
}
}