14 Commits
Author SHA1 Message Date
vhaudiquet 9d1fb40434 bump version (0.3.3)
record-daemon / Build (Windows x64) (push) Successful in 2m10s
record-daemon / Check and lint (Linux) (push) Successful in 1m13s
2026-11-24 00:20:31 +01:00
vhaudiquet 47510c88b5 app: drop the old Tauri front end
tauri-app/ was kept while the native app caught up, and the screens it had
are covered now. Its 48 tracked files go; the 7.6 GB of node_modules,
dist and target beside them were never tracked and are gone from the
working copy too.

The docs that said it was still in the tree name two programs now, and
the comments that pointed at a file inside it name the old app's file
instead, so nothing refers to a folder that is no longer there. The design
plans under plans/ keep their wording: they are dated documents, not
instructions.
2026-11-24 00:18:31 +01:00
vhaudiquet 046860ad1c app: scroll the log box and give it more height
Two hundred lines of log did not fit the card, so the text ran past the
card's edge.

The box is a scroll viewport now, 440 points tall, pinned to its newest
line until the reader scrolls, with its own bar in the strip the padding
leaves. It sits inside the settings scroller, so both bars share the
screen and the log takes the wheel while the pointer is over it.
2026-11-24 00:16:16 +01:00
vhaudiquet 42ba0ce882 app: read the log the daemon actually writes
The daemon rolls its log at midnight and keeps the --log-file path as a
stem, so it writes logs/daemon.YYYY-MM-DD.log. Reload log read the
literal logs/daemon.log, a path that never exists, so every press failed
with a missing file, and the Log file row named the same path.

Read the newest daily file instead and show that path. Strip the ANSI
colours from what is read too: the file layer had colour on, so lines
already on disk carry escapes the box would draw as noise. record-daemon
writes the file without colour from here on.
2026-11-24 00:16:08 +01:00
vhaudiquet 85b6602b31 app: put each audio volume under the source it drives
record-daemon / Build (Windows x64) (push) Successful in 1m55s
record-daemon / Check and lint (Linux) (push) Successful in 1m12s
The Audio tab's Levels card held the game, microphone and applications
volumes, so the microphone's level sat away from its picker, the game
had no on/off, and the applications volume was a fallback that the
per-application sliders made invisible.

The card is Game now: Record game audio, which switches the master and
the game capture together as the quick tab's does, and Game volume.
Microphone volume moves under the microphone picker. The applications
card keeps one volume per source and the row for all of them is gone.

apps_volume stays in the settings: the daemon reads it for a source that
has no volume of its own.
2026-11-24 00:02:43 +01:00
vhaudiquet c483c012b3 app: pick the recordings folder from the quick tab
The quick tab showed the folder read-only, so a user who wanted another
one had to find the recording tab for it.

The row is the recording tab's now: the path, and Select folder beside
it. Open folder stays in the card header for the folder in use.
2026-11-24 00:00:13 +01:00
vhaudiquet 1bb2874753 app: pick the recordings folder and cut paths to the row
The folder was a text field, and the path was always cut to its last
two folders, so a wide window dropped folders it had room for and a
narrow one showed only the tail.

The row now shows the path the settings hold, cut in the middle at
whatever width the labels and the button leave it, with Select folder
opening the system's folder dialog through rune's native-file-dialog
feature. Form keeps no copy of the path any more; the draft is the one
place it lives.

The quick tab's recordings folder and the daemon tab's log file get the
same cut, and short_path goes.
2026-11-23 23:53:21 +01:00
vhaudiquet dbdec05752 app: drop split and audio settings from the recording tab
The recorder declared split_size_mb and split_time_minutes and never read
them: no capture setting was built from either, so the two rows promised
a file split that the recorder does not do.

The recording tab also carried a card of audio toggles and a microphone
picker that the Quick tab already has, and a line that opened the Audio
tab. Every one of those settings stays where it belongs.

Recording is now the encoder and quality, then folder, file name and
container.
2026-11-23 23:30:53 +01:00
vhaudiquet 73b41fa86b app: fill the screen with a clip in review
The review screen gave the clip a framed stage with the header, the
details column and the status bar around it, so a clip watched there
filled a fraction of the display.

Full screen, the button beside the volume or F, hands the window to the
display with no frame of ours and draws the picture alone, letterboxed
at 16:9. The controls keep to a band at the bottom: a gradient no taller
than they are, the scrubber with its event marks, the transport and an
Exit full screen button. The band is its own hover group, so the pointer
comes to it for the controls to draw in over 200 ms, and they are gone
400 ms after it leaves. Escape, the button or a double press on the
picture leaves, and the double press enters from the windowed stage.

Being full screen belongs to the window, not to the review, so App keeps
the state it last asked of the window and poll reconciles the two: a way
out of the review, a jump to another screen, or a window closed and
reopened brings the title bar, the status bar and the frame back.
2026-11-23 23:24:11 +01:00
vhaudiquet e546ab6969 app: show the game being recorded while it runs
record-daemon / Check and lint (Linux) (push) Successful in 1m13s
record-daemon / Build (Windows x64) (push) Successful in 1m56s
The daemon's protocol says whether it is recording and which game it is
on, and nothing else, so the app could not say what was being recorded
or stop it.

A Recording screen now opens by itself when a recording starts, and at
launch if one is already running, and a button in the title bar brings it
back from any other screen. It shows the champion, the queue and the
summoner, when the game began, two clocks, the live scoreline and both
teams, and the clip being written as it grows on disk. The game's own
data is read once a second on a thread of its own, from the endpoint the
daemon polls for its events, which needs no login. Without an answer the
screen keeps what it has and says it is waiting.

Stop recording and Stop and delete end the game. A stop over the
protocol is not the stop the recorder gives a game that ends by itself.
The video lands in a new timeline while the open one is left behind,
which showed in the match history as a game that never happened, next to
one with no champion. Stopping from the app closes the open timeline into
the one holding the video, and deleting removes the clip and both. The
history skips timelines that have no end meanwhile, so a recording in
progress is not listed as a game.
2026-11-23 22:46:44 +01:00
vhaudiquet b9d97d0724 app: draw the title bar without a native frame
The window kept Windows' native caption above the app's own title bar:
two title bars, and nothing in the frame said the app was drawing its
own.

Setting `.titlebar(Titlebar::new(app::TITLEBAR_HEIGHT))` hands the
frame to Rune. The native caption goes; Windows keeps its resize edges,
snap layouts and window menu, and Rune draws the minimize, maximize and
close buttons over the bar's right edge in the ink the view gives with
`Cx::caption_color`. The bar pads itself by `Cx::chrome_insets`, so its
own buttons keep clear of those on either platform (macOS keeps its
traffic lights at the leading edge). The window now refuses to shrink
past the width where both rows fit.
2026-11-23 21:58:04 +01:00
vhaudiquet 7213c119da app: walk back through the screens you came from
The arrow was hardwired per screen: from a review it led to the match
history, even when the review was opened from a clip's card, and the
clip view was torn down on the way out.

App now keeps the trail of screens behind the one on screen. Opening a
row, a card, or an exported clip pushes the screen it came from; the
arrow and Escape pop. The title bar's Clips and Settings buttons and the
number keys jump to a root with the match history behind them. A clip or
a review that back can still reach is kept, paused where it was, so
returning shows it again rather than reopening it; either is dropped
once the trail no longer holds it.
2026-11-23 21:06:01 +01:00
vhaudiquet c452fab735 app: keep a renamed clip's game after the rename
The card that leads back to a clip's game found the recording by the id
the export writes into the file's name, and a title change takes that
name away. Saving a title now writes a small link file beside the clip,
`{name}.json`, naming the recording, and carries an existing one along,
so the card survives the rename, leaving the clip view, and a restart.
The clips folder reads the link back, which also keeps the champion on
a grid card. Deleting a clip deletes its link file too.
2026-11-23 20:53:09 +01:00
vhaudiquet 64b172649b app: open a clip's game from a card beside it
The clip view named the game in its heading and nothing else, so the
recording a clip was cut from was a dead end. A card under the title
now shows the champion, the scoreline, the queue and length, the result,
and when the game was played, and an arrow marks it as the way back
into that recording.

