app: add native rune client for record-daemon
Replaces the Vue/Tauri front end with a rune app that speaks the daemon's existing IPC protocol: settings (general, recording, audio), match history and game review with a scrubber, event markers and ffmpeg highlight export. Includes tray icon, launch at login, single instance, toasts, a headless snapshot path for checking screens, and a cargo-packager NSIS config. Rune is pinned to 4ddf696b0f and its three patched crates are vendored under app/vendor, since a dependency's [patch.crates-io] does not apply to the app. The daemon's OBS bootstrap never reached its IPC server on this machine, so the live check is a `--probe` command; the wire format is covered by tests.
This commit is contained in:
1 parent
d712c4ea85
commit
0377141e4f
349 files changed
+142819
No files matched your search
+725
@@ -0,0 +1,725 @@
|
||||
//! 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::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(),
|
||||
other if other.is_empty() => "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();
|
||||
let mut app = Self {
|
||||
screen: Screen::History,
|
||||
settings_tab: SettingsTab::General,
|
||||
dark: true,
|
||||
daemon: Daemon::start(headless),
|
||||
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 {
|
||||
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;
|
||||
let settings = Settings::default();
|
||||
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());
|
||||
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}"),
|
||||
}
|
||||
|
||||
app.refresh_settings();
|
||||
app.refresh_games();
|
||||
app.daemon.get_status();
|
||||
app.daemon.get_encoders();
|
||||
app.daemon.get_audio_devices();
|
||||
}
|
||||
|
||||
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 {
|
||||
loop {
|
||||
match rx.try_recv() {
|
||||
Ok(event) => tray_events.push(event),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
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.get(0) {
|
||||
app.review.highlights =
|
||||
crate::highlight::compute(game, game.summoner().as_deref(), Default::default());
|
||||
app.review.duration = game.duration_secs.max(0) as f64;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Finding, starting and logging the record-daemon process.
|
||||
//!
|
||||
//! Ported from `tauri-app/src-tauri/src/daemon_ipc.rs`. The daemon binary ships next to the
|
||||
//! app; inside a checkout it is found in `record-daemon/target/{release,debug}`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::ipc::Client;
|
||||
|
||||
/// The daemon's data directory, shared with the daemon itself.
|
||||
pub fn data_dir() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("com", "leaguerecorder", "record-daemon")
|
||||
.map(|dirs| dirs.data_dir().to_path_buf())
|
||||
}
|
||||
|
||||
/// Where recordings and timelines live.
|
||||
pub fn recordings_dir() -> PathBuf {
|
||||
data_dir()
|
||||
.map(|p| p.join("recordings"))
|
||||
.unwrap_or_else(|| PathBuf::from("./recordings"))
|
||||
}
|
||||
|
||||
/// Where the daemon writes its log.
|
||||
pub fn log_file() -> Option<PathBuf> {
|
||||
let dir = data_dir()?.join("logs");
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
Some(dir.join("daemon.log"))
|
||||
}
|
||||
|
||||
/// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a
|
||||
/// development checkout.
|
||||
pub fn find_binary() -> Option<PathBuf> {
|
||||
let name = if cfg!(windows) {
|
||||
"record-daemon.exe"
|
||||
} else {
|
||||
"record-daemon"
|
||||
};
|
||||
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
let exe_dir = exe.parent()?;
|
||||
let beside = exe_dir.join(name);
|
||||
if beside.exists() {
|
||||
return Some(beside);
|
||||
}
|
||||
if let Some(parent) = exe_dir.parent() {
|
||||
let resources = parent.join("resources").join(name);
|
||||
if resources.exists() {
|
||||
return Some(resources);
|
||||
}
|
||||
}
|
||||
let mut dir = exe_dir.to_path_buf();
|
||||
for _ in 0..6 {
|
||||
for suffix in ["record-daemon/target/release", "record-daemon/target/debug"] {
|
||||
let candidate = dir.join(suffix).join(name);
|
||||
if candidate.exists() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
if !dir.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let cwd = std::env::current_dir().ok()?;
|
||||
let mut dir = cwd.as_path();
|
||||
for _ in 0..5 {
|
||||
for suffix in ["record-daemon/target/release", "record-daemon/target/debug"] {
|
||||
let candidate = dir.join(suffix).join(name);
|
||||
if candidate.exists() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
dir = dir.parent()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Start the daemon detached, so it outlives the app.
|
||||
pub fn spawn() -> Result<PathBuf, String> {
|
||||
let binary = find_binary().ok_or_else(|| {
|
||||
"record-daemon was not found next to the app or in record-daemon/target".to_string()
|
||||
})?;
|
||||
let log = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?;
|
||||
|
||||
let mut command = std::process::Command::new(&binary);
|
||||
command.arg("--foreground").arg("--log-file").arg(&log);
|
||||
if let Some(dir) = binary.parent() {
|
||||
// The daemon finds its bundled OBS plugin data relative to itself.
|
||||
command.current_dir(dir);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
|
||||
command.creation_flags(0x0000_0200 | 0x0000_0008);
|
||||
}
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
command
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start record-daemon: {e}"))?;
|
||||
Ok(binary)
|
||||
}
|
||||
|
||||
/// Is a daemon answering on the pipe?
|
||||
|
||||
/// Wait up to `timeout` for the daemon to answer, starting it if it isn't running yet.
|
||||
pub async fn ensure_running() -> Result<(), String> {
|
||||
let client = Client::new();
|
||||
if client.is_running().await {
|
||||
return Ok(());
|
||||
}
|
||||
spawn()?;
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if client.is_running().await {
|
||||
return Ok(());
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err("record-daemon did not answer within 30 s".to_string());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `n` lines of the daemon log.
|
||||
pub fn read_logs(n: usize) -> Result<String, String> {
|
||||
let path = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
|
||||
let lines: Vec<&str> = text.lines().rev().take(n).collect();
|
||||
Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
|
||||
/// The log path as text, for the About tab.
|
||||
pub fn log_path() -> String {
|
||||
log_file()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Open a folder.
|
||||
pub fn open_folder(path: &Path) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = std::process::Command::new("explorer").arg(path).spawn();
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = path;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in
|
||||
//! `tauri-app/src-tauri/src/lib.rs`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed};
|
||||
use ffmpeg_sidecar::download::auto_download;
|
||||
use ffmpeg_sidecar::event::{FfmpegEvent, LogLevel};
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
/// The clips folder beside the recordings.
|
||||
pub fn clips_dir() -> PathBuf {
|
||||
let dir = daemon::recordings_dir().join("clips");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Download the ffmpeg sidecar on first use.
|
||||
pub fn ensure_ffmpeg() -> Result<(), String> {
|
||||
if ffmpeg_is_installed() {
|
||||
return Ok(());
|
||||
}
|
||||
auto_download().map_err(|e| format!("cannot download ffmpeg: {e}"))
|
||||
}
|
||||
|
||||
/// Export `start..end` of `video`. Stream copy is fast and keyframe-aligned; `precise` re-encodes
|
||||
/// with x264 for exact cuts.
|
||||
pub fn export_clip(
|
||||
video: &str,
|
||||
start: f64,
|
||||
end: f64,
|
||||
output_name: &str,
|
||||
precise: bool,
|
||||
quality: &str,
|
||||
) -> Result<String, String> {
|
||||
ensure_ffmpeg()?;
|
||||
if !PathBuf::from(video).exists() {
|
||||
return Err(format!("video file not found: {video}"));
|
||||
}
|
||||
let output = clips_dir().join(format!("{}.mp4", sanitize(output_name)));
|
||||
let duration = (end - start).max(0.0);
|
||||
if duration <= 0.0 {
|
||||
return Err("the clip has no length".into());
|
||||
}
|
||||
|
||||
let mut command = FfmpegCommand::new();
|
||||
command
|
||||
.arg("-y")
|
||||
.arg("-ss")
|
||||
.arg(format!("{start:.3}"))
|
||||
.arg("-i")
|
||||
.arg(video)
|
||||
.arg("-t")
|
||||
.arg(format!("{duration:.3}"));
|
||||
if precise {
|
||||
let crf = match quality {
|
||||
"low" => "28",
|
||||
"high" => "18",
|
||||
_ => "23",
|
||||
};
|
||||
command
|
||||
.arg("-c:v")
|
||||
.arg("libx264")
|
||||
.arg("-crf")
|
||||
.arg(crf)
|
||||
.arg("-preset")
|
||||
.arg("fast")
|
||||
.arg("-c:a")
|
||||
.arg("aac")
|
||||
.arg("-b:a")
|
||||
.arg("128k");
|
||||
} else {
|
||||
command
|
||||
.arg("-c")
|
||||
.arg("copy")
|
||||
.arg("-avoid_negative_ts")
|
||||
.arg("make_zero");
|
||||
}
|
||||
|
||||
let iter = command
|
||||
.arg(output.to_string_lossy().to_string())
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start ffmpeg: {e}"))?
|
||||
.iter()
|
||||
.map_err(|e| format!("cannot read ffmpeg output: {e}"))?;
|
||||
|
||||
let mut errors = Vec::new();
|
||||
for event in iter {
|
||||
match event {
|
||||
FfmpegEvent::Error(e) => errors.push(e),
|
||||
FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let size = std::fs::metadata(&output).map(|m| m.len()).unwrap_or(0);
|
||||
if size == 0 {
|
||||
return Err(if errors.is_empty() {
|
||||
"ffmpeg produced no output".to_string()
|
||||
} else {
|
||||
errors.join("; ")
|
||||
});
|
||||
}
|
||||
Ok(output.display().to_string())
|
||||
}
|
||||
|
||||
fn sanitize(name: &str) -> String {
|
||||
name.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Text formatting shared by the screens, matching `tauri-app/src/types/timeline.ts`.
|
||||
|
||||
use chrono::{DateTime, Local, Utc};
|
||||
|
||||
pub fn duration(secs: f64) -> String {
|
||||
let total = secs.max(0.0).round() as u64;
|
||||
format!("{}:{:02}", total / 60, total % 60)
|
||||
}
|
||||
|
||||
pub fn clock(secs: f64) -> String {
|
||||
let total = secs.max(0.0) as u64;
|
||||
format!("{}:{:02}", total / 60, total % 60)
|
||||
}
|
||||
|
||||
pub fn relative_time(when: DateTime<Utc>) -> String {
|
||||
let now = Utc::now();
|
||||
let delta = now.signed_duration_since(when);
|
||||
let days = delta.num_days();
|
||||
let local = when.with_timezone(&Local);
|
||||
if days > 7 {
|
||||
return local.format("%b %e, %Y, %H:%M").to_string();
|
||||
}
|
||||
if days > 0 {
|
||||
return format!("{days} day{} ago", plural(days));
|
||||
}
|
||||
let hours = delta.num_hours();
|
||||
if hours > 0 {
|
||||
return format!("{hours} hour{} ago", plural(hours));
|
||||
}
|
||||
let minutes = delta.num_minutes();
|
||||
if minutes > 0 {
|
||||
return format!("{minutes} minute{} ago", plural(minutes));
|
||||
}
|
||||
"Just now".into()
|
||||
}
|
||||
|
||||
pub fn game_start(when: DateTime<Utc>) -> String {
|
||||
let local = when.with_timezone(&Local);
|
||||
let now = Local::now();
|
||||
let day = local.date_naive();
|
||||
let time = local.format("%H:%M").to_string();
|
||||
if day == now.date_naive() {
|
||||
format!("Today at {time}")
|
||||
} else if day == now.date_naive() - chrono::Days::new(1) {
|
||||
format!("Yesterday at {time}")
|
||||
} else {
|
||||
format!("{} at {time}", local.format("%b %e"))
|
||||
}
|
||||
}
|
||||
|
||||
fn plural(n: i64) -> &'static str {
|
||||
if n == 1 { "" } else { "s" }
|
||||
}
|
||||
|
||||
pub fn kda_ratio(kills: u32, deaths: u32, assists: u32) -> String {
|
||||
let value = if deaths == 0 {
|
||||
(kills + assists) as f64
|
||||
} else {
|
||||
(kills + assists) as f64 / deaths as f64
|
||||
};
|
||||
format!("{value:.1}")
|
||||
}
|
||||
|
||||
pub fn cs_per_min(stats: &crate::history::Stats) -> String {
|
||||
if stats.game_duration == 0 {
|
||||
return "0.0".into();
|
||||
}
|
||||
format!(
|
||||
"{:.1}",
|
||||
stats.creep_score as f64 / (stats.game_duration as f64 / 60.0)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gold_per_min(stats: &crate::history::Stats) -> String {
|
||||
if stats.game_duration == 0 {
|
||||
return "0".into();
|
||||
}
|
||||
let value = stats.gold_earned as f64 / (stats.game_duration as f64 / 60.0);
|
||||
number(value.round() as u64)
|
||||
}
|
||||
|
||||
pub fn number(n: u64) -> String {
|
||||
if n >= 1_000_000 {
|
||||
format!("{:.1}M", n as f64 / 1_000_000.0)
|
||||
} else if n >= 1_000 {
|
||||
format!("{:.1}K", n as f64 / 1_000.0)
|
||||
} else {
|
||||
n.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rank(tier: &str, division: &str) -> String {
|
||||
if tier.is_empty() || tier == "UNRANKED" {
|
||||
return "Unranked".into();
|
||||
}
|
||||
let mut chars = tier.chars();
|
||||
let tidy = match chars.next() {
|
||||
Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
|
||||
None => String::new(),
|
||||
};
|
||||
if division.is_empty() {
|
||||
tidy
|
||||
} else {
|
||||
format!("{tidy} {division}")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lp_delta(delta: i64) -> String {
|
||||
if delta > 0 {
|
||||
format!("+{delta}")
|
||||
} else {
|
||||
delta.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::Stats;
|
||||
|
||||
#[test]
|
||||
fn durations_read_as_minutes_and_seconds() {
|
||||
assert_eq!(duration(1830.0), "30:30");
|
||||
assert_eq!(duration(65.4), "1:05");
|
||||
assert_eq!(duration(-3.0), "0:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kda_ratio_survives_zero_deaths() {
|
||||
assert_eq!(kda_ratio(9, 3, 7), "5.3");
|
||||
assert_eq!(kda_ratio(9, 0, 7), "16.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranks_are_tidied_for_people() {
|
||||
assert_eq!(rank("EMERALD", "II"), "Emerald II");
|
||||
assert_eq!(rank("UNRANKED", ""), "Unranked");
|
||||
assert_eq!(rank("GOLD", ""), "Gold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_minute_stats_use_the_game_length() {
|
||||
let stats = Stats {
|
||||
creep_score: 200,
|
||||
gold_earned: 12_000,
|
||||
game_duration: 1200,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(cs_per_min(&stats), "10.0");
|
||||
assert_eq!(gold_per_min(&stats), "600");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
//! Highlight clips from timeline events, ported from `computeHighlights` in
|
||||
//! `tauri-app/src/types/timeline.ts`.
|
||||
|
||||
use crate::history::{Timeline, TimelineEvent};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Kill,
|
||||
Death,
|
||||
Assist,
|
||||
MultiKill,
|
||||
TradeKill,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Kill => "Kill",
|
||||
Kind::Death => "Death",
|
||||
Kind::Assist => "Assist",
|
||||
Kind::MultiKill => "Multi kill",
|
||||
Kind::TradeKill => "Trade kill",
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(self) -> u8 {
|
||||
match self {
|
||||
Kind::MultiKill => 0,
|
||||
Kind::TradeKill => 1,
|
||||
Kind::Kill => 2,
|
||||
Kind::Death => 3,
|
||||
Kind::Assist => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Highlight {
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
pub kind: Kind,
|
||||
pub title: String,
|
||||
pub subtitle: String,
|
||||
/// Timestamps of the events inside the clip, for markers.
|
||||
pub events: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Options {
|
||||
pub before: f64,
|
||||
pub after: f64,
|
||||
pub min_duration: f64,
|
||||
pub merge_overlapping: bool,
|
||||
pub merge_gap: f64,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
before: 10.0,
|
||||
after: 3.0,
|
||||
min_duration: 5.0,
|
||||
merge_overlapping: true,
|
||||
merge_gap: 5.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn string_at<'a>(event: &'a TimelineEvent, key: &str) -> Option<&'a str> {
|
||||
event.raw_data.get(key).and_then(|v| v.as_str())
|
||||
}
|
||||
|
||||
fn involves(event: &TimelineEvent, player: &str) -> Option<Kind> {
|
||||
if string_at(event, "KillerName") == Some(player) {
|
||||
return Some(Kind::Kill);
|
||||
}
|
||||
if string_at(event, "VictimName") == Some(player) {
|
||||
return Some(Kind::Death);
|
||||
}
|
||||
let assist = event
|
||||
.raw_data
|
||||
.get("Assisters")
|
||||
.and_then(|v| v.as_array())
|
||||
.is_some_and(|a| a.iter().any(|n| n.as_str() == Some(player)));
|
||||
if assist {
|
||||
return Some(Kind::Assist);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// One clip per involvement, then multi-kills, then a merge pass.
|
||||
pub fn compute(timeline: &Timeline, player: Option<&str>, options: Options) -> Vec<Highlight> {
|
||||
let Some(player) = player else {
|
||||
return Vec::new();
|
||||
};
|
||||
let duration = timeline.duration_secs.max(0) as f64;
|
||||
let kills = timeline.events.iter().filter(|e| e.event_type == "kill");
|
||||
|
||||
let mut clips: Vec<Highlight> = Vec::new();
|
||||
let mut player_kills: Vec<f64> = Vec::new();
|
||||
let mut player_deaths: Vec<f64> = Vec::new();
|
||||
|
||||
for event in kills {
|
||||
let Some(kind) = involves(event, player) else {
|
||||
continue;
|
||||
};
|
||||
let at = event.time();
|
||||
let (title, subtitle) = match kind {
|
||||
Kind::Kill => (
|
||||
"Kill".to_string(),
|
||||
format!(
|
||||
"Killed {}",
|
||||
string_at(event, "VictimName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
Kind::Death => (
|
||||
"Death".to_string(),
|
||||
format!(
|
||||
"Killed by {}",
|
||||
string_at(event, "KillerName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
_ => (
|
||||
"Assist".to_string(),
|
||||
format!(
|
||||
"Assisted {} against {}",
|
||||
string_at(event, "KillerName").unwrap_or("an ally"),
|
||||
string_at(event, "VictimName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
};
|
||||
match kind {
|
||||
Kind::Kill => player_kills.push(at),
|
||||
Kind::Death => player_deaths.push(at),
|
||||
_ => {}
|
||||
}
|
||||
clips.push(Highlight {
|
||||
start: (at - options.before).max(0.0),
|
||||
end: (at + options.after).min(if duration > 0.0 { duration } else { f64::MAX }),
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
events: vec![at],
|
||||
});
|
||||
}
|
||||
|
||||
// Multi-kills: two or more of the player's kills within 12 s.
|
||||
player_kills.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
let mut i = 0;
|
||||
while i < player_kills.len() {
|
||||
let mut j = i;
|
||||
while j + 1 < player_kills.len() && player_kills[j + 1] - player_kills[j] <= 12.0 {
|
||||
j += 1;
|
||||
}
|
||||
let count = j - i + 1;
|
||||
if count >= 2 {
|
||||
let first = player_kills[i];
|
||||
let last = player_kills[j];
|
||||
let died = player_deaths
|
||||
.iter()
|
||||
.any(|d| *d >= first && *d <= last + 12.0);
|
||||
let (kind, title) = if died {
|
||||
(Kind::TradeKill, "Trade kill".to_string())
|
||||
} else {
|
||||
(Kind::MultiKill, multi_kill_label(count))
|
||||
};
|
||||
let subtitle = if died {
|
||||
format!("{count} kills but died in the trade")
|
||||
} else {
|
||||
format!("{count} kills in quick succession")
|
||||
};
|
||||
let mut events: Vec<f64> = player_kills[i..=j].to_vec();
|
||||
if died {
|
||||
events.extend(
|
||||
player_deaths
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|d| *d >= first && *d <= last + 12.0),
|
||||
);
|
||||
}
|
||||
let end = events.iter().cloned().fold(last, f64::max) + options.after;
|
||||
clips.push(Highlight {
|
||||
start: (first - options.before).max(0.0),
|
||||
end: end.min(if duration > 0.0 { duration } else { f64::MAX }),
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
events,
|
||||
});
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
|
||||
clips.sort_by(|a, b| a.start.partial_cmp(&b.start).unwrap());
|
||||
|
||||
let mut merged: Vec<Highlight> = Vec::new();
|
||||
let mut iter = clips.into_iter();
|
||||
let Some(mut current) = iter.next() else {
|
||||
return Vec::new();
|
||||
};
|
||||
for next in iter {
|
||||
let joins = options.merge_overlapping && next.start <= current.end + options.merge_gap;
|
||||
if joins {
|
||||
current.end = current.end.max(next.end);
|
||||
current.events.extend(next.events.iter().copied());
|
||||
if next.kind.priority() < current.kind.priority() {
|
||||
current.kind = next.kind;
|
||||
current.title = next.title;
|
||||
current.subtitle = next.subtitle;
|
||||
}
|
||||
} else {
|
||||
merged.push(current);
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
merged.push(current);
|
||||
|
||||
merged.retain(|c| c.end - c.start >= options.min_duration);
|
||||
merged
|
||||
}
|
||||
|
||||
fn multi_kill_label(count: usize) -> String {
|
||||
match count {
|
||||
2 => "Double kill".into(),
|
||||
3 => "Triple kill".into(),
|
||||
4 => "Quadra kill".into(),
|
||||
5 => "Penta kill".into(),
|
||||
n => format!("{n}x kill"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_sample_game_has_a_clip_for_each_involvement() {
|
||||
let game = &crate::history::sample()[0];
|
||||
let clips = compute(game, Some("Demo#EUW"), Options::default());
|
||||
assert_eq!(clips.len(), 3, "{clips:#?}");
|
||||
assert!(clips.iter().any(|c| c.kind == Kind::Death));
|
||||
assert!(clips.iter().all(|c| c.end > c.start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobody_named_means_no_clips() {
|
||||
let game = &crate::history::sample()[0];
|
||||
assert!(compute(game, None, Options::default()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Reading the daemon's timelines from disk and the values the screens show.
|
||||
//!
|
||||
//! Ported from `tauri-app/src-tauri/src/lib.rs` (`get_game_history`, `get_timeline`,
|
||||
//! `find_video_file`) and the extractors in `tauri-app/src/types/timeline.ts`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[allow(dead_code)] // every field mirrors the daemon's timeline JSON
|
||||
pub struct Timeline {
|
||||
pub recording_id: String,
|
||||
pub start_time: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub end_time: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub duration_secs: i64,
|
||||
#[serde(default)]
|
||||
pub events: Vec<TimelineEvent>,
|
||||
#[serde(default)]
|
||||
pub game_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub raw_session: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_summoner: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_champion_select: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_rune_page: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_live_client_data: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_end_game_stats: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub video_file: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct TimelineEvent {
|
||||
/// `(seconds, nanos)` since the recording started.
|
||||
#[serde(default)]
|
||||
pub video_timestamp: (i64, i32),
|
||||
#[serde(default)]
|
||||
pub game_timestamp: Option<(i64, i32)>,
|
||||
#[serde(default)]
|
||||
pub timestamp: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub event_type: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub raw_data: Value,
|
||||
#[serde(default)]
|
||||
pub uri: String,
|
||||
}
|
||||
|
||||
impl TimelineEvent {
|
||||
pub fn time(&self) -> f64 {
|
||||
self.video_timestamp.0 as f64 + self.video_timestamp.1 as f64 / 1e9
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Victory,
|
||||
Defeat,
|
||||
Terminated,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Outcome::Victory => "Victory",
|
||||
Outcome::Defeat => "Defeat",
|
||||
Outcome::Terminated => "Terminated",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Stats {
|
||||
pub kills: u32,
|
||||
pub deaths: u32,
|
||||
pub assists: u32,
|
||||
pub creep_score: u32,
|
||||
pub gold_earned: u64,
|
||||
pub damage_dealt: u64,
|
||||
pub vision_score: u32,
|
||||
pub game_duration: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LpChange {
|
||||
pub delta: i64,
|
||||
pub league_points: u32,
|
||||
pub tier: String,
|
||||
pub division: String,
|
||||
pub in_promos: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum QueueCategory {
|
||||
RankedSolo,
|
||||
RankedFlex,
|
||||
Normals,
|
||||
Aram,
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl QueueCategory {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
QueueCategory::RankedSolo => "Ranked Solo",
|
||||
QueueCategory::RankedFlex => "Ranked Flex",
|
||||
QueueCategory::Normals => "Normals",
|
||||
QueueCategory::Aram => "ARAM",
|
||||
QueueCategory::Custom => "Custom",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The timeline folder the daemon writes.
|
||||
pub fn timeline_dir() -> PathBuf {
|
||||
daemon::recordings_dir().join("timelines")
|
||||
}
|
||||
|
||||
/// Every timeline on disk, newest first. Files that fail to parse are skipped.
|
||||
pub fn load_all() -> Vec<Timeline> {
|
||||
let dir = timeline_dir();
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return out;
|
||||
};
|
||||
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;
|
||||
};
|
||||
match serde_json::from_str::<Timeline>(&text) {
|
||||
Ok(timeline) => out.push(timeline),
|
||||
Err(e) => eprintln!("skipping {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.start_time.cmp(&a.start_time));
|
||||
out
|
||||
}
|
||||
|
||||
/// One timeline by recording id.
|
||||
#[allow(dead_code)]
|
||||
pub fn load(recording_id: &str) -> Option<Timeline> {
|
||||
let path = timeline_dir().join(format!("{recording_id}.json"));
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&text).ok()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extractors, from types/timeline.ts
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
impl Timeline {
|
||||
fn end_stats(&self) -> Option<&Value> {
|
||||
self.raw_end_game_stats.as_ref()
|
||||
}
|
||||
|
||||
pub fn outcome(&self) -> Outcome {
|
||||
let stats = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.get("localPlayer"))
|
||||
.and_then(|p| p.get("stats"));
|
||||
if stats.and_then(|s| s.get("WIN")).and_then(|v| v.as_u64()) == Some(1) {
|
||||
Outcome::Victory
|
||||
} else if stats.and_then(|s| s.get("LOSE")).and_then(|v| v.as_u64()) == Some(1) {
|
||||
Outcome::Defeat
|
||||
} else {
|
||||
Outcome::Terminated
|
||||
}
|
||||
}
|
||||
|
||||
pub fn champion(&self) -> Option<String> {
|
||||
if let Some(name) = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.pointer("/localPlayer/championName"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return Some(name.to_string());
|
||||
}
|
||||
self.raw_live_client_data
|
||||
.as_ref()
|
||||
.and_then(|s| s.pointer("/activePlayer/championName"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub fn summoner(&self) -> Option<String> {
|
||||
if let Some(game_name) = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.pointer("/localPlayer/riotIdGameName"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
let tag = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.pointer("/localPlayer/riotIdTagLine"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
return Some(if tag.is_empty() {
|
||||
game_name.to_string()
|
||||
} else {
|
||||
format!("{game_name}#{tag}")
|
||||
});
|
||||
}
|
||||
let summoner = self.raw_summoner.as_ref()?;
|
||||
if let Some(name) = summoner.get("gameName").and_then(|v| v.as_str()) {
|
||||
let tag = summoner
|
||||
.get("tagLine")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
return Some(if tag.is_empty() {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{name}#{tag}")
|
||||
});
|
||||
}
|
||||
summoner
|
||||
.get("displayName")
|
||||
.or_else(|| summoner.get("name"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub fn queue_name(&self) -> Option<String> {
|
||||
self.raw_session
|
||||
.as_ref()
|
||||
.and_then(|s| s.pointer("/gameData/queue/name"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub fn queue_id(&self) -> Option<u64> {
|
||||
self.raw_session
|
||||
.as_ref()
|
||||
.and_then(|s| s.pointer("/gameData/queue/id"))
|
||||
.and_then(|v| v.as_u64())
|
||||
}
|
||||
|
||||
/// A display name for the queue, falling back to the queue id table.
|
||||
pub fn queue_label(&self) -> String {
|
||||
if let Some(name) = self.queue_name() {
|
||||
if name.contains("Practice") {
|
||||
return "Practice Tool".into();
|
||||
}
|
||||
if name.contains("Ranked Solo") {
|
||||
return "Ranked Solo".into();
|
||||
}
|
||||
if name.contains("Ranked Flex") {
|
||||
return "Ranked Flex".into();
|
||||
}
|
||||
if name.contains("ARAM") {
|
||||
return "ARAM".into();
|
||||
}
|
||||
if name.contains("Normal") {
|
||||
return "Normal".into();
|
||||
}
|
||||
if name.contains("Co-op") {
|
||||
return "Co-op vs AI".into();
|
||||
}
|
||||
return name;
|
||||
}
|
||||
match self.queue_id() {
|
||||
Some(420) => "Ranked Solo".into(),
|
||||
Some(440) => "Ranked Flex".into(),
|
||||
Some(450) => "ARAM".into(),
|
||||
Some(400) => "Normal Draft".into(),
|
||||
Some(430) => "Normal Blind".into(),
|
||||
Some(800..=850) => "Co-op vs AI".into(),
|
||||
Some(3140) => "Practice Tool".into(),
|
||||
Some(_) => "Custom Game".into(),
|
||||
None => "Custom Game".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn category(&self) -> QueueCategory {
|
||||
if let Some(name) = self.queue_name() {
|
||||
if name.contains("Ranked Solo") {
|
||||
return QueueCategory::RankedSolo;
|
||||
}
|
||||
if name.contains("Ranked Flex") {
|
||||
return QueueCategory::RankedFlex;
|
||||
}
|
||||
if name.contains("ARAM") {
|
||||
return QueueCategory::Aram;
|
||||
}
|
||||
if name.contains("Normal") || name.contains("Draft") || name.contains("Blind") {
|
||||
return QueueCategory::Normals;
|
||||
}
|
||||
if name.contains("Custom") || name.contains("Practice") {
|
||||
return QueueCategory::Custom;
|
||||
}
|
||||
}
|
||||
match self.queue_id() {
|
||||
Some(420) => QueueCategory::RankedSolo,
|
||||
Some(440) => QueueCategory::RankedFlex,
|
||||
Some(400 | 430) => QueueCategory::Normals,
|
||||
Some(450) => QueueCategory::Aram,
|
||||
_ => QueueCategory::Custom,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> Option<Stats> {
|
||||
let player = self.end_stats()?.get("localPlayer")?;
|
||||
let s = player.get("stats")?;
|
||||
let n = |k: &str| s.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
Some(Stats {
|
||||
kills: n("CHAMPIONS_KILLED") as u32,
|
||||
deaths: n("NUM_DEATHS") as u32,
|
||||
assists: n("ASSISTS") as u32,
|
||||
creep_score: n("MINIONS_KILLED") as u32,
|
||||
gold_earned: n("GOLD_EARNED"),
|
||||
damage_dealt: n("TOTAL_DAMAGE_DEALT_TO_CHAMPIONS"),
|
||||
vision_score: n("VISION_SCORE") as u32,
|
||||
game_duration: self
|
||||
.end_stats()
|
||||
.and_then(|s| s.get("gameLength"))
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(self.duration_secs.max(0) as u64),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn lp_change(&self) -> Option<LpChange> {
|
||||
let lp_events: Vec<&TimelineEvent> = self
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| e.event_type == "lp_change")
|
||||
.collect();
|
||||
let ranked = lp_events.iter().find(|e| {
|
||||
e.raw_data
|
||||
.get("tier")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_some_and(|t| t != "UNRANKED")
|
||||
});
|
||||
let event = ranked
|
||||
.or_else(|| {
|
||||
lp_events.iter().find(|e| {
|
||||
e.raw_data.get("leaguePointsDelta").and_then(|v| v.as_i64()) != Some(0)
|
||||
})
|
||||
})
|
||||
.or_else(|| lp_events.first())?;
|
||||
let raw = &event.raw_data;
|
||||
let delta = raw.get("leaguePointsDelta").and_then(|v| v.as_i64())?;
|
||||
Some(LpChange {
|
||||
delta,
|
||||
league_points: raw
|
||||
.get("leaguePoints")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32,
|
||||
tier: raw
|
||||
.get("tier")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("UNRANKED")
|
||||
.to_string(),
|
||||
division: raw
|
||||
.get("division")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
in_promos: raw
|
||||
.get("miniseriesProgress")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_some_and(|s| !s.is_empty()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The recording's video file, by name or by the timestamp prefix.
|
||||
pub fn video_path(&self) -> Option<PathBuf> {
|
||||
let dir = daemon::recordings_dir();
|
||||
find_video_file(&dir, self.video_file.as_deref()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact name first, then a file sharing the timestamp prefix.
|
||||
pub fn find_video_file(dir: &Path, filename: &str) -> Option<PathBuf> {
|
||||
let exact = dir.join(filename);
|
||||
if exact.exists() {
|
||||
return Some(exact);
|
||||
}
|
||||
let prefix = filename.replace("_unknown.mp4", "");
|
||||
let entries = std::fs::read_dir(dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let video = matches!(
|
||||
path.extension().and_then(|e| e.to_str()),
|
||||
Some("mp4" | "mkv" | "mov")
|
||||
);
|
||||
if !video {
|
||||
continue;
|
||||
}
|
||||
let name = path.file_name()?.to_string_lossy().to_string();
|
||||
if name.starts_with(&prefix) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Two made-up recordings for `--scene` snapshots and for checking layout without a daemon.
|
||||
pub fn sample() -> Vec<Timeline> {
|
||||
let now = Utc::now();
|
||||
let game = |id: &str,
|
||||
hours_ago: i64,
|
||||
champion: &str,
|
||||
win: bool,
|
||||
kills: u64,
|
||||
deaths: u64,
|
||||
assists: u64,
|
||||
cs: u64| {
|
||||
let start = now - chrono::Duration::hours(hours_ago);
|
||||
let event = |at: f64, kind: &str, description: &str, raw: Value| TimelineEvent {
|
||||
video_timestamp: (at as i64, ((at.fract()) * 1e9) as i32),
|
||||
game_timestamp: None,
|
||||
timestamp: None,
|
||||
event_type: kind.to_string(),
|
||||
description: description.to_string(),
|
||||
raw_data: raw,
|
||||
uri: String::new(),
|
||||
};
|
||||
let events = vec![
|
||||
event(12.0, "game_start", "Game start", Value::Null),
|
||||
event(
|
||||
212.0,
|
||||
"kill",
|
||||
"Killed Ahri",
|
||||
serde_json::json!({"KillerName": "Demo#EUW", "VictimName": "Ahri", "Assisters": ["Thresh"]}),
|
||||
),
|
||||
event(
|
||||
368.0,
|
||||
"kill",
|
||||
"Killed Lee Sin",
|
||||
serde_json::json!({"KillerName": "Demo#EUW", "VictimName": "Lee Sin", "Assisters": []}),
|
||||
),
|
||||
event(
|
||||
402.0,
|
||||
"kill",
|
||||
"Killed by Zed",
|
||||
serde_json::json!({"KillerName": "Zed", "VictimName": "Demo#EUW", "Assisters": []}),
|
||||
),
|
||||
event(744.0, "objective", "Dragon", Value::Null),
|
||||
event(1500.0, "game_end", "Game end", Value::Null),
|
||||
event(
|
||||
1510.0,
|
||||
"lp_change",
|
||||
"+21 LP",
|
||||
serde_json::json!({"leaguePointsDelta": 21, "leaguePoints": 74, "tier": "EMERALD", "division": "II", "queueType": "RANKED_SOLO_5x5"}),
|
||||
),
|
||||
];
|
||||
Timeline {
|
||||
recording_id: id.to_string(),
|
||||
start_time: start,
|
||||
end_time: Some(start + chrono::Duration::seconds(1830)),
|
||||
duration_secs: 1830,
|
||||
events,
|
||||
game_id: Some(7_000_000),
|
||||
raw_session: Some(
|
||||
serde_json::json!({"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}}),
|
||||
),
|
||||
raw_summoner: Some(serde_json::json!({"gameName": "Demo", "tagLine": "EUW"})),
|
||||
raw_champion_select: None,
|
||||
raw_rune_page: None,
|
||||
raw_live_client_data: None,
|
||||
raw_end_game_stats: Some(serde_json::json!({
|
||||
"gameLength": 1830,
|
||||
"localPlayer": {
|
||||
"championName": champion,
|
||||
"riotIdGameName": "Demo",
|
||||
"riotIdTagLine": "EUW",
|
||||
"stats": {
|
||||
"CHAMPIONS_KILLED": kills,
|
||||
"NUM_DEATHS": deaths,
|
||||
"ASSISTS": assists,
|
||||
"MINIONS_KILLED": cs,
|
||||
"GOLD_EARNED": 13_450,
|
||||
"TOTAL_DAMAGE_DEALT_TO_CHAMPIONS": 24_800,
|
||||
"VISION_SCORE": 32,
|
||||
"WIN": if win { 1 } else { 0 },
|
||||
"LOSE": if win { 0 } else { 1 }
|
||||
}
|
||||
}
|
||||
})),
|
||||
video_file: None,
|
||||
}
|
||||
};
|
||||
vec![
|
||||
game("demo-1", 3, "Kai'Sa", true, 9, 3, 7, 214),
|
||||
game("demo-2", 27, "Jinx", false, 4, 8, 5, 188),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TIMELINE: &str = r#"{
|
||||
"recording_id": "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c",
|
||||
"start_time": "2026-03-27T16:42:52Z",
|
||||
"end_time": "2026-03-27T17:13:22Z",
|
||||
"duration_secs": 1830,
|
||||
"events": [
|
||||
{"video_timestamp": [212, 0], "game_timestamp": null, "timestamp": "2026-03-27T16:46:24Z",
|
||||
"event_type": "kill", "description": "Killed Ahri", "uri": "",
|
||||
"raw_data": {"KillerName": "Me#EUW", "VictimName": "Ahri", "Assisters": []}},
|
||||
{"video_timestamp": [1500, 500000000], "event_type": "lp_change", "description": "",
|
||||
"raw_data": {"leaguePointsDelta": 21, "leaguePoints": 74, "tier": "EMERALD", "division": "II"}}
|
||||
],
|
||||
"raw_session": {"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}},
|
||||
"raw_end_game_stats": {"gameLength": 1830, "localPlayer": {"championName": "Kai'Sa",
|
||||
"riotIdGameName": "Demo", "riotIdTagLine": "EUW",
|
||||
"stats": {"CHAMPIONS_KILLED": 9, "NUM_DEATHS": 3, "ASSISTS": 7, "MINIONS_KILLED": 214,
|
||||
"GOLD_EARNED": 13450, "VISION_SCORE": 32, "WIN": 1, "LOSE": 0}}},
|
||||
"video_file": "2026-03-27_16-42-52_unknown.mp4"
|
||||
}"#;
|
||||
|
||||
fn parsed() -> Timeline {
|
||||
serde_json::from_str(TIMELINE).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeline_parses_with_duration_tuples() {
|
||||
let timeline = parsed();
|
||||
assert_eq!(timeline.duration_secs, 1830);
|
||||
assert!((timeline.events[0].time() - 212.0).abs() < 1e-9);
|
||||
assert!((timeline.events[1].time() - 1500.5).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_game_values_come_out_of_the_raw_responses() {
|
||||
let timeline = parsed();
|
||||
assert_eq!(timeline.champion().as_deref(), Some("Kai'Sa"));
|
||||
assert_eq!(timeline.summoner().as_deref(), Some("Demo#EUW"));
|
||||
assert_eq!(timeline.outcome(), Outcome::Victory);
|
||||
assert_eq!(timeline.queue_label(), "Ranked Solo");
|
||||
assert_eq!(timeline.category(), QueueCategory::RankedSolo);
|
||||
let stats = timeline.stats().unwrap();
|
||||
assert_eq!((stats.kills, stats.deaths, stats.assists), (9, 3, 7));
|
||||
assert_eq!(stats.creep_score, 214);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lp_event_is_the_ranked_one() {
|
||||
let lp = parsed().lp_change().unwrap();
|
||||
assert_eq!(lp.delta, 21);
|
||||
assert_eq!(lp.tier, "EMERALD");
|
||||
assert_eq!(lp.league_points, 74);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_video_is_found_by_its_timestamp_prefix() {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("2026-03-27_16-42-52_kai_sa.mp4"), b"x").unwrap();
|
||||
let found = find_video_file(&dir, "2026-03-27_16-42-52_unknown.mp4").unwrap();
|
||||
assert!(found.ends_with("2026-03-27_16-42-52_kai_sa.mp4"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
+493
@@ -0,0 +1,493 @@
|
||||
//! Client for the record-daemon's IPC protocol.
|
||||
//!
|
||||
//! Ported from `tauri-app/src-tauri/src/daemon_ipc.rs`. The wire format is the daemon's
|
||||
//! (`record-daemon/src/ipc/protocol.rs`): one JSON object per line over a named pipe, a
|
||||
//! `request` answered by one `response` with the same id.
|
||||
//!
|
||||
//! Requests are async (tokio). The UI runs on rune's thread and never blocks, so a worker thread
|
||||
//! owns a current-thread runtime, executes one request at a time and pushes results into a queue
|
||||
//! that `poll` drains.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Protocol
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Message type, as the daemon's `MessageType`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MessageType {
|
||||
Request,
|
||||
Response,
|
||||
Notification,
|
||||
}
|
||||
|
||||
/// Commands the daemon accepts (`IpcCommand`, camelCase).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Command {
|
||||
GetSettings,
|
||||
UpdateSettings,
|
||||
ResetSettings,
|
||||
GetStatus,
|
||||
GetEncoders,
|
||||
GetAudioDevices,
|
||||
AddAudioSource,
|
||||
RemoveAudioSource {
|
||||
id: String,
|
||||
},
|
||||
#[allow(dead_code)]
|
||||
UpdateAudioSource,
|
||||
StartRecording,
|
||||
StopRecording,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// Request envelope.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcMessage {
|
||||
#[serde(rename = "type")]
|
||||
pub message_type: MessageType,
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub command: Option<Command>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub payload: Option<Value>,
|
||||
}
|
||||
|
||||
/// Response envelope.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcResponse {
|
||||
pub request_id: String,
|
||||
pub success: bool,
|
||||
#[serde(default)]
|
||||
pub data: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// The pipe the daemon listens on.
|
||||
pub fn default_socket_path() -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
PathBuf::from(r"\.\pipe\record-daemon")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let dir = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| "/tmp".into());
|
||||
Path::new(&dir).join("record-daemon.sock")
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub struct Client {
|
||||
path: PathBuf,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
path: default_socket_path(),
|
||||
timeout: Duration::from_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one command and wait for its answer.
|
||||
pub async fn call(&self, command: Command, payload: Option<Value>) -> Result<Value, String> {
|
||||
let message = IpcMessage {
|
||||
message_type: MessageType::Request,
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
command: Some(command),
|
||||
payload,
|
||||
};
|
||||
let json = serde_json::to_string(&message).map_err(|e| format!("serialize: {e}"))?;
|
||||
let line = self.round_trip(&json).await?;
|
||||
let response: IpcResponse =
|
||||
serde_json::from_str(&line).map_err(|e| format!("parse response: {e}"))?;
|
||||
if response.success {
|
||||
Ok(response.data.unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(response
|
||||
.error
|
||||
.unwrap_or_else(|| "daemon returned an error".into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn is_running(&self) -> bool {
|
||||
self.call(Command::GetStatus, None).await.is_ok()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
async fn round_trip(&self, message: &str) -> Result<String, String> {
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::windows::named_pipe::ClientOptions;
|
||||
|
||||
let pipe = self.path.to_string_lossy().to_string();
|
||||
let client = tokio::time::timeout(self.timeout, async {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match ClientOptions::new().open(&pipe) {
|
||||
Ok(client) => return Ok(client),
|
||||
// ERROR_PIPE_BUSY: every instance is serving another client.
|
||||
Err(e) if e.raw_os_error() == Some(231) => {
|
||||
attempts += 1;
|
||||
if attempts > 5 {
|
||||
return Err(format!("daemon pipe busy: {e}"));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(format!("cannot connect to daemon: {e}")),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "connecting to the daemon timed out".to_string())??;
|
||||
|
||||
let (reader, mut writer) = tokio::io::split(client);
|
||||
writer
|
||||
.write_all(message.as_bytes())
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer.flush().await.map_err(|e| format!("flush: {e}"))?;
|
||||
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let line = tokio::time::timeout(self.timeout, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| "the daemon did not answer in time".to_string())?
|
||||
.map_err(|e| format!("read: {e}"))?;
|
||||
line.ok_or_else(|| "the daemon closed the pipe without answering".to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
async fn round_trip(&self, message: &str) -> Result<String, String> {
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
let stream = tokio::time::timeout(self.timeout, UnixStream::connect(&self.path))
|
||||
.await
|
||||
.map_err(|_| "connecting to the daemon timed out".to_string())?
|
||||
.map_err(|e| format!("cannot connect to daemon: {e}"))?;
|
||||
let (reader, mut writer) = stream.into_split();
|
||||
writer
|
||||
.write_all(message.as_bytes())
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer.flush().await.map_err(|e| format!("flush: {e}"))?;
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let line = tokio::time::timeout(self.timeout, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| "the daemon did not answer in time".to_string())?
|
||||
.map_err(|e| format!("read: {e}"))?;
|
||||
line.ok_or_else(|| "the daemon closed the socket without answering".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Background worker
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What a queued request is for, so `poll` can route its answer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Request {
|
||||
EnsureRunning,
|
||||
Settings,
|
||||
SaveSettings,
|
||||
ResetSettings,
|
||||
Status,
|
||||
Encoders,
|
||||
AudioDevices,
|
||||
AddAudioSource,
|
||||
RemoveAudioSource,
|
||||
UpdateAudioSource,
|
||||
StartRecording,
|
||||
StopRecording,
|
||||
Shutdown,
|
||||
Logs,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
request: Request,
|
||||
command: Command,
|
||||
payload: Option<Value>,
|
||||
}
|
||||
|
||||
/// An answer from the worker thread.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Event {
|
||||
pub request: Request,
|
||||
pub result: Result<Value, String>,
|
||||
}
|
||||
|
||||
/// A cloneable handle to the worker thread.
|
||||
#[derive(Clone)]
|
||||
pub struct Daemon {
|
||||
jobs: Sender<Job>,
|
||||
events: Arc<Mutex<Receiver<Event>>>,
|
||||
waker: Arc<Mutex<Option<rune::Waker>>>,
|
||||
/// Headless runs keep no worker and send nothing.
|
||||
off: bool,
|
||||
}
|
||||
|
||||
impl Daemon {
|
||||
/// Start the worker. It also brings the daemon process up on first use.
|
||||
/// A headless run (`--snap` and friends) starts nothing and talks to nobody.
|
||||
pub fn start(headless: bool) -> Self {
|
||||
let (job_tx, job_rx) = channel::<Job>();
|
||||
let (event_tx, event_rx) = channel::<Event>();
|
||||
let waker: Arc<Mutex<Option<rune::Waker>>> = Arc::new(Mutex::new(None));
|
||||
let worker_waker = waker.clone();
|
||||
if headless {
|
||||
return Self {
|
||||
jobs: job_tx,
|
||||
events: Arc::new(Mutex::new(event_rx)),
|
||||
waker,
|
||||
off: true,
|
||||
};
|
||||
}
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("daemon-ipc".into())
|
||||
.spawn(move || {
|
||||
let runtime = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
let _ = event_tx.send(Event {
|
||||
request: Request::EnsureRunning,
|
||||
result: Err(format!("no async runtime: {e}")),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
let client = Client::new();
|
||||
// Bring the daemon up before the first request. It takes a few seconds to
|
||||
// initialise OBS, so this must not run on the UI thread.
|
||||
let started = runtime
|
||||
.block_on(crate::daemon::ensure_running())
|
||||
.map(|_| Value::Null);
|
||||
let _ = event_tx.send(Event {
|
||||
request: Request::EnsureRunning,
|
||||
result: started,
|
||||
});
|
||||
wake(&worker_waker);
|
||||
|
||||
while let Ok(job) = job_rx.recv() {
|
||||
let result = match job.request {
|
||||
Request::EnsureRunning => runtime
|
||||
.block_on(crate::daemon::ensure_running())
|
||||
.map(|_| Value::Null),
|
||||
Request::Logs => crate::daemon::read_logs(200).map(Value::String),
|
||||
_ => runtime.block_on(client.call(job.command, job.payload)),
|
||||
};
|
||||
let _ = event_tx.send(Event {
|
||||
request: job.request,
|
||||
result,
|
||||
});
|
||||
wake(&worker_waker);
|
||||
}
|
||||
})
|
||||
.expect("spawn daemon worker");
|
||||
|
||||
Self {
|
||||
jobs: job_tx,
|
||||
events: Arc::new(Mutex::new(event_rx)),
|
||||
waker,
|
||||
off: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The waker rune hands to `AppSpec::setup`.
|
||||
pub fn set_waker(&self, waker: rune::Waker) {
|
||||
*self.waker.lock().unwrap() = Some(waker);
|
||||
}
|
||||
|
||||
fn send(&self, request: Request, command: Command, payload: Option<Value>) {
|
||||
if self.off {
|
||||
return;
|
||||
}
|
||||
let _ = self.jobs.send(Job {
|
||||
request,
|
||||
command,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn get_settings(&self) {
|
||||
self.send(Request::Settings, Command::GetSettings, None);
|
||||
}
|
||||
|
||||
pub fn save_settings(&self, settings: Value) {
|
||||
self.send(
|
||||
Request::SaveSettings,
|
||||
Command::UpdateSettings,
|
||||
Some(settings),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn reset_settings(&self) {
|
||||
self.send(Request::ResetSettings, Command::ResetSettings, None);
|
||||
}
|
||||
|
||||
pub fn get_status(&self) {
|
||||
self.send(Request::Status, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
pub fn get_encoders(&self) {
|
||||
self.send(Request::Encoders, Command::GetEncoders, None);
|
||||
}
|
||||
|
||||
pub fn get_audio_devices(&self) {
|
||||
self.send(Request::AudioDevices, Command::GetAudioDevices, None);
|
||||
}
|
||||
|
||||
pub fn add_audio_source(&self, source: Value) {
|
||||
self.send(
|
||||
Request::AddAudioSource,
|
||||
Command::AddAudioSource,
|
||||
Some(source),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn remove_audio_source(&self, id: &str) {
|
||||
self.send(
|
||||
Request::RemoveAudioSource,
|
||||
Command::RemoveAudioSource { id: id.to_string() },
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn update_audio_source(&self, source: Value) {
|
||||
self.send(
|
||||
Request::UpdateAudioSource,
|
||||
Command::UpdateAudioSource,
|
||||
Some(source),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn start_recording(&self) {
|
||||
self.send(Request::StartRecording, Command::StartRecording, None);
|
||||
}
|
||||
|
||||
pub fn stop_recording(&self) {
|
||||
self.send(Request::StopRecording, Command::StopRecording, None);
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) {
|
||||
self.send(Request::Shutdown, Command::Shutdown, None);
|
||||
}
|
||||
|
||||
pub fn ensure_running(&self) {
|
||||
self.send(Request::EnsureRunning, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
pub fn logs(&self) {
|
||||
self.send(Request::Logs, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
/// Answers that arrived since the last frame, without blocking.
|
||||
pub fn drain(&self) -> Vec<Event> {
|
||||
let rx = self.events.lock().unwrap();
|
||||
let mut out = Vec::new();
|
||||
while let Ok(event) = rx.try_recv() {
|
||||
out.push(event);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn wake(waker: &Mutex<Option<rune::Waker>>) {
|
||||
if let Some(w) = waker.lock().unwrap().as_ref() {
|
||||
w();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn request(command: Command, payload: Option<Value>) -> Value {
|
||||
let message = IpcMessage {
|
||||
message_type: MessageType::Request,
|
||||
id: "00000000-0000-4000-8000-000000000000".into(),
|
||||
command: Some(command),
|
||||
payload,
|
||||
};
|
||||
serde_json::to_value(message).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_command_is_a_plain_string() {
|
||||
assert_eq!(
|
||||
request(Command::GetSettings, None),
|
||||
json!({
|
||||
"type": "request",
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"command": "getSettings"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_with_a_field_is_an_object() {
|
||||
assert_eq!(
|
||||
request(Command::RemoveAudioSource { id: "abc".into() }, None),
|
||||
json!({
|
||||
"type": "request",
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"command": {"removeAudioSource": {"id": "abc"}}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_go_in_the_payload_untouched() {
|
||||
let payload = json!({"video": {"frame_rate": 60}});
|
||||
assert_eq!(
|
||||
request(Command::UpdateSettings, Some(payload.clone()))["payload"],
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_parse_with_and_without_data() {
|
||||
let ok: IpcResponse =
|
||||
serde_json::from_str(r#"{"request_id":"x","success":true,"data":{"a":1}}"#).unwrap();
|
||||
assert!(ok.success);
|
||||
assert_eq!(ok.data.unwrap()["a"], 1);
|
||||
|
||||
let err: IpcResponse =
|
||||
serde_json::from_str(r#"{"request_id":"x","success":false,"error":"nope"}"#).unwrap();
|
||||
assert!(!err.success);
|
||||
assert_eq!(err.error.as_deref(), Some("nope"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pipe_name_matches_the_daemon() {
|
||||
assert_eq!(
|
||||
default_socket_path().to_string_lossy(),
|
||||
r"\.\pipe\record-daemon"
|
||||
);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
//! League Recorder: a native desktop app for the record-daemon.
|
||||
//!
|
||||
//! Replaces `tauri-app`. The daemon keeps its IPC protocol; this app is a client of it.
|
||||
//! `cargo run` opens the window; `cargo run -- --snap out.png` renders it headless.
|
||||
|
||||
mod app;
|
||||
mod daemon;
|
||||
mod export;
|
||||
mod format;
|
||||
mod highlight;
|
||||
mod history;
|
||||
mod ipc;
|
||||
mod os;
|
||||
mod screens;
|
||||
mod settings;
|
||||
mod ui;
|
||||
|
||||
use rune::AppSpec;
|
||||
|
||||
fn main() {
|
||||
if std::env::args().any(|arg| arg == "--probe") {
|
||||
probe();
|
||||
return;
|
||||
}
|
||||
// A second launch hands its arguments to the first and exits.
|
||||
if !rune::single_instance(os::APP_ID) {
|
||||
return;
|
||||
}
|
||||
os::register_notifications();
|
||||
rune_notify::on_click(|_| rune_notify::bring_to_front());
|
||||
|
||||
let mut hidden = false;
|
||||
let args: Vec<String> = std::env::args()
|
||||
.filter(|arg| {
|
||||
if arg == "--hidden" {
|
||||
hidden = true;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
rune::App::new(AppSpec {
|
||||
scenes: &[
|
||||
("history", |_app: &mut app::App| {}),
|
||||
("settings", |app| app.screen = app::Screen::Settings),
|
||||
("recording", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Recording;
|
||||
}),
|
||||
("audio", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Audio;
|
||||
}),
|
||||
("daemon", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Daemon;
|
||||
}),
|
||||
("review", |app| app::demo_review(app)),
|
||||
],
|
||||
setup: Some(app::setup),
|
||||
poll: Some(app::poll),
|
||||
on_key: Some(app::on_key),
|
||||
..AppSpec::new("League Recorder", (1200.0, 800.0), app::App::new, app::view)
|
||||
})
|
||||
.args(args)
|
||||
.keep_running()
|
||||
.on_ready(move |handle| {
|
||||
app::remember_window(handle);
|
||||
if hidden {
|
||||
handle.hide();
|
||||
}
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
/// `--probe`: bring the daemon up and print what it answers, then exit. A quick check that the
|
||||
/// IPC client and the daemon agree without opening a window.
|
||||
fn probe() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("async runtime");
|
||||
runtime.block_on(async {
|
||||
match daemon::ensure_running().await {
|
||||
Ok(()) => println!("daemon: ready"),
|
||||
Err(e) => {
|
||||
println!("daemon: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
let client = ipc::Client::new();
|
||||
for (name, command) in [
|
||||
("status", ipc::Command::GetStatus),
|
||||
("settings", ipc::Command::GetSettings),
|
||||
("encoders", ipc::Command::GetEncoders),
|
||||
("audioDevices", ipc::Command::GetAudioDevices),
|
||||
] {
|
||||
match client.call(command, None).await {
|
||||
Ok(data) => println!("{name}: {data}"),
|
||||
Err(e) => println!("{name}: error: {e}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
//! Windows integration that the Tauri app got from plugins: launch at login, one instance,
|
||||
//! toast notifications and the tray icon.
|
||||
|
||||
/// The app's reverse-DNS id, used for single-instance and notifications.
|
||||
pub const APP_ID: &str = "v.leaguerecorder";
|
||||
pub const APP_NAME: &str = "League Recorder";
|
||||
|
||||
#[cfg(windows)]
|
||||
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
#[cfg(windows)]
|
||||
const RUN_VALUE: &str = "LeagueRecorder";
|
||||
|
||||
/// Launch at login writes the executable into the user's `Run` key.
|
||||
#[cfg(windows)]
|
||||
pub fn autostart_enabled() -> bool {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(RUN_KEY) else {
|
||||
return false;
|
||||
};
|
||||
key.get_value::<String, _>(RUN_VALUE).is_ok()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn autostart_enabled() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_autostart(on: bool) -> Result<(), String> {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let (key, _) = hkcu
|
||||
.create_subkey(RUN_KEY)
|
||||
.map_err(|e| format!("cannot open the Run key: {e}"))?;
|
||||
if on {
|
||||
let exe =
|
||||
std::env::current_exe().map_err(|e| format!("cannot find the executable: {e}"))?;
|
||||
let value = format!("\"{}\" --hidden", exe.display());
|
||||
key.set_value(RUN_VALUE, &value)
|
||||
.map_err(|e| format!("cannot write the Run key: {e}"))
|
||||
} else {
|
||||
match key.delete_value(RUN_VALUE) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(format!("cannot remove the Run value: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn set_autostart(_on: bool) -> Result<(), String> {
|
||||
Err("launch at login is implemented for Windows only".into())
|
||||
}
|
||||
|
||||
/// Register the app so Windows can show its toasts, and group its windows on the taskbar.
|
||||
pub fn register_notifications() {
|
||||
let identity = rune_notify::Identity::new(APP_ID, APP_NAME);
|
||||
if let Err(e) = rune_notify::register(&identity) {
|
||||
eprintln!("notifications unavailable: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Post a toast, unless a window already has the user's attention.
|
||||
pub fn notify(id: &str, title: &str, body: &str) {
|
||||
if rune_notify::app_focused() {
|
||||
return;
|
||||
}
|
||||
let notification = rune_notify::Notification::new(id, title).body(body);
|
||||
rune_notify::post(¬ification);
|
||||
}
|
||||
|
||||
/// A 32 px tray icon: an accent disc with a white play mark.
|
||||
pub fn tray_icon() -> rune::TrayIcon {
|
||||
const SIZE: u32 = 32;
|
||||
let mut pixels = vec![0u8; (SIZE * SIZE * 4) as usize];
|
||||
let accent = [0x5b, 0x7c, 0xfa];
|
||||
let half = SIZE as f32 / 2.0;
|
||||
let radius = half - 1.0;
|
||||
// Play triangle: apex right of centre, base left of centre.
|
||||
let (ax, ay) = (half + 4.5, half);
|
||||
let (bx, by) = (half - 4.0, half - 6.0);
|
||||
let (cx, cy) = (half - 4.0, half + 6.0);
|
||||
let edge = |px: f32, py: f32, x1: f32, y1: f32, x2: f32, y2: f32| {
|
||||
(x2 - x1) * (py - y1) - (y2 - y1) * (px - x1)
|
||||
};
|
||||
for y in 0..SIZE {
|
||||
for x in 0..SIZE {
|
||||
let px = x as f32 + 0.5;
|
||||
let py = y as f32 + 0.5;
|
||||
let dx = px - half;
|
||||
let dy = py - half;
|
||||
// Three pixels of antialiasing at the disc edge.
|
||||
let coverage = (radius - (dx * dx + dy * dy).sqrt()).clamp(0.0, 1.0);
|
||||
if coverage <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let e1 = edge(px, py, ax, ay, bx, by);
|
||||
let e2 = edge(px, py, bx, by, cx, cy);
|
||||
let e3 = edge(px, py, cx, cy, ax, ay);
|
||||
let inside =
|
||||
(e1 >= 0.0 && e2 >= 0.0 && e3 >= 0.0) || (e1 <= 0.0 && e2 <= 0.0 && e3 <= 0.0);
|
||||
let ink = if inside { [255, 255, 255] } else { accent };
|
||||
let i = ((y * SIZE + x) * 4) as usize;
|
||||
pixels[i] = ink[0];
|
||||
pixels[i + 1] = ink[1];
|
||||
pixels[i + 2] = ink[2];
|
||||
pixels[i + 3] = (coverage * 255.0) as u8;
|
||||
}
|
||||
}
|
||||
rune::TrayIcon::rgba(SIZE, SIZE, pixels)
|
||||
}
|
||||
|
||||
/// The tray menu. `recording` flips the record item's label.
|
||||
pub fn tray_menu(recording: bool) -> Vec<rune::TrayItem> {
|
||||
vec![
|
||||
rune::TrayItem::action("show", "Open League Recorder"),
|
||||
rune::TrayItem::action("hide", "Hide window"),
|
||||
rune::TrayItem::Separator,
|
||||
rune::TrayItem::action(
|
||||
"record",
|
||||
if recording {
|
||||
"Stop recording"
|
||||
} else {
|
||||
"Start recording"
|
||||
},
|
||||
),
|
||||
rune::TrayItem::Separator,
|
||||
rune::TrayItem::action("quit", "Quit"),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! Match history: the timelines on disk, newest first, filtered by queue.
|
||||
//!
|
||||
//! The card reads like `GameHistory.vue`: result banner, champion, queue, KDA, per-minute
|
||||
//! stats, items are not shown because the app has no Data Dragon image cache yet.
|
||||
|
||||
use rune::tok::{radius, space, type_};
|
||||
use rune::{Color, El, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
use crate::format;
|
||||
use crate::history::{Outcome, QueueCategory, Timeline};
|
||||
use crate::screens::review;
|
||||
use crate::ui::{self, Paint, body, heading};
|
||||
|
||||
const FILTERS: [Option<QueueCategory>; 6] = [
|
||||
None,
|
||||
Some(QueueCategory::RankedSolo),
|
||||
Some(QueueCategory::RankedFlex),
|
||||
Some(QueueCategory::Normals),
|
||||
Some(QueueCategory::Aram),
|
||||
Some(QueueCategory::Custom),
|
||||
];
|
||||
|
||||
fn filter_label(filter: Option<QueueCategory>) -> &'static str {
|
||||
filter.map_or("All", QueueCategory::label)
|
||||
}
|
||||
|
||||
fn outcome_color(p: Paint, outcome: Outcome) -> Color {
|
||||
match outcome {
|
||||
Outcome::Victory => p.success(),
|
||||
Outcome::Defeat => p.danger(),
|
||||
Outcome::Terminated => p.muted(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(app: &App, p: Paint) -> El {
|
||||
let filtered: Vec<(usize, &Timeline)> = app
|
||||
.games
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, g)| app.filter.is_none_or(|f| g.category() == f))
|
||||
.collect();
|
||||
|
||||
let mut list = col().key("games").w_full().gap(space::S2);
|
||||
if !app.games_loaded {
|
||||
list = list.child(
|
||||
text("Loading match history…")
|
||||
.key("loading")
|
||||
.font(body(13.0))
|
||||
.color(p.muted())
|
||||
.padding(space::S6),
|
||||
);
|
||||
} else if app.games.is_empty() {
|
||||
list = list.child(empty(
|
||||
p,
|
||||
"No games recorded",
|
||||
"Start playing: the daemon records each game and it shows up here.",
|
||||
));
|
||||
} else if filtered.is_empty() {
|
||||
list = list.child(empty(
|
||||
p,
|
||||
"No games match this filter",
|
||||
"Pick another queue above.",
|
||||
));
|
||||
} else {
|
||||
for (index, game) in filtered {
|
||||
list = list.child(game_card(p, game, index));
|
||||
}
|
||||
}
|
||||
|
||||
let mut filters = row().key("filters").gap(4.0).center_y();
|
||||
for filter in FILTERS {
|
||||
let selected = app.filter == filter;
|
||||
filters = filters.child(ui::tab(
|
||||
p,
|
||||
filter_label(filter),
|
||||
filter_label(filter),
|
||||
selected,
|
||||
move |app: &mut App| app.filter = filter,
|
||||
));
|
||||
}
|
||||
|
||||
col()
|
||||
.key("history")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.child(
|
||||
row()
|
||||
.key("history-header")
|
||||
.w_full()
|
||||
.justify_between()
|
||||
.center_y()
|
||||
.child(
|
||||
col()
|
||||
.key("history-title")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text("Match history")
|
||||
.key("title")
|
||||
.font(heading(20.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!("{} recordings", app.games.len()))
|
||||
.key("count")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(filters),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("list-scroller")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.scroll(rune::ScrollSpec {
|
||||
stick_bottom: false,
|
||||
})
|
||||
.child(list),
|
||||
)
|
||||
}
|
||||
|
||||
fn empty(p: Paint, title: &str, detail: &str) -> El {
|
||||
col()
|
||||
.key("empty")
|
||||
.w_full()
|
||||
.py(64.0)
|
||||
.gap(6.0)
|
||||
.center()
|
||||
.child(
|
||||
text(title)
|
||||
.key("empty-title")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("empty-detail")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
}
|
||||
|
||||
fn game_card(p: Paint, game: &Timeline, index: usize) -> El {
|
||||
let outcome = game.outcome();
|
||||
let ink = outcome_color(p, outcome);
|
||||
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
|
||||
let duration = game.duration_secs.max(0) as f64;
|
||||
let lp = game.lp_change();
|
||||
let stats = game.stats();
|
||||
|
||||
let mut banner = row()
|
||||
.key("banner")
|
||||
.w_full()
|
||||
.h(26.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.fill(ink.alpha(0.16))
|
||||
.child(
|
||||
row()
|
||||
.key("banner-left")
|
||||
.gap(8.0)
|
||||
.center_y()
|
||||
.child(
|
||||
text(outcome.label())
|
||||
.key("outcome")
|
||||
.font(type_::LABEL)
|
||||
.color(ink),
|
||||
)
|
||||
.child(
|
||||
text(game.summoner().unwrap_or_default())
|
||||
.key("summoner")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
);
|
||||
if let Some(lp) = &lp {
|
||||
let lp_ink = if lp.delta >= 0 {
|
||||
p.success()
|
||||
} else {
|
||||
p.danger()
|
||||
};
|
||||
banner = banner.child(
|
||||
text(format!(
|
||||
"{} LP · {}",
|
||||
format::lp_delta(lp.delta),
|
||||
format::rank(&lp.tier, &lp.division)
|
||||
))
|
||||
.key("lp")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(lp_ink),
|
||||
);
|
||||
}
|
||||
|
||||
let kda = match &stats {
|
||||
Some(s) => format!("{}/{}/{}", s.kills, s.deaths, s.assists),
|
||||
None => "0/0/0".into(),
|
||||
};
|
||||
let ratio = stats.as_ref().map_or("0.0".into(), |s| {
|
||||
format::kda_ratio(s.kills, s.deaths, s.assists)
|
||||
});
|
||||
let mut stats_row = row().key("stats").gap(18.0).center_y();
|
||||
if let Some(s) = &stats {
|
||||
stats_row = stats_row
|
||||
.child(stat(p, &format::cs_per_min(s), "CS/m"))
|
||||
.child(stat(p, &format::gold_per_min(s), "Gold/m"))
|
||||
.child(stat(p, &s.vision_score.to_string(), "Vision"));
|
||||
}
|
||||
|
||||
el().key(format!("game-{index}"))
|
||||
.role("button")
|
||||
.label(format!("{champion}, {}", outcome.label()))
|
||||
.focusable(true)
|
||||
.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)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(move |app: &mut App| review::open(app, index))
|
||||
.child(
|
||||
col().key("card").w_full().child(banner).child(
|
||||
row()
|
||||
.key("content")
|
||||
.w_full()
|
||||
.px(space::S3)
|
||||
.py(space::S3)
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
col()
|
||||
.key("identity")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text(champion)
|
||||
.key("champion")
|
||||
.font(heading(16.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!(
|
||||
"{} · {}",
|
||||
game.queue_label(),
|
||||
format::duration(duration)
|
||||
))
|
||||
.key("queue")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
text(format::relative_time(game.start_time))
|
||||
.key("when")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("kda")
|
||||
.gap(1.0)
|
||||
.items_end()
|
||||
.child(
|
||||
text(kda)
|
||||
.key("kda-values")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!("{ratio} KDA"))
|
||||
.key("kda-ratio")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(stats_row)
|
||||
.child(
|
||||
text("Review →")
|
||||
.key("open")
|
||||
.font(type_::LABEL)
|
||||
.color(p.accent),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn stat(p: Paint, value: &str, label: &str) -> El {
|
||||
col()
|
||||
.key(format!("stat-{label}"))
|
||||
.gap(0.0)
|
||||
.items_end()
|
||||
.child(
|
||||
text(value)
|
||||
.key("value")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(text(label).key("label").font(body(10.5)).color(p.muted()))
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! The three screens: settings, match history and the game review.
|
||||
|
||||
pub mod history;
|
||||
pub mod review;
|
||||
pub mod settings;
|
||||
@@ -0,0 +1,617 @@
|
||||
//! Game review: the recorded clip, a scrubber with event markers, highlights and export.
|
||||
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use rune::tok::{radius, space, type_};
|
||||
use rune::{El, Player, SurfaceFit, Tx, col, el, row, text};
|
||||
|
||||
use crate::app::{App, Screen};
|
||||
use crate::format;
|
||||
use crate::highlight::{self, Highlight};
|
||||
use crate::history::{Outcome, Timeline};
|
||||
use crate::ui::{self, Paint, body, heading};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Review {
|
||||
pub game: Option<String>,
|
||||
pub player: Option<Player>,
|
||||
pub time: f64,
|
||||
pub duration: f64,
|
||||
pub scrubber_width: f32,
|
||||
pub highlights: Vec<Highlight>,
|
||||
pub export: Option<Receiver<Result<String, String>>>,
|
||||
pub export_note: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl Review {
|
||||
fn playback(&mut self) {
|
||||
if let Some(player) = &self.player {
|
||||
if player.is_playing() {
|
||||
player.pause();
|
||||
} else {
|
||||
player.play();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn seek(&mut self, seconds: f64) {
|
||||
let at = seconds.clamp(0.0, self.duration.max(0.0));
|
||||
if let Some(player) = &self.player {
|
||||
player.seek(at);
|
||||
self.time = at;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a game in the review screen and load its clip.
|
||||
pub fn open(app: &mut App, index: usize) {
|
||||
leave(app);
|
||||
app.screen = Screen::Review;
|
||||
|
||||
let Some(game) = app.games.get(index) else {
|
||||
return;
|
||||
};
|
||||
// Keep the recording id, not the row number: a new recording can re-sort the list.
|
||||
app.review.game = Some(game.recording_id.clone());
|
||||
let path = game.video_path();
|
||||
let highlights = highlight::compute(
|
||||
game,
|
||||
game.summoner().as_deref(),
|
||||
highlight::Options::default(),
|
||||
);
|
||||
let duration = game.duration_secs.max(0) as f64;
|
||||
app.review.highlights = highlights;
|
||||
app.review.duration = duration;
|
||||
|
||||
let Some(path) = path else {
|
||||
app.review.error = Some(format!(
|
||||
"No video file found for this recording ({}).",
|
||||
game.video_file.as_deref().unwrap_or("unnamed")
|
||||
));
|
||||
return;
|
||||
};
|
||||
let player = Player::file(&path);
|
||||
player.set_looping(false);
|
||||
if let Some(waker) = &app.waker {
|
||||
player.set_waker(waker.clone());
|
||||
}
|
||||
app.review.player = Some(player);
|
||||
}
|
||||
|
||||
/// Leave the review screen and stop playback.
|
||||
pub fn leave(app: &mut App) {
|
||||
app.review.player = None;
|
||||
app.review.game = None;
|
||||
app.review.highlights.clear();
|
||||
app.review.time = 0.0;
|
||||
app.review.duration = 0.0;
|
||||
app.review.error = None;
|
||||
app.review.export_note = None;
|
||||
app.review.export = None;
|
||||
}
|
||||
|
||||
/// Called from `poll` while the review screen is up.
|
||||
pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
|
||||
let mut changed = false;
|
||||
if let Some(player) = &app.review.player {
|
||||
let time = player.time();
|
||||
if (time - app.review.time).abs() > 0.001 {
|
||||
app.review.time = time;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(duration) = player.duration() {
|
||||
if duration > 0.0 && (duration - app.review.duration).abs() > 0.05 {
|
||||
app.review.duration = duration;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if app.review.error.is_none() {
|
||||
if let rune::PlayerState::Failed(message) = player.state() {
|
||||
app.review.error = Some(message);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if player.is_playing() {
|
||||
tx.wake_after(std::time::Duration::from_millis(33));
|
||||
}
|
||||
}
|
||||
if let Some(rx) = &app.review.export {
|
||||
match rx.try_recv() {
|
||||
Ok(Ok(path)) => {
|
||||
app.review.export_note = Some(format!("Clip saved to {path}"));
|
||||
app.review.export = None;
|
||||
changed = true;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
app.review.export_note = Some(format!("Export failed: {e}"));
|
||||
app.review.export = None;
|
||||
changed = true;
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn view(app: &App, p: Paint) -> El {
|
||||
let Some(game) = app.reviewed() else {
|
||||
return col()
|
||||
.key("review")
|
||||
.padding(space::S6)
|
||||
.child(text("No game selected.").font(body(13.0)).color(p.muted()));
|
||||
};
|
||||
let outcome = game.outcome();
|
||||
let ink = match outcome {
|
||||
Outcome::Victory => p.success(),
|
||||
Outcome::Defeat => p.danger(),
|
||||
Outcome::Terminated => p.muted(),
|
||||
};
|
||||
|
||||
let header = row()
|
||||
.key("review-header")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
row()
|
||||
.key("review-title")
|
||||
.gap(10.0)
|
||||
.center_y()
|
||||
.child(ui::button(
|
||||
p,
|
||||
"back",
|
||||
"← Match history",
|
||||
false,
|
||||
|app: &mut App| {
|
||||
leave(app);
|
||||
app.screen = Screen::History;
|
||||
},
|
||||
))
|
||||
.child(
|
||||
text(game.champion().unwrap_or_else(|| "Unknown champion".into()))
|
||||
.key("champion")
|
||||
.font(heading(20.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(outcome.label())
|
||||
.key("outcome")
|
||||
.font(type_::LABEL)
|
||||
.color(ink),
|
||||
)
|
||||
.child(
|
||||
text(format!(
|
||||
"{} · {}",
|
||||
game.queue_label(),
|
||||
format::duration(app.review.duration)
|
||||
))
|
||||
.key("meta")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text(format::game_start(game.start_time))
|
||||
.key("started")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
);
|
||||
|
||||
col()
|
||||
.key("review")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.child(header)
|
||||
.child(video_stage(app, p))
|
||||
.child(scrubber(app, p))
|
||||
.child(
|
||||
row()
|
||||
.key("review-body")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.gap(space::S3)
|
||||
.child(highlights(app, p, game))
|
||||
.child(events(app, p, game)),
|
||||
)
|
||||
}
|
||||
|
||||
fn video_stage(app: &App, p: Paint) -> El {
|
||||
let mut stage = el()
|
||||
.key("stage")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.radius(radius::LG)
|
||||
.fill(rune::Color::BLACK)
|
||||
.clip_soft(radius::LG);
|
||||
|
||||
if let Some(player) = &app.review.player {
|
||||
stage = stage.child(
|
||||
el().key("video")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.video(player, SurfaceFit::Fit),
|
||||
);
|
||||
} else {
|
||||
stage = stage.child(
|
||||
col()
|
||||
.key("stage-empty")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.center()
|
||||
.gap(6.0)
|
||||
.child(
|
||||
text(
|
||||
app.review
|
||||
.error
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Loading the clip…".into()),
|
||||
)
|
||||
.key("stage-message")
|
||||
.font(body(13.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
col()
|
||||
.key("stage-column")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.gap(space::S2)
|
||||
.child(stage)
|
||||
.child(
|
||||
row()
|
||||
.key("transport")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.gap(space::S3)
|
||||
.child(ui::button(
|
||||
p,
|
||||
"play-pause",
|
||||
if playing(app) { "Pause" } else { "Play" },
|
||||
false,
|
||||
|app: &mut App| {
|
||||
app.review.playback();
|
||||
},
|
||||
))
|
||||
.child(ui::button(p, "rewind", "-10 s", false, |app: &mut App| {
|
||||
let at = app.review.time - 10.0;
|
||||
app.review.seek(at);
|
||||
}))
|
||||
.child(ui::button(p, "advance", "+10 s", false, |app: &mut App| {
|
||||
let at = app.review.time + 10.0;
|
||||
app.review.seek(at);
|
||||
}))
|
||||
.child(
|
||||
text(format!(
|
||||
"{} / {}",
|
||||
format::clock(app.review.time),
|
||||
format::clock(app.review.duration)
|
||||
))
|
||||
.key("time")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(el().grow(1.0))
|
||||
.child(
|
||||
text(
|
||||
app.review.export_note.clone().unwrap_or_else(|| {
|
||||
format!("{} highlights", app.review.highlights.len())
|
||||
}),
|
||||
)
|
||||
.key("export-note")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn playing(app: &App) -> bool {
|
||||
app.review.player.as_ref().is_some_and(Player::is_playing)
|
||||
}
|
||||
|
||||
fn scrubber(app: &App, p: Paint) -> El {
|
||||
let width = if app.review.scrubber_width > 0.0 {
|
||||
app.review.scrubber_width
|
||||
} else {
|
||||
800.0
|
||||
};
|
||||
let duration = app.review.duration.max(0.001);
|
||||
let progress = (app.review.time / duration).clamp(0.0, 1.0) as f32;
|
||||
let knob = 14.0;
|
||||
|
||||
let mut bar = el()
|
||||
.key("scrubber")
|
||||
.role("slider")
|
||||
.label("Playback position")
|
||||
.range_value(app.review.time, 0.0, duration)
|
||||
.w_full()
|
||||
.h(26.0)
|
||||
.on_layout(|app: &mut App, [_, _, w, _]| {
|
||||
app.review.scrubber_width = w;
|
||||
})
|
||||
.on_step(|app: &mut App, steps, _| {
|
||||
let at = app.review.time + steps as f64 * 5.0;
|
||||
app.review.seek(at);
|
||||
})
|
||||
.on_drag(move |app: &mut App, d: &mut rune::Drag, tx| {
|
||||
let w = app.review.scrubber_width.max(1.0);
|
||||
let at = (d.x / w).clamp(0.0, 1.0) as f64 * app.review.duration;
|
||||
app.review.seek(at);
|
||||
tx.instant();
|
||||
})
|
||||
.child(
|
||||
el().key("track")
|
||||
.w_full()
|
||||
.h(6.0)
|
||||
.absolute(0.0, 10.0)
|
||||
.radius(3.0)
|
||||
.fill(p.t.control_off)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("played")
|
||||
.w((width * progress).max(2.0))
|
||||
.h(6.0)
|
||||
.absolute(0.0, 10.0)
|
||||
.radius(3.0)
|
||||
.fill(p.accent)
|
||||
.a11y_hidden(),
|
||||
);
|
||||
|
||||
for (index, clip) in app.review.highlights.iter().enumerate() {
|
||||
let x = (clip.start / duration).clamp(0.0, 1.0) as f32 * (width - 6.0);
|
||||
let start = clip.start;
|
||||
bar = bar.child(
|
||||
el().key(format!("marker-{index}"))
|
||||
.role("button")
|
||||
.label(format!("{} at {}", clip.kind.label(), format::clock(start)))
|
||||
.w(6.0)
|
||||
.h(12.0)
|
||||
.absolute(x, 2.0)
|
||||
.radius(3.0)
|
||||
.fill(match clip.kind {
|
||||
highlight::Kind::Death => p.danger(),
|
||||
highlight::Kind::Assist => p.muted(),
|
||||
_ => p.success(),
|
||||
})
|
||||
.on_press(move |app: &mut App| app.review.seek(start))
|
||||
.a11y_hidden(),
|
||||
);
|
||||
}
|
||||
|
||||
bar.child(
|
||||
el().key("knob")
|
||||
.size(knob, knob)
|
||||
.absolute(progress * (width - knob), 6.0)
|
||||
.radius(knob / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
fn highlights(app: &App, p: Paint, game: &Timeline) -> El {
|
||||
let mut list = col().key("highlight-rows").w_full().gap(4.0);
|
||||
if app.review.highlights.is_empty() {
|
||||
list = list.child(
|
||||
text("No kills or deaths in this recording.")
|
||||
.key("no-highlights")
|
||||
.font(body(12.0))
|
||||
.color(p.muted())
|
||||
.padding(space::S2),
|
||||
);
|
||||
}
|
||||
for (index, clip) in app.review.highlights.iter().enumerate() {
|
||||
let start = clip.start;
|
||||
let end = clip.end;
|
||||
let video = game.video_path().map(|path| path.display().to_string());
|
||||
let name = format!("{}-highlight-{}", game.recording_id, index);
|
||||
let kind_ink = match clip.kind {
|
||||
highlight::Kind::Death => p.danger(),
|
||||
highlight::Kind::Assist => p.muted(),
|
||||
highlight::Kind::MultiKill | highlight::Kind::TradeKill => p.accent,
|
||||
highlight::Kind::Kill => p.success(),
|
||||
};
|
||||
let mut actions = row().key("actions").gap(6.0).center_y().child(ui::button(
|
||||
p,
|
||||
&format!("play-{index}"),
|
||||
"Play",
|
||||
false,
|
||||
move |app: &mut App| {
|
||||
app.review.seek(start);
|
||||
if let Some(player) = &app.review.player {
|
||||
player.play();
|
||||
}
|
||||
},
|
||||
));
|
||||
if video.is_some() {
|
||||
actions = actions.child(ui::button(
|
||||
p,
|
||||
&format!("export-{index}"),
|
||||
"Export",
|
||||
false,
|
||||
move |app: &mut App| {
|
||||
let (tx, rx) = channel();
|
||||
let Some(video) = video.clone() else { return };
|
||||
let name = name.clone();
|
||||
std::thread::spawn(move || {
|
||||
let result =
|
||||
crate::export::export_clip(&video, start, end, &name, true, "high");
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
app.review.export = Some(rx);
|
||||
app.review.export_note = Some("Exporting clip…".into());
|
||||
},
|
||||
));
|
||||
}
|
||||
list = list.child(
|
||||
row()
|
||||
.key(format!("highlight-{index}"))
|
||||
.w_full()
|
||||
.h(44.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.hover(p.t.hover)
|
||||
.on_press({
|
||||
let start = clip.start;
|
||||
move |app: &mut App| app.review.seek(start)
|
||||
})
|
||||
.child(
|
||||
col()
|
||||
.key("labels")
|
||||
.gap(1.0)
|
||||
.child(
|
||||
row()
|
||||
.key("title-row")
|
||||
.gap(6.0)
|
||||
.center_y()
|
||||
.child(ui::dot(kind_ink))
|
||||
.child(
|
||||
text(clip.title.clone())
|
||||
.key("title")
|
||||
.font(type_::LABEL)
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!(
|
||||
"{} to {}",
|
||||
format::clock(start),
|
||||
format::clock(end)
|
||||
))
|
||||
.key("range")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text(clip.subtitle.clone())
|
||||
.key("subtitle")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(actions),
|
||||
);
|
||||
}
|
||||
|
||||
col()
|
||||
.key("highlights-panel")
|
||||
.w(360.0)
|
||||
.h_full()
|
||||
.gap(space::S2)
|
||||
.child(
|
||||
text("Highlights")
|
||||
.key("header")
|
||||
.font(type_::SECTION)
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("highlight-scroller")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.scroll(rune::ScrollSpec {
|
||||
stick_bottom: false,
|
||||
})
|
||||
.child(list),
|
||||
)
|
||||
}
|
||||
|
||||
fn events(_app: &App, p: Paint, game: &Timeline) -> El {
|
||||
let interesting = |kind: &str| {
|
||||
matches!(
|
||||
kind,
|
||||
"kill" | "death" | "objective" | "game_start" | "game_end" | "lp_change"
|
||||
)
|
||||
};
|
||||
let mut list = col().key("event-rows").w_full().gap(1.0);
|
||||
let mut shown = 0;
|
||||
for event in game.events.iter().filter(|e| interesting(&e.event_type)) {
|
||||
let at = event.time();
|
||||
let label = match event.event_type.as_str() {
|
||||
"kill" => "Kill",
|
||||
"death" => "Death",
|
||||
"objective" => "Objective",
|
||||
"game_start" => "Game start",
|
||||
"game_end" => "Game end",
|
||||
"lp_change" => "LP change",
|
||||
other => other,
|
||||
};
|
||||
let detail = if event.description.is_empty() {
|
||||
label.to_string()
|
||||
} else {
|
||||
event.description.clone()
|
||||
};
|
||||
list = list.child(
|
||||
row()
|
||||
.key(format!("event-{shown}"))
|
||||
.w_full()
|
||||
.h(30.0)
|
||||
.px(space::S2)
|
||||
.center_y()
|
||||
.gap(space::S2)
|
||||
.radius(radius::SM)
|
||||
.hover(p.t.hover)
|
||||
.on_press(move |app: &mut App| app.review.seek(at))
|
||||
.child(
|
||||
text(format::clock(at))
|
||||
.key("time")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("detail")
|
||||
.font(body(11.5))
|
||||
.color(p.t.text)
|
||||
.grow(1.0)
|
||||
.shrink()
|
||||
.truncate(),
|
||||
),
|
||||
);
|
||||
shown += 1;
|
||||
}
|
||||
if shown == 0 {
|
||||
list = list.child(
|
||||
text("No timeline events.")
|
||||
.key("no-events")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
);
|
||||
}
|
||||
|
||||
col()
|
||||
.key("events-panel")
|
||||
.grow(1.0)
|
||||
.min_w(240.0)
|
||||
.h_full()
|
||||
.gap(space::S2)
|
||||
.child(
|
||||
text("Timeline")
|
||||
.key("header")
|
||||
.font(type_::SECTION)
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("event-scroller")
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.scroll(rune::ScrollSpec {
|
||||
stick_bottom: false,
|
||||
})
|
||||
.child(list),
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,437 @@
|
||||
//! The daemon's settings model (`record-daemon/src/config/settings.rs`).
|
||||
//!
|
||||
//! Kept field for field, snake_case and all: `updateSettings` parses this with serde and rejects
|
||||
//! anything it does not expect.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Settings {
|
||||
#[serde(default)]
|
||||
pub video: VideoSettings,
|
||||
#[serde(default)]
|
||||
pub output: OutputSettings,
|
||||
#[serde(default)]
|
||||
pub audio: AudioSettings,
|
||||
#[serde(default)]
|
||||
pub daemon: DaemonSettings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VideoSettings {
|
||||
#[serde(default)]
|
||||
pub encoder_preset: EncoderPreset,
|
||||
#[serde(default)]
|
||||
pub quality: Quality,
|
||||
#[serde(default = "frame_rate")]
|
||||
pub frame_rate: u32,
|
||||
#[serde(default = "yes")]
|
||||
pub hardware_acceleration: bool,
|
||||
}
|
||||
|
||||
impl Default for VideoSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
encoder_preset: EncoderPreset::default(),
|
||||
quality: Quality::default(),
|
||||
frame_rate: frame_rate(),
|
||||
hardware_acceleration: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum EncoderPreset {
|
||||
Nvenc {
|
||||
#[serde(default = "nvenc_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default = "nvenc_cq")]
|
||||
cq_level: u32,
|
||||
#[serde(default = "yes")]
|
||||
two_pass: bool,
|
||||
},
|
||||
Amf {
|
||||
#[serde(default = "nvenc_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default)]
|
||||
quality: AmfQuality,
|
||||
},
|
||||
X264 {
|
||||
#[serde(default = "x264_preset")]
|
||||
preset: String,
|
||||
#[serde(default = "x264_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default)]
|
||||
crf: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for EncoderPreset {
|
||||
fn default() -> Self {
|
||||
Self::Nvenc {
|
||||
bitrate: nvenc_bitrate(),
|
||||
cq_level: nvenc_cq(),
|
||||
two_pass: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // encoder_id and bitrate are read by the tests
|
||||
impl EncoderPreset {
|
||||
/// The daemon's encoder id for this preset (`GetEncodersResponse::current`).
|
||||
pub fn encoder_id(&self) -> &'static str {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { .. } => "jim_nvenc",
|
||||
EncoderPreset::Amf { .. } => "amd_amf_h264",
|
||||
EncoderPreset::X264 { .. } => "x264",
|
||||
}
|
||||
}
|
||||
|
||||
/// This preset with the encoder changed, keeping the bitrate where both have one.
|
||||
pub fn with_kind(&self, kind: &str) -> EncoderPreset {
|
||||
let bitrate = match self {
|
||||
EncoderPreset::Nvenc { bitrate, .. }
|
||||
| EncoderPreset::Amf { bitrate, .. }
|
||||
| EncoderPreset::X264 { bitrate, .. } => *bitrate,
|
||||
};
|
||||
match kind {
|
||||
"amf" | "AMD AMF" => EncoderPreset::Amf {
|
||||
bitrate,
|
||||
quality: AmfQuality::Balanced,
|
||||
},
|
||||
"x264" | "x264 (Software)" => EncoderPreset::X264 {
|
||||
preset: x264_preset(),
|
||||
bitrate,
|
||||
crf: None,
|
||||
},
|
||||
_ => EncoderPreset::Nvenc {
|
||||
bitrate,
|
||||
cq_level: nvenc_cq(),
|
||||
two_pass: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bitrate(&self) -> u32 {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { bitrate, .. }
|
||||
| EncoderPreset::Amf { bitrate, .. }
|
||||
| EncoderPreset::X264 { bitrate, .. } => *bitrate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AmfQuality {
|
||||
Speed,
|
||||
Balanced,
|
||||
Quality,
|
||||
}
|
||||
|
||||
impl Default for AmfQuality {
|
||||
fn default() -> Self {
|
||||
Self::Balanced
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Quality {
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
Ultra,
|
||||
}
|
||||
|
||||
impl Default for Quality {
|
||||
fn default() -> Self {
|
||||
Self::High
|
||||
}
|
||||
}
|
||||
|
||||
impl Quality {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Low => "Low",
|
||||
Quality::Medium => "Medium",
|
||||
Quality::High => "High",
|
||||
Quality::Ultra => "Ultra",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Low => "720p @ 30fps",
|
||||
Quality::Medium => "1080p @ 30fps",
|
||||
Quality::High => "1080p @ 60fps",
|
||||
Quality::Ultra => "1440p @ 60fps",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct OutputSettings {
|
||||
#[serde(default = "output_path")]
|
||||
pub path: String,
|
||||
#[serde(default = "naming_pattern")]
|
||||
pub naming_pattern: String,
|
||||
#[serde(default = "container")]
|
||||
pub container: String,
|
||||
#[serde(default)]
|
||||
pub split_size_mb: u32,
|
||||
#[serde(default)]
|
||||
pub split_time_minutes: u32,
|
||||
}
|
||||
|
||||
impl Default for OutputSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
path: output_path(),
|
||||
naming_pattern: naming_pattern(),
|
||||
container: container(),
|
||||
split_size_mb: 0,
|
||||
split_time_minutes: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct DaemonSettings {
|
||||
#[serde(default = "yes")]
|
||||
pub auto_record: bool,
|
||||
#[serde(default = "yes")]
|
||||
pub monitor_client: bool,
|
||||
#[serde(default = "poll_interval")]
|
||||
pub poll_interval_ms: u64,
|
||||
#[serde(default)]
|
||||
pub socket_path: Option<String>,
|
||||
#[serde(default = "log_level")]
|
||||
pub log_level: String,
|
||||
#[serde(default = "yes")]
|
||||
pub save_timeline: bool,
|
||||
}
|
||||
|
||||
impl Default for DaemonSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_record: true,
|
||||
monitor_client: true,
|
||||
poll_interval_ms: poll_interval(),
|
||||
socket_path: None,
|
||||
log_level: log_level(),
|
||||
save_timeline: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct AudioSettings {
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
#[serde(default = "audio_bitrate")]
|
||||
pub bitrate: u32,
|
||||
#[serde(default = "sample_rate")]
|
||||
pub sample_rate: u32,
|
||||
#[serde(default = "channels")]
|
||||
pub channels: u32,
|
||||
#[serde(default = "yes")]
|
||||
pub capture_game: bool,
|
||||
#[serde(default = "volume")]
|
||||
pub game_volume: u32,
|
||||
#[serde(default)]
|
||||
pub capture_mic: bool,
|
||||
#[serde(default)]
|
||||
pub mic_device: Option<String>,
|
||||
#[serde(default = "volume")]
|
||||
pub mic_volume: u32,
|
||||
#[serde(default)]
|
||||
pub capture_apps: Vec<AudioSource>,
|
||||
#[serde(default = "volume")]
|
||||
pub apps_volume: u32,
|
||||
}
|
||||
|
||||
impl Default for AudioSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
bitrate: audio_bitrate(),
|
||||
sample_rate: sample_rate(),
|
||||
channels: channels(),
|
||||
capture_game: true,
|
||||
game_volume: volume(),
|
||||
capture_mic: false,
|
||||
mic_device: None,
|
||||
mic_volume: volume(),
|
||||
capture_apps: Vec::new(),
|
||||
apps_volume: volume(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct AudioSource {
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub source_type: AudioSourceType,
|
||||
pub device: String,
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub volume: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AudioSourceType {
|
||||
Application,
|
||||
DeviceOutput,
|
||||
DeviceInput,
|
||||
}
|
||||
|
||||
impl AudioSourceType {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
AudioSourceType::Application => "Application",
|
||||
AudioSourceType::DeviceOutput => "Output device",
|
||||
AudioSourceType::DeviceInput => "Input device",
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---------------------------------------------------------------------------
|
||||
// Defaults, matching the daemon
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn frame_rate() -> u32 {
|
||||
60
|
||||
}
|
||||
fn nvenc_bitrate() -> u32 {
|
||||
8000
|
||||
}
|
||||
fn nvenc_cq() -> u32 {
|
||||
20
|
||||
}
|
||||
fn x264_preset() -> String {
|
||||
"veryfast".into()
|
||||
}
|
||||
fn x264_bitrate() -> u32 {
|
||||
6000
|
||||
}
|
||||
fn output_path() -> String {
|
||||
daemon::recordings_dir().display().to_string()
|
||||
}
|
||||
fn naming_pattern() -> String {
|
||||
"{date}_{time}_{champion}".into()
|
||||
}
|
||||
fn container() -> String {
|
||||
"mp4".into()
|
||||
}
|
||||
fn poll_interval() -> u64 {
|
||||
1000
|
||||
}
|
||||
fn log_level() -> String {
|
||||
"info".into()
|
||||
}
|
||||
fn audio_bitrate() -> u32 {
|
||||
160
|
||||
}
|
||||
fn sample_rate() -> u32 {
|
||||
48_000
|
||||
}
|
||||
fn channels() -> u32 {
|
||||
2
|
||||
}
|
||||
fn volume() -> u32 {
|
||||
100
|
||||
}
|
||||
|
||||
/// Split the daemon's `{ settings: {...} }` wrapper.
|
||||
pub fn from_response(data: &serde_json::Value) -> Result<Settings, String> {
|
||||
let inner = data
|
||||
.get("settings")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| data.clone());
|
||||
serde_json::from_value(inner).map_err(|e| format!("settings did not parse: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn defaults_serialize_the_way_the_daemon_reads_them() {
|
||||
let value = serde_json::to_value(Settings::default()).unwrap();
|
||||
// The daemon parses these exact keys; a rename here makes updateSettings fail.
|
||||
assert_eq!(value["video"]["encoder_preset"]["type"], "nvenc");
|
||||
assert_eq!(value["video"]["encoder_preset"]["cq_level"], 20);
|
||||
assert_eq!(value["video"]["quality"], "high");
|
||||
assert_eq!(value["video"]["frame_rate"], 60);
|
||||
assert_eq!(value["output"]["container"], "mp4");
|
||||
assert!(value["output"]["path"].is_string());
|
||||
assert_eq!(value["audio"]["game_volume"], 100);
|
||||
assert_eq!(value["daemon"]["poll_interval_ms"], 1000);
|
||||
assert!(value["daemon"]["socket_path"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_through_json() {
|
||||
let settings = Settings::default();
|
||||
let text = serde_json::to_string(&settings).unwrap();
|
||||
let back: Settings = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(settings, back);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_response_wrapper_is_peeled_once() {
|
||||
let wrapped = json!({"settings": serde_json::to_value(Settings::default()).unwrap()});
|
||||
assert!(from_response(&wrapped).is_ok());
|
||||
let bare = serde_json::to_value(Settings::default()).unwrap();
|
||||
assert!(from_response(&bare).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encoder_keeps_its_bitrate_when_it_changes_kind() {
|
||||
let preset = EncoderPreset::X264 {
|
||||
preset: "medium".into(),
|
||||
bitrate: 9000,
|
||||
crf: None,
|
||||
};
|
||||
let nvenc = preset.with_kind("nvenc");
|
||||
assert_eq!(nvenc.encoder_id(), "jim_nvenc");
|
||||
assert_eq!(nvenc.bitrate(), 9000);
|
||||
assert_eq!(preset.with_kind("amf").encoder_id(), "amd_amf_h264");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_an_encoder_by_its_menu_label_works() {
|
||||
let preset = EncoderPreset::default();
|
||||
assert_eq!(preset.with_kind("AMD AMF").encoder_id(), "amd_amf_h264");
|
||||
assert_eq!(preset.with_kind("x264 (Software)").encoder_id(), "x264");
|
||||
assert_eq!(preset.with_kind("NVIDIA NVENC").encoder_id(), "jim_nvenc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_source_type_names_match_the_daemon() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::Application).unwrap(),
|
||||
"application"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::DeviceOutput).unwrap(),
|
||||
"deviceoutput"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::DeviceInput).unwrap(),
|
||||
"deviceinput"
|
||||
);
|
||||
}
|
||||
}
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
//! Shared colours and small controls for the screens.
|
||||
|
||||
use rune::tok::{self, Theme, motion, radius, space, type_};
|
||||
use rune::{Color, Drag, El, Phase, TextStyle, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Paint {
|
||||
pub t: Theme,
|
||||
pub accent: Color,
|
||||
pub dark: bool,
|
||||
pub hair: f32,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
pub fn new(dark: bool, scale: f32) -> Self {
|
||||
Self {
|
||||
t: tok::theme(dark),
|
||||
accent: tok::accent(0, dark),
|
||||
dark,
|
||||
hair: 1.0 / scale,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn muted(&self) -> Color {
|
||||
self.t.text_secondary
|
||||
}
|
||||
|
||||
pub fn danger(&self) -> Color {
|
||||
tok::accent(2, self.dark)
|
||||
}
|
||||
|
||||
pub fn success(&self) -> Color {
|
||||
tok::accent(4, self.dark)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn heading(size: f32) -> TextStyle {
|
||||
TextStyle::new(size, 600.0)
|
||||
}
|
||||
|
||||
pub fn body(size: f32) -> TextStyle {
|
||||
TextStyle::new(size, 400.0)
|
||||
}
|
||||
|
||||
/// A titled card of rows with hairlines between them.
|
||||
pub fn card(p: Paint, title: Option<&str>, rows: Vec<El>) -> El {
|
||||
let count = rows.len();
|
||||
let mut inner = col()
|
||||
.key("card")
|
||||
.padding(space::S1)
|
||||
.fill(p.t.card)
|
||||
.radius(radius::LG)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft);
|
||||
for (i, r) in rows.into_iter().enumerate() {
|
||||
inner = inner.child(r);
|
||||
if i + 1 < count {
|
||||
inner = inner.child(
|
||||
el().key(format!("sep{i}"))
|
||||
.h(p.hair)
|
||||
.ml(space::S3)
|
||||
.mr(space::S3)
|
||||
.fill(p.t.separator)
|
||||
.a11y_hidden(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut section = col().gap(space::S2);
|
||||
if let Some(title) = title {
|
||||
section = section.child(
|
||||
text(title)
|
||||
.key("header")
|
||||
.font(type_::SECTION)
|
||||
.color(p.t.text_secondary)
|
||||
.ml(space::S3),
|
||||
);
|
||||
}
|
||||
section.child(inner)
|
||||
}
|
||||
|
||||
/// The 44-point row every setting sits in: a label on the left, a control on the right.
|
||||
pub fn setting_row(p: Paint, key: &str, label: &str, control: El) -> El {
|
||||
row()
|
||||
.key(key)
|
||||
.h(44.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.label(label)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::BODY)
|
||||
.color(p.t.text)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(control)
|
||||
}
|
||||
|
||||
/// A row with a subtitle under the label.
|
||||
pub fn setting_row_with(p: Paint, key: &str, label: &str, subtitle: &str, control: El) -> El {
|
||||
row()
|
||||
.key(key)
|
||||
.h(52.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.label(label)
|
||||
.child(
|
||||
col()
|
||||
.key("labels")
|
||||
.gap(1.0)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::BODY)
|
||||
.color(p.t.text)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
text(subtitle)
|
||||
.key("subtitle")
|
||||
.font(body(11.5))
|
||||
.color(p.t.text_secondary)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
.child(control)
|
||||
}
|
||||
|
||||
/// A 38 × 22 switch with a 18-point knob.
|
||||
pub fn switch(p: Paint, key: &str, on: bool) -> El {
|
||||
let (w, h, k) = (38.0, 22.0, 18.0);
|
||||
let inset = (h - k) / 2.0;
|
||||
el().key(key)
|
||||
.role("switch")
|
||||
.size(w, h)
|
||||
.radius(h / 2.0)
|
||||
.fill(if on { p.accent } else { p.t.control_off })
|
||||
.motion(motion::SNAPPY)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(k, k)
|
||||
.absolute(if on { w - k - inset } else { inset }, inset)
|
||||
.radius(k / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A labelled switch row. The whole row is the target and the keyboard stop.
|
||||
pub fn toggle_row(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
on: bool,
|
||||
flip: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
setting_row(
|
||||
p,
|
||||
key,
|
||||
label,
|
||||
switch(p, &format!("{key}-switch"), on).a11y_hidden(),
|
||||
)
|
||||
.role("switch")
|
||||
.checked(on)
|
||||
.focusable(true)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(flip)
|
||||
}
|
||||
|
||||
/// A 0-100 slider with its value spelled out on the right.
|
||||
pub fn slider(
|
||||
p: Paint,
|
||||
key: &'static str,
|
||||
label: &'static str,
|
||||
value: u32,
|
||||
on_change: impl Fn(&mut App, u32) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
let (w, h, k, bar) = (180.0, 22.0, 18.0, 4.0);
|
||||
let travel = w - k;
|
||||
let v = (value.min(100) as f32 / 100.0).clamp(0.0, 1.0);
|
||||
let to_value = move |x: f32| (((x - k / 2.0) / travel).clamp(0.0, 1.0) * 100.0).round() as u32;
|
||||
let on_change = std::sync::Arc::new(on_change);
|
||||
let drag_change = on_change.clone();
|
||||
let step_change = on_change;
|
||||
row()
|
||||
.key(format!("{key}-control"))
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(
|
||||
el().key(key)
|
||||
.role("slider")
|
||||
.label(label)
|
||||
.range_value(f64::from(value.min(100)), 0.0, 100.0)
|
||||
.range_step(5.0)
|
||||
.a11y_value(format!("{value}%"))
|
||||
.on_step(move |s: &mut App, steps, _| {
|
||||
let next = (i64::from(value) + i64::from(steps) * 5).clamp(0, 100) as u32;
|
||||
step_change(s, next);
|
||||
})
|
||||
.size(w, h)
|
||||
.motion(motion::SNAPPY)
|
||||
.on_drag(move |s: &mut App, d: &mut Drag, tx| match d.phase {
|
||||
Phase::Down => {
|
||||
d.data = v;
|
||||
let knob = k / 2.0 + v * travel;
|
||||
if (d.x - knob).abs() > k / 2.0 + 2.0 {
|
||||
let next = to_value(d.x);
|
||||
drag_change(s, next);
|
||||
}
|
||||
}
|
||||
Phase::Move => {
|
||||
let knob = k / 2.0 + d.data * travel;
|
||||
let grab = if (d.start_x - knob).abs() <= k / 2.0 + 2.0 {
|
||||
d.start_x - knob
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let next = to_value(d.x - grab);
|
||||
drag_change(s, next);
|
||||
tx.instant();
|
||||
}
|
||||
Phase::Up => {}
|
||||
})
|
||||
.child(
|
||||
el().key("track")
|
||||
.size(w, bar)
|
||||
.absolute(0.0, (h - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.t.control_off)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("fill")
|
||||
.size(k / 2.0 + v * travel, bar)
|
||||
.absolute(0.0, (h - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.accent)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(k, k)
|
||||
.absolute(v * travel, (h - k) / 2.0)
|
||||
.radius(k / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text(format!("{value}%"))
|
||||
.key("value")
|
||||
.w(40.0)
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.t.text_secondary)
|
||||
.align(rune::Align::End)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A pill tab; the selected one fills with the accent.
|
||||
pub fn tab(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
selected: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("tab")
|
||||
.label(label)
|
||||
.checked(selected)
|
||||
.focusable(true)
|
||||
.px(14.0)
|
||||
.h(28.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if selected {
|
||||
p.accent.alpha(0.16)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
})
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(if selected {
|
||||
p.accent
|
||||
} else {
|
||||
p.t.text_secondary
|
||||
})
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A small pill button.
|
||||
pub fn button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary { p.accent } else { p.t.control_off })
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(if primary { Color::WHITE } else { p.t.text })
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A coloured dot used for status.
|
||||
pub fn dot(color: Color) -> El {
|
||||
el().key("dot")
|
||||
.size(8.0, 8.0)
|
||||
.radius(4.0)
|
||||
.fill(color)
|
||||
.a11y_hidden()
|
||||
}
|
||||
Reference in new issue
Block a user