The card reads the recording id the export writes into the file's name.
Its row comes from the loaded history, or from the timeline itself when
the history has not paged that far. The clip view keeps the summary, so
renaming a clip keeps the card. The line under the heading now
describes the file itself, its size and export time, since the card
carries the game.
2026-11-23 20:45:12 +01:00
81 changed files with 2474 additions and 16410 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
# Working in this repository # Working in this repository
The repository holds two Rust programs: `record-daemon/` (the recorder) and `app/` (the rune The repository holds two Rust programs: `record-daemon/` (the recorder) and `app/` (the rune
front end). `tauri-app/` is the old front end, kept for reference. front end).
## Before every commit ## Before every commit
+28 -1
View File
@@ -758,6 +758,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"block2 0.6.2",
"libc",
"objc2 0.6.5", "objc2 0.6.5",
] ]
@@ -1545,7 +1547,7 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]] [[package]]
name = "leaguerecorder" name = "leaguerecorder"
version = "0.3.2" version = "0.3.3"
dependencies = [ dependencies = [
"chrono", "chrono",
"directories", "directories",
@@ -1894,6 +1896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"block2 0.6.2",
"objc2 0.6.5", "objc2 0.6.5",
"objc2-core-foundation", "objc2-core-foundation",
"objc2-core-graphics", "objc2-core-graphics",
@@ -2730,6 +2733,29 @@ dependencies = [
"usvg", "usvg",
] ]
[[package]]
name = "rfd"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220"
dependencies = [
"block2 0.6.2",
"dispatch2",
"js-sys",
"libc",
"log",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"percent-encoding",
"raw-window-handle",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "rgb" name = "rgb"
version = "0.8.53" version = "0.8.53"
@@ -2801,6 +2827,7 @@ dependencies = [
"png 0.18.1", "png 0.18.1",
"pollster", "pollster",
"raw-window-handle", "raw-window-handle",
"rfd",
"rune-core", "rune-core",
"rune-edit", "rune-edit",
"rune-gpu", "rune-gpu",
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "leaguerecorder" name = "leaguerecorder"
version = "0.3.2" version = "0.3.3"
edition = "2024" edition = "2024"
description = "Native League Recorder desktop app (rune)" description = "Native League Recorder desktop app (rune)"
license = "MIT" license = "MIT"
@@ -14,7 +14,7 @@ path = "src/main.rs"
winresource = "0.1" winresource = "0.1"
[dependencies] [dependencies]
rune = { path = "vendor/rune/crates/rune" } rune = { path = "vendor/rune/crates/rune", features = ["native-file-dialog"] }
rune-kit = { path = "vendor/rune/crates/rune-kit" } rune-kit = { path = "vendor/rune/crates/rune-kit" }
rune-notify = { path = "vendor/rune/crates/rune-notify" } rune-notify = { path = "vendor/rune/crates/rune-notify" }
+33 -7
View File
@@ -1,6 +1,6 @@
# League Recorder (rune app) # League Recorder (rune app)
The native replacement for `tauri-app`. It talks to `record-daemon` over the daemon's existing The native front end for `record-daemon`. It talks to the daemon over its existing
named-pipe protocol and draws with [rune](https://github.com/anomalyco/rune). named-pipe protocol and draws with [rune](https://github.com/anomalyco/rune).
## Run it ## Run it
@@ -23,9 +23,13 @@ Headless renders, for looking at a screen without a window:
```sh ```sh
cargo run -- --snap history.png --scene history cargo run -- --snap history.png --scene history
cargo run -- --snap settings.png --scene settings cargo run -- --snap settings.png --scene settings
cargo run -- --snap recording.png --scene recording cargo run -- --snap recording.png --scene recording # the settings tab
cargo run -- --snap recording-live.png --scene recording-live # a game being recorded
cargo run -- --snap recording-live-delete.png --scene recording-live-delete
cargo run -- --snap recording-idle.png --scene recording-idle
cargo run -- --snap audio.png --scene audio cargo run -- --snap audio.png --scene audio
cargo run -- --snap review.png --scene review cargo run -- --snap review.png --scene review
cargo run -- --snap review-full.png --scene review-full # the picture alone, at rest
cargo run -- --snap clips.png --scene clips cargo run -- --snap clips.png --scene clips
cargo run -- --snap clip.png --scene clip cargo run -- --snap clip.png --scene clip
cargo run -- --snap clips-many.png --scene clips-many --at 1 # 36 demo clips, to see the scrollbar cargo run -- --snap clips-many.png --scene clips-many --at 1 # 36 demo clips, to see the scrollbar
@@ -70,7 +74,7 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti
| `src/export.rs` | ffmpeg clip export, the clips folder it fills and its miniatures | | `src/export.rs` | ffmpeg clip export, the clips folder it fills and its miniatures |
| `src/os.rs` | Run key, toasts, tray icon and menu | | `src/os.rs` | Run key, toasts, tray icon and menu |
| `src/ui.rs` | Colours, cards, switches, sliders, buttons | | `src/ui.rs` | Colours, cards, switches, sliders, buttons |
| `src/screens/` | Settings, match history, clips, game review | | `src/screens/` | Settings, match history, clips, game review, the recording in progress |
## Where this stands against TODO.txt ## Where this stands against TODO.txt
@@ -82,7 +86,11 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti
are tested against the daemon's serde names. are tested against the daemon's serde names.
3. Settings: done. General, recording, audio and daemon tabs; device and encoder lists come from 3. Settings: done. General, recording, audio and daemon tabs; device and encoder lists come from
`getAudioDevices` and `getEncoders`; changes go out through `updateSettings`, and each `getAudioDevices` and `getEncoders`; changes go out through `updateSettings`, and each
application volume slider sends `updateAudioSource` as it moves. application volume slider sends `updateAudioSource` as it moves. The recordings folder is
shown, not typed, on the quick and recording tabs: `Select folder` asks the system for
one, through the `native-file-dialog` feature `Cargo.toml` turns on, and headless runs
answer it from a script. Every path the settings show is cut in the middle against the
row it sits in, so a narrow window elides and a wide one shows the whole thing.
4. Match history: done. Cards read `GameHistory.vue`'s fields (result, champion portrait, 4. Match history: done. Cards read `GameHistory.vue`'s fields (result, champion portrait,
queue, KDA, CS/m, gold/m, LP change) from the raw API responses in each timeline, with the queue, KDA, CS/m, gold/m, LP change) from the raw API responses in each timeline, with the
queue filters. Portraits come from Data Dragon and are cached on disk (`src/portraits.rs`). queue filters. Portraits come from Data Dragon and are cached on disk (`src/portraits.rs`).
@@ -96,7 +104,10 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti
mpv's, the three options in TODO.txt still apply; `Player` is confined to `screens/review.rs`. mpv's, the three options in TODO.txt still apply; `Player` is confined to `screens/review.rs`.
6. Game review: done. The clip fills the window at 16:9, with play/pause, +/-10 s, and a 6. Game review: done. The clip fills the window at 16:9, with play/pause, +/-10 s, and a
scrubber that marks every event; highlights (play, export) and the timeline sit in a side scrubber that marks every event; highlights (play, export) and the timeline sit in a side
panel, one press away. ffmpeg exports each highlight. panel, one press away. ffmpeg exports each highlight. The Full screen button beside the
volume, a double press on the picture, or F takes the whole display: the picture fills the
screen and the controls fade in over its bottom while the pointer is on them, gone 400 ms
after it leaves. Escape goes back.
7. Audio channels: the recorder writes one audio stream per source, and the review screen opens 7. Audio channels: the recorder writes one audio stream per source, and the review screen opens
one player per stream (`export::extract_tracks` copies each into the audio cache). Toggles one player per stream (`export::extract_tracks` copies each into the audio cache). Toggles
under the transport mute a channel for listening, and clip and highlight exports mix only under the transport mute a channel for listening, and clip and highlight exports mix only
@@ -107,8 +118,23 @@ reading (`history::tests`), highlight clipping (`highlight::tests`) and formatti
runtime beside the exe. `cargo install cargo-packager --locked && cargo packager --release`. runtime beside the exe. `cargo install cargo-packager --locked && cargo packager --release`.
On the first run the app downloads ffmpeg (`--fetch-ffmpeg` does it from a shell), so clip On the first run the app downloads ffmpeg (`--fetch-ffmpeg` does it from a shell), so clip
export is ready before the first clip. The installer has not been run on a clean VM yet. export is ready before the first clip. The installer has not been run on a clean VM yet.
10. Parity: `tauri-app` is still in the tree. Delete it once the items above are verified on a
machine with a live League Client. ### The recording screen
While the daemon records, the app opens on the game it is recording and can stop it. The
daemon's protocol answers about the daemon only — recording or not, and which game id — so the
screen reads the game where it is: `/liveclientdata/allgamedata` on `https://127.0.0.1:2999`,
the endpoint the daemon itself polls for its events, which needs no login. It is read once a
second on a thread of its own, together with the timeline the recorder opened for this game
(the champion, the queue and the summoner it fetched at the start) and the clip being written
in the recordings folder. Without the game's answer the screen still shows what it has, and
says it is waiting.
Stopping over the protocol is not the stop the recorder gives a game that ends by itself: the
recorder writes the video into a new timeline and leaves the open one behind, which would show
in Match history as a game that never happened, next to one with no champion. The app closes
the open timeline into the one holding the video (`history::close_stopped`), and "Stop and
delete" removes the clip and both.
### Known gaps ### Known gaps
+5 -8
View File
@@ -1,4 +1,4 @@
Rune app (replaces tauri-app) Rune app
Decided Decided
- UI framework: rune (github.com/anomalyco/rune, pin a dev rev). gpui is the - UI framework: rune (github.com/anomalyco/rune, pin a dev rev). gpui is the
@@ -49,17 +49,14 @@ framework, stop and switch to gpui before writing anything else.
8. Installer: cargo-packager NSIS target with the bundle list below. 8. Installer: cargo-packager NSIS target with the bundle list below.
Done when the installer works on a clean Windows VM and the app Done when the installer works on a clean Windows VM and the app
records a real game end to end. records a real game end to end.
9. Parity check against tauri-app, then delete it.
Stable contracts Stable contracts
- record-daemon does not change. The IPC protocol (IpcCommand serde types - record-daemon does not change. The IPC protocol (IpcCommand serde types
over named pipes) is the versioned interface between app and daemon. over named pipes) is the versioned interface between app and daemon.
- Port tauri-app/src-tauri/src/daemon_ipc.rs (645 lines, pipe client) into - The pipe client came from the old Tauri app's daemon_ipc.rs (645 lines),
app/ nearly as-is; it is plain Rust + tokio. ported into app/ nearly as-is; it is plain Rust + tokio.
- Port the disk-side helpers from src-tauri/src/lib.rs: get_game_history, - The disk-side helpers came from its lib.rs: get_game_history, export_clip,
export_clip, find_video_file and the ffmpeg_sidecar download logic. find_video_file and the ffmpeg_sidecar download logic.
- Keep tauri-app/ working until the native app reaches feature parity.
Build app/ as a separate crate; do not mutate tauri-app in place.
Installer contents Installer contents
- app exe, record-daemon.exe, obs.dll, ffmpeg sidecar, libmpv-2.dll. - app exe, record-daemon.exe, obs.dll, ffmpeg sidecar, libmpv-2.dll.
+1 -1
View File
@@ -8,7 +8,7 @@
name = "leaguerecorder" name = "leaguerecorder"
product-name = "League Recorder" product-name = "League Recorder"
identifier = "v.leaguerecorder" identifier = "v.leaguerecorder"
version = "0.3.2" version = "0.3.3"
description = "Records League of Legends games through the record-daemon." description = "Records League of Legends games through the record-daemon."
out-dir = "dist" out-dir = "dist"
# A config file is not read from Cargo.toml, so the binary has to be named. The app crate # A config file is not read from Cargo.toml, so the binary has to be named. The app crate
+220 -65
View File
@@ -5,7 +5,7 @@ use std::sync::mpsc::{Receiver, TryRecvError, channel};
use std::time::Duration; use std::time::Duration;
use rune::tok::type_; use rune::tok::type_;
use rune::{Cx, El, Key, KeyEvent, Tx, col, el, row, text}; use rune::{ChromeInsets, Cx, El, Key, KeyEvent, Tx, col, el, row, text};
use crate::export::{self, Clip}; use crate::export::{self, Clip};
use crate::history::{self, QueueCategory, Summary, Timeline}; use crate::history::{self, QueueCategory, Summary, Timeline};
@@ -17,6 +17,9 @@ use crate::screens;
use crate::settings::{AudioSource, AudioSourceType, Settings}; use crate::settings::{AudioSource, AudioSourceType, Settings};
use crate::ui::{self, Paint, body, heading}; use crate::ui::{self, Paint, body, heading};
/// The band the app draws its own title bar in, which the window's controls sit over.
pub const TITLEBAR_HEIGHT: f32 = 48.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen { pub enum Screen {
Settings, Settings,
@@ -24,6 +27,7 @@ pub enum Screen {
Clips, Clips,
Clip, Clip,
Review, Review,
Recording,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -115,6 +119,14 @@ pub struct Notice {
pub struct App { pub struct App {
pub screen: Screen, pub screen: Screen,
/// Whether the screens show `history::sample` rather than the disk: a snapshot run, which
/// never starts the daemon and has nothing live to read.
pub sample: bool,
/// The screens behind this one, oldest first: the back arrow returns through them.
pub behind: Vec<Screen>,
/// Whether the window is full screen at the app's asking. The review asks for it, and a
/// window that disagrees follows it in the next poll.
pub window_full: bool,
pub settings_tab: SettingsTab, pub settings_tab: SettingsTab,
pub dark: bool, pub dark: bool,
pub daemon: Daemon, pub daemon: Daemon,
@@ -155,6 +167,8 @@ pub struct App {
pub clips_menu_open: Option<usize>, pub clips_menu_open: Option<usize>,
/// The clip the delete dialog is about, by its `id@start` key. /// The clip the delete dialog is about, by its `id@start` key.
pub confirm_clip_delete: Option<String>, pub confirm_clip_delete: Option<String>,
/// The game being recorded: what the recording screen has read of it.
pub recording: screens::recording::State,
pub review: screens::review::Review, pub review: screens::review::Review,
pub portraits: Option<portraits::Portraits>, pub portraits: Option<portraits::Portraits>,
/// The icons of the processes the audio sources name, decoded from their executables. /// The icons of the processes the audio sources name, decoded from their executables.
@@ -168,6 +182,8 @@ pub struct App {
pub clips_scroll: ui::ScrollBar, pub clips_scroll: ui::ScrollBar,
pub highlights_scroll: ui::ScrollBar, pub highlights_scroll: ui::ScrollBar,
pub events_scroll: ui::ScrollBar, pub events_scroll: ui::ScrollBar,
pub recording_scroll: ui::ScrollBar,
pub log_scroll: ui::ScrollBar,
pub notice: Option<Notice>, pub notice: Option<Notice>,
/// ffmpeg being downloaded on the first run, and the whole percent it last reported. /// ffmpeg being downloaded on the first run, and the whole percent it last reported.
pub ffmpeg_rx: Option<Receiver<export::FetchEvent>>, pub ffmpeg_rx: Option<Receiver<export::FetchEvent>>,
@@ -189,7 +205,10 @@ impl App {
// `--live` renders headless but talks to the daemon and reads the real recordings. // `--live` renders headless but talks to the daemon and reads the real recordings.
let live = std::env::args().any(|arg| arg == "--live"); let live = std::env::args().any(|arg| arg == "--live");
let mut app = Self { let mut app = Self {
sample: headless && !live,
window_full: false,
screen: Screen::History, screen: Screen::History,
behind: Vec::new(),
settings_tab: SettingsTab::Quick, settings_tab: SettingsTab::Quick,
dark: true, dark: true,
daemon: Daemon::start(headless && !live), daemon: Daemon::start(headless && !live),
@@ -216,6 +235,7 @@ impl App {
thumbs_rx: None, thumbs_rx: None,
clips_menu_open: None, clips_menu_open: None,
confirm_clip_delete: None, confirm_clip_delete: None,
recording: screens::recording::State::default(),
review: screens::review::Review::default(), review: screens::review::Review::default(),
portraits: None, portraits: None,
icons: None, icons: None,
@@ -226,6 +246,8 @@ impl App {
clips_scroll: ui::ScrollBar::new(), clips_scroll: ui::ScrollBar::new(),
highlights_scroll: ui::ScrollBar::new(), highlights_scroll: ui::ScrollBar::new(),
events_scroll: ui::ScrollBar::new(), events_scroll: ui::ScrollBar::new(),
recording_scroll: ui::ScrollBar::new(),
log_scroll: ui::ScrollBar::new(),
notice: None, notice: None,
ffmpeg_rx: None, ffmpeg_rx: None,
ffmpeg_pct: None, ffmpeg_pct: None,
@@ -264,6 +286,7 @@ impl App {
name, name,
path: PathBuf::new(), path: PathBuf::new(),
thumb: None, thumb: None,
recording_id: None,
exported: Some( exported: Some(
std::time::SystemTime::now() std::time::SystemTime::now()
- chrono::Duration::hours(hours_ago) - chrono::Duration::hours(hours_ago)
@@ -388,6 +411,73 @@ impl App {
} }
} }
/// Show `screen`, leaving the one on screen behind for the back arrow. What the screen
/// being left was playing stops; one that stays behind keeps its place, paused.
pub fn go(&mut self, screen: Screen) {
if screen == self.screen {
return;
}
// The clip view and the review each hold one screen's state, and the one this shows
// replaces it: an entry for the same screen deeper in the trail names what is gone.
if matches!(screen, Screen::Clip | Screen::Review) {
self.behind.retain(|behind| *behind != screen);
}
self.pause_away();
self.behind.push(self.screen);
self.screen = screen;
self.settle();
}
/// Return to the screen left behind. The match history is the root and has none, so
/// there it does nothing.
pub fn back(&mut self) {
let Some(screen) = self.behind.pop() else {
return;
};
self.pause_away();
self.screen = screen;
self.settle();
}
/// Jump to a screen the title bar or a number key names, with the match history behind
/// it. Whatever the trail held is dropped: this is a place of its own, not one on top.
pub fn jump(&mut self, screen: Screen) {
if self.screen != screen {
self.pause_away();
}
self.behind.clear();
if screen != Screen::History {
self.behind.push(Screen::History);
}
self.screen = screen;
self.settle();
}
/// Stop what the screen being left is playing: it is out of sight, and its sound would
/// carry under the next screen.
fn pause_away(&mut self) {
match self.screen {
Screen::Clip => {
if let Some(player) = self.clip.as_ref().and_then(|view| view.player.as_ref()) {
player.pause();
}
}
Screen::Review => self.review.pause(),
_ => {}
}
}
/// Drop the state of screens the trail no longer holds. A clip view and a review are each
/// a player and a timeline, kept only while back can return to them.
fn settle(&mut self) {
if self.screen != Screen::Clip && !self.behind.contains(&Screen::Clip) {
self.clip = None;
}
if self.screen != Screen::Review && !self.behind.contains(&Screen::Review) {
screens::review::leave(self);
}
}
/// Stop the clip and the review where they are. The window is going away and the app stays /// Stop the clip and the review where they are. The window is going away and the app stays
/// in the tray, so sound with no picture should not carry on: reopening shows the same /// in the tray, so sound with no picture should not carry on: reopening shows the same
/// screen, paused at the same second. /// screen, paused at the same second.
@@ -500,6 +590,14 @@ impl App {
} }
} }
/// The container the recorder writes new recordings in, as the settings say.
pub fn container(&self) -> String {
self.settings
.as_ref()
.map(|settings| settings.output.container.clone())
.unwrap_or_else(|| self.form.draft.output.container.clone())
}
/// The folders a recording's clip may be in: the configured output folder first, then the /// The folders a recording's clip may be in: the configured output folder first, then the
/// default one, where timelines and the clips folder live. /// default one, where timelines and the clips folder live.
pub fn video_roots(&self) -> Vec<PathBuf> { pub fn video_roots(&self) -> Vec<PathBuf> {
@@ -635,6 +733,9 @@ thread_local! {
/// no picture. Reopening brings the same screen back, paused where it was. /// no picture. Reopening brings the same screen back, paused where it was.
pub fn window_closed(app: &mut App, _tx: &mut Tx) { pub fn window_closed(app: &mut App, _tx: &mut Tx) {
app.pause_playback(); app.pause_playback();
// The window comes back at its spec size, so a full screen review ends with it.
app.review.fullscreen = false;
app.window_full = false;
} }
pub fn remember_window(handle: &rune::WindowHandle) { pub fn remember_window(handle: &rune::WindowHandle) {
@@ -719,9 +820,23 @@ impl App {
self.refresh_games(); self.refresh_games();
// A stop can take a moment to write the timeline; read it again shortly. // A stop can take a moment to write the timeline; read it again shortly.
tx.wake_after(Duration::from_millis(1500)); tx.wake_after(Duration::from_millis(1500));
if self.screen == Screen::Recording {
self.jump(Screen::History);
}
self.recording.forget();
} }
self.tray_recording = self.status.is_recording; self.tray_recording = self.status.is_recording;
} }
// The screen a game opens: what is being recorded, until it stops. A recording that is
// already running when the app starts is the first thing it shows too.
if self.status.is_recording && !was_recording {
self.recording.begin();
if first {
self.jump(Screen::Recording);
} else {
self.go(Screen::Recording);
}
}
true true
} }
} }
@@ -730,6 +845,17 @@ impl App {
fn handle_poll(&mut self, t: f64, tx: &mut Tx) -> bool { fn handle_poll(&mut self, t: f64, tx: &mut Tx) -> bool {
let mut changed = false; let mut changed = false;
// Being full screen is a state of the window, not only of the review: the view drops
// the title bar and the status bar the moment the review asks for it, and the window
// follows in the same frame. Any way out of the review, or off the screen it was on,
// brings both back.
let full = self.screen == Screen::Review && self.review.fullscreen;
self.review.fullscreen = full;
if full != self.window_full {
self.window_full = full;
tx.toggle_full_screen();
}
for event in self.daemon.drain() { for event in self.daemon.drain() {
changed = true; changed = true;
match (event.request, event.result) { match (event.request, event.result) {
@@ -799,11 +925,13 @@ impl App {
(ipc::Request::StartRecording, Err(e)) => { (ipc::Request::StartRecording, Err(e)) => {
self.notify_error(format!("Cannot start recording: {e}")) self.notify_error(format!("Cannot start recording: {e}"))
} }
(ipc::Request::StopRecording, Ok(_)) => { (ipc::Request::StopRecording, Ok(data)) => {
self.notify("Recording stopped"); screens::recording::stopped(self, &data);
self.refresh_games();
} }
(ipc::Request::StopRecording, Err(e)) => { (ipc::Request::StopRecording, Err(e)) => {
// The stop never happened, so nothing was written: a "stop and delete" that
// failed must not turn into a plain stop later.
self.recording.deleting = false;
self.notify_error(format!("Cannot stop recording: {e}")) self.notify_error(format!("Cannot stop recording: {e}"))
} }
(ipc::Request::Logs, Ok(data)) => { (ipc::Request::Logs, Ok(data)) => {
@@ -996,13 +1124,22 @@ impl App {
// Keep the clock running so the status stays live even when nothing draws. // Keep the clock running so the status stays live even when nothing draws.
tx.wake_after(Duration::from_millis(1000)); tx.wake_after(Duration::from_millis(1000));
// The clip view plays its file; leaving the screen behind stops it with the view. // The clip view plays its file; leaving it for good stops it with the view. It stays
if self.screen != Screen::Clip && self.clip.take().is_some() { // under the review, so back returns to the clip paused where it was.
if self.screen != Screen::Clip
&& !self.behind.contains(&Screen::Clip)
&& self.clip.take().is_some()
{
changed = true; changed = true;
} }
if self.screen == Screen::Review { if self.screen == Screen::Review {
changed |= screens::review::tick(self, tx); changed |= screens::review::tick(self, tx);
} }
// The recording screen reads the game and the disk; it only does it while it shows,
// and reads them again on the way back in.
if self.screen == Screen::Recording {
changed |= screens::recording::tick(self, t);
}
changed |= screens::clip::tick(self, tx); changed |= screens::clip::tick(self, tx);
changed changed
} }
@@ -1030,30 +1167,21 @@ pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool {
let command = event.mods.ctrl || event.mods.cmd; let command = event.mods.ctrl || event.mods.cmd;
match (&event.key, command) { match (&event.key, command) {
(Key::Text(t), false) if t == "1" => { (Key::Text(t), false) if t == "1" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None; app.menu_open = None;
app.clips_menu_open = None; app.clips_menu_open = None;
app.screen = Screen::History; app.jump(Screen::History);
true true
} }
(Key::Text(t), false) if t == "2" => { (Key::Text(t), false) if t == "2" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None; app.menu_open = None;
app.clips_menu_open = None; app.clips_menu_open = None;
app.screen = Screen::Settings; app.jump(Screen::Settings);
true true
} }
(Key::Text(t), false) if t == "3" => { (Key::Text(t), false) if t == "3" => {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.menu_open = None; app.menu_open = None;
app.clips_menu_open = None; app.clips_menu_open = None;
app.screen = Screen::Clips; app.jump(Screen::Clips);
true true
} }
(Key::Escape, _) if app.form.add_open => { (Key::Escape, _) if app.form.add_open => {
@@ -1064,6 +1192,10 @@ pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool {
app.confirm_delete = None; app.confirm_delete = None;
true true
} }
(Key::Escape, _) if app.recording.confirm_delete => {
app.recording.confirm_delete = false;
true
}
(Key::Escape, _) if app.confirm_clip_delete.is_some() => { (Key::Escape, _) if app.confirm_clip_delete.is_some() => {
app.confirm_clip_delete = None; app.confirm_clip_delete = None;
true true
@@ -1072,24 +1204,19 @@ pub fn on_key(app: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool {
app.clips_menu_open = None; app.clips_menu_open = None;
true true
} }
(Key::Escape, _) if app.screen == Screen::Clip => { // A full screen clip leaves the screen it fills before it leaves the screen.
app.menu_open = None; (Key::Escape, _) if app.review.fullscreen => {
app.screen = Screen::Clips; app.review.fullscreen = false;
true true
} }
(Key::Escape, _) if app.screen == Screen::Clips => { (Key::Escape, _) if !app.behind.is_empty() => {
app.menu_open = None; app.menu_open = None;
app.screen = Screen::History; app.clips_menu_open = None;
app.back();
true true
} }
(Key::Escape, _) if app.screen == Screen::Review => { (Key::Text(t), false) if app.screen == Screen::Review && t.eq_ignore_ascii_case("f") => {
screens::review::leave(app); app.review.fullscreen = !app.review.fullscreen;
app.screen = Screen::History;
true
}
(Key::Escape, _) if app.screen == Screen::Settings => {
app.menu_open = None;
app.screen = Screen::History;
true true
} }
(Key::Text(t), true) if t.eq_ignore_ascii_case("r") => { (Key::Text(t), true) if t.eq_ignore_ascii_case("r") => {
@@ -1161,35 +1288,26 @@ fn statusbar(p: Paint, app: &App) -> El {
bar bar
} }
fn titlebar(p: Paint, app: &App) -> El { /// What the back arrow says it returns to.
fn back_label(screen: Screen) -> &'static str {
match screen {
Screen::History => "← Match history",
Screen::Clips => "← Clips",
Screen::Clip => "← Clip",
Screen::Review => "← Game",
Screen::Settings => "← Settings",
Screen::Recording => "← Recording",
}
}
fn titlebar(p: Paint, app: &App, insets: ChromeInsets) -> El {
// Leaving a screen is on the left, where a window's back arrow lives; the app's own // Leaving a screen is on the left, where a window's back arrow lives; the app's own
// actions stay on the right. // actions stay on the right.
let mut leading = row().key("leading").gap(8.0).center_y(); let mut leading = row().key("leading").gap(8.0).center_y();
if matches!( if let Some(behind) = app.behind.last().copied() {
app.screen, leading = leading.child(ui::button(p, "back", back_label(behind), false, |app| {
Screen::Settings | Screen::Clips | Screen::Clip | Screen::Review app.back();
) { }));
let from_clip = app.screen == Screen::Clip;
leading = leading.child(ui::button(
p,
"back",
if from_clip {
"← Clips"
} else {
"← Match history"
},
false,
|app: &mut App| {
if app.screen == Screen::Review {
screens::review::leave(app);
}
app.screen = if app.screen == Screen::Clip {
Screen::Clips
} else {
Screen::History
};
},
));
} }
let leading = leading.child( let leading = leading.child(
text("League Recorder") text("League Recorder")
@@ -1201,6 +1319,20 @@ fn titlebar(p: Paint, app: &App) -> El {
// On the settings screen the title bar has nothing to offer: refreshing and opening // On the settings screen the title bar has nothing to offer: refreshing and opening
// settings again would only repeat what the screen already does. // settings again would only repeat what the screen already does.
if app.screen != Screen::Settings { if app.screen != Screen::Settings {
// A game being recorded is one click away, whatever screen the viewer wandered to.
if app.status.is_recording && app.screen != Screen::Recording {
actions = actions.child(ui::button(
p,
"open-recording",
"Recording",
false,
|app: &mut App| {
app.menu_open = None;
app.clips_menu_open = None;
app.jump(Screen::Recording);
},
));
}
if !matches!(app.screen, Screen::Clips | Screen::Clip) { if !matches!(app.screen, Screen::Clips | Screen::Clip) {
actions = actions.child(ui::button( actions = actions.child(ui::button(
p, p,
@@ -1210,8 +1342,7 @@ fn titlebar(p: Paint, app: &App) -> El {
|app: &mut App| { |app: &mut App| {
app.menu_open = None; app.menu_open = None;
app.clips_menu_open = None; app.clips_menu_open = None;
screens::review::leave(app); app.jump(Screen::Clips);
app.screen = Screen::Clips;
}, },
)); ));
} }
@@ -1237,16 +1368,18 @@ fn titlebar(p: Paint, app: &App) -> El {
false, false,
|app: &mut App| { |app: &mut App| {
app.menu_open = None; app.menu_open = None;
screens::review::leave(app); app.jump(Screen::Settings);
app.screen = Screen::Settings;
}, },
)); ));
} }
row() row()
.key("titlebar") .key("titlebar")
.h(48.0) .h(TITLEBAR_HEIGHT)
.w_full() .w_full()
.px(16.0) // What the window's controls take: the traffic lights on macOS, the caption buttons on
// Windows, which are drawn over this band.
.pl(16.0 + insets.leading)
.pr(16.0 + insets.trailing)
.gap(8.0) .gap(8.0)
.center_y() .center_y()
.justify_between() .justify_between()
@@ -1290,15 +1423,24 @@ fn notice(p: Paint, notice: &Notice) -> El {
pub fn view(app: &App, cx: &mut Cx<App>) -> El { pub fn view(app: &App, cx: &mut Cx<App>) -> El {
let p = Paint::new(app.dark, cx.env().scale); let p = Paint::new(app.dark, cx.env().scale);
// The window's own controls sit over the title bar and take its ink: the caption buttons
// on Windows, the traffic lights on macOS.
cx.caption_color(p.t.text);
// Menus and dialogs cover the whole window, title bar and status bar included: the // Menus and dialogs cover the whole window, title bar and status bar included: the
// history row menus, the add-application form and the delete confirmation. // history row menus, the add-application form and the delete confirmation.
let mut overlays = Vec::new(); let mut overlays = Vec::new();
// A full screen review is the picture alone: the title bar and the status bar would draw
// on it, and the window has no frame to hold them.
if app.screen == Screen::Review && app.review.fullscreen {
return rune_kit::root(screens::review::fullscreen(app, p), overlays);
}
let content = match app.screen { let content = match app.screen {
Screen::Settings => screens::settings::view(app, p), Screen::Settings => screens::settings::view(app, p),
Screen::History => screens::history::view(app, p, &mut overlays), Screen::History => screens::history::view(app, p, &mut overlays),
Screen::Clips => screens::clips::view(app, p, &mut overlays), Screen::Clips => screens::clips::view(app, p, &mut overlays),
Screen::Clip => screens::clip::view(app, p), Screen::Clip => screens::clip::view(app, p),
Screen::Review => screens::review::view(app, p), Screen::Review => screens::review::view(app, p),
Screen::Recording => screens::recording::view(app, p),
}; };
let mut main = col().key("main").grow(1.0).min_h(0.0).w_full().fill(p.t.bg); let mut main = col().key("main").grow(1.0).min_h(0.0).w_full().fill(p.t.bg);
if let Some(banner) = &app.notice { if let Some(banner) = &app.notice {
@@ -1310,7 +1452,7 @@ pub fn view(app: &App, cx: &mut Cx<App>) -> El {
.w_full() .w_full()
.h_full() .h_full()
.fill(p.t.bg) .fill(p.t.bg)
.child(titlebar(p, app)) .child(titlebar(p, app, cx.chrome_insets()))
.child(main) .child(main)
.child(statusbar(p, app)); .child(statusbar(p, app));
let content = match app.screen { let content = match app.screen {
@@ -1324,6 +1466,16 @@ pub fn view(app: &App, cx: &mut Cx<App>) -> El {
.child(app.events_scroll.thumb(p, "events-thumb", "event-scroller")), .child(app.events_scroll.thumb(p, "events-thumb", "event-scroller")),
Screen::Review => window, Screen::Review => window,
Screen::Clips => window.child(app.clips_scroll.thumb(p, "clips-thumb", "clips-scroller")), Screen::Clips => window.child(app.clips_scroll.thumb(p, "clips-thumb", "clips-scroller")),
Screen::Recording => window.child(app.recording_scroll.thumb(
p,
"recording-thumb",
"recording-scroller",
)),
// The Advanced tab puts the log box inside the settings scroller, so it draws a second
// thumb, and only while that tab is up: the box leaves the window with the tab.
Screen::Settings if app.settings_tab == SettingsTab::Advanced => window
.child(app.scroll.thumb(p, "scroll-thumb", "scroller"))
.child(app.log_scroll.thumb(p, "log-thumb", "log-scroller")),
Screen::Settings => window.child(app.scroll.thumb(p, "scroll-thumb", "scroller")), Screen::Settings => window.child(app.scroll.thumb(p, "scroll-thumb", "scroller")),
Screen::History => window.child(app.scroll.thumb(p, "scroll-thumb", "list-scroller")), Screen::History => window.child(app.scroll.thumb(p, "scroll-thumb", "list-scroller")),
// A clip fills its screen with a player, not a list: the history or settings thumb would // A clip fills its screen with a player, not a list: the history or settings thumb would
@@ -1339,6 +1491,9 @@ pub fn view(app: &App, cx: &mut Cx<App>) -> El {
if app.confirm_clip_delete.is_some() { if app.confirm_clip_delete.is_some() {
screens::clips::delete_dialog(app, p, &mut overlays); screens::clips::delete_dialog(app, p, &mut overlays);
} }
if app.recording.confirm_delete {
screens::recording::confirm_dialog(app, p, &mut overlays);
}
rune_kit::root(content, overlays) rune_kit::root(content, overlays)
} }
@@ -1361,7 +1516,7 @@ pub fn headless() -> bool {
/// Put the first sample game on the review screen, for `--scene review`. /// Put the first sample game on the review screen, for `--scene review`.
pub fn demo_review(app: &mut App) { pub fn demo_review(app: &mut App) {
app.screen = Screen::Review; app.go(Screen::Review);
if app.games.is_empty() { if app.games.is_empty() {
// Opened before the history finished loading: `poll` opens it once it has. // Opened before the history finished loading: `poll` opens it once it has.
app.pending_review = true; app.pending_review = true;
+106 -10
View File
@@ -1,6 +1,6 @@
//! Finding, starting and logging the record-daemon process. //! 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 //! Ported from the old Tauri app's `daemon_ipc.rs`. The daemon binary ships next to the
//! app; inside a checkout it is found in `record-daemon/target/{release,debug}`. //! app; inside a checkout it is found in `record-daemon/target/{release,debug}`.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -34,11 +34,20 @@ pub fn recordings_dir() -> PathBuf {
.unwrap_or_else(|| PathBuf::from("./recordings")) .unwrap_or_else(|| PathBuf::from("./recordings"))
} }
/// Where the daemon writes its log. /// The folder the daemon keeps its daily logs in.
pub fn log_file() -> Option<PathBuf> { pub fn log_dir() -> Option<PathBuf> {
let dir = data_dir()?.join("logs"); let dir = data_dir()?.join("logs");
std::fs::create_dir_all(&dir).ok()?; std::fs::create_dir_all(&dir).ok()?;
Some(dir.join("daemon.log")) Some(dir)
}
/// The `--log-file` the app starts the daemon with.
///
/// The daemon takes the stem of the path and adds the date and the extension (see `init_logging`
/// in `record-daemon/src/main.rs`), so it writes `daemon.YYYY-MM-DD.log` beside this path
/// rather than the path itself.
pub fn log_file() -> Option<PathBuf> {
Some(log_dir()?.join("daemon.log"))
} }
/// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a /// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a
@@ -147,20 +156,68 @@ pub async fn ensure_running() -> Result<(), String> {
} }
} }
/// The last `n` lines of the daemon log. /// The last `n` lines of the log the daemon is writing now.
pub fn read_logs(n: usize) -> Result<String, String> { 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 path = current_log().ok_or_else(|| "the recorder has written no log yet".to_string())?;
let text = std::fs::read_to_string(&path) let text = std::fs::read_to_string(&path)
.map_err(|e| format!("cannot read {}: {e}", path.display()))?; .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
let lines: Vec<&str> = text.lines().rev().take(n).collect(); let lines: Vec<String> = text.lines().rev().take(n).map(strip_ansi).collect();
Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n")) Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n"))
} }
/// The log path as text, for the About tab. /// What a log line says without the color codes.
///
/// The daemon used to write ANSI escapes into the file, so lines from before that fix carry
/// them. `ESC [ params final` is the only form tracing emitted.
fn strip_ansi(line: &str) -> String {
if !line.contains('\u{1b}') {
return line.to_string();
}
let mut out = String::with_capacity(line.len());
let mut chars = line.chars();
while let Some(c) = chars.next() {
if c != '\u{1b}' {
out.push(c);
} else if chars.next() == Some('[') {
for c in chars.by_ref() {
if ('@'..='~').contains(&c) {
break;
}
}
}
}
out
}
/// The log file the daemon is appending to now, as text for the Advanced tab.
pub fn log_path() -> String { pub fn log_path() -> String {
log_file() current_log()
.map(|p| p.display().to_string()) .map(|p| p.display().to_string())
.unwrap_or_default() .unwrap_or_else(|| "None yet".to_string())
}
/// The log file the daemon is appending to now.
pub fn current_log() -> Option<PathBuf> {
let dir = data_dir()?.join("logs");
newest_log(&dir)
}
/// The newest daily file in the logs folder.
///
/// The daemon rolls the log over at midnight, so the folder holds one file per day and the
/// newest is the one still being written. The date in the name is in ISO order, so comparing
/// names finds it without reading each file's timestamp.
fn newest_log(dir: &Path) -> Option<PathBuf> {
std::fs::read_dir(dir)
.ok()?
.filter_map(|entry| {
let path = entry.ok()?.path();
let name = path.file_name()?.to_str()?;
let date = name.strip_prefix("daemon.")?.strip_suffix(".log")?;
date.starts_with(|c: char| c.is_ascii_digit())
.then_some(path)
})
.max()
} }
/// Open a folder. /// Open a folder.
@@ -172,3 +229,42 @@ pub fn open_folder(path: &Path) {
#[cfg(not(windows))] #[cfg(not(windows))]
let _ = path; let _ = path;
} }
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir() -> PathBuf {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn the_newest_day_is_the_log_the_daemon_writes() {
let dir = temp_dir();
std::fs::write(dir.join("daemon.2026-11-21.log"), "yesterday").unwrap();
let today = dir.join("daemon.2026-11-22.log");
std::fs::write(&today, "today").unwrap();
std::fs::write(dir.join("notes.txt"), "not a log").unwrap();
assert_eq!(newest_log(&dir), Some(today));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_folder_without_a_log_has_no_log_to_read() {
let dir = temp_dir();
assert_eq!(newest_log(&dir), None);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_log_line_loses_its_color_codes() {
let line =
"\u{1b}[2m2026-11-23T23:06:51Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m record_daemon: ready";
assert_eq!(
strip_ansi(line),
"2026-11-23T23:06:51Z INFO record_daemon: ready"
);
}
}
+46 -1
View File
@@ -1,5 +1,5 @@
//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in //! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in
//! `tauri-app/src-tauri/src/lib.rs`. //! the old Tauri app's `lib.rs`.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Mutex; use std::sync::Mutex;
@@ -30,6 +30,9 @@ pub struct Clip {
pub bytes: u64, pub bytes: u64,
/// The miniature cut from the video, when one is on disk and as new as the clip. /// The miniature cut from the video, when one is on disk and as new as the clip.
pub thumb: Option<PathBuf>, pub thumb: Option<PathBuf>,
/// The recording the clip was cut from, from the file a rename leaves beside it. A clip
/// still named as it was exported carries the id in its name instead.
pub recording_id: Option<String>,
} }
/// Where the clips' miniatures live, beside the clips. /// Where the clips' miniatures live, beside the clips.
@@ -146,6 +149,7 @@ pub fn list_clips() -> Vec<Clip> {
exported: meta.modified().ok(), exported: meta.modified().ok(),
bytes: meta.len(), bytes: meta.len(),
thumb: None, thumb: None,
recording_id: recording_link(&path),
}; };
clip.thumb = thumb_of(&clip); clip.thumb = thumb_of(&clip);
Some(clip) Some(clip)
@@ -155,6 +159,28 @@ pub fn list_clips() -> Vec<Clip> {
clips clips
} }
/// The file beside a clip that names the recording it was cut from.
///
/// The export writes the recording's id into the clip's name, and the name is the user's to
/// change. A clip renamed in the app carries this file instead, so a screen that leads back to
/// the game still finds it.
pub fn link_path(clip: &Path) -> PathBuf {
clip.with_extension("json")
}
/// Name the recording beside `clip`. True when the file landed.
pub fn link_recording(clip: &Path, recording_id: &str) -> bool {
let text = serde_json::json!({ "recording_id": recording_id }).to_string();
std::fs::write(link_path(clip), text).is_ok()
}
/// The recording `clip`'s link file names, when one sits beside it.
pub fn recording_link(clip: &Path) -> Option<String> {
let text = std::fs::read_to_string(link_path(clip)).ok()?;
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
value.get("recording_id")?.as_str().map(str::to_string)
}
/// The clips folder beside the recordings. /// The clips folder beside the recordings.
pub fn clips_dir() -> PathBuf { pub fn clips_dir() -> PathBuf {
let dir = daemon::recordings_dir().join("clips"); let dir = daemon::recordings_dir().join("clips");
@@ -437,3 +463,22 @@ fn sanitize(name: &str) -> String {
}) })
.collect() .collect()
} }
#[cfg(test)]
mod tests {
use super::{link_path, link_recording, recording_link};
use std::path::Path;
#[test]
fn a_link_file_names_the_recording_beside_its_clip() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let clip = dir.join("My Ace.mp4");
std::fs::write(&clip, b"").unwrap();
assert_eq!(link_path(&clip), Path::new(&dir).join("My Ace.json"));
assert_eq!(recording_link(&clip), None);
assert!(link_recording(&clip, "demo-1"));
assert_eq!(recording_link(&clip).as_deref(), Some("demo-1"));
let _ = std::fs::remove_dir_all(&dir);
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
//! Text formatting shared by the screens, matching `tauri-app/src/types/timeline.ts`. //! Text formatting shared by the screens, matching the old Tauri app's `types/timeline.ts`.
use chrono::{DateTime, Local, Utc}; use chrono::{DateTime, Local, Utc};
+1 -1
View File
@@ -1,5 +1,5 @@
//! Highlight clips from timeline events, ported from `computeHighlights` in //! Highlight clips from timeline events, ported from `computeHighlights` in
//! `tauri-app/src/types/timeline.ts`. //! the old Tauri app's `types/timeline.ts`.
use crate::history::{Timeline, TimelineEvent}; use crate::history::{Timeline, TimelineEvent};
+345 -5
View File
@@ -1,7 +1,7 @@
//! Reading the daemon's timelines from disk and the values the screens show. //! 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`, //! Ported from the old Tauri app's `lib.rs` (`get_game_history`, `get_timeline`,
//! `find_video_file`) and the extractors in `tauri-app/src/types/timeline.ts`. //! `find_video_file`) and the extractors in its `types/timeline.ts`.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@@ -147,8 +147,11 @@ pub fn timeline_dir() -> PathBuf {
/// recording is written when its game ends, which matches when it started closely enough for /// recording is written when its game ends, which matches when it started closely enough for
/// a list that gets re-sorted by `start_time` as pages arrive. /// a list that gets re-sorted by `start_time` as pages arrive.
pub fn timeline_paths() -> Vec<PathBuf> { pub fn timeline_paths() -> Vec<PathBuf> {
let dir = timeline_dir(); paths_in(&timeline_dir())
let Ok(entries) = std::fs::read_dir(&dir) else { }
fn paths_in(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new(); return Vec::new();
}; };
let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
@@ -176,7 +179,10 @@ pub fn summaries(paths: &[PathBuf]) -> Vec<Summary> {
fn summary_of(path: &Path) -> Option<Summary> { fn summary_of(path: &Path) -> Option<Summary> {
let text = std::fs::read_to_string(path).ok()?; let text = std::fs::read_to_string(path).ok()?;
match serde_json::from_str::<Timeline>(&text) { match serde_json::from_str::<Timeline>(&text) {
Ok(timeline) => Some(timeline.summary()), // A game the recorder is still writing has no end yet: it is the recording screen's,
// and Match history is what has been recorded.
Ok(timeline) if timeline.end_time.is_some() => Some(timeline.summary()),
Ok(_) => None,
Err(e) => { Err(e) => {
eprintln!("skipping {}: {e}", path.display()); eprintln!("skipping {}: {e}", path.display());
None None
@@ -300,6 +306,197 @@ fn delete_in(recording_id: &str, video: Option<&Path>, recordings: &Path) -> Res
Ok(()) Ok(())
} }
/// The timeline a recording is being written into: the newest file with no end yet.
///
/// The recorder opens a timeline when a game starts and writes its end when it stops, so a
/// file without `end_time` is a game that is still going. The game id picks it out when the
/// client reported one; the newest open file is the answer otherwise.
/// The timeline a recording is being written into: the newest file with no end yet.
///
/// The recorder opens a timeline when a game starts and writes its end when it stops, so a
/// file without `end_time` is a game that is still going. The game id picks it out when the
/// client reported one; the newest open file is the answer otherwise.
pub fn open_timeline(game_id: Option<u64>) -> Option<(PathBuf, Timeline)> {
open_in(&timeline_dir(), game_id)
}
fn open_in(dir: &Path, game_id: Option<u64>) -> Option<(PathBuf, Timeline)> {
let mut newest = None;
// The file being written is the newest. One left open by an earlier stop can only be
// older than everything written since, so a few of the newest is enough.
for path in paths_in(dir).into_iter().take(4) {
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(timeline) = serde_json::from_str::<Timeline>(&text) else {
continue;
};
if timeline.end_time.is_some() {
continue;
}
if game_id.is_none() || timeline.game_id == game_id {
return Some((path, timeline));
}
if newest.is_none() {
newest = Some((path, timeline));
}
}
newest
}
/// The clip a recording is writing into `dir`, with the bytes on disk so far.
///
/// The recorder names the file when it starts and only reports it when it stops, so the file
/// is found rather than asked for: the newest one of the container the settings name that was
/// written since the recording began. `None` until it exists, and in a folder the recorder
/// writes nothing to.
pub fn writing_file(dir: &Path, container: &str, since: DateTime<Utc>) -> Option<(PathBuf, u64)> {
let since: std::time::SystemTime = (since - chrono::Duration::minutes(2)).into();
let entries = std::fs::read_dir(dir).ok()?;
let mut newest: Option<(std::time::SystemTime, PathBuf, u64)> = None;
for entry in entries.flatten() {
let path = entry.path();
if !path.is_file() {
continue;
}
let ours = path
.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| e.eq_ignore_ascii_case(container));
if !ours {
continue;
}
let Ok(meta) = entry.metadata() else {
continue;
};
let Ok(written) = meta.modified() else {
continue;
};
if written < since {
continue;
}
if newest.as_ref().is_none_or(|(at, _, _)| written > *at) {
newest = Some((written, path, meta.len()));
}
}
newest.map(|(_, path, bytes)| (path, bytes))
}
/// Finish the timeline the recorder left open for a game the app stopped.
///
/// A game the recorder ends by itself is finalized: one timeline with the game, the video and
/// the end. Stopped over the protocol it writes the video into a new timeline and leaves the
/// open one behind, so Match history would show two rows for one game: a game that never
/// happened, and one with a video but no champion or queue. What the open timeline knows
/// moves to the one holding the video, and the leftover is deleted.
///
/// `discard` is the app's "stop and delete": the video goes with both timelines, so a game
/// stopped that way leaves nothing behind at all.
pub fn close_stopped(open: Option<&Path>, video: &Path, discard: bool) -> Result<(), String> {
close_stopped_in(&timeline_dir(), open, video, discard)
}
fn close_stopped_in(
dir: &Path,
open: Option<&Path>,
video: &Path,
discard: bool,
) -> Result<(), String> {
let held = timeline_for_video(dir, video);
if discard {
let mut failed = None;
let files = [
held.map(|(path, _)| path),
Some(video.to_path_buf()),
open.map(Path::to_path_buf),
];
for path in files.into_iter().flatten() {
if let Err(e) = remove(&path) {
failed.get_or_insert(e);
}
}
return failed.map_or(Ok(()), Err);
}
let (Some(open), Some((held, mut finished))) = (open, held) else {
return Ok(());
};
if held == open {
// The recorder finished this timeline itself: there is nothing to move.
return Ok(());
}
let text = std::fs::read_to_string(open)
.map_err(|e| format!("could not read {}: {e}", open.display()))?;
let game: Value = serde_json::from_str(&text)
.map_err(|e| format!("{} is not a timeline: {e}", open.display()))?;
// A file left open by some other game is not this one's to finish: merging two recordings
// would name one game with another's video.
let wanted = finished.get("game_id").and_then(Value::as_u64);
let offered = game.get("game_id").and_then(Value::as_u64);
if wanted.is_some() && offered.is_some() && wanted != offered {
return Ok(());
}
// The fields the recorder fills in when a game starts, which only the open timeline
// holds: everything a row names the game by.
for key in [
"game_id",
"raw_session",
"raw_summoner",
"raw_champion_select",
"raw_rune_page",
"raw_live_client_data",
] {
if finished.get(key).is_none_or(Value::is_null)
&& let Some(value) = game.get(key)
{
finished[key] = value.clone();
}
}
let json = serde_json::to_string_pretty(&finished)
.map_err(|e| format!("could not write {}: {e}", held.display()))?;
std::fs::write(&held, json).map_err(|e| format!("could not write {}: {e}", held.display()))?;
remove(open)
}
/// The timeline holding `video`, with its JSON, as the recorder writes it when it stops.
///
/// The clip's file name ties the two together: the recorder stores it in the timeline it
/// wrote for that clip.
fn timeline_for_video(dir: &Path, video: &Path) -> Option<(PathBuf, Value)> {
let name = video.file_name()?.to_str()?;
let entries = std::fs::read_dir(dir).ok()?;
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(value) = serde_json::from_str::<Value>(&text) else {
continue;
};
let stored = value.get("video_file").and_then(Value::as_str).or_else(|| {
value
.get("video_path")
.and_then(Value::as_str)
.and_then(|path| Path::new(path).file_name())
.and_then(|name| name.to_str())
});
if stored == Some(name) {
return Some((path, value));
}
}
None
}
/// Remove a file, saying which one could not go.
fn remove(path: &Path) -> Result<(), String> {
if !path.exists() {
return Ok(());
}
std::fs::remove_file(path).map_err(|e| format!("could not delete {}: {e}", path.display()))
}
impl Timeline { impl Timeline {
fn end_stats(&self) -> Option<&Value> { fn end_stats(&self) -> Option<&Value> {
self.raw_end_game_stats.as_ref() self.raw_end_game_stats.as_ref()
@@ -825,4 +1022,147 @@ mod tests {
let _ = std::fs::remove_dir_all(dir); let _ = std::fs::remove_dir_all(dir);
} }
/// A timeline the recorder opened for a game, without an end yet.
fn open_game(game_id: u64, champion: &str) -> String {
serde_json::json!({
"recording_id": uuid::Uuid::new_v4().to_string(),
"start_time": "2026-03-27T16:42:52Z",
"end_time": null,
"duration_secs": 0,
"events": [],
"game_id": game_id,
"raw_session": {"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}},
"raw_summoner": {"gameName": "Demo", "tagLine": "EUW"},
"raw_live_client_data": {"activePlayer": {"championName": champion}},
"video_file": null
})
.to_string()
}
fn write_timeline(dir: &Path, name: &str, json: &str) -> PathBuf {
let path = dir.join(format!("{name}.json"));
std::fs::write(&path, json).unwrap();
path
}
fn temp_dir() -> PathBuf {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn the_game_being_recorded_is_the_timeline_without_an_end() {
let dir = temp_dir();
write_timeline(&dir, "finished", TIMELINE);
// Written last, so it is the newest: the game the recorder is writing.
let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa"));
assert_eq!(
open_in(&dir, Some(70)).map(|(path, _)| path),
Some(open.clone())
);
// The game id of a game that is not open falls back to the newest open file.
assert_eq!(open_in(&dir, Some(99)).map(|(path, _)| path), Some(open));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_game_still_being_recorded_is_not_in_the_history() {
let dir = temp_dir();
let finished = write_timeline(&dir, "finished", TIMELINE);
let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa"));
let rows = summaries(&[finished, open]);
assert_eq!(rows.len(), 1, "only the game that ended has a row");
assert_eq!(rows[0].recording_id, parsed().recording_id);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_stop_from_the_app_moves_the_game_onto_its_video() {
let dir = temp_dir();
let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa"));
// What the recorder writes when it stops over the protocol: the video, and no game.
let stopped = write_timeline(
&dir,
"stopped",
&serde_json::json!({
"recording_id": uuid::Uuid::new_v4().to_string(),
"start_time": "2026-03-27T16:42:52Z",
"end_time": "2026-03-27T16:55:00Z",
"duration_secs": 728,
"events": [],
"game_id": 70,
"video_file": "2026-03-27_16-42-52_7000000.mp4",
"video_path": "C:/clips/2026-03-27_16-42-52_7000000.mp4"
})
.to_string(),
);
let video = Path::new("C:/clips/2026-03-27_16-42-52_7000000.mp4");
close_stopped_in(&dir, Some(&open), video, false).unwrap();
assert!(!open.exists(), "the leftover timeline is deleted");
let merged: Value =
serde_json::from_str(&std::fs::read_to_string(&stopped).unwrap()).unwrap();
let game = Timeline {
raw_session: merged.get("raw_session").cloned(),
raw_summoner: merged.get("raw_summoner").cloned(),
..parsed()
};
assert_eq!(game.champion().as_deref(), Some("Kai'Sa"));
assert_eq!(game.summoner().as_deref(), Some("Demo#EUW"));
assert_eq!(game.queue_label(), "Ranked Solo");
// What the recorder wrote stays: the video and the end.
assert_eq!(merged["duration_secs"], 728);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn stopping_and_deleting_takes_the_video_with_both_timelines() {
let dir = temp_dir();
let open = write_timeline(&dir, "open", &open_game(70, "Kai'Sa"));
let stopped = write_timeline(
&dir,
"stopped",
&serde_json::json!({
"recording_id": uuid::Uuid::new_v4().to_string(),
"start_time": "2026-03-27T16:42:52Z",
"end_time": "2026-03-27T16:55:00Z",
"duration_secs": 728,
"events": [],
"game_id": 70,
"video_file": "game.mp4"
})
.to_string(),
);
let clips = temp_dir();
let video = clips.join("game.mp4");
std::fs::write(&video, b"x").unwrap();
close_stopped_in(&dir, Some(&open), &video, true).unwrap();
assert!(!open.exists());
assert!(!stopped.exists());
assert!(!video.exists(), "the clip goes with it");
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(clips);
}
#[test]
fn the_clip_being_written_is_the_newest_of_its_container() {
let dir = temp_dir();
std::fs::write(dir.join("notes.txt"), b"n").unwrap();
std::fs::write(dir.join("old.mp4"), b"old").unwrap();
std::fs::write(dir.join("new.mp4"), b"newer!").unwrap();
let since = Utc::now() - chrono::Duration::minutes(1);
let (path, bytes) = writing_file(&dir, "mp4", since).unwrap();
assert_eq!(path.file_name().and_then(|n| n.to_str()), Some("new.mp4"));
assert_eq!(bytes, 6);
// Nothing was written since a folder scan later than every file: there is nothing to
// name until the recorder starts.
let later = Utc::now() + chrono::Duration::minutes(5);
assert!(writing_file(&dir, "mp4", later).is_none());
let _ = std::fs::remove_dir_all(dir);
}
} }
+1 -1
View File
@@ -1,6 +1,6 @@
//! Client for the record-daemon's IPC protocol. //! 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 //! Ported from the old Tauri app's `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 //! (`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. //! `request` answered by one `response` with the same id.
//! //!
+44 -11
View File
@@ -1,6 +1,6 @@
//! League Recorder: a native desktop app for the record-daemon. //! 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. //! Replaces the old 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. //! `cargo run` opens the window; `cargo run -- --snap out.png` renders it headless.
//! //!
//! The binary is a windowed app on Windows, so launching it from Explorer, the Run key or the //! The binary is a windowed app on Windows, so launching it from Explorer, the Run key or the
@@ -42,6 +42,17 @@ fn attach_console() {}
use rune::AppSpec; use rune::AppSpec;
/// `--scene recording-live`: the daemon recording, with the sample game on the screen.
fn demo_recording(app: &mut app::App) {
app.status = app::Status {
status: "recording".into(),
is_recording: true,
current_game_id: Some(7_000_000),
client_connected: true,
};
screens::recording::demo(app);
}
fn main() { fn main() {
attach_console(); attach_console();
if std::env::args().any(|arg| arg == "--games") { if std::env::args().any(|arg| arg == "--games") {
@@ -82,17 +93,27 @@ fn main() {
rune::App::new(AppSpec { rune::App::new(AppSpec {
scenes: &[ scenes: &[
("history", |_app: &mut app::App| {}), ("history", |_app: &mut app::App| {}),
("settings", |app| app.screen = app::Screen::Settings), ("recording-live", |app| {
demo_recording(app);
app.jump(app::Screen::Recording);
}),
("recording-live-delete", |app| {
demo_recording(app);
app.jump(app::Screen::Recording);
app.recording.confirm_delete = true;
}),
("recording-idle", |app| app.jump(app::Screen::Recording)),
("settings", |app| app.jump(app::Screen::Settings)),
("recording", |app| { ("recording", |app| {
app.screen = app::Screen::Settings; app.jump(app::Screen::Settings);
app.settings_tab = app::SettingsTab::Recording; app.settings_tab = app::SettingsTab::Recording;
}), }),
("audio", |app| { ("audio", |app| {
app.screen = app::Screen::Settings; app.jump(app::Screen::Settings);
app.settings_tab = app::SettingsTab::Audio; app.settings_tab = app::SettingsTab::Audio;
}), }),
("add-app", |app| { ("add-app", |app| {
app.screen = app::Screen::Settings; app.jump(app::Screen::Settings);
app.settings_tab = app::SettingsTab::Audio; app.settings_tab = app::SettingsTab::Audio;
app.form.open_add(); app.form.open_add();
app.form.source_name = rune::TextEdit::new("Discord"); app.form.source_name = rune::TextEdit::new("Discord");
@@ -102,7 +123,7 @@ fn main() {
app.confirm_delete = app.games.first().map(|game| game.recording_id.clone()); app.confirm_delete = app.games.first().map(|game| game.recording_id.clone());
}), }),
("daemon", |app| { ("daemon", |app| {
app.screen = app::Screen::Settings; app.jump(app::Screen::Settings);
app.settings_tab = app::SettingsTab::Advanced; app.settings_tab = app::SettingsTab::Advanced;
}), }),
("review", |app| app::demo_review(app)), ("review", |app| app::demo_review(app)),
@@ -110,13 +131,17 @@ fn main() {
app::demo_review(app); app::demo_review(app);
app.review.show_details = true; app.review.show_details = true;
}), }),
("review-full", |app| {
app::demo_review(app);
app.review.fullscreen = true;
}),
("clips-empty", |app| { ("clips-empty", |app| {
app.screen = app::Screen::Clips; app.jump(app::Screen::Clips);
app.clips.clear(); app.clips.clear();
app.clips_loaded = true; app.clips_loaded = true;
}), }),
("clips", |app| { ("clips", |app| {
app.screen = app::Screen::Clips; app.jump(app::Screen::Clips);
app.clips_menu_open = None; app.clips_menu_open = None;
app.spawn_thumbs(); app.spawn_thumbs();
}), }),
@@ -125,13 +150,15 @@ fn main() {
if app.clips.is_empty() { if app.clips.is_empty() {
app.refresh_clips(); app.refresh_clips();
} }
// The grid is where a clip is opened from: the back arrow leads to it.
app.jump(app::Screen::Clips);
app.spawn_thumbs(); app.spawn_thumbs();
if let Some(first) = app.clips.first().cloned() { if let Some(first) = app.clips.first().cloned() {
screens::clip::open(app, &first.name); screens::clip::open(app, &first.name);
} }
}), }),
("clips-many", |app| { ("clips-many", |app| {
app.screen = app::Screen::Clips; app.jump(app::Screen::Clips);
app.spawn_thumbs(); app.spawn_thumbs();
app.clips = (0..12) app.clips = (0..12)
.flat_map(|page| { .flat_map(|page| {
@@ -145,12 +172,12 @@ fn main() {
app.clips_loaded = true; app.clips_loaded = true;
}), }),
("clips-delete", |app| { ("clips-delete", |app| {
app.screen = app::Screen::Clips; app.jump(app::Screen::Clips);
app.spawn_thumbs(); app.spawn_thumbs();
app.confirm_clip_delete = app.clips.first().map(|clip| clip.name.clone()); app.confirm_clip_delete = app.clips.first().map(|clip| clip.name.clone());
}), }),
("many", |app| { ("many", |app| {
app.screen = app::Screen::History; app.jump(app::Screen::History);
app.games = (0..30) app.games = (0..30)
.flat_map(|_| crate::history::sample()) .flat_map(|_| crate::history::sample())
.map(|game| game.summary()) .map(|game| game.summary())
@@ -161,9 +188,15 @@ fn main() {
setup: Some(app::setup), setup: Some(app::setup),
poll: Some(app::poll), poll: Some(app::poll),
on_key: Some(app::on_key), on_key: Some(app::on_key),
// Narrower than this, the title bar's own buttons would run under the window's
// caption buttons.
min_size: Some((640.0, 480.0)),
..AppSpec::new("League Recorder", (1200.0, 800.0), app::App::new, app::view) ..AppSpec::new("League Recorder", (1200.0, 800.0), app::App::new, app::view)
}) })
.args(args) .args(args)
// The app draws the title bar itself, so the window keeps no native caption: Rune draws the
// caption buttons over the bar's right edge and keeps Windows' resize edges and snap.
.titlebar(rune::Titlebar::new(app::TITLEBAR_HEIGHT))
.keep_running() .keep_running()
.on_close(app::window_closed) .on_close(app::window_closed)
.on_quit(app::window_closed) .on_quit(app::window_closed)
+1 -1
View File
@@ -1,4 +1,4 @@
//! Windows integration that the Tauri app got from plugins: launch at login, one instance, //! Windows integration that the old Tauri app got from plugins: launch at login, one instance,
//! toast notifications and the tray icon. //! toast notifications and the tray icon.
/// The app's reverse-DNS id, used for single-instance and notifications. /// The app's reverse-DNS id, used for single-instance and notifications.
+272 -20
View File
@@ -3,6 +3,7 @@
//! The grid opens it on a card, and an export opens it when the clip lands. The title is //! The grid opens it on a card, and an export opens it when the clip lands. The title is
//! the file's name: saving renames the clip, and the grid follows. //! the file's name: saving renames the clip, and the grid follows.
use std::path::Path;
use std::time::Duration; use std::time::Duration;
use rune::tok::{radius, space, type_}; use rune::tok::{radius, space, type_};
@@ -14,6 +15,7 @@ use rune::{
use crate::app::{App, Screen}; use crate::app::{App, Screen};
use crate::export::{self, Clip}; use crate::export::{self, Clip};
use crate::format; use crate::format;
use crate::history::{self, Outcome, Summary};
use crate::icons; use crate::icons;
use crate::ui::{self, Paint, body, heading}; use crate::ui::{self, Paint, body, heading};
@@ -23,6 +25,9 @@ pub struct ClipView {
pub name: String, pub name: String,
/// The title as it is being typed. Saving turns it into the file's name. /// The title as it is being typed. Saving turns it into the file's name.
pub title: TextEdit, pub title: TextEdit,
/// The recording the clip was cut from, once it is found: the card in the side panel shows
/// it, and the card leads back to it. Kept here so a renamed clip keeps the way back.
pub game: Option<Summary>,
pub player: Option<Player>, pub player: Option<Player>,
/// Shown over the stage when the file refuses to play. /// Shown over the stage when the file refuses to play.
pub error: Option<String>, pub error: Option<String>,
@@ -61,6 +66,7 @@ pub fn open(app: &mut App, name: &str) {
app.clip = Some(ClipView { app.clip = Some(ClipView {
name: clip.name.clone(), name: clip.name.clone(),
title: TextEdit::new(clip.name.clone()), title: TextEdit::new(clip.name.clone()),
game: recording_of(app, &clip),
player: Some(player), player: Some(player),
error: None, error: None,
muted: false, muted: false,
@@ -68,7 +74,51 @@ pub fn open(app: &mut App, name: &str) {
at: 0.0, at: 0.0,
long: 0.0, long: 0.0,
}); });
app.screen = Screen::Clip; app.go(Screen::Clip);
}
/// The recording a clip was cut from.
///
/// A clip the app renamed carries a file naming its recording; one still named as the export
/// left it carries the id in the name. Either way the row comes from the loaded history when it
/// is there, and from the timeline itself when the history has not paged that far, so an old
/// clip still leads back to its game.
fn recording_of(app: &App, clip: &Clip) -> Option<Summary> {
let id = match &clip.recording_id {
Some(id) => id.clone(),
None => recording_id_in_export_name(app, &clip.name)?,
};
if let Some(game) = app.games.iter().find(|game| game.recording_id == id) {
return Some(game.clone());
}
history::load(&id).map(|game| game.summary())
}
/// The recording a clip's export name carries. The export writes the id into the name, so the
/// id is a substring of it; a clip renamed away from that name carries a link file instead.
fn recording_id_in_export_name(app: &App, clip_name: &str) -> Option<String> {
if let Some(game) = app
.games
.iter()
.find(|game| clip_name.contains(&game.recording_id))
{
return Some(game.recording_id.clone());
}
let paths = if app.games_paths.is_empty() {
history::timeline_paths()
} else {
app.games_paths.clone()
};
let ids = paths
.iter()
.filter_map(|path| path.file_stem().and_then(|stem| stem.to_str()));
recording_id(clip_name, ids).map(str::to_string)
}
/// The recording a name carries, from ids the caller has. A substring check: the export appends
/// to the id, and no two ids share a prefix.
fn recording_id<'a>(clip_name: &str, ids: impl Iterator<Item = &'a str>) -> Option<&'a str> {
ids.into_iter().find(|id| clip_name.contains(id))
} }
/// Follow the clip's clock so the bar and the time move, and hand a pending share to the /// Follow the clip's clock so the bar and the time move, and hand a pending share to the
@@ -156,10 +206,19 @@ pub fn save_title(app: &mut App) {
}; };
let (from_thumb, to_thumb) = (export::thumb_path(&clip), export::thumb_path(&renamed)); let (from_thumb, to_thumb) = (export::thumb_path(&clip), export::thumb_path(&renamed));
let _ = std::fs::rename(from_thumb, &to_thumb); let _ = std::fs::rename(from_thumb, &to_thumb);
// The link to the recording follows the file: a new name no longer names it.
let recording = app
.clip
.as_ref()
.and_then(|view| view.game.as_ref())
.map(|game| game.recording_id.clone())
.or_else(|| clip.recording_id.clone());
keep_link(&clip.path, &to, recording.as_deref());
let entry = &mut app.clips[index]; let entry = &mut app.clips[index];
entry.name = wanted.clone(); entry.name = wanted.clone();
entry.path = to; entry.path = to;
entry.thumb = to_thumb.exists().then_some(to_thumb); entry.thumb = to_thumb.exists().then_some(to_thumb);
entry.recording_id = recording;
let view = app.clip.as_mut().expect("checked above"); let view = app.clip.as_mut().expect("checked above");
view.name = wanted; view.name = wanted;
view.title = TextEdit::new(view.name.clone()); view.title = TextEdit::new(view.name.clone());
@@ -167,6 +226,16 @@ pub fn save_title(app: &mut App) {
app.spawn_thumbs(); app.spawn_thumbs();
} }
/// Keep a clip's link to its recording through a move. One already beside the old file moves
/// with it; a clip that has none gets one from `recording`, while the view still knows it.
fn keep_link(from: &Path, to: &Path, recording: Option<&str>) {
if std::fs::rename(export::link_path(from), export::link_path(to)).is_err()
&& let Some(id) = recording
{
export::link_recording(to, id);
}
}
/// The file name for a typed title. Characters a Windows file cannot carry become dashes, /// The file name for a typed title. Characters a Windows file cannot carry become dashes,
/// the edges lose their stray spaces and dots, and the whole stays short enough to show. /// the edges lose their stray spaces and dots, and the whole stays short enough to show.
fn title_name(title: &str) -> String { fn title_name(title: &str) -> String {
@@ -192,27 +261,23 @@ pub fn view(app: &App, p: Paint) -> El {
); );
}; };
let clip = app.clips.iter().find(|clip| clip.name == view.name); let clip = app.clips.iter().find(|clip| clip.name == view.name);
let game = clip.and_then(|clip| { let game = view.game.as_ref();
app.games
.iter()
.find(|game| clip.name.contains(&game.recording_id))
});
let title = game let title = game
.map(|game| game.champion().unwrap_or_else(|| view.name.clone())) .map(|game| game.champion().unwrap_or_else(|| view.name.clone()))
.unwrap_or_else(|| view.name.clone()); .unwrap_or_else(|| view.name.clone());
let detail = match (clip, game) { // The card below says what the game was; this line is what the file is.
(Some(clip), Some(game)) => { let detail = clip
format!("{} · {}", game.queue_label(), format::age(clip.exported)) .map(|clip| {
} format!(
(Some(clip), None) => format!( "{} · {}",
"{} · {}", format::bytes(clip.bytes),
format::bytes(clip.bytes), format::age(clip.exported)
format::age(clip.exported) )
), })
_ => String::new(), .unwrap_or_default();
};
// The player takes the window; the side panel holds the title, the share and the facts. // The player takes the window; the side panel holds the title, the share, and the card
// that leads back to the game the clip was cut from.
let body = row() let body = row()
.key("clip-body") .key("clip-body")
.w_full() .w_full()
@@ -311,7 +376,8 @@ pub fn view(app: &App, p: Paint) -> El {
.unwrap_or_default(); .unwrap_or_default();
request_share(app, &name); request_share(app, &name);
})), })),
), )
.children(game.map(|game| game_card(app, p, game))),
); );
col() col()
.key("clip-view") .key("clip-view")
@@ -322,6 +388,144 @@ pub fn view(app: &App, p: Paint) -> El {
.child(body) .child(body)
} }
/// The card at the foot of the side panel: the champion the clip stars, the scoreline, and the
/// game the clip was cut from. The whole card opens that recording; the arrow marks it as a link.
fn game_card(app: &App, p: Paint, game: &Summary) -> El {
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
let outcome = game.outcome();
let ink = match outcome {
Outcome::Victory => p.success,
Outcome::Defeat => p.danger,
Outcome::Terminated => p.muted(),
};
let stats = game.stats();
let score = stats.as_ref().map_or_else(
|| "0/0/0".to_string(),
|s| format!("{}/{}/{}", s.kills, s.deaths, s.assists),
);
let ratio = stats.as_ref().map_or_else(
|| "0.0".to_string(),
|s| format::kda_ratio(s.kills, s.deaths, s.assists),
);
let queue = game.queue_label().to_string();
let length = format::duration(game.duration_secs.max(0) as f64);
let id = game.recording_id.clone();
let label = format!("Open the game this clip came from: {champion}, {score}, {queue}");
col()
.key("game-card")
.role("button")
.label(label)
.focusable(true)
.w_full()
.padding(space::S3)
.gap(space::S2)
.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| crate::screens::review::open(app, &id))
.child(
row()
.key("card-head")
.w_full()
.gap(space::S2)
.center_y()
.child(ui::champion_portrait(
app,
p,
game.champion().as_deref(),
40.0,
))
.child(
col()
.key("card-who")
.grow(1.0)
.min_w(0.0)
.gap(1.0)
.child(
text(champion)
.key("card-champion")
.font(heading(14.0))
.color(p.t.text)
.shrink()
.truncate(),
)
.child(
text(format!("{queue} · {length}"))
.key("card-queue")
.font(body(11.0))
.color(p.muted())
.shrink()
.truncate(),
),
)
.child(
text(outcome.label())
.key("card-outcome")
.font(type_::LABEL)
.color(ink),
),
)
.child(
row()
.key("card-score")
.w_full()
.center_y()
.gap(space::S2)
.child(
text(score)
.key("card-kda")
.font(heading(17.0))
.color(p.t.text),
)
.child(
text(format!("{ratio} KDA"))
.key("card-ratio")
.font(body(11.0))
.color(p.muted()),
)
.child(el().grow(1.0))
.child(
text(format::relative_time(game.start_time))
.key("card-when")
.font(body(11.0))
.color(p.muted())
.shrink()
.truncate(),
),
)
.child(
el().key("card-sep")
.w_full()
.h(p.hair)
.fill(p.t.separator)
.a11y_hidden(),
)
.child(
row()
.key("card-open")
.w_full()
.center_y()
.justify_between()
.child(
text("Original game")
.key("card-open-label")
.font(type_::LABEL)
.color(p.accent),
)
.child(
text("→")
.key("card-open-arrow")
.font(heading(14.0))
.color(p.accent)
.a11y_hidden(),
),
)
}
/// The stage: the clip on black, the largest 16:9 box that fits, with the controls drawn over /// The stage: the clip on black, the largest 16:9 box that fits, with the controls drawn over
/// it. /// it.
fn video_stage(app: &App, p: Paint) -> El { fn video_stage(app: &App, p: Paint) -> El {
@@ -580,7 +784,55 @@ fn seek(app: &mut App, seconds: f64) {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::title_name; use super::{keep_link, recording_id, title_name};
use crate::export::{link_path, link_recording, recording_link};
#[test]
fn a_renamed_clip_keeps_the_link_to_its_recording() {
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let from = dir.join("demo-1-clip.mp4");
let to = dir.join("My Ace.mp4");
std::fs::write(&from, b"").unwrap();
std::fs::write(&to, b"").unwrap();
// A link from an earlier rename moves with the file.
link_recording(&from, "demo-1");
keep_link(&from, &to, Some("ignored"));
assert_eq!(recording_link(&to).as_deref(), Some("demo-1"));
// A clip exported before links existed gets one from the game the view knows.
std::fs::remove_file(link_path(&to)).unwrap();
keep_link(&from, &to, Some("demo-2"));
assert_eq!(recording_link(&to).as_deref(), Some("demo-2"));
// With no game known there is nothing to write.
std::fs::remove_file(link_path(&to)).unwrap();
keep_link(&from, &to, None);
assert_eq!(recording_link(&to), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_clip_name_carries_the_recording_it_was_cut_from() {
let ids = ["demo-1", "demo-2"].into_iter();
assert_eq!(
recording_id("demo-1-clip", ids.clone()),
Some("demo-1"),
"the export appends to the id"
);
assert_eq!(
recording_id("demo-2-highlight-3", ids.clone()),
Some("demo-2"),
"a highlight carries it too"
);
assert_eq!(
recording_id("pentakill", ids),
None,
"a renamed clip names no recording"
);
}
#[test] #[test]
fn a_title_keeps_its_letters_and_spaces() { fn a_title_keeps_its_letters_and_spaces() {
+14 -6
View File
@@ -127,13 +127,18 @@ struct Card {
impl Card { impl Card {
/// The card for one clip. The game the clip was cut from, when its recording is in the /// The card for one clip. The game the clip was cut from, when its recording is in the
/// loaded history, names the card; otherwise the file does. Export names carry the /// loaded history, names the card; otherwise the file does. The recording comes from the
/// recording's id somewhere in them, so a match is a contains check away. /// clip's link file, or from the export name, which carries the id.
fn of(app: &App, clip: &Clip, index: usize) -> Card { fn of(app: &App, clip: &Clip, index: usize) -> Card {
let game = app let game = clip
.games .recording_id
.iter() .as_deref()
.find(|game| clip.name.contains(&game.recording_id)); .and_then(|id| app.games.iter().find(|game| game.recording_id == id))
.or_else(|| {
app.games
.iter()
.find(|game| clip.name.contains(&game.recording_id))
});
let when = format::age(clip.exported); let when = format::age(clip.exported);
match game { match game {
Some(game) => Card { Some(game) => Card {
@@ -353,6 +358,9 @@ fn delete_confirmed(app: &mut App) {
}; };
let clip = app.clips.remove(index); let clip = app.clips.remove(index);
let _ = std::fs::remove_file(crate::export::thumb_path(&clip)); let _ = std::fs::remove_file(crate::export::thumb_path(&clip));
if !clip.path.as_os_str().is_empty() {
let _ = std::fs::remove_file(crate::export::link_path(&clip.path));
}
match std::fs::remove_file(&clip.path) { match std::fs::remove_file(&clip.path) {
Ok(()) => app.notify("Clip deleted"), Ok(()) => app.notify("Clip deleted"),
Err(error) => { Err(error) => {
+3 -1
View File
@@ -1,7 +1,9 @@
//! The screens: settings, match history, the clips grid, one open clip and the game review. //! The screens: settings, match history, the clips grid, one open clip, the game review and
//! the recording in progress.
pub mod clip; pub mod clip;
pub mod clips; pub mod clips;
pub mod history; pub mod history;
pub mod recording;
pub mod review; pub mod review;
pub mod settings; pub mod settings;
File diff suppressed because it is too large. Load diff
+145 -49
View File
@@ -47,6 +47,9 @@ pub struct Review {
/// move under the pointer. /// move under the pointer.
pub frozen_window: Option<(f64, f64)>, pub frozen_window: Option<(f64, f64)>,
pub show_details: bool, pub show_details: bool,
/// The window fills the display and the picture fills the window, with the controls over
/// its bottom: entered from the transport, a double press on the picture, or F.
pub fullscreen: bool,
pub highlights: Vec<Highlight>, pub highlights: Vec<Highlight>,
/// The clip being chosen on the scrubber, once the Clip button is pressed. /// The clip being chosen on the scrubber, once the Clip button is pressed.
pub clip: Option<Clip>, pub clip: Option<Clip>,
@@ -379,6 +382,7 @@ impl Default for Review {
highlights: Vec::new(), highlights: Vec::new(),
clip: None, clip: None,
show_details: false, show_details: false,
fullscreen: false,
export: None, export: None,
export_note: None, export_note: None,
error: None, error: None,
@@ -398,7 +402,7 @@ impl Default for Review {
/// [`show`] when it arrives. /// [`show`] when it arrives.
pub fn open(app: &mut App, recording_id: &str) { pub fn open(app: &mut App, recording_id: &str) {
leave(app); leave(app);
app.screen = Screen::Review; app.go(Screen::Review);
app.review.loading = true; app.review.loading = true;
let id = recording_id.to_string(); let id = recording_id.to_string();
@@ -501,6 +505,7 @@ pub fn leave(app: &mut App) {
app.review.error = None; app.review.error = None;
app.review.export_note = None; app.review.export_note = None;
app.review.export = None; app.review.export = None;
app.review.fullscreen = false;
} }
/// Called from `poll` while the review screen is up. /// Called from `poll` while the review screen is up.
/// Sound from a second player drifts from the pictures by a few milliseconds a minute. Past a /// Sound from a second player drifts from the pictures by a few milliseconds a minute. Past a
@@ -583,8 +588,7 @@ pub fn tick(app: &mut App, tx: &mut Tx) -> bool {
.file_stem() .file_stem()
.and_then(|stem| stem.to_str()) .and_then(|stem| stem.to_str())
{ {
// The review's soundtrack would keep playing under the clip view. // The clip view takes over the sound, and the review waits behind it.
leave(app);
app.refresh_clips(); app.refresh_clips();
crate::screens::clip::open(app, name); crate::screens::clip::open(app, name);
} }
@@ -710,6 +714,81 @@ pub fn view(app: &App, p: Paint) -> El {
.child(body) .child(body)
} }
/// The picture filling the window, with the controls over its bottom. The picture is the whole
/// screen, so the controls keep to their band: the pointer finds them there, and 200 ms after it
/// arrives they draw in, 400 ms after it leaves they are gone again.
pub fn fullscreen(app: &App, p: Paint) -> El {
let stage = el()
.key("fullscreen-stage")
.w_full()
.h_full()
.fill(rune::Color::BLACK)
.center();
// A double press on the picture leaves the full screen, as it enters one. It sits on the
// picture, not the stage, so the controls over it keep their own presses.
let stage = match &app.review.player {
Some(player) => stage.child(
el().key("video")
.aspect_fit(16.0 / 9.0)
.video(player, SurfaceFit::Fill)
.on_double_press(|app: &mut App| app.review.fullscreen = false),
),
None => stage.child(
text(
app.review
.error
.clone()
.unwrap_or_else(|| "Loading the clip…".into()),
)
.key("stage-message")
.font(body(13.0))
.color(p.muted()),
),
};
// A band on the bottom of the picture, not a sheet over all of it: the gradient reaches
// black under the transport and is already gone a hand's width above the scrubber, so the
// picture shows at its own brightness on every display. The band is the hover group, so the
// pointer has to come to the controls for them to show, and leaving them puts them away.
let band = col()
.key("fullscreen-controls")
.pin(Some(0.0), None, Some(0.0), Some(0.0))
.hover_group()
.hover_motion(
rune::Spring::smooth(0.2, 0.0),
rune::Spring::smooth(0.4, 0.0),
);
let mut controls = col()
.key("fullscreen-bar")
.w_full()
.gap(space::S2)
.px(space::S6)
.pt(space::S6)
.pb(space::S3)
.gradient(rune::Color::TRANSPARENT, rune::Color::BLACK.alpha(0.8))
.group_opacity(0.0, 1.0);
if let Some(game) = app.reviewed() {
controls = controls.child(scrubber(app, p, game));
}
controls = controls.child(
row()
.key("fullscreen-transport")
.w_full()
.center_y()
.gap(space::S2)
.child(playback(app, p))
.child(volume(app, p))
.child(el().grow(1.0))
.child(ui::button(
p,
"exit-fullscreen",
"Exit full screen",
false,
|app: &mut App| app.review.fullscreen = false,
)),
);
stage.child(band.child(controls))
}
/// The clip itself: the largest 16:9 box that fits, on black, with a message when there is no /// The clip itself: the largest 16:9 box that fits, on black, with a message when there is no
/// file to play. /// file to play.
fn video_stage(app: &App, p: Paint) -> El { fn video_stage(app: &App, p: Paint) -> El {
@@ -721,7 +800,8 @@ fn video_stage(app: &App, p: Paint) -> El {
.fill(rune::Color::BLACK) .fill(rune::Color::BLACK)
.radius(radius::LG) .radius(radius::LG)
.clip_soft(radius::LG) .clip_soft(radius::LG)
.center(); .center()
.on_double_press(|app: &mut App| app.review.fullscreen = true);
match &app.review.player { match &app.review.player {
Some(player) => stage.child( Some(player) => stage.child(
@@ -783,6 +863,67 @@ fn transport(app: &App, p: Paint) -> El {
.w_full() .w_full()
.center_y() .center_y()
.gap(space::S2) .gap(space::S2)
.child(playback(app, p))
.child(volume(app, p))
.child(ui::button(
p,
"fullscreen",
"Full screen",
false,
|app: &mut App| app.review.fullscreen = true,
))
.child(el().grow(1.0));
if let Some(note) = &app.review.export_note {
bar = bar.child(
text(note.clone())
.key("export-note")
.font(body(11.5))
.color(p.muted()),
);
}
let bar = bar
.child(ui::button(
p,
"clip",
"Clip",
app.review.clip.is_some(),
|app: &mut App| app.review.toggle_clip(),
))
.child(ui::button(
p,
"toggle-details",
&if app.review.show_details {
"Hide details".to_string()
} else {
format!("Highlights · {count}")
},
false,
|app: &mut App| {
app.review.show_details = !app.review.show_details;
},
));
let mut column = col()
.key("transport-bar")
.w_full()
.gap(space::S2)
.child(bar);
if let Some(line) = channels(app, p) {
column = column.child(line);
}
if let Some(clip) = app.review.clip {
column = column.child(clip_row(app, p, clip));
}
column
}
/// Back ten seconds, play or pause, forward ten, and the clock: the bar and the full screen
/// picture show the same controls.
fn playback(app: &App, p: Paint) -> El {
row()
.key("playback")
.center_y()
.gap(space::S2)
.child(ui::media_button( .child(ui::media_button(
p, p,
"rewind", "rewind",
@@ -829,52 +970,7 @@ fn transport(app: &App, p: Paint) -> El {
.font(type_::MONO_CAPTION) .font(type_::MONO_CAPTION)
.color(p.muted()), .color(p.muted()),
) )
.child(volume(app, p))
.child(el().grow(1.0));
if let Some(note) = &app.review.export_note {
bar = bar.child(
text(note.clone())
.key("export-note")
.font(body(11.5))
.color(p.muted()),
);
}
let bar = bar
.child(ui::button(
p,
"clip",
"Clip",
app.review.clip.is_some(),
|app: &mut App| app.review.toggle_clip(),
))
.child(ui::button(
p,
"toggle-details",
&if app.review.show_details {
"Hide details".to_string()
} else {
format!("Highlights · {count}")
},
false,
|app: &mut App| {
app.review.show_details = !app.review.show_details;
},
));
let mut column = col()
.key("transport-bar")
.w_full()
.gap(space::S2)
.child(bar);
if let Some(line) = channels(app, p) {
column = column.child(line);
}
if let Some(clip) = app.review.clip {
column = column.child(clip_row(app, p, clip));
}
column
} }
/// One toggle per audio track, shown once the clip carries more than one. A track that is off /// One toggle per audio track, shown once the clip carries more than one. A track that is off
/// is neither heard nor kept in an export. /// is neither heard nor kept in an export.
fn channels(app: &App, p: Paint) -> Option<El> { fn channels(app: &App, p: Paint) -> Option<El> {
+111 -147
View File
@@ -15,10 +15,7 @@ pub struct Form {
pub dirty: bool, pub dirty: bool,
pub saving: bool, pub saving: bool,
pub open_select: Option<&'static str>, pub open_select: Option<&'static str>,
pub path: TextEdit,
pub naming: TextEdit, pub naming: TextEdit,
pub split_size: TextEdit,
pub split_time: TextEdit,
pub poll_interval: TextEdit, pub poll_interval: TextEdit,
pub bitrate: TextEdit, pub bitrate: TextEdit,
pub source_name: TextEdit, pub source_name: TextEdit,
@@ -30,10 +27,7 @@ impl Form {
pub fn empty() -> Self { pub fn empty() -> Self {
let draft = Settings::default(); let draft = Settings::default();
Self { Self {
path: TextEdit::new(&draft.output.path),
naming: TextEdit::new(&draft.output.naming_pattern), naming: TextEdit::new(&draft.output.naming_pattern),
split_size: TextEdit::new(draft.output.split_size_mb.to_string()),
split_time: TextEdit::new(draft.output.split_time_minutes.to_string()),
poll_interval: TextEdit::new(draft.daemon.poll_interval_ms.to_string()), poll_interval: TextEdit::new(draft.daemon.poll_interval_ms.to_string()),
bitrate: TextEdit::new(draft.audio.bitrate.to_string()), bitrate: TextEdit::new(draft.audio.bitrate.to_string()),
source_name: TextEdit::new(""), source_name: TextEdit::new(""),
@@ -53,12 +47,7 @@ impl Form {
return; return;
} }
self.draft = settings.clone(); self.draft = settings.clone();
self.path.replace_text(&settings.output.path);
self.naming.replace_text(&settings.output.naming_pattern); self.naming.replace_text(&settings.output.naming_pattern);
self.split_size
.replace_text(settings.output.split_size_mb.to_string());
self.split_time
.replace_text(settings.output.split_time_minutes.to_string());
self.poll_interval self.poll_interval
.replace_text(settings.daemon.poll_interval_ms.to_string()); .replace_text(settings.daemon.poll_interval_ms.to_string());
self.bitrate self.bitrate
@@ -71,10 +60,7 @@ impl Form {
/// Pull the text fields into the draft and hand it to `updateSettings`. /// Pull the text fields into the draft and hand it to `updateSettings`.
pub fn settings(&mut self) -> Settings { pub fn settings(&mut self) -> Settings {
let mut out = self.draft.clone(); let mut out = self.draft.clone();
out.output.path = self.path.text.trim().to_string();
out.output.naming_pattern = self.naming.text.trim().to_string(); out.output.naming_pattern = self.naming.text.trim().to_string();
out.output.split_size_mb = self.split_size.text.trim().parse().unwrap_or(0);
out.output.split_time_minutes = self.split_time.text.trim().parse().unwrap_or(0);
out.daemon.poll_interval_ms = self out.daemon.poll_interval_ms = self
.poll_interval .poll_interval
.text .text
@@ -144,6 +130,57 @@ fn text_row(
ui::setting_row_with(p, key, label, hint, ui::text_field(p, key, label, edit, to)) ui::setting_row_with(p, key, label, hint, ui::text_field(p, key, label, edit, to))
} }
/// The folder recordings land in, as the settings hold it, and the button that replaces it with
/// one the system's dialog picks. The path is read back, not typed: a folder is a thing you find.
fn path_row(p: Paint, app: &App, key: &'static str, label: &'static str, hint: &'static str) -> El {
// The whole path, not the last folders. It gets what the labels and the button leave, and a
// middle "…" when that is not enough, so the window's width picks the cut and no character
// count does. The margin holds it off the labels once the row is tight.
let shown = text(&app.form.draft.output.path)
.key("path")
.font(body(12.0))
.color(p.muted())
.ml(space::S2)
.truncate_middle();
let pick = ui::button_tx(
p,
"pick-folder",
"Select folder",
false,
move |app: &mut App, tx: &mut rune::Tx| {
let options = rune::FileDialogOptions {
title: hint.to_string(),
directory: Some(app.output_dir()),
..Default::default()
};
tx.open_folder(options, |app: &mut App, result, _| match result {
Ok(Some(path)) => {
app.form.draft.output.path = path.display().to_string();
app.form.dirty = true;
}
Ok(None) => {}
Err(e) => app.notify_error(format!("No folder dialog: {e}")),
});
},
);
ui::setting_row_with(
p,
key,
label,
hint,
// Growing the control and letting itself be small give the text a bounded width to elide
// inside; content-sized, the row would run off the card.
row()
.gap(space::S2)
.center_y()
.grow(1.0)
.min_w(0.0)
.justify_end()
.child(shown)
.child(pick),
)
}
#[allow(clippy::too_many_arguments)] // the columns of a settings row #[allow(clippy::too_many_arguments)] // the columns of a settings row
fn select_row( fn select_row(
p: Paint, p: Paint,
@@ -401,33 +438,18 @@ fn quick(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content:
crate::daemon::open_folder(&app.output_dir()); crate::daemon::open_folder(&app.output_dir());
}, },
)), )),
vec![ui::setting_row( vec![path_row(
p, p,
app,
"recordings-folder", "recordings-folder",
"Recordings folder", "Recordings folder",
text(short_path(&app.form.draft.output.path)) "Where finished recordings are written",
.key("path")
.font(body(12.0))
.color(p.muted()),
)], )],
)) ))
} }
/// A path as it fits on a row: the last two segments, with the rest elided.
fn short_path(path: &str) -> String {
let sep = std::path::MAIN_SEPARATOR;
let normalized = path.replace(sep, "/");
let parts: Vec<&str> = normalized.split('/').filter(|p| !p.is_empty()).collect();
match parts.len() {
0 => path.to_string(),
1 | 2 => parts.join(&sep.to_string()),
n => format!("…{sep}{}{sep}{}", parts[n - 2], parts[n - 1]),
}
}
fn recording(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content: El) -> El { fn recording(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content: El) -> El {
let v = &app.form.draft.video; let v = &app.form.draft.video;
let a = &app.form.draft.audio;
let o = &app.form.draft.output; let o = &app.form.draft.output;
// Only the encoders this machine reports are offered. The static list stands in until the // Only the encoders this machine reports are offered. The static list stands in until the
@@ -484,13 +506,12 @@ fn recording(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, cont
}, },
)), )),
vec![ vec![
text_row( path_row(
p, p,
app,
"output-path", "output-path",
"Folder", "Folder",
"Where finished recordings are written", "Where finished recordings are written",
&app.form.path,
|app| &mut app.form.path,
), ),
text_row( text_row(
p, p,
@@ -511,73 +532,8 @@ fn recording(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, cont
Some(o.container.clone()), Some(o.container.clone()),
app, app,
), ),
text_row(
p,
"split-size",
"Split at size",
"Start a new file past this many MB (0 for never)",
&app.form.split_size,
|app| &mut app.form.split_size,
),
text_row(
p,
"split-time",
"Split at time",
"Start a new file after this many minutes (0 for never)",
&app.form.split_time,
|app| &mut app.form.split_time,
),
], ],
)) ))
.child(ui::card(
p,
Some("Audio"),
vec![
ui::toggle_row(
p,
"rec-game",
"Game audio",
a.enabled && a.capture_game,
|app: &mut App| {
let on =
!(app.form.draft.audio.enabled && app.form.draft.audio.capture_game);
app.form.draft.audio.enabled = on;
app.form.draft.audio.capture_game = on;
app.form.dirty = true;
},
),
ui::toggle_row(
p,
"rec-mic",
"Microphone",
a.capture_mic,
|app: &mut App| {
app.form.draft.audio.capture_mic ^= true;
app.form.dirty = true;
},
),
mic_row(p, kit, layer, app, "rec-mic-device"),
ui::setting_row_with(
p,
"rec-apps",
"Applications",
&source_summary(&a.capture_apps),
ui::button(p, "edit-apps", "Edit", false, |app: &mut App| {
app.settings_tab = SettingsTab::Audio;
}),
),
],
))
}
/// The applications a clip takes sound from, as one line.
fn source_summary(sources: &[AudioSource]) -> String {
match sources.len() {
0 => "None yet".to_string(),
1 => sources[0].name.clone(),
2 => format!("{} and {}", sources[0].name, sources[1].name),
n => format!("{} and {} more", sources[0].name, n - 1),
}
} }
/// The microphone picker: the system default plus every input device the daemon reports. /// The microphone picker: the system default plus every input device the daemon reports.
@@ -651,8 +607,21 @@ fn audio(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content:
content content
.child(ui::card( .child(ui::card(
p, p,
Some("Levels"), Some("Game"),
vec![ vec![
ui::toggle_row(
p,
"game-audio",
"Record game audio",
a.enabled && a.capture_game,
|app: &mut App| {
let on =
!(app.form.draft.audio.enabled && app.form.draft.audio.capture_game);
app.form.draft.audio.enabled = on;
app.form.draft.audio.capture_game = on;
app.form.dirty = true;
},
),
ui::setting_row( ui::setting_row(
p, p,
"game-volume", "game-volume",
@@ -668,36 +637,6 @@ fn audio(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content:
}, },
), ),
), ),
ui::setting_row(
p,
"mic-volume",
"Microphone volume",
ui::slider(
p,
"mic-volume",
"Microphone volume",
a.mic_volume,
|app, value| {
app.form.draft.audio.mic_volume = value;
app.form.dirty = true;
},
),
),
ui::setting_row(
p,
"apps-volume",
"Applications volume",
ui::slider(
p,
"apps-volume",
"Applications volume",
a.apps_volume,
|app, value| {
app.form.draft.audio.apps_volume = value;
app.form.dirty = true;
},
),
),
], ],
)) ))
.child(ui::card( .child(ui::card(
@@ -715,6 +654,21 @@ fn audio(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, content:
}, },
), ),
mic_row(p, kit, layer, app, "mic-device"), mic_row(p, kit, layer, app, "mic-device"),
ui::setting_row(
p,
"mic-volume",
"Microphone volume",
ui::slider(
p,
"mic-volume",
"Microphone volume",
a.mic_volume,
|app, value| {
app.form.draft.audio.mic_volume = value;
app.form.dirty = true;
},
),
),
], ],
)) ))
.child(ui::card_action( .child(ui::card_action(
@@ -989,7 +943,10 @@ fn advanced(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, conte
text(value) text(value)
.key("value") .key("value")
.font(type_::MONO_CAPTION) .font(type_::MONO_CAPTION)
.color(p.muted()), .color(p.muted())
.ml(space::S2)
// A long value, the log path most of all, is cut to the row's width.
.truncate_middle(),
) )
}; };
let recording = if app.status.is_recording { "yes" } else { "no" }; let recording = if app.status.is_recording { "yes" } else { "no" };
@@ -1027,11 +984,7 @@ fn advanced(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, conte
.map(|id| id.to_string()) .map(|id| id.to_string())
.unwrap_or_else(|| "none".into()), .unwrap_or_else(|| "none".into()),
), ),
status_row( status_row("daemon-log", "Log file", crate::daemon::log_path()),
"daemon-log",
"Log file",
short_path(&crate::daemon::log_path()),
),
], ],
)) ))
.child(ui::card( .child(ui::card(
@@ -1128,16 +1081,27 @@ fn advanced(app: &App, p: Paint, kit: &rune_kit::Kit, layer: &mut Vec<El>, conte
p, p,
Some("Log"), Some("Log"),
vec![ vec![
col().key("log").padding(space::S3).h(300.0).gap(0.0).child( app.log_scroll.follow(
text(if app.logs.is_empty() { "log-scroller",
"No log loaded. Press Reload log." col()
} else { .key("log")
&app.logs .padding(space::S3)
}) // Room for the scroll bar the box draws at the viewport's end edge.
.key("log-text") .pr(14.0)
.font(type_::MONO_CAPTION) .h(440.0)
.color(p.muted()) .gap(0.0)
.w_full(), .scroll(rune::ScrollSpec { stick_bottom: true })
.child(
text(if app.logs.is_empty() {
"No log loaded. Press Reload log."
} else {
&app.logs
})
.key("log-text")
.font(type_::MONO_CAPTION)
.color(p.muted())
.w_full(),
),
), ),
], ],
)) ))
-6
View File
@@ -190,10 +190,6 @@ pub struct OutputSettings {
pub naming_pattern: String, pub naming_pattern: String,
#[serde(default = "container")] #[serde(default = "container")]
pub container: String, pub container: String,
#[serde(default)]
pub split_size_mb: u32,
#[serde(default)]
pub split_time_minutes: u32,
} }
impl Default for OutputSettings { impl Default for OutputSettings {
@@ -202,8 +198,6 @@ impl Default for OutputSettings {
path: output_path(), path: output_path(),
naming_pattern: naming_pattern(), naming_pattern: naming_pattern(),
container: container(), container: container(),
split_size_mb: 0,
split_time_minutes: 0,
} }
} }
} }
+13 -1
View File
@@ -412,6 +412,18 @@ pub fn button(
label: &str, label: &str,
primary: bool, primary: bool,
on_press: impl Fn(&mut App) + Send + Sync + 'static, on_press: impl Fn(&mut App) + Send + Sync + 'static,
) -> El {
button_tx(p, key, label, primary, move |app, _| on_press(app))
}
/// [`button`] whose press gets the frame's [`Tx`], for a control that asks the window for
/// something: a native folder dialog, an open URL, a clipboard read.
pub fn button_tx(
p: Paint,
key: &str,
label: &str,
primary: bool,
on_press: impl Fn(&mut App, &mut rune::Tx) + Send + Sync + 'static,
) -> El { ) -> El {
el().key(key) el().key(key)
.role("button") .role("button")
@@ -424,7 +436,7 @@ pub fn button(
.fill(if primary { p.accent } else { p.t.control_off }) .fill(if primary { p.accent } else { p.t.control_off })
.hover(p.t.hover) .hover(p.t.hover)
.press(p.t.press) .press(p.t.press)
.on_press(on_press) .on_press_tx(on_press)
.child( .child(
text(label) text(label)
.key("label") .key("label")
+1 -1
View File
@@ -2387,7 +2387,7 @@ dependencies = [
[[package]] [[package]]
name = "record-daemon" name = "record-daemon"
version = "0.3.2" version = "0.3.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "record-daemon" name = "record-daemon"
version = "0.3.2" version = "0.3.3"
edition = "2021" edition = "2021"
description = "High-performance League of Legends recording daemon using libobs" description = "High-performance League of Legends recording daemon using libobs"
authors = ["LeagueRecorder"] authors = ["LeagueRecorder"]
+2 -2
View File
@@ -8,7 +8,7 @@ A high-performance League of Legends recording daemon built with Rust and libobs
- **Game Event Capture**: Captures game events (kills, deaths, objectives) via the League Client API (LQP) - **Game Event Capture**: Captures game events (kills, deaths, objectives) via the League Client API (LQP)
- **Event Timeline**: Maps game events to video timestamps for easy navigation - **Event Timeline**: Maps game events to video timestamps for easy navigation
- **Hardware Encoding**: Supports NVIDIA NVENC, AMD AMF, and software encoding (x264) - **Hardware Encoding**: Supports NVIDIA NVENC, AMD AMF, and software encoding (x264)
- **IPC Interface**: Unix sockets (Linux) / Named pipes (Windows) for configuration and control from a Tauri app - **IPC Interface**: Unix sockets (Linux) / Named pipes (Windows) for configuration and control from the app
- **Configurable Presets**: Quality presets from 720p30 to 1440p60 - **Configurable Presets**: Quality presets from 720p30 to 1440p60
- **Cross-Platform**: Supports Windows and Linux - **Cross-Platform**: Supports Windows and Linux
@@ -200,7 +200,7 @@ crf = 23
## IPC Protocol ## IPC Protocol
The daemon exposes an IPC server for communication with the Tauri app. The daemon exposes an IPC server for communication with the app.
### Socket Location ### Socket Location
- Linux: `$XDG_RUNTIME_DIR/record-daemon.sock` (or `/tmp/record-daemon.sock`) - Linux: `$XDG_RUNTIME_DIR/record-daemon.sock` (or `/tmp/record-daemon.sock`)
-10
View File
@@ -87,14 +87,6 @@ pub struct OutputSettings {
/// Container format (mp4, mkv, etc.). /// Container format (mp4, mkv, etc.).
#[serde(default = "default_container")] #[serde(default = "default_container")]
pub container: String, pub container: String,
/// Split recordings by size (MB). 0 = no splitting.
#[serde(default)]
pub split_size_mb: u32,
/// Split recordings by time (minutes). 0 = no splitting.
#[serde(default)]
pub split_time_minutes: u32,
} }
impl Default for OutputSettings { impl Default for OutputSettings {
@@ -103,8 +95,6 @@ impl Default for OutputSettings {
path: default_output_path(), path: default_output_path(),
naming_pattern: default_naming_pattern(), naming_pattern: default_naming_pattern(),
container: default_container(), container: default_container(),
split_size_mb: 0,
split_time_minutes: 0,
} }
} }
} }
+2 -2
View File
@@ -1,7 +1,7 @@
//! IPC module for communication with the Tauri app. //! IPC module for communication with the app.
//! //!
//! This module provides a Unix socket-based IPC server that allows //! This module provides a Unix socket-based IPC server that allows
//! the Tauri app to configure and control the daemon. //! the app to configure and control the daemon.
mod handlers; mod handlers;
mod protocol; mod protocol;
+3 -3
View File
@@ -1,4 +1,4 @@
//! IPC server for communication with the Tauri app. //! IPC server for communication with the app.
//! //!
//! Uses Unix domain sockets on Linux and named pipes on Windows. //! Uses Unix domain sockets on Linux and named pipes on Windows.
@@ -52,7 +52,7 @@ type PlatformListener = tokio::net::UnixListener;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
type PlatformStream = tokio::net::UnixStream; type PlatformStream = tokio::net::UnixStream;
/// IPC server for communication with Tauri app (Linux). /// IPC server for communication with the app (Linux).
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
pub struct IpcServer { pub struct IpcServer {
/// Server configuration. /// Server configuration.
@@ -306,7 +306,7 @@ impl Clone for IpcServer {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
/// IPC server for communication with Tauri app (Windows). /// IPC server for communication with the app (Windows).
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub struct IpcServer { pub struct IpcServer {
/// Server configuration. /// Server configuration.
+1 -1
View File
@@ -2,7 +2,7 @@
//! //!
//! This daemon automatically records League of Legends matches using libobs, //! This daemon automatically records League of Legends matches using libobs,
//! captures game events via the League Client API (LQP), and exposes //! captures game events via the League Client API (LQP), and exposes
//! configuration via a Unix socket IPC for the Tauri app. //! configuration via a Unix socket IPC for the app.
pub mod config; pub mod config;
pub mod error; pub mod error;
+2 -2
View File
@@ -2,8 +2,8 @@
//! //!
//! The record-daemon stores raw API JSON data only — no typed event parsing. //! The record-daemon stores raw API JSON data only — no typed event parsing.
//! Event types are simple string constants derived from the URI, used for //! Event types are simple string constants derived from the URI, used for
//! classification and state machine transitions. The tauri-app parses the //! classification and state machine transitions. The app parses the raw data
//! raw data it needs on the frontend side. //! it needs on the frontend side.
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
+5 -1
View File
@@ -629,7 +629,11 @@ fn init_logging(level: &str, log_file: Option<&std::path::Path>) {
tracing_subscriber::registry() tracing_subscriber::registry()
.with(filter) .with(filter)
.with(tracing_subscriber::fmt::layer().with_writer(non_blocking)) .with(
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false),
)
.init(); .init();
eprintln!("Logging to file: {}", log_path.display()); eprintln!("Logging to file: {}", log_path.display());
+1 -1
View File
@@ -27,7 +27,7 @@ pub struct TimestampedEvent {
#[serde(default)] #[serde(default)]
pub description: String, pub description: String,
/// The raw JSON data from the API — the single source of truth. /// The raw JSON data from the API — the single source of truth.
/// The tauri-app parses the values it needs from this data. /// The app parses the values it needs from this data.
#[serde(default)] #[serde(default)]
pub raw_data: serde_json::Value, pub raw_data: serde_json::Value,
/// URI of the endpoint that triggered this event. /// URI of the endpoint that triggered this event.
-24
View File
@@ -1,24 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
-7
View File
@@ -1,7 +0,0 @@
{
"recommendations": [
"Vue.volar",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}
-16
View File
@@ -1,16 +0,0 @@
# Tauri + Vue + TypeScript
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)
## Type Support For `.vue` Imports in TS
Since TypeScript cannot handle type information for `.vue` imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in `.vue` imports (for example to get props validation when using manual `h(...)` calls), you can enable Volar's Take Over mode by following these steps:
1. Run `Extensions: Show Built-in Extensions` from VS Code's command palette, look for `TypeScript and JavaScript Language Features`, then right click and select `Disable (Workspace)`. By default, Take Over mode will enable itself if the default TypeScript extension is disabled.
2. Reload the VS Code window by running `Developer: Reload Window` from the command palette.
You can learn more about Take Over mode [here](https://github.com/johnsoncodehk/volar/discussions/471).
-14
View File
@@ -1,14 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Tauri + Vue + Typescript App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
-1626
View File
File diff suppressed because it is too large. Load diff
-24
View File
@@ -1,24 +0,0 @@
{
"name": "tauri-app",
"private": true,
"version": "0.3.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"vue": "^3.5.13",
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@vitejs/plugin-vue": "^5.2.1",
"typescript": "~5.6.2",
"vite": "^6.0.3",
"vue-tsc": "^2.1.10",
"@tauri-apps/cli": "^2"
}
}
-6
View File
@@ -1,6 +0,0 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

-10
View File
@@ -1,10 +0,0 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas
# Bundled record-daemon binaries (built by build.rs)
/binaries/
-5794
View File
File diff suppressed because it is too large. Load diff
-31
View File
@@ -1,31 +0,0 @@
[package]
name = "leaguerecorder"
version = "0.3.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "tauri_app_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["protocol-asset"] }
tauri-plugin-opener = "2"
tauri-plugin-autostart = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4", "serde"] }
directories = "6"
ffmpeg-sidecar = "2.4"
tokio = { version = "1", features = ["net", "io-util", "time", "rt"] }
-103
View File
@@ -1,103 +0,0 @@
fn main() {
build_record_daemon();
tauri_build::build()
}
/// Build the record-daemon in release mode and place it in the binaries/
/// directory with the target-triple suffix that Tauri's `externalBin` feature
/// expects.
///
/// The resulting binary is copied to:
/// src-tauri/binaries/record-daemon-<target-triple>[.exe]
///
/// This runs as part of `cargo build`, so the daemon is always available when
/// the Tauri bundler needs it. Because record-daemon lives in a separate
/// Cargo workspace, invoking `cargo build` from here does not conflict with
/// the parent build's lock.
fn build_record_daemon() {
use std::env;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
let target = env::var("TARGET").unwrap();
let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
// Resolve the record-daemon crate root (../../record-daemon/ from src-tauri/)
let daemon_dir = manifest_dir
.parent()
.expect("CARGO_MANIFEST_DIR has no parent")
.parent()
.expect("parent of CARGO_MANIFEST_DIR has no parent")
.join("record-daemon");
let daemon_manifest = daemon_dir.join("Cargo.toml");
if !daemon_manifest.exists() {
eprintln!(
"cargo:warning=record-daemon not found at {}, skipping daemon build",
daemon_manifest.display()
);
return;
}
// Build the daemon in release mode for the same target triple.
// Passing --target ensures the output lands in a predictable directory
// and supports cross-compilation.
let status = Command::new("cargo")
.args([
"build",
"--release",
"--manifest-path",
])
.arg(&daemon_manifest)
.arg("--target")
.arg(&target)
.status()
.expect("Failed to execute cargo build for record-daemon");
if !status.success() {
panic!("Failed to build record-daemon in release mode");
}
// Locate the built binary.
// When --target is specified, cargo places output in target/<triple>/release/.
let src_name = if target.contains("windows") {
"record-daemon.exe"
} else {
"record-daemon"
};
let src_binary = daemon_dir
.join("target")
.join(&target)
.join("release")
.join(src_name);
if !src_binary.exists() {
panic!(
"record-daemon binary not found at {} after successful build",
src_binary.display()
);
}
// Copy to src-tauri/binaries/record-daemon-<target-triple>[.exe]
let binaries_dir = manifest_dir.join("binaries");
fs::create_dir_all(&binaries_dir).expect("Failed to create binaries directory");
let dst_name = if target.contains("windows") {
format!("record-daemon-{}.exe", target)
} else {
format!("record-daemon-{}", target)
};
let dst_binary = binaries_dir.join(&dst_name);
fs::copy(&src_binary, &dst_binary).expect("Failed to copy record-daemon binary");
fs::copy(daemon_dir
.join("target")
.join(&target)
.join("release")
.join("obs.dll"), binaries_dir.join("obs.dll")).expect("Failed to copy record-daemon dummy obs.dll");
println!(
"cargo:warning=Bundled record-daemon → {}",
dst_binary.display()
);
}
@@ -1,13 +0,0 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default",
"autostart:allow-enable",
"autostart:allow-disable",
"autostart:allow-is-enabled"
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 797 KiB

-645
View File
@@ -1,645 +0,0 @@
//! IPC client for communicating with the record-daemon.
//!
//! Connects to the daemon via named pipes on Windows or Unix sockets on Linux,
//! using the same JSON-over-newline-delimited protocol.
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;
// ---------------------------------------------------------------------------
// Protocol types (mirror of record-daemon IPC protocol)
// ---------------------------------------------------------------------------
/// IPC message wrapper.
#[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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payload: Option<serde_json::Value>,
}
/// Message type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageType {
Request,
Response,
Notification,
}
/// IPC response from the daemon.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IpcResponse {
pub request_id: String,
pub success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
// ---------------------------------------------------------------------------
// IPC commands (camelCase to match daemon's serde rename)
// ---------------------------------------------------------------------------
/// IPC command names matching the daemon's `IpcCommand` enum.
pub mod commands {
pub const GET_SETTINGS: &str = "getSettings";
pub const UPDATE_SETTINGS: &str = "updateSettings";
pub const RESET_SETTINGS: &str = "resetSettings";
pub const GET_STATUS: &str = "getStatus";
pub const GET_ENCODERS: &str = "getEncoders";
pub const GET_AUDIO_DEVICES: &str = "getAudioDevices";
pub const ADD_AUDIO_SOURCE: &str = "addAudioSource";
pub const REMOVE_AUDIO_SOURCE: &str = "removeAudioSource";
pub const UPDATE_AUDIO_SOURCE: &str = "updateAudioSource";
pub const START_RECORDING: &str = "startRecording";
pub const STOP_RECORDING: &str = "stopRecording";
pub const SHUTDOWN: &str = "shutdown";
}
// ---------------------------------------------------------------------------
// Default socket path (same logic as daemon)
// ---------------------------------------------------------------------------
/// Default socket path for the IPC server.
#[cfg(target_os = "windows")]
pub fn default_socket_path() -> PathBuf {
PathBuf::from(r"\\.\pipe\record-daemon")
}
/// Default socket path for the IPC server.
#[cfg(target_os = "linux")]
pub fn default_socket_path() -> PathBuf {
std::env::var("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("/tmp"))
.join("record-daemon.sock")
}
// ---------------------------------------------------------------------------
// IPC Client
// ---------------------------------------------------------------------------
/// IPC client for communicating with the record-daemon.
pub struct IpcClient {
socket_path: PathBuf,
timeout: Duration,
}
impl IpcClient {
/// Create a new IPC client with the default socket path.
pub fn new() -> Self {
Self {
socket_path: default_socket_path(),
timeout: Duration::from_secs(5),
}
}
/// Create a new IPC client with a custom socket path.
#[allow(dead_code)]
pub fn with_socket_path(socket_path: PathBuf) -> Self {
Self {
socket_path,
timeout: Duration::from_secs(5),
}
}
/// Send a command to the daemon and return the response.
pub async fn send_command(
&self,
command: &str,
payload: Option<serde_json::Value>,
) -> Result<IpcResponse, String> {
let id = uuid::Uuid::new_v4().to_string();
let message = IpcMessage {
message_type: MessageType::Request,
id: id.clone(),
command: Some(command.to_string()),
payload,
};
let message_json = serde_json::to_string(&message)
.map_err(|e| format!("Failed to serialize message: {}", e))?;
let response_str = self.send_raw(&message_json).await?;
let response: IpcResponse = serde_json::from_str(&response_str)
.map_err(|e| format!("Failed to parse response: {}", e))?;
Ok(response)
}
/// Send a raw JSON string and read the response.
#[cfg(target_os = "windows")]
async fn send_raw(&self, message: &str) -> Result<String, String> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::windows::named_pipe::ClientOptions;
// Connect to the named pipe
let pipe_name = self.socket_path.to_string_lossy().to_string();
let client = tokio::time::timeout(self.timeout, async {
// Try to connect - if the pipe is busy, retry a few times
let mut attempts = 0;
loop {
match ClientOptions::new().open(&pipe_name) {
Ok(client) => return Ok(client),
Err(e) if e.raw_os_error() == Some(231) => {
// ERROR_PIPE_BUSY = 231
attempts += 1;
if attempts > 5 {
return Err(format!("Pipe busy after 5 attempts: {}", e));
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(e) => return Err(format!("Failed to connect to daemon: {}", e)),
}
}
})
.await
.map_err(|_| "Connection to daemon timed out".to_string())??;
let (reader, mut writer) = tokio::io::split(client);
// Send message
writer
.write_all(message.as_bytes())
.await
.map_err(|e| format!("Failed to write to pipe: {}", e))?;
writer
.write_all(b"\n")
.await
.map_err(|e| format!("Failed to write newline: {}", e))?;
writer
.flush()
.await
.map_err(|e| format!("Failed to flush pipe: {}", e))?;
// Read response
let mut lines = BufReader::new(reader).lines();
let line = tokio::time::timeout(self.timeout, lines.next_line())
.await
.map_err(|_| "Reading from daemon timed out".to_string())?
.map_err(|e| format!("Failed to read from pipe: {}", e))?;
match line {
Some(line) => Ok(line),
None => Err("Daemon closed connection without response".to_string()),
}
}
/// Send a raw JSON string and read the response (Linux).
#[cfg(target_os = "linux")]
async fn send_raw(&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.socket_path))
.await
.map_err(|_| "Connection to daemon timed out".to_string())?
.map_err(|e| format!("Failed to connect to daemon: {}", e))?;
let (reader, mut writer) = stream.into_split();
// Send message
writer
.write_all(message.as_bytes())
.await
.map_err(|e| format!("Failed to write to socket: {}", e))?;
writer
.write_all(b"\n")
.await
.map_err(|e| format!("Failed to write newline: {}", e))?;
writer
.flush()
.await
.map_err(|e| format!("Failed to flush socket: {}", e))?;
// Read response
let mut lines = BufReader::new(reader).lines();
let line = tokio::time::timeout(self.timeout, lines.next_line())
.await
.map_err(|_| "Reading from daemon timed out".to_string())?
.map_err(|e| format!("Failed to read from socket: {}", e))?;
match line {
Some(line) => Ok(line),
None => Err("Daemon closed connection without response".to_string()),
}
}
/// Check if the daemon is reachable.
pub async fn is_daemon_running(&self) -> bool {
self.send_command(commands::GET_STATUS, None).await.is_ok()
}
}
// ---------------------------------------------------------------------------
// Daemon binary discovery & process spawning
// ---------------------------------------------------------------------------
/// Find the record-daemon binary.
///
/// Search order:
/// 1. Next to the current executable (bundled / installed mode)
/// 2. In `<exe_dir>/../resources/` (macOS .app bundle)
/// 3. Relative to the executable – walk up to the workspace root and look for
/// `record-daemon/target/{release,debug}/` (development mode)
/// 4. Relative to the current working directory (fallback for dev mode)
fn find_daemon_binary() -> Option<PathBuf> {
let exe_name = if cfg!(windows) {
"record-daemon.exe"
} else {
"record-daemon"
};
if let Ok(exe_path) = std::env::current_exe() {
// 1. Next to the current executable
if let Some(exe_dir) = exe_path.parent() {
let candidate = exe_dir.join(exe_name);
if candidate.exists() {
return Some(candidate);
}
}
// 2. In <exe_dir>/../resources/
if let Some(exe_dir) = exe_path.parent().and_then(|p| p.parent()) {
let candidate = exe_dir.join("resources").join(exe_name);
if candidate.exists() {
return Some(candidate);
}
}
// 3. Development mode – relative to the exe location.
// The exe is typically at <workspace>/tauri-app/src-tauri/target/debug/tauri-app.exe
// so we walk up to find <workspace>/record-daemon/target/{release,debug}/
if let Some(exe_dir) = exe_path.parent() {
// Try walking up from the exe directory to find the daemon
let dev_suffixes = [
Path::new("record-daemon/target/release"),
Path::new("record-daemon/target/debug"),
];
// Walk up at most 6 levels from the exe directory
let mut dir = exe_dir.to_path_buf();
for _ in 0..6 {
for suffix in &dev_suffixes {
let candidate = dir.join(suffix).join(exe_name);
if candidate.exists() {
return Some(candidate);
}
}
if !dir.pop() {
break;
}
}
}
}
// 4. Fallback – look relative to the current working directory
let cwd_dev_paths = [
Path::new("../../record-daemon/target/release"),
Path::new("../../record-daemon/target/debug"),
Path::new("../record-daemon/target/release"),
Path::new("../record-daemon/target/debug"),
];
for dir in &cwd_dev_paths {
let candidate = dir.join(exe_name);
if candidate.exists() {
return Some(candidate);
}
}
None
}
/// Get the log file path for the daemon.
///
/// Returns a path in the app's data directory.
fn get_log_file_path() -> Result<PathBuf, String> {
let data_dir = directories::ProjectDirs::from("com", "leaguerecorder", "record-daemon")
.ok_or_else(|| "Failed to get app data directory".to_string())?;
let log_dir = data_dir.data_dir().join("logs");
std::fs::create_dir_all(&log_dir)
.map_err(|e| format!("Failed to create log directory: {}", e))?;
Ok(log_dir.join("daemon.log"))
}
/// Spawn the record-daemon as a detached background process.
///
/// Returns `Ok(())` if the process was successfully spawned.
fn spawn_daemon() -> Result<(), String> {
let binary = find_daemon_binary()
.ok_or_else(|| "record-daemon binary not found".to_string())?;
let log_file = get_log_file_path()?;
eprintln!("[daemon] Spawning record-daemon: {}", binary.display());
eprintln!("[daemon] Log file: {}", log_file.display());
let mut cmd = std::process::Command::new(&binary);
cmd.arg("--foreground");
cmd.arg("--log-file").arg(&log_file);
// Set the working directory to the daemon binary's directory so it can
// find its bundled resources (OBS plugins, etc.) relative to itself.
if let Some(bin_dir) = binary.parent() {
cmd.current_dir(bin_dir);
}
// Detach from the parent process group so the daemon survives if the
// Tauri app is restarted.
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// CREATE_NEW_PROCESS_GROUP (0x200) | DETACHED_PROCESS (0x8)
cmd.creation_flags(0x00000200 | 0x00000008);
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Start in a new session so the daemon gets its own process group
cmd.process_group(0);
}
// Redirect stdio so the daemon doesn't inherit our handles
cmd.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
cmd.spawn()
.map_err(|e| format!("Failed to spawn record-daemon: {}", e))?;
Ok(())
}
/// Ensure the record-daemon is running.
///
/// If the daemon is already reachable via IPC, returns immediately.
/// Otherwise, spawns the daemon binary and waits up to `timeout_secs` seconds
/// for it to become ready.
pub async fn ensure_daemon_running(timeout_secs: u64) -> Result<bool, String> {
let client = IpcClient::new();
// Fast path – already running
if client.is_daemon_running().await {
return Ok(true);
}
// Spawn the daemon
spawn_daemon()?;
// Poll until the daemon responds or we time out
let deadline = tokio::time::Instant::now() + Duration::from_secs(timeout_secs);
loop {
if client.is_daemon_running().await {
return Ok(true);
}
if tokio::time::Instant::now() >= deadline {
return Ok(false);
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
}
// ---------------------------------------------------------------------------
// Tauri commands
// ---------------------------------------------------------------------------
/// Check if the record-daemon is running.
#[tauri::command]
pub async fn daemon_is_running() -> bool {
let client = IpcClient::new();
client.is_daemon_running().await
}
/// Ensure the record-daemon is running, starting it if necessary.
///
/// Returns `true` if the daemon is running (either already was or just started),
/// `false` if it could not be started within the timeout.
#[tauri::command]
pub async fn daemon_ensure_running() -> Result<bool, String> {
ensure_daemon_running(30).await
}
/// Get the daemon status.
#[tauri::command]
pub async fn daemon_get_status() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::GET_STATUS, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Get the current daemon settings.
#[tauri::command]
pub async fn daemon_get_settings() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::GET_SETTINGS, None)
.await
.map_err(|e| e)?;
if response.success {
// The daemon wraps settings in { settings: {...} }
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Update daemon settings.
#[tauri::command]
pub async fn daemon_update_settings(settings: serde_json::Value) -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::UPDATE_SETTINGS, Some(settings))
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Reset daemon settings to defaults.
#[tauri::command]
pub async fn daemon_reset_settings() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::RESET_SETTINGS, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Get available encoders from the daemon.
#[tauri::command]
pub async fn daemon_get_encoders() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::GET_ENCODERS, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Start recording manually via the daemon.
#[tauri::command]
pub async fn daemon_start_recording() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::START_RECORDING, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Stop recording via the daemon.
#[tauri::command]
pub async fn daemon_stop_recording() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::STOP_RECORDING, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Shutdown the daemon.
#[tauri::command]
pub async fn daemon_shutdown() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::SHUTDOWN, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Get available audio devices from the daemon.
#[tauri::command]
pub async fn daemon_get_audio_devices() -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::GET_AUDIO_DEVICES, None)
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Add an audio source to the daemon settings.
#[tauri::command]
pub async fn daemon_add_audio_source(source: serde_json::Value) -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::ADD_AUDIO_SOURCE, Some(source))
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Remove an audio source from the daemon settings.
#[tauri::command]
pub async fn daemon_remove_audio_source(id: String) -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::REMOVE_AUDIO_SOURCE, Some(serde_json::json!({ "id": id })))
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Update an audio source in the daemon settings.
#[tauri::command]
pub async fn daemon_update_audio_source(source: serde_json::Value) -> Result<serde_json::Value, String> {
let client = IpcClient::new();
let response = client
.send_command(commands::UPDATE_AUDIO_SOURCE, Some(source))
.await
.map_err(|e| e)?;
if response.success {
Ok(response.data.unwrap_or(serde_json::Value::Null))
} else {
Err(response.error.unwrap_or_else(|| "Unknown error".to_string()))
}
}
/// Get the daemon log file path.
#[tauri::command]
pub fn daemon_get_log_path() -> Result<String, String> {
get_log_file_path()
.map(|p| p.to_string_lossy().to_string())
}
/// Read the daemon log file.
///
/// Returns the last `lines` lines of the log file (default 100, max 1000).
#[tauri::command]
pub fn daemon_read_logs(lines: Option<usize>) -> Result<String, String> {
let log_path = get_log_file_path()?;
let max_lines = lines.unwrap_or(100).min(1000);
let content = std::fs::read_to_string(&log_path)
.map_err(|e| format!("Failed to read log file: {}", e))?;
let lines: Vec<&str> = content.lines().rev().take(max_lines).collect();
Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n"))
}
-455
View File
@@ -1,455 +0,0 @@
mod daemon_ipc;
use ffmpeg_sidecar::{
command::{ffmpeg_is_installed, FfmpegCommand},
download::auto_download,
event::{FfmpegEvent, LogLevel},
paths::sidecar_path,
};
use serde_json::Value;
use std::fs;
use std::path::PathBuf;
/// Get the default output directory for recordings.
/// Uses the same directory structure as the record-daemon.
fn get_default_output_dir() -> Option<PathBuf> {
directories::ProjectDirs::from("com", "leaguerecorder", "record-daemon")
.map(|dirs| dirs.data_dir().join("recordings"))
}
/// Get the timeline storage directory.
/// Uses the same directory structure as the record-daemon.
fn get_timeline_dir() -> PathBuf {
get_default_output_dir()
.map(|p| p.join("timelines"))
.unwrap_or_else(|| PathBuf::from("./recordings/timelines"))
}
/// Load all timelines from disk as raw JSON values.
fn load_timelines() -> Vec<Value> {
let timeline_dir = get_timeline_dir();
let mut timelines = Vec::new();
if !timeline_dir.exists() {
return timelines;
}
if let Ok(entries) = fs::read_dir(&timeline_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map(|e| e == "json").unwrap_or(false) {
if let Ok(contents) = fs::read_to_string(&path) {
if let Ok(timeline) = serde_json::from_str::<Value>(&contents) {
timelines.push(timeline);
}
}
}
}
}
// Sort by start time, newest first
timelines.sort_by(|a, b| {
let a_time = a.get("start_time").and_then(|v| v.as_str()).unwrap_or("");
let b_time = b.get("start_time").and_then(|v| v.as_str()).unwrap_or("");
b_time.cmp(a_time)
});
timelines
}
/// Get game history - returns full timeline data for each game as raw JSON.
#[tauri::command]
fn get_game_history() -> Vec<Value> {
load_timelines()
}
/// Get a specific timeline by recording ID as raw JSON.
#[tauri::command]
fn get_timeline(recording_id: String) -> Option<Value> {
let timeline_dir = get_timeline_dir();
let path = timeline_dir.join(format!("{}.json", recording_id));
if path.exists() {
if let Ok(contents) = fs::read_to_string(&path) {
return serde_json::from_str::<Value>(&contents).ok();
}
}
None
}
/// Get the recordings directory path.
#[tauri::command]
fn get_recordings_dir() -> String {
get_default_output_dir()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|| "./recordings".to_string())
}
/// Find a video file in the recordings directory.
/// Searches for exact filename match or pattern match.
#[tauri::command]
fn find_video_file(recordings_dir: String, filename: String) -> Option<String> {
let recordings_path = PathBuf::from(&recordings_dir);
if !recordings_path.exists() {
return None;
}
// Try exact match first
let exact_path = recordings_path.join(&filename);
if exact_path.exists() {
return Some(exact_path.to_string_lossy().to_string());
}
// Try to find by pattern (date_time_*.mp4)
if let Ok(entries) = fs::read_dir(&recordings_path) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map(|e| e == "mp4" || e == "mkv" || e == "mov").unwrap_or(false) {
let file_name = path.file_name()?.to_string_lossy().to_string();
// Check if filename starts with the same date/time pattern
// filename format: "2026-03-27_16-42-52_unknown.mp4"
// We match the date_time prefix
if file_name.starts_with(&filename.replace("_unknown.mp4", "")) {
return Some(path.to_string_lossy().to_string());
}
}
}
}
None
}
/// Get list of video files in recordings directory.
#[tauri::command]
fn list_video_files(recordings_dir: String) -> Vec<String> {
let recordings_path = PathBuf::from(&recordings_dir);
let mut videos = Vec::new();
if !recordings_path.exists() {
return videos;
}
if let Ok(entries) = fs::read_dir(&recordings_path) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().map(|e| e == "mp4" || e == "mkv" || e == "mov").unwrap_or(false) {
videos.push(path.to_string_lossy().to_string());
}
}
}
// Sort by modification time, newest first
videos.sort_by(|a, b| {
let a_time = fs::metadata(a).and_then(|m| m.modified()).ok();
let b_time = fs::metadata(b).and_then(|m| m.modified()).ok();
b_time.cmp(&a_time)
});
videos
}
/// Ensure ffmpeg is available, downloading if necessary.
fn ensure_ffmpeg() -> Result<(), String> {
if ffmpeg_is_installed() {
return Ok(());
}
// Auto-download ffmpeg for the current platform
auto_download().map_err(|e| format!("Failed to download ffmpeg: {}", e))?;
Ok(())
}
/// Export a clip from a video using ffmpeg-sidecar (stream copy for speed).
#[tauri::command]
fn export_clip(
video_path: String,
start_time: f64,
end_time: f64,
output_name: String,
) -> Result<String, String> {
// Ensure ffmpeg is available
ensure_ffmpeg()?;
// Verify input file exists
if !PathBuf::from(&video_path).exists() {
return Err(format!("Video file not found: {}", video_path));
}
// Get output directory
let output_dir = get_default_output_dir()
.map(|p| p.join("clips"))
.unwrap_or_else(|| PathBuf::from("./clips"));
// Create clips directory if it doesn't exist
if !output_dir.exists() {
fs::create_dir_all(&output_dir)
.map_err(|e| format!("Failed to create clips directory: {}", e))?;
}
let output_path = output_dir.join(format!("{}.mp4", output_name));
let duration = end_time - start_time;
// Build ffmpeg command with stream copy (fast, no re-encoding)
// Note: Put -ss before -i for fast seeking (input seeking)
let iter = FfmpegCommand::new()
.arg("-y") // Overwrite output file
.arg("-ss").arg(&format!("{:.3}", start_time))
.arg("-i").arg(&video_path)
.arg("-t").arg(&format!("{:.3}", duration))
.arg("-c").arg("copy") // Stream copy for fast export
.arg("-avoid_negative_ts").arg("make_zero")
.arg(&output_path.to_string_lossy().to_string())
.spawn()
.map_err(|e| format!("Failed to spawn ffmpeg: {}", e))?
.iter()
.map_err(|e| format!("Failed to create ffmpeg iterator: {}", e))?;
// Process the ffmpeg command and collect all errors
let mut errors = Vec::new();
for event in iter {
match event {
FfmpegEvent::Error(e) => {
errors.push(format!("FFmpeg error: {}", e));
}
FfmpegEvent::Log(LogLevel::Error, msg) => {
errors.push(format!("FFmpeg log error: {}", msg));
}
FfmpegEvent::Log(LogLevel::Warning, msg) => {
// Log warnings but don't fail
eprintln!("FFmpeg warning: {}", msg);
}
_ => {}
}
}
// Check if output file was created
if !output_path.exists() {
return Err(format!(
"Export failed - output file not created. Errors: {}",
errors.join("; ")
));
}
// Check if output file has content
let metadata = fs::metadata(&output_path)
.map_err(|e| format!("Failed to check output file: {}", e))?;
if metadata.len() == 0 {
return Err(format!(
"Export failed - output file is empty. Errors: {}",
errors.join("; ")
));
}
Ok(output_path.to_string_lossy().to_string())
}
/// Export a clip with re-encoding for more precise cuts.
#[tauri::command]
fn export_clip_precise(
video_path: String,
start_time: f64,
end_time: f64,
output_name: String,
quality: String,
) -> Result<String, String> {
// Ensure ffmpeg is available
ensure_ffmpeg()?;
// Verify input file exists
if !PathBuf::from(&video_path).exists() {
return Err(format!("Video file not found: {}", video_path));
}
let output_dir = get_default_output_dir()
.map(|p| p.join("clips"))
.unwrap_or_else(|| PathBuf::from("./clips"));
if !output_dir.exists() {
fs::create_dir_all(&output_dir)
.map_err(|e| format!("Failed to create clips directory: {}", e))?;
}
let output_path = output_dir.join(format!("{}.mp4", output_name));
let duration = end_time - start_time;
// Quality presets (CRF values - lower is better quality)
let crf = match quality.as_str() {
"low" => "28",
"medium" => "23",
"high" => "18",
_ => "23",
};
// Build ffmpeg command with re-encoding
let iter = FfmpegCommand::new()
.arg("-y") // Overwrite output file
.arg("-ss").arg(&format!("{:.3}", start_time))
.arg("-i").arg(&video_path)
.arg("-t").arg(&format!("{:.3}", duration))
.arg("-c:v").arg("libx264")
.arg("-crf").arg(crf)
.arg("-preset").arg("fast")
.arg("-c:a").arg("aac")
.arg("-b:a").arg("128k")
.arg(&output_path.to_string_lossy().to_string())
.spawn()
.map_err(|e| format!("Failed to spawn ffmpeg: {}", e))?
.iter()
.map_err(|e| format!("Failed to create ffmpeg iterator: {}", e))?;
// Process the ffmpeg command and collect all errors
let mut errors = Vec::new();
for event in iter {
match event {
FfmpegEvent::Error(e) => {
errors.push(format!("FFmpeg error: {}", e));
}
FfmpegEvent::Log(LogLevel::Error, msg) => {
errors.push(format!("FFmpeg log error: {}", msg));
}
FfmpegEvent::Log(LogLevel::Warning, msg) => {
eprintln!("FFmpeg warning: {}", msg);
}
_ => {}
}
}
// Check if output file was created
if !output_path.exists() {
return Err(format!(
"Export failed - output file not created. Errors: {}",
errors.join("; ")
));
}
// Check if output file has content
let metadata = fs::metadata(&output_path)
.map_err(|e| format!("Failed to check output file: {}", e))?;
if metadata.len() == 0 {
return Err(format!(
"Export failed - output file is empty. Errors: {}",
errors.join("; ")
));
}
Ok(output_path.to_string_lossy().to_string())
}
/// Check if ffmpeg is available.
#[tauri::command]
fn check_ffmpeg() -> bool {
ffmpeg_is_installed()
}
/// Download ffmpeg if not already installed.
#[tauri::command]
fn download_ffmpeg() -> Result<String, String> {
ensure_ffmpeg()?;
Ok(sidecar_path().unwrap_or_default().to_string_lossy().to_string())
}
/// Get video file metadata using ffprobe.
#[tauri::command]
fn get_video_metadata(video_path: String) -> Result<Value, String> {
// Ensure ffmpeg is available
ensure_ffmpeg()?;
// Use ffprobe via ffmpeg-sidecar
let iter = FfmpegCommand::new()
.arg("-v").arg("quiet")
.arg("-print_format").arg("json")
.arg("-show_format")
.arg("-show_streams")
.arg(&video_path)
.spawn()
.map_err(|e| format!("Failed to spawn ffprobe: {}", e))?
.iter()
.map_err(|e| format!("Failed to create ffprobe iterator: {}", e))?;
let mut json_output = String::new();
for event in iter {
match event {
FfmpegEvent::Log(LogLevel::Info, msg) | FfmpegEvent::Log(LogLevel::Unknown, msg) => {
// Capture JSON output
if msg.trim().starts_with('{') || msg.trim().starts_with('[') {
json_output.push_str(&msg);
}
}
FfmpegEvent::Error(e) => {
return Err(format!("FFprobe error: {}", e));
}
_ => {}
}
}
// Parse the JSON output
serde_json::from_str(&json_output)
.map_err(|e| format!("Failed to parse ffprobe output: {}", e))
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_autostart::init(
tauri_plugin_autostart::MacosLauncher::LaunchAgent,
Some(vec!["--hidden"]),
))
.setup(|app| {
// Auto-start the record-daemon on app launch.
// We spawn a background task so the UI isn't blocked while the
// daemon boots (it can take a few seconds to initialise OBS).
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
match daemon_ipc::ensure_daemon_running(30).await {
Ok(true) => {
eprintln!("[tauri] record-daemon is running");
}
Ok(false) => {
eprintln!("[tauri] record-daemon did not become ready within the timeout");
}
Err(e) => {
eprintln!("[tauri] failed to start record-daemon: {}", e);
}
}
// Drop the handle – no further use
drop(handle);
});
Ok(())
})
.invoke_handler(tauri::generate_handler![
get_game_history,
get_timeline,
get_recordings_dir,
find_video_file,
list_video_files,
export_clip,
export_clip_precise,
check_ffmpeg,
download_ffmpeg,
get_video_metadata,
// Daemon IPC commands
daemon_ipc::daemon_is_running,
daemon_ipc::daemon_ensure_running,
daemon_ipc::daemon_get_status,
daemon_ipc::daemon_get_settings,
daemon_ipc::daemon_update_settings,
daemon_ipc::daemon_reset_settings,
daemon_ipc::daemon_get_encoders,
daemon_ipc::daemon_get_audio_devices,
daemon_ipc::daemon_add_audio_source,
daemon_ipc::daemon_remove_audio_source,
daemon_ipc::daemon_update_audio_source,
daemon_ipc::daemon_start_recording,
daemon_ipc::daemon_stop_recording,
daemon_ipc::daemon_shutdown,
daemon_ipc::daemon_get_log_path,
daemon_ipc::daemon_read_logs,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
-6
View File
@@ -1,6 +0,0 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
tauri_app_lib::run()
}
-49
View File
@@ -1,49 +0,0 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "leaguerecorder",
"version": "0.3.0",
"identifier": "v.leaguerecorder",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
"beforeBuildCommand": "npm run build",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"title": "League Recorder",
"width": 1280,
"height": 800,
"minWidth": 800,
"minHeight": 600
}
],
"security": {
"csp": null,
"assetProtocol": {
"enable": true,
"scope": [
"$APPDATA/**",
"$APPDATA/../**",
"C:/Users/**/AppData/Roaming/**"
]
}
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"resources": {
"binaries/obs.dll": "obs.dll"
},
"externalBin": ["binaries/record-daemon"]
}
}
-164
View File
@@ -1,164 +0,0 @@
<script setup lang="ts">
import { ref, onMounted } from "vue";
import GameHistory from "./components/GameHistory.vue";
import GameReview from "./components/GameReview.vue";
import Settings from "./components/Settings.vue";
import type { GameHistoryItem } from "./types/timeline";
import { fetchLatestDdragonVersion } from "./types/ddragon";
// Current view state
const currentView = ref<"history" | "review" | "settings">("history");
const selectedGame = ref<GameHistoryItem | null>(null);
// Navigate to review view
function openReview(game: GameHistoryItem) {
selectedGame.value = game;
currentView.value = "review";
}
// Navigate back to history
function closeReview() {
currentView.value = "history";
selectedGame.value = null;
}
// Navigate to settings
function openSettings() {
currentView.value = "settings";
}
// Navigate back from settings
function closeSettings() {
currentView.value = "history";
}
// Initialize DDragon version on app mount
onMounted(() => {
fetchLatestDdragonVersion();
});
</script>
<template>
<div class="app">
<!-- Navigation bar -->
<nav v-if="currentView !== 'review'" class="app-nav">
<div class="nav-left">
<button
:class="['nav-tab', { active: currentView === 'history' }]"
@click="currentView = 'history'"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="3" width="7" height="7" rx="1" />
<rect x="14" y="3" width="7" height="7" rx="1" />
<rect x="3" y="14" width="7" height="7" rx="1" />
<rect x="14" y="14" width="7" height="7" rx="1" />
</svg>
Game History
</button>
<button
:class="['nav-tab', { active: currentView === 'settings' }]"
@click="openSettings"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
</svg>
Settings
</button>
</div>
</nav>
<GameHistory
v-if="currentView === 'history'"
@open-review="openReview"
/>
<GameReview
v-else-if="currentView === 'review' && selectedGame"
:game="selectedGame"
@back="closeReview"
/>
<Settings
v-else-if="currentView === 'settings'"
@back="closeSettings"
/>
</div>
</template>
<style>
/* Global styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.3);
}
.app {
min-height: 100vh;
background: #0a0a13;
}
/* Navigation bar */
.app-nav {
display: flex;
align-items: center;
padding: 0 24px;
height: 48px;
background: rgba(255, 255, 255, 0.03);
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}
.nav-left {
display: flex;
gap: 4px;
}
.nav-tab {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
background: none;
border: none;
border-radius: 6px;
color: #94a3b8;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s;
}
.nav-tab:hover {
color: #e2e8f0;
background: rgba(255, 255, 255, 0.06);
}
.nav-tab.active {
color: #f1f5f9;
background: rgba(255, 255, 255, 0.08);
}
</style>
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

Before

Width:  |  Height:  |  Size: 496 B

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,721 +0,0 @@
<script setup lang="ts">
import { ref, computed, watch } from "vue";
import type {
HighlightClip,
HighlightSettings,
HighlightType,
} from "../types/timeline";
import {
DEFAULT_HIGHLIGHT_SETTINGS,
getHighlightTypeColor,
getHighlightTypeIcon,
formatDuration,
} from "../types/timeline";
// Props
const props = defineProps<{
highlights: HighlightClip[];
currentVideoTime: number;
videoDuration: number;
isPlaying: boolean;
isExporting: boolean;
exportingClipId: number | null;
}>();
// Emits
const emit = defineEmits<{
(e: "seek-to", time: number): void;
(e: "play-clip", clip: HighlightClip): void;
(e: "play-all"): void;
(e: "export-clip", clip: HighlightClip): void;
(e: "export-all"): void;
(e: "settings-changed", settings: HighlightSettings): void;
}>();
// Settings panel state
const showSettings = ref(false);
const settings = ref<HighlightSettings>({ ...DEFAULT_HIGHLIGHT_SETTINGS });
// Type filter toggles
const typeToggles = ref<Record<HighlightType, boolean>>({
kill: DEFAULT_HIGHLIGHT_SETTINGS.included_types.includes("kill"),
death: DEFAULT_HIGHLIGHT_SETTINGS.included_types.includes("death"),
assist: DEFAULT_HIGHLIGHT_SETTINGS.included_types.includes("assist"),
multi_kill: DEFAULT_HIGHLIGHT_SETTINGS.included_types.includes("multi_kill"),
trade_kill: DEFAULT_HIGHLIGHT_SETTINGS.included_types.includes("trade_kill"),
});
// Watch type toggles and update settings
watch(
typeToggles,
(toggles) => {
const included_types = (Object.entries(toggles) as [HighlightType, boolean][])
.filter(([, enabled]) => enabled)
.map(([type]) => type);
settings.value = { ...settings.value, included_types };
emit("settings-changed", settings.value);
},
{ deep: true },
);
// Watch buffer settings and emit
watch(
() => [settings.value.buffer_before, settings.value.buffer_after, settings.value.merge_overlapping, settings.value.merge_gap_secs],
() => {
emit("settings-changed", settings.value);
},
);
// Currently active clip (the one whose time range contains the current video time)
const activeClipId = computed(() => {
for (const clip of props.highlights) {
if (
props.currentVideoTime >= clip.start_time &&
props.currentVideoTime <= clip.end_time
) {
return clip.id;
}
}
return null;
});
// Stats
const killCount = computed(() => props.highlights.filter(h => h.highlight_type === "kill").length);
const deathCount = computed(() => props.highlights.filter(h => h.highlight_type === "death").length);
const multiKillCount = computed(() => props.highlights.filter(h => h.highlight_type === "multi_kill").length);
const tradeKillCount = computed(() => props.highlights.filter(h => h.highlight_type === "trade_kill").length);
const assistCount = computed(() => props.highlights.filter(h => h.highlight_type === "assist").length);
const totalDuration = computed(() => {
const total = props.highlights.reduce((sum, h) => sum + (h.end_time - h.start_time), 0);
return total;
});
// Seek to the start of a clip
function seekToClip(clip: HighlightClip) {
emit("seek-to", clip.start_time);
}
// Play a specific clip
function playClip(clip: HighlightClip) {
emit("play-clip", clip);
}
// Export a single clip
function exportClip(clip: HighlightClip) {
emit("export-clip", clip);
}
// Format clip time range
function formatClipTime(clip: HighlightClip): string {
return `${formatDuration(clip.start_time)} - ${formatDuration(clip.end_time)}`;
}
// Format clip duration
function formatClipDuration(clip: HighlightClip): string {
return formatDuration(clip.end_time - clip.start_time);
}
</script>
<template>
<div class="highlights-panel">
<!-- Header -->
<div class="highlights-header">
<h3>
<span class="header-icon">🎬</span>
Highlights
</h3>
<button
class="settings-toggle"
:class="{ active: showSettings }"
@click="showSettings = !showSettings"
title="Highlight settings"
>
⚙️
</button>
</div>
<!-- Settings Panel (collapsible) -->
<div v-if="showSettings" class="settings-panel">
<div class="settings-group">
<label class="settings-label">Buffer Before</label>
<div class="slider-row">
<input
type="range"
min="2"
max="30"
step="1"
v-model.number="settings.buffer_before"
class="settings-slider"
/>
<span class="slider-value">{{ settings.buffer_before }}s</span>
</div>
</div>
<div class="settings-group">
<label class="settings-label">Buffer After</label>
<div class="slider-row">
<input
type="range"
min="2"
max="30"
step="1"
v-model.number="settings.buffer_after"
class="settings-slider"
/>
<span class="slider-value">{{ settings.buffer_after }}s</span>
</div>
</div>
<div class="settings-group">
<label class="settings-label">Include Types</label>
<div class="type-toggles">
<label
v-for="typeInfo in [
{ type: 'kill' as HighlightType, label: 'Kills', icon: '⚔️' },
{ type: 'death' as HighlightType, label: 'Deaths', icon: '💀' },
{ type: 'assist' as HighlightType, label: 'Assists', icon: '🤝' },
{ type: 'multi_kill' as HighlightType, label: 'Multi Kills', icon: '🔥' },
{ type: 'trade_kill' as HighlightType, label: 'Trade Kills', icon: '🔄' },
]"
:key="typeInfo.type"
class="type-toggle"
:style="{ borderColor: typeToggles[typeInfo.type] ? getHighlightTypeColor(typeInfo.type) : 'rgba(255,255,255,0.1)' }"
>
<input
type="checkbox"
v-model="typeToggles[typeInfo.type]"
class="toggle-checkbox"
/>
<span class="toggle-icon">{{ typeInfo.icon }}</span>
<span class="toggle-label">{{ typeInfo.label }}</span>
</label>
</div>
</div>
<div class="settings-group">
<label class="settings-row-label">
<input
type="checkbox"
v-model="settings.merge_overlapping"
class="toggle-checkbox"
/>
Merge overlapping clips
</label>
</div>
<div v-if="settings.merge_overlapping" class="settings-group">
<label class="settings-label">Merge Gap</label>
<div class="slider-row">
<input
type="range"
min="0"
max="20"
step="1"
v-model.number="settings.merge_gap_secs"
class="settings-slider"
/>
<span class="slider-value">{{ settings.merge_gap_secs }}s</span>
</div>
</div>
</div>
<!-- Quick Stats -->
<div class="highlights-stats">
<div class="stat-pill" v-if="killCount > 0">
<span>⚔️</span> {{ killCount }}
</div>
<div class="stat-pill" v-if="deathCount > 0">
<span>💀</span> {{ deathCount }}
</div>
<div class="stat-pill" v-if="assistCount > 0">
<span>🤝</span> {{ assistCount }}
</div>
<div class="stat-pill" v-if="multiKillCount > 0">
<span>🔥</span> {{ multiKillCount }}
</div>
<div class="stat-pill" v-if="tradeKillCount > 0">
<span>🔄</span> {{ tradeKillCount }}
</div>
<div class="stat-pill total">
<span>⏱️</span> {{ formatDuration(totalDuration) }}
</div>
</div>
<!-- Action Buttons -->
<div class="highlights-actions">
<button
class="action-btn play-all"
@click="emit('play-all')"
:disabled="highlights.length === 0"
>
▶ Play All
</button>
<button
class="action-btn export-all"
@click="emit('export-all')"
:disabled="highlights.length === 0 || isExporting"
>
{{ isExporting ? "Exporting..." : "📦 Export All" }}
</button>
</div>
<!-- Empty State -->
<div v-if="highlights.length === 0" class="empty-highlights">
<div class="empty-icon">🎬</div>
<p>No highlights detected</p>
<p class="empty-hint">Highlights are generated from kills, deaths, and multi-kills during the game.</p>
</div>
<!-- Highlights List -->
<div v-else class="highlights-list">
<div
v-for="clip in highlights"
:key="clip.id"
class="highlight-card"
:class="{
active: activeClipId === clip.id,
[clip.highlight_type]: true,
}"
@click="seekToClip(clip)"
>
<div class="highlight-indicator" :style="{ backgroundColor: getHighlightTypeColor(clip.highlight_type) }"></div>
<div class="highlight-content">
<div class="highlight-title-row">
<span class="highlight-icon">{{ getHighlightTypeIcon(clip.highlight_type) }}</span>
<span class="highlight-title">{{ clip.title }}</span>
<span class="highlight-duration">{{ formatClipDuration(clip) }}</span>
</div>
<div v-if="clip.subtitle" class="highlight-subtitle">
{{ clip.subtitle }}
</div>
<div class="highlight-time-row">
<span class="highlight-time">{{ formatClipTime(clip) }}</span>
</div>
</div>
<div class="highlight-actions">
<button
class="mini-btn play"
@click.stop="playClip(clip)"
title="Play this clip"
>
▶
</button>
<button
class="mini-btn export"
@click.stop="exportClip(clip)"
:disabled="isExporting && exportingClipId === clip.id"
title="Export this clip"
>
💾
</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.highlights-panel {
display: flex;
flex-direction: column;
gap: 0.75rem;
height: 100%;
overflow: hidden;
padding: 1rem;
}
/* Header */
.highlights-header {
display: flex;
align-items: center;
justify-content: space-between;
}
.highlights-header h3 {
margin: 0;
font-size: 1rem;
color: #c8aa6e;
display: flex;
align-items: center;
gap: 0.5rem;
}
.header-icon {
font-size: 1.1rem;
}
.settings-toggle {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 6px;
padding: 0.3rem 0.5rem;
cursor: pointer;
font-size: 0.85rem;
transition: all 0.2s;
line-height: 1;
}
.settings-toggle:hover {
background: rgba(255, 255, 255, 0.1);
}
.settings-toggle.active {
background: rgba(200, 170, 110, 0.15);
border-color: #c8aa6e;
}
/* Settings Panel */
.settings-panel {
background: rgba(0, 0, 0, 0.2);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
padding: 0.75rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.settings-group {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.settings-label {
font-size: 0.75rem;
color: #888;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.settings-row-label {
font-size: 0.8rem;
color: #ccc;
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
}
.slider-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.settings-slider {
flex: 1;
height: 4px;
-webkit-appearance: none;
background: rgba(255, 255, 255, 0.15);
border-radius: 2px;
cursor: pointer;
}
.settings-slider::-webkit-slider-thumb {
-webkit-appearance: none;
width: 14px;
height: 14px;
background: #c8aa6e;
border-radius: 50%;
cursor: pointer;
}
.slider-value {
font-family: monospace;
font-size: 0.8rem;
color: #c8aa6e;
min-width: 2.5rem;
text-align: right;
}
.type-toggles {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.type-toggle {
display: flex;
align-items: center;
gap: 0.3rem;
padding: 0.3rem 0.6rem;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
font-size: 0.75rem;
}
.type-toggle:hover {
background: rgba(255, 255, 255, 0.05);
}
.toggle-checkbox {
display: none;
}
.toggle-icon {
font-size: 0.85rem;
}
.toggle-label {
color: #ccc;
}
/* Quick Stats */
.highlights-stats {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.stat-pill {
display: flex;
align-items: center;
gap: 0.25rem;
padding: 0.25rem 0.6rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 12px;
font-size: 0.75rem;
color: #ccc;
}
.stat-pill.total {
color: #c8aa6e;
background: rgba(200, 170, 110, 0.1);
}
/* Action Buttons */
.highlights-actions {
display: flex;
gap: 0.5rem;
}
.action-btn {
flex: 1;
padding: 0.5rem 0.75rem;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 6px;
cursor: pointer;
font-size: 0.8rem;
font-weight: 500;
transition: all 0.2s;
text-align: center;
}
.action-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.action-btn.play-all {
background: rgba(74, 222, 128, 0.15);
border-color: rgba(74, 222, 128, 0.3);
color: #4ade80;
}
.action-btn.play-all:hover:not(:disabled) {
background: rgba(74, 222, 128, 0.25);
}
.action-btn.export-all {
background: rgba(200, 170, 110, 0.15);
border-color: rgba(200, 170, 110, 0.3);
color: #c8aa6e;
}
.action-btn.export-all:hover:not(:disabled) {
background: rgba(200, 170, 110, 0.25);
}
/* Empty State */
.empty-highlights {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem 1rem;
color: #666;
text-align: center;
}
.empty-icon {
font-size: 2.5rem;
margin-bottom: 0.75rem;
opacity: 0.5;
}
.empty-highlights p {
margin: 0.25rem 0;
font-size: 0.85rem;
}
.empty-hint {
font-size: 0.75rem !important;
color: #555;
}
/* Highlights List */
.highlights-list {
flex: 1;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 0.4rem;
padding-right: 0.25rem;
}
.highlight-card {
display: flex;
align-items: stretch;
gap: 0;
min-height: 56px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
cursor: pointer;
transition: all 0.2s;
overflow: hidden;
flex-shrink: 0;
}
.highlight-card:hover {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.15);
}
.highlight-card.active {
background: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.2);
}
.highlight-card.active.kill {
border-color: rgba(74, 222, 128, 0.4);
background: rgba(74, 222, 128, 0.08);
}
.highlight-card.active.death {
border-color: rgba(248, 113, 113, 0.4);
background: rgba(248, 113, 113, 0.08);
}
.highlight-card.active.assist {
border-color: rgba(167, 139, 250, 0.4);
background: rgba(167, 139, 250, 0.08);
}
.highlight-card.active.multi_kill {
border-color: rgba(249, 115, 22, 0.4);
background: rgba(249, 115, 22, 0.08);
}
.highlight-indicator {
width: 4px;
min-height: 100%;
flex-shrink: 0;
}
.highlight-content {
flex: 1;
padding: 0.5rem 0.65rem;
min-width: 0;
}
.highlight-title-row {
display: flex;
align-items: center;
gap: 0.35rem;
}
.highlight-icon {
font-size: 0.85rem;
flex-shrink: 0;
}
.highlight-title {
font-size: 0.85rem;
font-weight: 600;
color: #fff;
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.highlight-duration {
font-family: monospace;
font-size: 0.7rem;
color: #888;
flex-shrink: 0;
}
.highlight-subtitle {
font-size: 0.72rem;
color: #999;
margin-top: 0.15rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.highlight-time-row {
margin-top: 0.2rem;
}
.highlight-time {
font-family: monospace;
font-size: 0.65rem;
color: #666;
}
.highlight-actions {
display: flex;
flex-direction: column;
justify-content: center;
gap: 0.25rem;
padding: 0.35rem 0.5rem;
opacity: 0;
transition: opacity 0.2s;
}
.highlight-card:hover .highlight-actions,
.highlight-card.active .highlight-actions {
opacity: 1;
}
.mini-btn {
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 4px;
padding: 0.2rem 0.4rem;
cursor: pointer;
font-size: 0.7rem;
transition: all 0.15s;
line-height: 1;
}
.mini-btn:hover {
background: rgba(255, 255, 255, 0.15);
}
.mini-btn.play:hover {
background: rgba(74, 222, 128, 0.2);
border-color: rgba(74, 222, 128, 0.3);
}
.mini-btn.export:hover {
background: rgba(200, 170, 110, 0.2);
border-color: rgba(200, 170, 110, 0.3);
}
.mini-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
</style>
File diff suppressed because it is too large. Load diff
-4
View File
@@ -1,4 +0,0 @@
import { createApp } from "vue";
import App from "./App.vue";
createApp(App).mount("#app");
-178
View File
@@ -1,178 +0,0 @@
/**
* TypeScript types for daemon settings and status.
* Mirrors the Rust types from record-daemon/src/config/ and record-daemon/src/ipc/protocol.rs.
*/
// ---------------------------------------------------------------------------
// Encoder presets
// ---------------------------------------------------------------------------
export interface NvencPreset {
type: "nvenc";
bitrate: number;
cq_level: number;
two_pass: boolean;
}
export interface AmfPreset {
type: "amf";
bitrate: number;
quality: "speed" | "balanced" | "quality";
}
export interface X264Preset {
type: "x264";
preset: string;
bitrate: number;
crf: number | null;
}
export type EncoderPreset = NvencPreset | AmfPreset | X264Preset;
// ---------------------------------------------------------------------------
// Quality level
// ---------------------------------------------------------------------------
export type QualityLevel = "low" | "medium" | "high" | "ultra";
// ---------------------------------------------------------------------------
// Settings structures
// ---------------------------------------------------------------------------
export interface VideoSettings {
encoder_preset: EncoderPreset;
quality: QualityLevel;
frame_rate: number;
hardware_acceleration: boolean;
}
export interface OutputSettings {
path: string;
naming_pattern: string;
container: string;
split_size_mb: number;
split_time_minutes: number;
}
export interface AudioSettings {
enabled: boolean;
bitrate: number;
sample_rate: number;
channels: number;
capture_game: boolean;
game_volume: number;
capture_mic: boolean;
mic_device: string | null;
mic_volume: number;
capture_apps: AudioSourceConfig[];
apps_volume: number;
}
export interface AudioSourceConfig {
id: string;
name: string;
type: AudioSourceType;
device: string;
enabled: boolean;
volume: number | null;
}
export type AudioSourceType = "application" | "deviceOutput" | "deviceInput";
export interface AudioDeviceInfo {
id: string;
name: string;
is_default: boolean;
}
export interface GetAudioDevicesResponse {
input_devices: AudioDeviceInfo[];
output_devices: AudioDeviceInfo[];
}
export interface AudioSourceResponse {
source: AudioSourceConfig;
}
export interface DaemonSettings {
auto_record: boolean;
monitor_client: boolean;
poll_interval_ms: number;
socket_path: string | null;
log_level: string;
save_timeline: boolean;
}
export interface Settings {
video: VideoSettings;
output: OutputSettings;
audio: AudioSettings;
daemon: DaemonSettings;
}
/** Response wrapper from daemon_get_settings (daemon wraps in { settings: {...} }). */
export interface GetSettingsResponse {
settings: Settings;
}
// ---------------------------------------------------------------------------
// Daemon status
// ---------------------------------------------------------------------------
export type DaemonStatus = "idle" | "monitoring" | "recording" | "error" | "shutting_down";
export interface DaemonStatusResponse {
status: DaemonStatus;
is_recording: boolean;
current_game_id: number | null;
client_connected: boolean;
}
// ---------------------------------------------------------------------------
// Encoder info
// ---------------------------------------------------------------------------
export interface EncoderInfo {
id: string;
name: string;
is_hardware: boolean;
available: boolean;
}
export interface EncodersResponse {
available: EncoderInfo[];
current: string;
}
// ---------------------------------------------------------------------------
// Quality level metadata
// ---------------------------------------------------------------------------
export const QUALITY_LEVELS: { value: QualityLevel; label: string; description: string }[] = [
{ value: "low", label: "Low", description: "720p @ 30fps" },
{ value: "medium", label: "Medium", description: "1080p @ 30fps" },
{ value: "high", label: "High", description: "1080p @ 60fps" },
{ value: "ultra", label: "Ultra", description: "1440p @ 60fps" },
];
export const CONTAINER_FORMATS = ["mp4", "mkv", "mov", "flv"] as const;
export const LOG_LEVELS = ["trace", "debug", "info", "warn", "error"] as const;
export const X264_PRESETS = [
"ultrafast",
"superfast",
"veryfast",
"faster",
"fast",
"medium",
"slow",
"slower",
"veryslow",
] as const;
export const AMF_QUALITIES: { value: "speed" | "balanced" | "quality"; label: string }[] = [
{ value: "speed", label: "Speed" },
{ value: "balanced", label: "Balanced" },
{ value: "quality", label: "Quality" },
];
-91
View File
@@ -1,91 +0,0 @@
/**
* DDragon version resolver for Data Dragon asset URLs.
*
* Resolves the appropriate patch version with the following priority:
* 1. Game-specific version (from recorded timeline data)
* 2. Latest version fetched from the DDragon API
* 3. Hardcoded fallback version
*/
import { ref } from "vue";
/** DDragon versions API endpoint. */
const DDRAGON_VERSIONS_URL = "https://ddragon.leagueoflegends.com/api/versions.json";
/** Fallback version used when the DDragon API is unreachable. */
const FALLBACK_VERSION = "16.10.1";
/** Latest version from DDragon API (reactive — updates trigger Vue re-renders). */
export const ddragonVersion = ref<string>(FALLBACK_VERSION);
/** Whether the version has been fetched at least once. */
let versionInitialized = false;
/**
* Fetch the latest game version from the DDragon API.
* Results are cached after the first call — subsequent calls return immediately.
* Safe to call multiple times (deduplicated).
*/
export async function fetchLatestDdragonVersion(): Promise<string> {
if (versionInitialized) {
return ddragonVersion.value;
}
try {
const response = await fetch(DDRAGON_VERSIONS_URL);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const versions: string[] = await response.json();
if (versions.length > 0) {
ddragonVersion.value = versions[0];
}
} catch (err) {
console.warn("[ddragon] Failed to fetch versions, using fallback:", err);
} finally {
versionInitialized = true;
}
return ddragonVersion.value;
}
/**
* Get the current DDragon version (synchronous).
* Returns the cached latest version, or the fallback if not yet fetched.
*/
export function getDdragonVersion(): string {
return ddragonVersion.value;
}
/**
* Convert a League game version string to DDragon format.
*
* The League Client reports versions like "16.10.1" or "16.10.1.1234".
* DDragon uses the first three components (e.g., "16.10.1").
*
* @returns The DDragon-formatted version string, or null if the input is invalid.
*/
export function gameVersionToDdragonVersion(gameVersion: string | null | undefined): string | null {
if (!gameVersion || typeof gameVersion !== "string") {
return null;
}
const trimmed = gameVersion.trim();
if (!trimmed) {
return null;
}
// DDragon versions are in the format "XX.YY.ZZ" (e.g., "16.10.1")
// The game client may report "XX.YY.ZZ.WWWW" — we take the first 3 parts
const parts = trimmed.split(".");
if (parts.length >= 3) {
return `${parts[0]}.${parts[1]}.${parts[2]}`;
}
// Two-part version — unlikely but handle gracefully
if (parts.length === 2) {
return trimmed;
}
return null;
}
File diff suppressed because it is too large. Load diff
-7
View File
@@ -1,7 +0,0 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<{}, {}, any>;
export default component;
}
-25
View File
@@ -1,25 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
-10
View File
@@ -1,10 +0,0 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}
-32
View File
@@ -1,32 +0,0 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST;
// https://vitejs.dev/config/
export default defineConfig(async () => ({
plugins: [vue()],
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));