From 28cfdaa463c13e840f3a539f082638da6278e817 Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 06:15:30 -0700 Subject: [PATCH] feat(viewer): view a recording `komorebi-recorder view ` opens a recording in a window: the video of every display, a timeline with a lane for the bug regions, events, log errors, the machine and the findings, and an inspector for the state at the playhead, one event traced end to end, and komorebi's log. The window is untitled so komorebi leaves it alone, and out of any recording being made. It is where a bug is marked: the form takes the region from the selection or the playhead and asks what went wrong and what was expected. It opens from the recorder window as well. --- README.md | 1 + docs/usage/investigating-a-recording.md | 34 +- docs/usage/recording-a-bug-repro.md | 11 + komorebi-recorder/src/cli/mod.rs | 5 + komorebi-recorder/src/cli/viewer_command.rs | 13 + komorebi-recorder/src/lib.rs | 2 + komorebi-recorder/src/viewer/app.rs | 1267 +++++++++++++++++++ komorebi-recorder/src/viewer/composer.rs | 512 ++++++++ komorebi-recorder/src/viewer/inspector.rs | 882 +++++++++++++ komorebi-recorder/src/viewer/keymap.rs | 366 ++++++ komorebi-recorder/src/viewer/lanes.rs | 1048 +++++++++++++++ komorebi-recorder/src/viewer/loaded.rs | 342 +++++ komorebi-recorder/src/viewer/mod.rs | 156 +++ komorebi-recorder/src/viewer/prefs.rs | 253 ++++ komorebi-recorder/src/viewer/theme.rs | 146 +++ komorebi-recorder/src/viewer/timeline.rs | 679 ++++++++++ komorebi-recorder/src/viewer/video.rs | 458 +++++++ 17 files changed, 6173 insertions(+), 2 deletions(-) create mode 100644 komorebi-recorder/src/cli/viewer_command.rs create mode 100644 komorebi-recorder/src/viewer/app.rs create mode 100644 komorebi-recorder/src/viewer/composer.rs create mode 100644 komorebi-recorder/src/viewer/inspector.rs create mode 100644 komorebi-recorder/src/viewer/keymap.rs create mode 100644 komorebi-recorder/src/viewer/lanes.rs create mode 100644 komorebi-recorder/src/viewer/loaded.rs create mode 100644 komorebi-recorder/src/viewer/mod.rs create mode 100644 komorebi-recorder/src/viewer/prefs.rs create mode 100644 komorebi-recorder/src/viewer/theme.rs create mode 100644 komorebi-recorder/src/viewer/timeline.rs create mode 100644 komorebi-recorder/src/viewer/video.rs diff --git a/README.md b/README.md index b6f385ba..8df35910 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ when things happened (events | errors | incidents): 00:04.500 ############################## 1 0 0 ``` +`komorebi-recorder view ./repro` opens the recording in the viewer, which is where you mark where the bug is. Every command takes `--json`, and `komorebi-recorder guide` prints a playbook for an agent. [Investigating a recording](docs/usage/investigating-a-recording.md) walks through both ways of working. diff --git a/docs/usage/investigating-a-recording.md b/docs/usage/investigating-a-recording.md index cd90a1ec..06fd2639 100644 --- a/docs/usage/investigating-a-recording.md +++ b/docs/usage/investigating-a-recording.md @@ -14,13 +14,43 @@ Every command takes `--json`, which prints an envelope `{ok, schema, data, warni error, 2 usage, 3 not found, 4 the session cannot answer (still recording, or the recorder died: `reindex` it), 5 over budget. -Everything a recording holds is available from the command line, so an agent can investigate headlessly: +## The viewer + +``` +komorebi-recorder view +``` + +opens the recording in its own window, for the person who made it (or anyone with the folder) to play, scrub and mark. +The recorder window has **Open session…** and **Open last** for the same thing. + +- The **video** of every display, side by side. A display that was unplugged or asleep shows why it has nothing there, + and the others carry on. **State overlay** draws komorebi's idea of the layout over the picture: where each tiled + window was meant to be (dashed) and where it really was (solid, red if it looks wrong). +- The **timeline** under it has a lane for the **bug regions** you marked, komorebi's **events** (coloured by what kind, + with echoes faint), errors and warnings in komorebi's log, what happened to the **machine** (a display unplugged, a + sleep), the **findings** that look wrong, and the **video** each display has. Click anywhere to go there, drag to + scrub, pinch or ⌘-scroll to zoom, scroll to pan, Shift-drag to select a range. +- **Playing** goes forwards and backwards at 0.25× to 8×; J, K and L shuttle like a video editor; ← and → step one + frame; `,` and `.` jump between events. Press **?** in the window for every key. +- The **inspector** on the right: _Now_ is the state at the playhead and what has just happened; _Event_ is a selected + event traced end to end, as `trace` shows it, ending with what the OS trace recorded around it (komorebi's own calls + into the OS, the system, each application) as groups you can open; _Findings_ is what looks wrong, ranked; _Bugs_ is what was marked and + concluded; _Log_ is komorebi's own log, following the playhead. + +### Marking the bug + +Press **B** (or **Mark bug**) to describe the bug: the form takes the region from your selection (`[` and `]` mark its +ends, or Shift-drag on the timeline) or from the playhead, asks what goes wrong and what you expected, and saves it the +moment you press Save. Drag a region's edges on the timeline to adjust it. **Copy a prompt for an agent** in the _Bugs_ +tab puts an instruction on the clipboard that starts an agent on `brief` with your description. + +Everything the viewer shows is also available from the command line, so an agent can investigate headlessly: ## What the user said The first thing in a [brief](#brief) is the **bug region**: the stretch of the recording the user marked, with their description of what is wrong and what they expected. -Add one with `annotate`: +The user marks it in the viewer. To add one without a window, as a script or an agent would: ``` komorebi-recorder annotate add --kind bug --start 12.5 --end 18 \ diff --git a/docs/usage/recording-a-bug-repro.md b/docs/usage/recording-a-bug-repro.md index e9b41a3f..c04acc9b 100644 --- a/docs/usage/recording-a-bug-repro.md +++ b/docs/usage/recording-a-bug-repro.md @@ -60,6 +60,7 @@ The recorder window keeps itself out of the video (Windows 10 version 2004 or la The recorder window is borderless and untitled on purpose: komorebi does not manage windows without a title, so opening it does not move your layout around while you are trying to reproduce a layout bug. It is also excluded from the video, as is any other `komorebi-recorder` process. +The viewer is one such process. ## Recording @@ -94,6 +95,16 @@ Useful options: | `--probe-windows` | Windows: after each window event, record what Windows says about that window (see below) | | `--fps N`, `--retina`, `--codec hevc\|h264` | Video settings (30 fps cap, logical points, HEVC by default) | +### Marking where the bug is + +A bug is marked in one place, the viewer, after the recording: `komorebi-recorder view ` opens it, and **Mark +bug** (or **B**) takes a stretch of the recording and what went wrong in it. That marks a _region_, not a single moment. +The recorder window has no button for it, so while recording there is nothing to do but reproduce the problem. + +This is what makes the recording useful to whoever investigates it, person or agent: your description is the ground +truth of _what_ went wrong, and everything else in the session is evidence of _why_. See +[Investigating a recording](investigating-a-recording.md#marking-the-bug). + ### Without video `komorebi-recorder record --no-video` records everything but the screen: komorebi's events and log, the OS trace and diff --git a/komorebi-recorder/src/cli/mod.rs b/komorebi-recorder/src/cli/mod.rs index a1ae05b1..c78b2e7e 100644 --- a/komorebi-recorder/src/cli/mod.rs +++ b/komorebi-recorder/src/cli/mod.rs @@ -12,6 +12,7 @@ mod investigate; mod query; mod record; mod video; +mod viewer_command; use crate::analysis::envelope::unusable; use crate::analysis::envelope::with_hint; @@ -46,6 +47,7 @@ pub use query::SummaryArgs; pub use record::RecordArgs; pub use video::ChangesArgs; pub use video::SheetArgs; +pub use viewer_command::ViewArgs; /// The command line of `komorebi-recorder`. #[derive(Parser)] @@ -112,6 +114,8 @@ pub enum Command { Changes(ChangesArgs), /// A contact sheet image of frames, with the times, events and bug region marked Sheet(SheetArgs), + /// Open a recording in a window: play and scrub the video with every event on a timeline + View(ViewArgs), /// Which line of komorebi's source wrote a line of its log, with the code around it Code(CodeArgs), /// Add, edit or delete a session's bug regions, notes and an agent's findings @@ -239,6 +243,7 @@ pub fn run(command: Command) -> eyre::Result<()> { Command::Trace(args) => investigate::trace(&args), Command::Window(args) => investigate::window(&args), Command::Changes(args) => video::changes(&args), + Command::View(args) => crate::viewer::run(args.session), Command::Sheet(args) => video::sheet(&args), Command::Annotate(args) => annotate::annotate(&args), Command::Annotations(args) => annotate::list(&args), diff --git a/komorebi-recorder/src/cli/viewer_command.rs b/komorebi-recorder/src/cli/viewer_command.rs new file mode 100644 index 00000000..dbb6870c --- /dev/null +++ b/komorebi-recorder/src/cli/viewer_command.rs @@ -0,0 +1,13 @@ +//! `view`: the arguments of the viewer window. +//! +//! The command table runs the command with `crate::viewer::run`; this file holds only its arguments. + +use clap::Args; +use std::path::PathBuf; + +/// The arguments of `view`: the session to open, if one is given. +#[derive(Args, Debug)] +pub struct ViewArgs { + /// The recording's folder [default: choose one in the window] + pub session: Option, +} diff --git a/komorebi-recorder/src/lib.rs b/komorebi-recorder/src/lib.rs index 6aae8dbc..c24f89b9 100644 --- a/komorebi-recorder/src/lib.rs +++ b/komorebi-recorder/src/lib.rs @@ -60,6 +60,7 @@ //! | [`doctor`] | what a recording leans on, and probes that measure it | //! | [`report`] | answers as text for a terminal | //! | [`playback`] | a clock that runs forwards or backwards, and the decoding that follows it | +//! | [`viewer`] | the window that plays a recording | //! //! # What is not supported //! @@ -100,3 +101,4 @@ pub mod system_state; pub mod testkit; pub mod timecode; pub mod timeline; +pub mod viewer; diff --git a/komorebi-recorder/src/viewer/app.rs b/komorebi-recorder/src/viewer/app.rs new file mode 100644 index 00000000..903b0671 --- /dev/null +++ b/komorebi-recorder/src/viewer/app.rs @@ -0,0 +1,1267 @@ +//! The viewer window: opening a session and keeping everything on screen in step. +//! +//! [`ViewerApp`] is the whole application and holds a [`Screen`]: nothing opened yet, a session +//! loading, a session that failed to open, or an [`Open`] session. [`ViewerApp::ui`] draws one frame +//! of whichever it is. An [`Open`] is where the state of a session being viewed lives (the +//! playhead's [`Playback`], the visible stretch of the timeline, the selection, which event or +//! finding or bug region is selected, the form being filled in), and its methods are spread +//! over the files that draw each part: this file keeps it in step with the keyboard, and the lanes, +//! the inspector, the video and the composer each add the methods that draw and act on their +//! part. +//! +//! Everything here needs an `egui::Context` to draw, so none of it has an example. The tests at the +//! bottom of this file run [`ViewerApp::ui`] headlessly through `egui::Context::run` with real key +//! events, against sessions made by the test kit, and are what covers the behavior. + +use super::keymap; +use super::keymap::Action; +use super::loaded::Loaded; +use super::loaded::name_of; +use super::prefs::Prefs; +use super::theme; +use super::timeline; +use super::timeline::View; +use crate::analysis::guard::SessionPath; +use crate::analysis::state::Snapshot; +use crate::analysis::trace::TraceData; +use crate::playback::Playback; +use color_eyre::eyre; +use crossbeam_channel::Receiver; +use eframe::egui; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + +/// How wide decoded frames are asked for, in pixels: enough for a large window on a retina +/// display. It is what [`Playback::start`] is given. +pub const DECODE_WIDTH: u32 = 1600; + +/// Which tab of the inspector on the right is showing. +/// +/// The inspector is described in full in the private `inspector` module of the viewer; in short, +/// each tab answers one question about the playhead or about the recording. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tab { + /// The state komorebi was in at the playhead, what is wrong in it, and the events just before. + Now, + /// One selected event end to end: what its handler logged, what changed and who changed it, and + /// what the rest of the system did around it. + Event, + /// The findings: what looks wrong in the recording, ranked. + Findings, + /// The bug regions marked, and the notes and findings annotated, with the form to mark one. + Bugs, + /// komorebi's own log, following the playhead. + Log, +} + +/// A frame of a display uploaded to the graphics card, and which frame it is. +/// +/// A new [`Frame`](crate::playback::Frame) from [`Playback`] is uploaded again when it differs +/// from the one in the tile, so the same picture is never uploaded twice. +pub struct Tile { + /// The picture, as a texture on the graphics card. + pub texture: egui::TextureHandle, + /// Which [`Frame`](crate::playback::Frame) it was made from, by address: a new frame is a new + /// `Arc`. + pub frame: usize, +} + +/// A session, open and showing: everything the window keeps for the session being viewed. +/// +/// It is made by [`ViewerApp`] when a session has loaded, and it owns the session's data +/// ([`Loaded`]), the [`Playback`] of its video and the state of every part of the window. It also +/// owns the background scan for changes in the picture, which stops when it is dropped. +/// +/// A window is needed to draw it (see [`Open::ui`]), and the fields are public so that the tests +/// can look at what a key press did. +pub struct Open { + /// The session, read. + pub loaded: Loaded, + /// The playhead and the decoding of the video. + pub playback: Playback, + /// The picture of each display last uploaded, by display id. + pub tiles: HashMap, + /// The display that stepping acts on and whose picture is outlined. It is picked by clicking + /// a picture or with the number keys, and is the first display with video when a session opens. + /// `None` if no display has video. + pub focus: Option, + /// The stretch of the recording the timeline shows. + pub view: View, + /// A range picked on the timeline, as `(start, end)` in session video seconds: marked with `[` + /// and `]` or by dragging with Shift. + pub selection: Option<(f64, f64)>, + /// The sequence number of the event selected, whose trace the Event tab shows. + pub selected_event: Option, + /// The index into [`Loaded::findings`] of the finding selected. + pub selected_finding: Option, + /// The id of the annotation selected in the Bugs tab and on the bugs lane. + pub selected_bug: Option, + /// The tab of the inspector that is showing. + pub tab: Tab, + /// Whether komorebi's state is drawn over the video (the "state overlay" box and `O`). It is + /// kept in the preferences. + pub overlay: bool, + /// Whether the list of keys is open. + pub help: bool, + /// The form for marking or editing a bug region, while it is open. + pub composer: Option, + /// The trace of each event looked at, by sequence number, worked out once. + pub traces: HashMap>, + /// The OS trace around each event looked at, by sequence number, worked out once. + pub os_traces: HashMap>, + /// The state the overlay draws: the id of the state notification it came from and the state. + /// It is kept while the playhead stays within the same notification (see + /// [`Open::state_at`]). + pub state: Option<(u64, Arc)>, + /// A note to show in the top bar and when it was said. The bar shows it for four seconds. + pub message: Option<(String, Instant)>, + /// Annotations deleted, newest last, to bring back. + pub deleted: Vec, + /// The drag going on across the lanes of the timeline, if one is. + pub drag: Option, + /// When the picture changed, found in the background after opening. `None` until the scan + /// finishes, and after it fails. + pub changes: Option, + /// Where the scan sends its result, until it arrives. `None` once it has, and when there is + /// nothing to scan (no display has video). + pub changes_result: Option>>, + /// Set to stop the background scan when this session is closed. + changes_cancel: Arc, + /// A bug region whose edge is being dragged: its id and where its start and end would be. + pub edge_preview: Option<(String, f64, f64)>, +} + +/// The screen the window is showing: a session, or what stands in for one. +/// +/// A [`ViewerApp`] is always on exactly one of these. [`ViewerApp::open`] moves it from `Empty` +/// (or any screen) to `Loading`, and from there to `Open` or `Failed` when the load finishes. +pub enum Screen { + /// Nothing opened yet: the start screen, with the recent sessions that still exist. + Empty, + /// A session is being read in the background: a spinner. + Loading { + /// The session being opened. + dir: PathBuf, + /// Where the load's result arrives. + result: Receiver>, + }, + /// The session would not open: the start screen again, with the reason. + Failed { + /// The session that was being opened. + dir: PathBuf, + /// Why it would not open: the error with its causes, on one line. + message: String, + }, + /// A session, open and showing. + Open(Box), +} + +/// The viewer application: the preferences and the screen being shown. +/// +/// This is what [`run`](super::run) hands to `eframe`. [`ViewerApp::new`] makes one showing the +/// start screen, [`ViewerApp::open`] opens a session, and [`ViewerApp::ui`] draws a frame. It needs +/// a window to draw and so has no example. +pub struct ViewerApp { + /// The viewer's preferences. Saved when a session is opened and when the state overlay is + /// switched. + pub prefs: Prefs, + prefs_dir: PathBuf, + /// The screen the window is showing. + pub screen: Screen, + picker: Option>>, +} + +/// Ask the user for a folder with the system's own dialog, off the UI thread. +fn pick_folder() -> Receiver> { + let (sender, receiver) = crossbeam_channel::bounded(1); + std::thread::spawn(move || { + let _ = sender.send(crate::platform::shell::pick_folder("Choose a recording")); + }); + receiver +} + +impl ViewerApp { + /// Returns a viewer showing the start screen, with the preferences kept in `prefs_dir`. + /// + /// The preferences are read with [`Prefs::load`], so a missing or damaged file gives the + /// defaults. Nothing is opened: see [`ViewerApp::open`]. + #[must_use] + pub fn new(prefs_dir: PathBuf) -> Self { + Self { + prefs: Prefs::load(&prefs_dir), + prefs_dir, + screen: Screen::Empty, + picker: None, + } + } + + /// Starts opening the session in `dir` in the background. + /// + /// The screen becomes [`Screen::Loading`] at once, replacing whatever was showing, and + /// [`ViewerApp::ui`] brings the result in when the load has finished: an [`Open`] session, or + /// [`Screen::Failed`] with the reason. A session that cannot be opened is therefore not an error + /// here; see [`Loaded::load`] for what can go wrong. + pub fn open(&mut self, dir: &Path) { + let (sender, result) = crossbeam_channel::bounded(1); + let target = dir.to_path_buf(); + std::thread::spawn(move || { + let _ = sender.send(Loaded::load(&target)); + }); + self.screen = Screen::Loading { + dir: dir.to_path_buf(), + result, + }; + } + + /// Opens the session in `dir` and waits for it: for tests, which have nothing to draw + /// meanwhile. + /// + /// On success the screen is [`Screen::Open`], the session is at the top of the recent + /// sessions (and the preferences are saved), and the playhead is a second before where the + /// first bug region starts, if there is one. + /// + /// # Errors + /// + /// Returns an error if the session cannot be loaded (see [`Loaded::load`]), if `dir` is not a + /// session directory, or if the playback cannot be started (see [`Playback::start`]). The + /// screen is left as it was: unlike [`ViewerApp::open`], a failure is not shown in the window. + pub fn open_now(&mut self, dir: &Path) -> eyre::Result<()> { + let loaded = Loaded::load(dir)?; + self.finish_open(loaded) + } + + fn finish_open(&mut self, loaded: Loaded) -> eyre::Result<()> { + let guard = SessionPath::new(&loaded.dir)?; + let playback = Playback::start(loaded.analysis.manifest.clone(), guard, DECODE_WIDTH)?; + self.prefs.opened(&loaded.dir); + self.prefs.save(&self.prefs_dir); + + let first_bug = loaded.bugs().next().map(|bug| bug.id.clone()); + let focus = loaded.displays.first().map(|display| display.id); + let duration = loaded.duration_s; + let start = loaded.bugs().next().map(|bug| bug.start_video_s); + let mut open = Open { + view: View::whole(duration), + selection: None, + selected_event: None, + selected_finding: None, + selected_bug: first_bug, + tab: if loaded.bugs().next().is_some() { + Tab::Bugs + } else { + Tab::Findings + }, + overlay: self.prefs.overlay, + help: false, + composer: None, + traces: HashMap::new(), + os_traces: HashMap::new(), + state: None, + message: None, + deleted: Vec::new(), + tiles: HashMap::new(), + focus, + playback, + loaded, + drag: None, + changes: None, + changes_result: None, + changes_cancel: Arc::new(std::sync::atomic::AtomicBool::new(false)), + edge_preview: None, + }; + open.scan_for_changes(); + + // start where the user said the bug begins + if let Some(start) = start { + open.playback.seek((start - 1.0).max(0.0)); + } + self.screen = Screen::Open(Box::new(open)); + Ok(()) + } + + /// Bring a finished load into the window, or show why it failed. + fn poll_loading(&mut self) { + let Screen::Loading { dir, result } = &self.screen else { + return; + }; + + let Ok(outcome) = result.try_recv() else { + return; + }; + let dir = dir.clone(); + match outcome.and_then(|loaded| self.finish_open(loaded)) { + Ok(()) => {} + Err(error) => { + self.screen = Screen::Failed { + dir, + message: format!("{error:#}"), + }; + } + } + } + + fn poll_picker(&mut self) { + let Some(picker) = &self.picker else { + return; + }; + let Ok(chosen) = picker.try_recv() else { + return; + }; + + self.picker = None; + if let Some(dir) = chosen { + self.open(&dir); + } + } + + /// Draws one frame of the window. + /// + /// It first takes in a finished load and a folder chosen in the system's dialog, then draws the + /// top bar and the screen, and saves the preferences if the state overlay was switched. While a + /// session is loading, or the dialog is open, it asks `ctx` to draw again soon, so the result + /// shows without anyone touching the window. An open session draws itself with [`Open::ui`]. + /// + /// Needs an `egui::Context`, so a window is needed (the tests of this module draw frames + /// headlessly with `egui::Context::run`). + pub fn ui(&mut self, ctx: &egui::Context) { + self.poll_loading(); + self.poll_picker(); + + let mut to_open: Option = None; + let mut choose = false; + + egui::TopBottomPanel::top("top") + .frame( + egui::Frame::new() + .fill(theme::BACKGROUND) + .inner_margin(egui::Margin::symmetric(10, 6)), + ) + .show(ctx, |ui| { + ui.horizontal(|ui| { + // leave room for the window controls that sit over the content + ui.add_space(70.0); + if ui.button("Open…").clicked() { + choose = true; + } + match &mut self.screen { + Screen::Open(open) => { + ui.label(egui::RichText::new(name_of(&open.loaded.dir)).strong()); + open.top_bar(ui, &mut self.prefs); + } + Screen::Loading { dir, .. } => { + ui.spinner(); + ui.label(format!("opening {}…", name_of(dir))); + } + _ => {} + } + }); + }); + + match &mut self.screen { + Screen::Open(open) => open.ui(ctx), + Screen::Empty => { + egui::CentralPanel::default().show(ctx, |ui| { + to_open = start_screen(ui, &self.prefs, None); + }); + } + Screen::Failed { dir, message } => { + let (dir, message) = (dir.clone(), message.clone()); + egui::CentralPanel::default().show(ctx, |ui| { + to_open = start_screen(ui, &self.prefs, Some((&dir, &message))); + }); + } + Screen::Loading { .. } => { + egui::CentralPanel::default().show(ctx, |ui| { + ui.centered_and_justified(|ui| ui.spinner()); + }); + ctx.request_repaint_after(Duration::from_millis(50)); + } + } + + if choose && self.picker.is_none() { + self.picker = Some(pick_folder()); + } + if let Some(dir) = to_open { + self.open(&dir); + } + if self.picker.is_some() { + ctx.request_repaint_after(Duration::from_millis(100)); + } + + if let Screen::Open(open) = &self.screen + && open.overlay != self.prefs.overlay + { + self.prefs.overlay = open.overlay; + self.prefs.save(&self.prefs_dir); + } + } +} + +/// What to show before a session is open (or when it would not open). +fn start_screen( + ui: &mut egui::Ui, + prefs: &Prefs, + failure: Option<(&Path, &str)>, +) -> Option { + let mut chosen = None; + ui.vertical_centered(|ui| { + ui.add_space(80.0); + ui.heading("komorebi-recorder viewer"); + ui.add_space(6.0); + ui.label("Open a recording's folder to play it and see everything that happened in it."); + ui.add_space(16.0); + + if let Some((dir, message)) = failure { + ui.colored_label(theme::BUG, format!("{} could not be opened:", name_of(dir))); + ui.label(message); + ui.add_space(16.0); + } + + let recent = prefs.existing(); + if !recent.is_empty() { + ui.label(egui::RichText::new("Recent").color(theme::TEXT_DIM)); + for dir in recent { + if ui.link(dir.display().to_string()).clicked() { + chosen = Some(dir); + } + } + } + }); + chosen +} + +impl Drop for Open { + fn drop(&mut self) { + self.changes_cancel + .store(true, std::sync::atomic::Ordering::Relaxed); + } +} + +impl Open { + /// Returns the playhead, in session video time. + #[must_use] + pub fn position(&self) -> f64 { + self.playback.position() + } + + /// Shows `text` in the top bar for four seconds, as a note about what was just done. + pub fn say(&mut self, text: impl Into) { + self.message = Some((text.into(), Instant::now())); + } + + /// Everything that sits in the bar along the top once a session is open. + fn top_bar(&mut self, ui: &mut egui::Ui, _prefs: &mut Prefs) { + let manifest = &self.loaded.analysis.manifest; + ui.label( + egui::RichText::new(format!( + "{} displays · {} events · {} s", + self.loaded.displays.len(), + self.loaded.events.len(), + self.loaded.duration_s.round() as i64 + )) + .color(theme::TEXT_DIM), + ); + let versions: Vec = manifest + .komorebi + .versions + .iter() + .filter_map(|version| { + version + .commit + .as_ref() + .map(|commit| commit[..commit.len().min(7)].to_string()) + }) + .collect(); + if !versions.is_empty() { + ui.label( + egui::RichText::new(format!("komorebi {}", versions.join(", "))) + .color(theme::TEXT_DIM), + ); + } + if let Some(warning) = &self.loaded.skew.warning { + let label = ui.colored_label(egui::Color32::from_rgb(235, 185, 60), "⚠ source differs"); + label.on_hover_text(warning); + } + if !self.loaded.warnings.is_empty() { + ui.colored_label(egui::Color32::from_rgb(235, 185, 60), "⚠") + .on_hover_text(self.loaded.warnings.join("\n")); + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("?").on_hover_text("Keys").clicked() { + self.help = !self.help; + } + ui.checkbox(&mut self.overlay, "state overlay"); + if let Some((text, at)) = &self.message + && at.elapsed() < Duration::from_secs(4) + { + ui.label(egui::RichText::new(text).color(theme::OK)); + } + }); + } + + /// Carries out what a key asked for. + /// + /// | action | what happens | + /// |---|---| + /// | [`Action::TogglePlay`], [`Action::Pause`] | the playhead plays or pauses | + /// | [`Action::PlayForwards`], [`Action::PlayBackwards`] | plays at [`keymap::shuttle`] of the current rate | + /// | [`Action::StepFrame`] | one frame of the focused display (see [`Playback::step`]); with no display focused, pauses and moves a thirtieth of a second | + /// | [`Action::Skip`] | moves that many seconds, without pausing | + /// | [`Action::ToStart`], [`Action::ToEnd`] | moves to `0` or to the end | + /// | [`Action::PreviousEvent`], [`Action::NextEvent`] | selects and goes to the event before or after the playhead | + /// | [`Action::PreviousBug`], [`Action::NextBug`] | moves to the start of the bug region before or after the playhead | + /// | [`Action::SetIn`], [`Action::SetOut`] | sets the start or the end of the selection to the playhead; a missing end is the end of the recording, a missing start is `0`, and the other end moves with the playhead if it would cross it | + /// | [`Action::ClearSelection`] | clears the selection and stops looping | + /// | [`Action::MarkBug`] | opens the form for a bug region | + /// | [`Action::ToggleLoop`] | stops looping, or, with a selection, moves to its start and loops it, playing forwards at the current speed; with neither says to select a range first | + /// | [`Action::ToggleOverlay`], [`Action::Help`] | switches the overlay, or the list of keys | + /// | [`Action::ZoomIn`], [`Action::ZoomOut`] | zooms the timeline by a factor of 1.5 around the playhead | + /// | [`Action::FitTimeline`] | shows the whole recording | + /// | [`Action::FocusDisplay`] | focuses that display; an index beyond the displays does nothing | + /// | [`Action::Escape`] | closes the list of keys if it is open, else the form for a bug region, else clears the selection and stops looping | + /// + /// Positions that fall outside the recording are clamped by the playhead (see + /// [`Transport::seek`](crate::playback::Transport::seek)), so a skip past an end stops at it. + pub fn apply(&mut self, action: Action) { + let position = self.position(); + let duration = self.loaded.duration_s; + match action { + Action::TogglePlay => self.playback.toggle(), + Action::Pause => self.playback.pause(), + Action::PlayForwards | Action::PlayBackwards => { + let forwards = action == Action::PlayForwards; + let rate = + keymap::shuttle(self.playback.rate(), self.playback.is_playing(), forwards); + self.playback.play(rate); + } + Action::StepFrame(direction) => { + if let Some(display) = self.focus { + self.playback.step(display, direction); + } else { + self.playback.pause(); + self.playback.seek(position + f64::from(direction) / 30.0); + } + } + Action::Skip(seconds) => self.playback.seek(position + f64::from(seconds)), + Action::ToStart => self.playback.seek(0.0), + Action::ToEnd => self.playback.seek(duration), + Action::PreviousEvent => { + if let Some(time) = timeline::previous_before(&self.loaded.event_times, position) { + self.select_event_at(time); + } + } + Action::NextEvent => { + if let Some(time) = timeline::next_after(&self.loaded.event_times, position) { + self.select_event_at(time); + } + } + Action::PreviousBug => { + let starts: Vec = self.loaded.bugs().map(|bug| bug.start_video_s).collect(); + if let Some(time) = timeline::previous_before(&starts, position) { + self.playback.seek(time); + } + } + Action::NextBug => { + let starts: Vec = self.loaded.bugs().map(|bug| bug.start_video_s).collect(); + if let Some(time) = timeline::next_after(&starts, position) { + self.playback.seek(time); + } + } + Action::SetIn => { + let end = self + .selection + .map_or(duration, |(_, end)| end.max(position)); + self.selection = Some((position, end)); + } + Action::SetOut => { + let start = self.selection.map_or(0.0, |(start, _)| start.min(position)); + self.selection = Some((start, position)); + } + Action::ClearSelection => { + self.selection = None; + self.playback.set_loop(None); + } + Action::MarkBug => self.open_composer(), + Action::ToggleLoop => { + if self.playback.looping().is_some() { + self.playback.set_loop(None); + self.say("loop off"); + } else if let Some(selection) = self.selection { + self.playback.seek(selection.0); + self.playback.set_loop(Some(selection)); + self.playback.play(self.playback.rate().abs()); + self.say("looping the selection"); + } else { + self.say("select a range first: [ and ] mark its ends"); + } + } + Action::ToggleOverlay => self.overlay = !self.overlay, + Action::ZoomIn => self.view.zoom(position, 1.5, duration), + Action::ZoomOut => self.view.zoom(position, 1.0 / 1.5, duration), + Action::FitTimeline => self.view = View::whole(duration), + Action::FocusDisplay(index) => { + if let Some(display) = self.loaded.displays.get(index) { + self.focus = Some(display.id); + } + } + Action::Help => self.help = !self.help, + Action::Escape => { + if self.help { + self.help = false; + } else if self.composer.is_some() { + self.composer = None; + } else { + self.selection = None; + self.playback.set_loop(None); + } + } + } + } + + /// Moves the playhead to the event received at `time` and selects it. + /// + /// The event is the one nearest `time`, within a millisecond; if there is none, nothing + /// happens. See [`Open::select_event`]. + pub fn select_event_at(&mut self, time: f64) { + let Some(index) = timeline::nearest(&self.loaded.event_times, time, 1e-3) else { + return; + }; + self.select_event(index); + } + + /// Selects event number `index` of [`Loaded::events`] and goes to when it was received. + /// + /// It also shows the Event tab, pauses, and scrolls the timeline to keep the event in view. An + /// `index` beyond the list does nothing. + pub fn select_event(&mut self, index: usize) { + let Some(event) = self.loaded.events.get(index) else { + return; + }; + + self.selected_event = Some(event.seq); + self.tab = Tab::Event; + self.playback.pause(); + self.playback.seek(event.video_s); + self.view.reveal(event.video_s, self.loaded.duration_s); + } + + /// Read the keyboard, unless a text box wants it. + fn keys(&mut self, ctx: &egui::Context) { + if ctx.wants_keyboard_input() { + return; + } + + // ⌘Z brings back what was deleted + if ctx.input(|input| input.modifiers.command && input.key_pressed(egui::Key::Z)) { + self.undo_delete(); + } + + let actions: Vec = ctx.input(|input| { + let typed: Vec = input + .events + .iter() + .filter_map(|event| match event { + egui::Event::Text(text) => Some(text.clone()), + _ => None, + }) + .collect(); + input + .events + .iter() + .filter_map(|event| match event { + egui::Event::Key { + key, + pressed: true, + modifiers, + .. + } => { + let text = typed.first().map(String::as_str); + keymap::action(*key, *modifiers, text) + } + _ => None, + }) + .collect() + }); + + for action in actions { + self.apply(action); + } + } + + /// Starts looking for where the picture changed, off the UI thread. + /// + /// The result arrives in [`Open::changes_result`] and is moved into [`Open::changes`] by a + /// later frame. A session with no video has nothing to scan: nothing starts. The scan reads the + /// video of every display from the start to the end of the recording, at the default + /// sensitivity (see [`Analysis::changes_until`](crate::analysis::Analysis::changes_until)), and + /// stops early when the session is closed (the [`Open`] is dropped). + pub fn scan_for_changes(&mut self) { + if self.loaded.displays.is_empty() { + return; + } + + let (sender, receiver) = crossbeam_channel::bounded(1); + let analysis = self.loaded.analysis.clone(); + let displays: Vec = self + .loaded + .displays + .iter() + .map(|display| display.id) + .collect(); + let duration = self.loaded.duration_s; + let cancel = self.changes_cancel.clone(); + std::thread::spawn(move || { + let outcome = SessionPath::new(&analysis.session.dir).and_then(|guard| { + let video = crate::analysis::video::SessionVideo::new(&analysis.manifest, &guard); + analysis.changes_until(&video, &displays, 0.0, duration, 1.0, Some(&cancel)) + }); + let _ = sender.send(outcome); + }); + self.changes_result = Some(receiver); + } + + /// Take the result of the background scan when it arrives. + fn poll_changes(&mut self) { + let Some(receiver) = &self.changes_result else { + return; + }; + let Ok(outcome) = receiver.try_recv() else { + return; + }; + + self.changes_result = None; + match outcome { + Ok(data) => self.changes = Some(data), + Err(error) => self.say(format!("could not look for screen changes: {error:#}")), + } + } + + /// Draws the open session: the panels, the form and the list of keys, and reads the keyboard. + /// + /// The panels are the timeline along the bottom, the inspector on the right and the video in the + /// middle. While the playhead is moving the timeline follows it and the window asks to be drawn + /// again at once; paused, it asks again in 100 ms, enough to bring in decoded frames and the + /// result of the scan. Needs an `egui::Context`, so a window is needed. + pub fn ui(&mut self, ctx: &egui::Context) { + self.poll_changes(); + if self.changes_result.is_some() { + ctx.request_repaint_after(Duration::from_millis(250)); + } + self.keys(ctx); + + let playing = self.playback.is_playing(); + let position = self.position(); + if playing { + // keep the window with the playhead while it plays + self.view.reveal(position, self.loaded.duration_s); + } + + self.timeline_panel(ctx); + self.inspector_panel(ctx); + egui::CentralPanel::default() + .frame( + egui::Frame::new() + .fill(theme::BACKGROUND) + .inner_margin(egui::Margin::same(8)), + ) + .show(ctx, |ui| self.video_ui(ui, ctx)); + + self.composer_window(ctx); + if self.help { + self.help_window(ctx); + } + + if playing { + ctx.request_repaint(); + } else { + ctx.request_repaint_after(Duration::from_millis(100)); + } + } + + fn help_window(&mut self, ctx: &egui::Context) { + let mut open = true; + egui::Window::new("Keys") + .open(&mut open) + .collapsible(false) + .resizable(false) + .show(ctx, |ui| { + egui::Grid::new("keys") + .num_columns(2) + .spacing([24.0, 4.0]) + .show(ui, |ui| { + for (keys, does) in keymap::BINDINGS { + ui.monospace(*keys); + ui.label(*does); + ui.end_row(); + } + }); + }); + if !open { + self.help = false; + } + } + + /// Returns the state komorebi was in at session video time `time`, for the overlay. + /// + /// The state is the one in force at that moment, which is the state of the last notification + /// before it, so it is kept in [`Open::state`] while the playhead stays within the same + /// notification and not worked out again. `None` if the state at `time` cannot be read. + pub fn state_at(&mut self, time: f64) -> Option> { + let mach = self.loaded.analysis.manifest.mach_at_video_seconds(time); + let found = self.loaded.analysis.state_at(mach).ok()?; + if let Some((id, snapshot)) = &self.state + && found.state_id == Some(*id) + { + return Some(snapshot.clone()); + } + + if let Some(id) = found.state_id { + self.state = Some((id, found.snapshot.clone())); + } + Some(found.snapshot) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::annotations; + use crate::testkit; + use crate::testkit::SessionBuilder; + use serde_json::json; + + fn prefs_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "komorebi-recorder-viewer-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + fn input(events: Vec) -> egui::RawInput { + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(1500.0, 920.0), + )), + events, + ..egui::RawInput::default() + } + } + + fn frame(app: &mut ViewerApp, ctx: &egui::Context, events: Vec) { + let _ = ctx.run(input(events), |ctx| app.ui(ctx)); + } + + fn key(key: egui::Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: Some(key), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + } + } + + fn typed(character: &str, which: egui::Key) -> Vec { + vec![key(which), egui::Event::Text(character.to_string())] + } + + fn open(app: &mut ViewerApp) -> &mut Open { + match &mut app.screen { + Screen::Open(open) => open, + _ => panic!("no session is open"), + } + } + + fn session(name: &str, with_video: bool) -> PathBuf { + let mut builder = SessionBuilder::new(name) + .event( + 2.0, + json!({"type": "Retile"}), + Some(testkit::state_with_windows(&[(1, "Ghostty"), (2, "Brave")])), + ) + .event( + 4.0, + json!({"type": "FocusChange", "content": [{"type": "Accessibility", "content": "AXApplicationActivated"}, 5, 1]}), + Some(testkit::state_with_windows(&[(1, "Ghostty"), (2, "Brave")])), + ) + .log(3.0, "ERROR", "komorebi::macos_api: failed to get window position: AXError::InvalidUIElement") + .incident(5.0, "display-disconnected", "display 3 went away"); + if with_video { + builder = builder.video(1, 0.0, 90, 30); + } + builder.build().0.dir + } + + #[test] + fn the_window_draws_with_nothing_open() { + let mut app = ViewerApp::new(prefs_dir("empty")); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + assert!(matches!(app.screen, Screen::Empty)); + } + + #[test] + fn a_session_that_will_not_open_says_why_on_the_start_screen() { + let (session, mut manifest) = SessionBuilder::new("viewer-unfinished").build(); + manifest.status = "recording".to_string(); + session.write_manifest(&manifest).expect("manifest"); + + let mut app = ViewerApp::new(prefs_dir("failed")); + let ctx = egui::Context::default(); + app.open(&session.dir); + + let deadline = Instant::now() + Duration::from_secs(5); + while matches!(app.screen, Screen::Loading { .. }) && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(20)); + } + let Screen::Failed { message, .. } = &app.screen else { + panic!("the unfinished session opened"); + }; + assert!(message.contains("left unfinished"), "{message}"); + frame(&mut app, &ctx, vec![]); + } + + #[test] + fn an_opened_session_is_remembered() { + let dir = session("viewer-remember", false); + let prefs = prefs_dir("remember"); + let mut app = ViewerApp::new(prefs.clone()); + app.open_now(&dir).expect("open"); + + assert_eq!(Prefs::load(&prefs).recent, [dir.display().to_string()]); + } + + #[test] + fn a_session_draws_and_the_pictures_arrive() { + if !testkit::ffmpeg_available() { + eprintln!("skipped: ffmpeg is not available to make a test video"); + return; + } + + let dir = session("viewer-draw", true); + let mut app = ViewerApp::new(prefs_dir("draw")); + app.open_now(&dir).expect("open"); + let ctx = egui::Context::default(); + + // the picture for display 1 is decoded off the UI thread and turns up in a later frame + let deadline = Instant::now() + Duration::from_secs(8); + while open(&mut app).tiles.is_empty() && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(20)); + } + assert!( + open(&mut app).tiles.contains_key(&1), + "display 1's picture never arrived" + ); + assert_eq!(open(&mut app).focus, Some(1)); + } + + #[test] + fn screen_changes_are_found_in_the_background_and_shown() { + if !testkit::ffmpeg_available() { + eprintln!("skipped: ffmpeg is not available to make a test video"); + return; + } + + let (session, _) = SessionBuilder::new("viewer-changes") + .video_showing(1, 0.0, 90, 30, |frame| if frame < 30 { frame } else { 29 }) + .build(); + let mut app = ViewerApp::new(prefs_dir("changes")); + app.open_now(&session.dir).expect("open"); + let ctx = egui::Context::default(); + + let deadline = Instant::now() + Duration::from_secs(10); + while open(&mut app).changes.is_none() && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(30)); + } + let changes = open(&mut app).changes.clone().expect("the scan finished"); + assert_eq!(changes.spans.len(), 1, "{changes:#?}"); + assert!(changes.spans[0].end_video_s < 1.1); + frame(&mut app, &ctx, vec![]); + } + + #[test] + fn the_keys_drive_the_playhead() { + let dir = session("viewer-keys", false); + let mut app = ViewerApp::new(prefs_dir("keys")); + app.open_now(&dir).expect("open"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + + // space plays and pauses + frame(&mut app, &ctx, vec![key(egui::Key::Space)]); + assert!(open(&mut app).playback.is_playing()); + frame(&mut app, &ctx, vec![key(egui::Key::Space)]); + assert!(!open(&mut app).playback.is_playing()); + + // the event keys land on the events and select them + open(&mut app).playback.seek(0.0); + frame(&mut app, &ctx, typed(".", egui::Key::Period)); + assert!((open(&mut app).position() - 2.0).abs() < 1e-3); + assert_eq!(open(&mut app).selected_event, Some(1)); + frame(&mut app, &ctx, typed(".", egui::Key::Period)); + assert_eq!(open(&mut app).selected_event, Some(2)); + frame(&mut app, &ctx, typed(",", egui::Key::Comma)); + assert_eq!(open(&mut app).selected_event, Some(1)); + + // brackets pick a range + open(&mut app).playback.seek(3.0); + frame(&mut app, &ctx, typed("[", egui::Key::OpenBracket)); + open(&mut app).playback.seek(6.0); + frame(&mut app, &ctx, typed("]", egui::Key::CloseBracket)); + assert_eq!(open(&mut app).selection, Some((3.0, 6.0))); + frame(&mut app, &ctx, vec![key(egui::Key::Escape)]); + assert_eq!(open(&mut app).selection, None); + + // J goes backwards, L forwards, each press faster + frame(&mut app, &ctx, vec![key(egui::Key::J)]); + assert!(open(&mut app).playback.rate() < 0.0); + frame(&mut app, &ctx, vec![key(egui::Key::L)]); + assert!(open(&mut app).playback.rate() > 0.0); + frame(&mut app, &ctx, vec![key(egui::Key::L)]); + assert!((open(&mut app).playback.rate() - 2.0).abs() < 1e-9); + frame(&mut app, &ctx, vec![key(egui::Key::K)]); + assert!(!open(&mut app).playback.is_playing()); + + // the help comes and goes + frame(&mut app, &ctx, typed("?", egui::Key::Questionmark)); + assert!(open(&mut app).help); + frame(&mut app, &ctx, vec![key(egui::Key::Escape)]); + assert!(!open(&mut app).help); + } + + #[test] + fn typing_in_a_text_box_does_not_press_keys() { + let dir = session("viewer-typing", false); + let mut app = ViewerApp::new(prefs_dir("typing")); + app.open_now(&dir).expect("open"); + let ctx = egui::Context::default(); + + // while something wants the keyboard, Space is a space + ctx.memory_mut(|memory| memory.request_focus(egui::Id::new("a text box"))); + let _ = ctx.run(input(vec![]), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + let mut text = String::new(); + let response = + ui.add(egui::TextEdit::singleline(&mut text).id(egui::Id::new("a text box"))); + response.request_focus(); + }); + }); + assert!(ctx.wants_keyboard_input()); + let _ = ctx.run(input(vec![key(egui::Key::Space)]), |ctx| { + if let Screen::Open(open) = &mut app.screen { + open.ui(ctx); + } + }); + assert!(!open(&mut app).playback.is_playing()); + } + + #[test] + fn marking_a_bug_from_a_selection_saves_a_region_anyone_can_read() { + let dir = session("viewer-mark", false); + let mut app = ViewerApp::new(prefs_dir("mark")); + app.open_now(&dir).expect("open"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + + // pick a range with the brackets, then B opens the form from it + open(&mut app).playback.seek(3.0); + frame(&mut app, &ctx, typed("[", egui::Key::OpenBracket)); + open(&mut app).playback.seek(6.0); + frame(&mut app, &ctx, typed("]", egui::Key::CloseBracket)); + frame(&mut app, &ctx, vec![key(egui::Key::B)]); + + let form = open(&mut app).composer.as_ref().expect("the form is open"); + assert_eq!(form.start, "00:03.000"); + assert_eq!(form.end, "00:06.000"); + frame(&mut app, &ctx, vec![]); + + { + let form = open(&mut app).composer.as_mut().expect("form"); + form.text = + "the Brave window vanishes instead of moving to the laptop screen".to_string(); + form.expected = "it should move".to_string(); + } + open(&mut app).save_composer().expect("saved"); + + let loaded = annotations::load(&dir).expect("load"); + let bug = loaded.bugs().next().expect("a bug region was written"); + assert_eq!( + bug.text, + "the Brave window vanishes instead of moving to the laptop screen" + ); + assert_eq!(bug.expected.as_deref(), Some("it should move")); + assert_eq!(bug.author, annotations::AUTHOR_USER); + let manifest = &open(&mut app).loaded.analysis.manifest.clone(); + assert!((manifest.video_seconds(bug.start_mach_ns) - 3.0).abs() < 1e-3); + assert!((manifest.video_seconds(bug.end_mach_ns.expect("end")) - 6.0).abs() < 1e-3); + + // the window shows it, closes the form and selects the new region + assert!(open(&mut app).composer.is_none()); + assert_eq!(open(&mut app).loaded.bugs().count(), 1); + assert_eq!( + open(&mut app).selected_bug.as_deref(), + Some(bug.id.as_str()) + ); + frame(&mut app, &ctx, vec![]); + } + + #[test] + fn a_region_the_form_cannot_make_sense_of_stays_open_and_says_why() { + let dir = session("viewer-refuse", false); + let mut app = ViewerApp::new(prefs_dir("refuse")); + app.open_now(&dir).expect("open"); + open(&mut app).open_composer(); + + // no description + let error = open(&mut app).save_composer().expect_err("refused"); + assert!(error.contains("say what goes wrong"), "{error}"); + assert!(open(&mut app).composer.is_some()); + + open(&mut app).composer.as_mut().expect("form").text = "wrong".to_string(); + for (start, end, expected) in [ + ("banana", "00:05.000", "the start is not a time"), + ("00:05.000", "00:02.000", "the end is before the start"), + ("00:01.000", "99:00.000", "outside the recording"), + ] { + let form = open(&mut app).composer.as_mut().expect("form"); + form.start = start.to_string(); + form.end = end.to_string(); + let error = open(&mut app).save_composer().expect_err("refused"); + assert!(error.contains(expected), "{start} to {end}: {error}"); + } + + assert!( + annotations::load(&dir) + .expect("load") + .annotations + .is_empty(), + "nothing was written" + ); + } + + #[test] + fn a_region_can_be_open_ended() { + let dir = session("viewer-open-ended", false); + let mut app = ViewerApp::new(prefs_dir("open-ended")); + app.open_now(&dir).expect("open"); + open(&mut app).open_composer(); + { + let form = open(&mut app).composer.as_mut().expect("form"); + form.text = "still broken when I stopped".to_string(); + form.open_ended = true; + form.end = "nonsense".to_string(); + } + open(&mut app) + .save_composer() + .expect("saved without reading the end"); + + let bug = annotations::load(&dir) + .expect("load") + .bugs() + .next() + .cloned() + .expect("bug"); + assert!(bug.open_ended()); + } + + #[test] + fn a_region_can_be_edited_dragged_deleted_and_brought_back() { + let dir = session("viewer-edit", false); + let mut app = ViewerApp::new(prefs_dir("edit")); + app.open_now(&dir).expect("open"); + open(&mut app).selection = Some((2.0, 4.0)); + open(&mut app).open_composer(); + open(&mut app).composer.as_mut().expect("form").text = "first words".to_string(); + open(&mut app).save_composer().expect("saved"); + let id = open(&mut app).selected_bug.clone().expect("selected"); + + // edit the words + open(&mut app).open_composer_for(&id); + assert_eq!( + open(&mut app).composer.as_ref().expect("form").text, + "first words" + ); + open(&mut app).composer.as_mut().expect("form").text = "better words".to_string(); + open(&mut app).save_composer().expect("saved"); + assert_eq!( + open(&mut app).loaded.bugs().next().expect("bug").text, + "better words" + ); + assert_eq!( + open(&mut app).loaded.bugs().count(), + 1, + "an edit is not a second region" + ); + + // drag the edges: the end can move, but not before the start + open(&mut app) + .move_bug_edge(&id, false, 5.0) + .expect("end moved"); + open(&mut app) + .move_bug_edge(&id, true, 1.0) + .expect("start moved"); + let bug = open(&mut app).loaded.bugs().next().cloned().expect("bug"); + assert!((bug.start_video_s - 1.0).abs() < 1e-3 && (bug.end_video_s - 5.0).abs() < 1e-3); + let error = open(&mut app) + .move_bug_edge(&id, false, 0.5) + .expect_err("refused"); + assert!(error.contains("cannot end before it starts"), "{error}"); + + // delete it, and bring it back + open(&mut app).delete_annotation(&id); + assert_eq!(open(&mut app).loaded.bugs().count(), 0); + open(&mut app).undo_delete(); + let back = open(&mut app) + .loaded + .bugs() + .next() + .cloned() + .expect("it is back"); + assert_eq!(back.text, "better words"); + assert!((back.start_video_s - 1.0).abs() < 1e-3 && (back.end_video_s - 5.0).abs() < 1e-3); + } + + #[test] + fn every_tab_of_the_inspector_draws() { + let dir = session("viewer-tabs", false); + let mut app = ViewerApp::new(prefs_dir("tabs")); + app.open_now(&dir).expect("open"); + let ctx = egui::Context::default(); + + // an event selected so the Event tab has a trace to show, and a region marked + open(&mut app).select_event(1); + open(&mut app).selection = Some((1.0, 2.0)); + open(&mut app).open_composer(); + open(&mut app).composer.as_mut().expect("form").text = "x".to_string(); + open(&mut app).save_composer().expect("saved"); + + for tab in [Tab::Now, Tab::Event, Tab::Findings, Tab::Bugs, Tab::Log] { + open(&mut app).tab = tab; + frame(&mut app, &ctx, vec![]); + } + + // and with the form and the help open over them + open(&mut app).open_composer(); + open(&mut app).help = true; + frame(&mut app, &ctx, vec![]); + } + + #[test] + fn the_agent_prompt_names_the_session_and_the_commands_to_start_with() { + let prompt = super::super::inspector::agent_prompt(Path::new("/tmp/a session")); + assert!(prompt.contains("/tmp/a session")); + assert!(prompt.contains("komorebi-recorder brief")); + assert!(prompt.contains("komorebi-recorder guide")); + } +} diff --git a/komorebi-recorder/src/viewer/composer.rs b/komorebi-recorder/src/viewer/composer.rs new file mode 100644 index 00000000..2ae6ef74 --- /dev/null +++ b/komorebi-recorder/src/viewer/composer.rs @@ -0,0 +1,512 @@ +//! Marking a bug region: where it starts and ends, and what is wrong. +//! +//! This is the most important thing the viewer writes. The region and the words are what an +//! investigation starts from, so the form asks for the words, makes the times easy to take from the +//! video, and shows plainly that a region without a description is not much use. +//! +//! A [`Composer`] is the form's state: the text boxes as typed, so what is in them is not yet a +//! time or a region. [`Open::composer_window`] draws it, and [`Open::save_composer`] checks it and +//! writes the region to the session's annotations file (the same append-only `annotations.jsonl` +//! the command line reads, through [`annotations::add`] and [`annotations::edit`]). The same file +//! is also changed by what the other methods here do to a region once it exists: edit it +//! ([`Open::open_composer_for`]), move an edge of it ([`Open::move_bug_edge`]), delete it and bring +//! it back ([`Open::delete_annotation`], [`Open::undo_delete`]). +//! +//! This module is the only part of the viewer that writes to the session, and only to its +//! annotations. It needs an `egui::Context` to draw, so there are no examples; the tests in `viewer::app` fill +//! the form in and save it (`marking_a_bug_from_a_selection_saves_a_region_anyone_can_read`), cover +//! what a form is refused for (`a_region_the_form_cannot_make_sense_of_stays_open_and_says_why`), +//! open-ended regions (`a_region_can_be_open_ended`), and editing, dragging, deleting and bringing +//! one back (`a_region_can_be_edited_dragged_deleted_and_brought_back`). + +use super::app::Open; +use super::app::Tab; +use super::theme; +use crate::analysis::envelope; +use crate::annotations; +use crate::annotations::AnnotationView; +use crate::annotations::Kind; +use crate::annotations::New; +use crate::annotations::Patch; +use crate::timecode; +use eframe::egui; + +/// The form for one bug region. +/// +/// Every field is what is in a box of the form, as typed: the times are timecodes in text, and +/// nothing is checked until [`Open::save_composer`] reads the form. +pub struct Composer { + /// The id of the region being changed; `None` for a new one. + pub editing: Option, + /// An optional short title for the region. + pub title: String, + /// The description of what goes wrong, in the user's words. It is required: a region without + /// one is refused. + pub text: String, + /// A description of what should have happened instead. Optional. + pub expected: String, + /// Where the region starts, as a timecode as typed (`00:03.000`, or any form + /// [`timecode::parse`] reads, such as `3.5` or `1:02`). + pub start: String, + /// Where the region ends, as a timecode as typed. Ignored while [`Composer::open_ended`] is set. + pub end: String, + /// It was still going on when the recording ended. + pub open_ended: bool, + /// Which displays it was seen on, as `(display id, ticked)`; none ticked means any. + pub displays: Vec<(u32, bool)>, + /// Why the last attempt to save was refused, shown in the form. + pub error: Option, + /// Focus the description when the form first shows. + first: bool, +} + +impl Composer { + /// Returns a blank form for a region from `start_s` to `end_s`, in session video seconds. + /// + /// The times are shown as timecodes. `displays` are the ids of the displays offered to tick, + /// none of them ticked. + #[must_use] + pub fn new(start_s: f64, end_s: f64, displays: &[u32]) -> Self { + Self { + editing: None, + title: String::new(), + text: String::new(), + expected: String::new(), + start: timecode::format(start_s), + end: timecode::format(end_s), + open_ended: false, + displays: displays.iter().map(|id| (*id, false)).collect(), + error: None, + first: true, + } + } + + /// Returns the form for changing the existing region `bug`, filled in with its values. + /// + /// `displays` are the ids of the displays offered to tick; the ones `bug` was seen on are + /// ticked. + #[must_use] + pub fn editing(bug: &AnnotationView, displays: &[u32]) -> Self { + Self { + editing: Some(bug.id.clone()), + title: bug.title.clone(), + text: bug.text.clone(), + expected: bug.expected.clone().unwrap_or_default(), + start: timecode::format(bug.start_video_s), + end: timecode::format(bug.end_video_s), + open_ended: bug.open_ended, + displays: displays + .iter() + .map(|id| (*id, bug.displays.contains(id))) + .collect(), + error: None, + first: true, + } + } +} + +impl Open { + /// Opens the form for a new region, and shows the Bugs tab. + /// + /// The region is the selection if there is one, else from the playhead to five seconds after it + /// (or to the end of the recording, if that comes first). + pub fn open_composer(&mut self) { + let duration = self.loaded.duration_s; + let (start, end) = self.selection.unwrap_or_else(|| { + let position = self.position(); + (position, (position + 5.0).min(duration)) + }); + let displays: Vec = self + .loaded + .displays + .iter() + .map(|display| display.id) + .collect(); + self.composer = Some(Composer::new(start, end, &displays)); + self.tab = Tab::Bugs; + } + + /// Opens the form for changing the bug region `id`. + /// + /// Nothing happens if there is no bug region with that id. A note or a finding is not a bug + /// region and cannot be changed here. + pub fn open_composer_for(&mut self, id: &str) { + let displays: Vec = self + .loaded + .displays + .iter() + .map(|display| display.id) + .collect(); + if let Some(bug) = self.loaded.bugs().find(|bug| bug.id == id) { + self.composer = Some(Composer::editing(bug, &displays)); + } + } + + /// Writes the form to `annotations.jsonl`: a new bug region, or a change to the one being edited. + /// + /// On success the annotations are read again, the saved region is selected, the selection on the + /// timeline is cleared, the form is closed and the top bar shows that it was saved. Nothing happens, + /// and `Ok` is returned, if no form is open. A new region is written with the user as its + /// author, and ticked displays are recorded as where it was seen (none ticked: any). + /// + /// The start (and the end, unless the form's `open_ended` box is ticked) is read with + /// [`timecode::parse`] and may be up to a millisecond outside the recording, which is then + /// clamped to it. An open-ended region has no end. Editing can set an end but not take one + /// away: ticking "still happening" on a region that already has an end leaves its end as it was. + /// + /// # Errors + /// + /// Returns a message, fit to show a person, and leaves the form open and nothing written, if + /// + /// - the start is not a time ("the start is not a time like 12.5 or 0:12.500"), or the end is + /// not one and the region is not open-ended, + /// - a time is outside the recording ("the start is outside the recording (0 to 00:10.000)"), + /// - the end is before the start ("the end is before the start"), or + /// - the description is empty, after trimming ("say what goes wrong: whoever investigates reads + /// this first"). + /// + /// It also returns a message, with the cause, if the annotations file cannot be written + /// (including a region that does not exist, when editing) or, after the region has been + /// written, cannot be read again. + /// + /// Covered by `a_region_the_form_cannot_make_sense_of_stays_open_and_says_why` and + /// `a_region_can_be_open_ended`. + pub fn save_composer(&mut self) -> Result<(), String> { + let Some(form) = &self.composer else { + return Ok(()); + }; + + let manifest = &self.loaded.analysis.manifest; + let duration = self.loaded.duration_s; + let parse = |what: &str, text: &str| -> Result { + timecode::parse(text) + .map_err(|_| format!("{what} is not a time like 12.5 or 0:12.500")) + .and_then(|seconds| { + if (-0.001..=duration + 0.001).contains(&seconds) { + Ok(seconds.clamp(0.0, duration)) + } else { + Err(format!( + "{what} is outside the recording (0 to {})", + timecode::format(duration) + )) + } + }) + }; + + let start_s = parse("the start", &form.start)?; + let end_s = if form.open_ended { + None + } else { + Some(parse("the end", &form.end)?) + }; + if let Some(end) = end_s + && end < start_s + { + return Err("the end is before the start".to_string()); + } + let text = form.text.trim().to_string(); + if text.is_empty() { + return Err("say what goes wrong: whoever investigates reads this first".to_string()); + } + + let displays: Vec = form + .displays + .iter() + .filter(|(_, ticked)| *ticked) + .map(|(id, _)| *id) + .collect(); + let expected = form.expected.trim().to_string(); + let start_ns = manifest.mach_at_video_seconds(start_s); + let end_ns = end_s.map(|end| manifest.mach_at_video_seconds(end)); + + let dir = self.loaded.dir.clone(); + let saved = match &form.editing { + Some(id) => { + let id = id.clone(); + annotations::edit( + &dir, + &id, + Patch { + start_mach_ns: Some(start_ns), + end_mach_ns: end_ns, + title: Some(form.title.trim().to_string()), + text: Some(text), + expected: Some(expected), + displays: Some(displays), + refs: None, + }, + ) + .map(|()| id) + } + None => annotations::add( + &dir, + New { + kind: Some(Kind::Bug), + start_mach_ns: start_ns, + end_mach_ns: end_ns, + title: form.title.trim().to_string(), + text, + expected: (!expected.is_empty()).then_some(expected), + displays, + author: Some(annotations::AUTHOR_USER.to_string()), + about: None, + refs: Vec::new(), + }, + ), + } + .map_err(|error| format!("{error:#}"))?; + + self.loaded + .reload_annotations() + .map_err(|error| format!("{error:#}"))?; + self.selected_bug = Some(saved); + self.selection = None; + self.composer = None; + self.say("saved: this is what an investigation will start from"); + Ok(()) + } + + /// Deletes the annotation `id` (a bug region, note or finding), keeping a copy to bring back. + /// + /// The top bar shows that it was deleted and that `Command`-`Z` brings it back. The line stays in the + /// annotations file as a tombstone (see [`annotations::delete`]). Nothing happens if there is no + /// such annotation. If the file cannot be written the top bar shows why, and nothing is deleted. + pub fn delete_annotation(&mut self, id: &str) { + let Some(gone) = self + .loaded + .annotations + .iter() + .find(|annotation| annotation.id == id) + .cloned() + else { + return; + }; + + match annotations::delete(&self.loaded.dir, id) { + Ok(()) => { + let _ = self.loaded.reload_annotations(); + if self.selected_bug.as_deref() == Some(id) { + self.selected_bug = None; + } + self.deleted.push(gone); + self.say("deleted (⌘Z brings it back)"); + } + Err(error) => self.say(format!("could not delete: {error:#}")), + } + } + + /// Brings back the annotation deleted last. + /// + /// It is added to the annotations file again with everything it had (kind, times, title, text, + /// what was expected, displays, author, what it is about and its references), so it has a new + /// id, and it is selected. Nothing happens if nothing was deleted. If it cannot be added the top + /// bar shows why. + pub fn undo_delete(&mut self) { + let Some(back) = self.deleted.pop() else { + return; + }; + let manifest = &self.loaded.analysis.manifest; + let result = annotations::add( + &self.loaded.dir, + New { + kind: Some(back.kind), + start_mach_ns: back.start_mach_ns, + end_mach_ns: back.end_mach_ns, + title: back.title.clone(), + text: back.text.clone(), + expected: back.expected.clone(), + displays: back.displays.clone(), + author: Some(back.author.clone()), + about: back.about.clone(), + refs: back.refs.clone(), + }, + ); + let _ = manifest; + match result { + Ok(id) => { + let _ = self.loaded.reload_annotations(); + self.selected_bug = Some(id); + self.say("brought back"); + } + Err(error) => self.say(format!("could not bring it back: {error:#}")), + } + } + + /// Moves one edge of the bug region `id` to `to_s` seconds, from dragging it on the timeline. + /// + /// `moving_start` says which edge: the start if `true`, the end if `false`. `to_s` is clamped + /// to the recording. The annotations are read again afterwards. + /// + /// # Errors + /// + /// Returns a message, fit to show a person, if + /// + /// - the change would put the end before the start ("a region cannot end before it starts"), or + /// - the annotations file cannot be written (including a region that does not exist) or cannot + /// be read again, which gives the cause. + /// + /// Covered by `a_region_can_be_edited_dragged_deleted_and_brought_back`. + pub fn move_bug_edge(&mut self, id: &str, moving_start: bool, to_s: f64) -> Result<(), String> { + let manifest = &self.loaded.analysis.manifest; + let ns = manifest.mach_at_video_seconds(to_s.clamp(0.0, self.loaded.duration_s)); + let patch = if moving_start { + Patch { + start_mach_ns: Some(ns), + ..Patch::default() + } + } else { + Patch { + end_mach_ns: Some(ns), + ..Patch::default() + } + }; + + annotations::edit(&self.loaded.dir, id, patch).map_err( + |error| match envelope::exit_kind(&error) { + envelope::ExitKind::Usage => "a region cannot end before it starts".to_string(), + _ => format!("{error:#}"), + }, + )?; + self.loaded + .reload_annotations() + .map_err(|error| format!("{error:#}")) + } + + /// Draws the form, if one is open, as a window in the middle of the screen. + /// + /// The window is titled "Mark a bug region", or "Edit bug region" for an existing one. It asks + /// for what goes wrong, what was expected and a short title, and for the times, each with a + /// button that takes the playhead's time and one that shows that moment. Save calls + /// [`Open::save_composer`] and, if it is refused, shows the reason in the form. Cancel, or + /// closing the window, drops the form without saving anything. + /// + /// Needs an `egui::Context`, so a window is needed. + pub fn composer_window(&mut self, ctx: &egui::Context) { + let Some(form) = self.composer.as_mut() else { + return; + }; + + let position = self.playback.position(); + let mut save = false; + let mut cancel = false; + let mut seek: Option = None; + let mut open = true; + let title = if form.editing.is_some() { + "Edit bug region" + } else { + "Mark a bug region" + }; + + egui::Window::new(title) + .open(&mut open) + .collapsible(false) + .resizable(true) + .default_width(460.0) + .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]) + .show(ctx, |ui| { + ui.label( + egui::RichText::new( + "Mark the stretch of the recording where the bug is visible, and say what it looks like. \ + Whoever investigates it starts from exactly this.", + ) + .color(theme::TEXT_DIM), + ); + ui.add_space(8.0); + + ui.label("What goes wrong"); + let description = ui.add( + egui::TextEdit::multiline(&mut form.text) + .hint_text("e.g. after unplugging the monitor, my browser window disappears instead of moving to the laptop screen") + .desired_rows(4) + .desired_width(f32::INFINITY), + ); + if form.first { + description.request_focus(); + form.first = false; + } + + ui.add_space(4.0); + ui.label("What you expected instead (optional)"); + ui.add( + egui::TextEdit::multiline(&mut form.expected) + .desired_rows(2) + .desired_width(f32::INFINITY), + ); + + ui.add_space(4.0); + ui.label("A short title (optional)"); + ui.add(egui::TextEdit::singleline(&mut form.title).desired_width(f32::INFINITY)); + + ui.add_space(8.0); + egui::Grid::new("times").num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| { + ui.label("starts"); + ui.add(egui::TextEdit::singleline(&mut form.start).desired_width(90.0).font(egui::TextStyle::Monospace)); + if ui.button("= playhead").clicked() { + form.start = timecode::format(position); + } + if ui.button("go").on_hover_text("show this moment").clicked() { + seek = Some(form.start.clone()); + } + ui.end_row(); + + ui.label("ends"); + ui.add_enabled( + !form.open_ended, + egui::TextEdit::singleline(&mut form.end).desired_width(90.0).font(egui::TextStyle::Monospace), + ); + if ui.add_enabled(!form.open_ended, egui::Button::new("= playhead")).clicked() { + form.end = timecode::format(position); + } + if ui.add_enabled(!form.open_ended, egui::Button::new("go")).clicked() { + seek = Some(form.end.clone()); + } + ui.end_row(); + }); + ui.checkbox(&mut form.open_ended, "still happening when the recording ended"); + + if form.displays.len() > 1 { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.label("seen on"); + for (id, ticked) in &mut form.displays { + ui.checkbox(ticked, format!("display {id}")); + } + ui.label(egui::RichText::new("(none ticked: any)").small().color(theme::TEXT_DIM)); + }); + } + + if let Some(error) = &form.error { + ui.add_space(6.0); + ui.colored_label(theme::BUG, error); + } + + ui.add_space(10.0); + ui.horizontal(|ui| { + if ui + .add(egui::Button::new(egui::RichText::new("Save").color(egui::Color32::WHITE)).fill(egui::Color32::from_rgb(150, 40, 40))) + .clicked() + { + save = true; + } + if ui.button("Cancel").clicked() { + cancel = true; + } + }); + }); + + if let Some(text) = seek + && let Ok(seconds) = timecode::parse(&text) + { + self.playback.pause(); + self.playback.seek(seconds); + } + if cancel || !open { + self.composer = None; + } else if save + && let Err(message) = self.save_composer() + && let Some(form) = self.composer.as_mut() + { + form.error = Some(message); + } + } +} diff --git a/komorebi-recorder/src/viewer/inspector.rs b/komorebi-recorder/src/viewer/inspector.rs new file mode 100644 index 00000000..9943f03e --- /dev/null +++ b/komorebi-recorder/src/viewer/inspector.rs @@ -0,0 +1,882 @@ +//! The panel on the right: what the thing under the playhead is, and the detail behind it. +//! +//! Five tabs ([`Tab`]): +//! +//! | tab | what it shows | +//! |---|---| +//! | *Now* | the state at the playhead and what has just happened | +//! | *Event* | one event end to end: what its handler logged, with the line of komorebi's source for each; what changed and who changed it; and what the rest of the system did around it (komorebi's own calls into the OS, the system, each application), which opens out into the records themselves | +//! | *Findings* | what looks wrong, ranked | +//! | *Bugs* | what was marked as the bug and what has been concluded | +//! | *Log* | komorebi's own log, following the playhead | +//! +//! Drawing the panel does not act on the session. What a click asks for (go to a time, select an +//! event, edit or delete a bug region, copy a command) is collected while drawing and carried out +//! once drawing is done, because drawing borrows the session and acting on it needs it mutably. +//! +//! An event is shown through [`Analysis::trace`](crate::analysis::Analysis::trace) and +//! [`Analysis::os_trace`](crate::analysis::Analysis::os_trace), worked out the first time the +//! Event tab shows the event and kept in [`Open::traces`] and [`Open::os_traces`]. The panel needs +//! an `egui::Context`, so there are no examples; `every_tab_of_the_inspector_draws` in `viewer::app` +//! draws each tab. + +use super::app::Open; +use super::app::Tab; +use super::theme; +use crate::analysis::classify::Class; +use crate::analysis::os_trace::GroupKind; +use crate::analysis::os_trace::OsTraceData; +use crate::analysis::os_trace::Phase; +use crate::analysis::trace::TraceData; +use crate::annotations::Kind; +use crate::timecode; +use eframe::egui; +use eframe::egui::Color32; +use eframe::egui::RichText; +use std::sync::Arc; + +/// What the user asked for in the panel, carried out once drawing is done (drawing borrows the +/// session, acting on it needs it mutably). +#[derive(Default)] +struct Wants { + seek: Option, + select_event: Option, + select_finding: Option, + select_bug: Option, + edit_bug: Option, + delete_bug: Option, + loop_region: Option<(f64, f64)>, + copy: Option, + mark: bool, +} + +fn chip(ui: &mut egui::Ui, text: &str, colour: Color32) { + ui.label( + RichText::new(format!(" {text} ")) + .small() + .color(Color32::BLACK) + .background_color(colour), + ); +} + +fn class_name(class: Class) -> String { + format!("{class:?}").to_lowercase() +} + +fn actor_colour(actor: &str) -> Color32 { + match actor { + "handler" => theme::ACCENT, + "reaper" => Color32::from_rgb(235, 185, 60), + "workspace-reconciliator" => Color32::from_rgb(205, 130, 240), + _ => theme::BUG, + } +} + +impl Open { + /// Draws the panel on the right, with the tab chosen in [`Open::tab`] showing, and then carries + /// out what the user asked for in it. + /// + /// The tabs act on the session through the same methods as the keys and the timeline: going + /// somewhere pauses and moves the playhead and scrolls the timeline to it, and selecting an + /// event shows the Event tab. The buttons to mark and edit a bug region open the composer, + /// delete calls [`Open::delete_annotation`], and "loop it" repeats the region. Other buttons + /// copy text: a `trace` command for the event, a command for the records of a source, the + /// location of a line of komorebi's source, and a ready-to-paste prompt that starts an + /// agent's investigation (see `agent_prompt` in the `inspector` module). + /// + /// Needs an `egui::Context`, so a window is needed. + pub fn inspector_panel(&mut self, ctx: &egui::Context) { + let mut wants = Wants::default(); + + egui::SidePanel::right("inspector") + .default_width(430.0) + .min_width(300.0) + .frame( + egui::Frame::new() + .fill(theme::BACKGROUND) + .inner_margin(egui::Margin::same(10)), + ) + .show(ctx, |ui| { + ui.horizontal(|ui| { + for (tab, name) in [ + (Tab::Now, "Now"), + (Tab::Event, "Event"), + (Tab::Findings, "Findings"), + (Tab::Bugs, "Bugs"), + (Tab::Log, "Log"), + ] { + ui.selectable_value(&mut self.tab, tab, name); + } + }); + ui.separator(); + + match self.tab { + Tab::Now => self.now_tab(ui, &mut wants), + Tab::Event => self.event_tab(ui, &mut wants), + Tab::Findings => self.findings_tab(ui, &mut wants), + Tab::Bugs => self.bugs_tab(ui, &mut wants), + Tab::Log => self.log_tab(ui, &mut wants), + } + }); + + self.carry_out(ctx, wants); + } + + fn carry_out(&mut self, ctx: &egui::Context, wants: Wants) { + if let Some(time) = wants.seek { + self.playback.pause(); + self.playback.seek(time); + self.view.reveal(time, self.loaded.duration_s); + } + if let Some(seq) = wants.select_event + && let Some(index) = self.loaded.events.iter().position(|event| event.seq == seq) + { + self.select_event(index); + } + if let Some(index) = wants.select_finding + && let Some(finding) = self.loaded.findings.get(index) + { + let (start, first_event) = ( + finding.start_video_s, + finding + .refs + .iter() + .find_map(|reference| reference.strip_prefix("event:")?.parse::().ok()), + ); + self.selected_finding = Some(index); + self.playback.pause(); + self.playback.seek(start); + self.view.reveal(start, self.loaded.duration_s); + if let Some(seq) = first_event { + self.selected_event = Some(seq); + } + } + if let Some(id) = wants.select_bug { + if let Some(start) = self + .loaded + .bugs() + .find(|bug| bug.id == id) + .map(|bug| bug.start_video_s) + { + self.playback.pause(); + self.playback.seek(start); + self.view.reveal(start, self.loaded.duration_s); + } + self.selected_bug = Some(id); + } + if let Some(id) = wants.edit_bug { + self.open_composer_for(&id); + } + if let Some(id) = wants.delete_bug { + self.delete_annotation(&id); + } + if let Some((from, to)) = wants.loop_region { + self.selection = Some((from, to)); + self.playback.seek(from); + self.playback.set_loop(Some((from, to))); + self.playback.play(self.playback.rate().abs()); + } + if let Some(text) = wants.copy { + ctx.copy_text(text); + self.say("copied"); + } + if wants.mark { + self.open_composer(); + } + } + + /// What the OS trace recorded around an event, worked out once. + fn os_trace_of(&mut self, seq: u64) -> Option> { + if let Some(found) = self.os_traces.get(&seq) { + return Some(found.clone()); + } + + let data = Arc::new(self.loaded.analysis.os_trace(seq).ok()?); + self.os_traces.insert(seq, data.clone()); + Some(data) + } + + /// The trace of an event, worked out once. + fn trace_of(&mut self, seq: u64) -> Option> { + if let Some(found) = self.traces.get(&seq) { + return Some(found.clone()); + } + + let trace = Arc::new(self.loaded.analysis.trace(seq).ok()?); + self.traces.insert(seq, trace.clone()); + Some(trace) + } + + fn now_tab(&mut self, ui: &mut egui::Ui, wants: &mut Wants) { + let time = self.position(); + let mach = self.loaded.analysis.manifest.mach_at_video_seconds(time); + ui.label(RichText::new(timecode::format(time)).monospace().size(18.0)); + if let Some(wall) = self.loaded.analysis.wall_utc(mach) { + ui.label(RichText::new(wall).small().color(theme::TEXT_DIM)); + } + ui.add_space(6.0); + + egui::ScrollArea::vertical().show(ui, |ui| { + match self.loaded.analysis.state_answer(mach, &crate::analysis::answers::StateQuery::default()) { + Ok(state) => { + if let Some(focus) = &state.focus { + ui.label(format!( + "focus: window {} on display {}, workspace {}", + focus.window_id.map_or_else(|| "(none)".to_string(), |id| id.to_string()), + focus.monitor_id, + focus.workspace + )); + } + if state.paused { + ui.colored_label(theme::BUG, "komorebi is paused"); + } + if let Some(age) = state.origin.age_ms + && age > 3000.0 + { + ui.label( + RichText::new(format!( + "no notification for {:.0} s: komorebi can change state without one, so this may be out of date", + age / 1000.0 + )) + .small() + .color(theme::TEXT_DIM), + ); + } + + ui.add_space(6.0); + if state.violations.is_empty() { + ui.label(RichText::new("nothing looks wrong in this state").color(theme::OK)); + } else { + ui.label(RichText::new("wrong in this state").strong()); + for violation in &state.violations { + ui.horizontal_wrapped(|ui| { + chip(ui, &format!("{:?}", violation.severity).to_lowercase(), theme::severity(violation.severity)); + ui.label(&violation.message); + }); + } + } + + ui.add_space(8.0); + ui.label(RichText::new("windows").strong()); + for monitor in &state.monitors { + ui.label(RichText::new(format!("display {}", monitor.id)).color(theme::TEXT_DIM)); + for workspace in &monitor.workspaces { + for (index, container) in workspace.containers.iter().enumerate() { + for window in &container.windows { + let rect = window.rect.as_ref().map_or_else(String::new, |rect| rect.describe()); + ui.label( + RichText::new(format!(" {index} {} \"{}\" {rect}", window.exe, window.title)) + .monospace() + .size(11.0), + ); + } + } + } + } + } + Err(error) => { + ui.label(RichText::new(error.to_string()).color(theme::TEXT_DIM)); + } + } + + ui.add_space(10.0); + ui.label(RichText::new("just before").strong()); + let before: Vec = (0..self.loaded.events.len()) + .filter(|index| self.loaded.events[*index].video_s <= time + 1e-3) + .rev() + .take(8) + .collect(); + if before.is_empty() { + ui.label(RichText::new("no events yet").color(theme::TEXT_DIM)); + } + for index in before { + let event = &self.loaded.events[index]; + ui.horizontal(|ui| { + chip(ui, &class_name(event.class), theme::class(event.class)); + if ui + .link(RichText::new(format!("#{} {}", event.seq, event.summary)).size(12.0)) + .clicked() + { + wants.select_event = Some(event.seq); + } + ui.label( + RichText::new(format!("{:.1} s ago", time - event.video_s)) + .small() + .color(theme::TEXT_DIM), + ); + }); + } + }); + } + + fn event_tab(&mut self, ui: &mut egui::Ui, wants: &mut Wants) { + let Some(seq) = self.selected_event else { + ui.label( + RichText::new( + "Select an event on the timeline, or press . and , to step through them.", + ) + .color(theme::TEXT_DIM), + ); + return; + }; + let Some(trace) = self.trace_of(seq) else { + ui.label(format!("event #{seq} could not be traced")); + return; + }; + let event = &trace.event; + + ui.horizontal(|ui| { + chip(ui, &class_name(event.class), theme::class(event.class)); + ui.label(RichText::new(format!("#{} {}", event.seq, event.summary)).strong()); + }); + ui.label(RichText::new(&event.reason).small().color(theme::TEXT_DIM)); + ui.horizontal(|ui| { + ui.label( + RichText::new(format!("received {}", timecode::format(event.video_s))).monospace(), + ); + if let Some(handler) = &event.handler { + if ui + .small_button("go to its start") + .on_hover_text("when its handler began") + .clicked() + { + wants.seek = Some(handler.started_video_s); + } + ui.label( + RichText::new( + handler + .handler_ms + .map_or_else(String::new, |ms| format!("handled in ≥ {ms:.0} ms")), + ) + .small() + .color(theme::TEXT_DIM), + ); + } + if ui.small_button("go to its end").clicked() { + wants.seek = Some(event.video_s); + } + }); + ui.horizontal(|ui| { + if ui.small_button("◀ previous").clicked() + && let Some(index) = self + .loaded + .events + .iter() + .position(|candidate| candidate.seq == seq) + && index > 0 + { + wants.select_event = Some(self.loaded.events[index - 1].seq); + } + if ui.small_button("next ▶").clicked() + && let Some(index) = self + .loaded + .events + .iter() + .position(|candidate| candidate.seq == seq) + && let Some(next) = self.loaded.events.get(index + 1) + { + wants.select_event = Some(next.seq); + } + if ui.small_button("copy trace command").clicked() { + wants.copy = Some(format!( + "komorebi-recorder trace '{}' event:{}", + self.loaded.dir.display(), + seq + )); + } + }); + ui.separator(); + + let os_trace = self.os_trace_of(seq); + egui::ScrollArea::vertical().show(ui, |ui| { + if !trace.notes.is_empty() { + for note in &trace.notes { + ui.label( + RichText::new(format!("• {note}")) + .small() + .color(Color32::from_rgb(235, 185, 60)), + ); + } + ui.add_space(6.0); + } + + ui.label(RichText::new(format!("what changed ({})", trace.changes.len())).strong()); + if trace.changes.is_empty() { + ui.label(RichText::new("the state did not change").color(theme::TEXT_DIM)); + } + for traced in &trace.changes { + ui.horizontal_wrapped(|ui| { + chip( + ui, + &traced.attribution.actor, + actor_colour(&traced.attribution.actor), + ); + ui.label( + RichText::new(&traced.attribution.confidence) + .small() + .color(theme::TEXT_DIM), + ); + ui.label(&traced.change.text); + }); + ui.label( + RichText::new(format!(" {}", traced.attribution.reason)) + .small() + .color(theme::TEXT_DIM), + ); + if !traced.attribution.evidence.is_empty() { + let lines: Vec = traced + .attribution + .evidence + .iter() + .map(|line| format!("log:{line}")) + .collect(); + ui.label( + RichText::new(format!(" evidence {}", lines.join(" "))) + .small() + .monospace() + .color(theme::TEXT_DIM), + ); + } + } + + for (heading, list) in [ + ( + "wrong after this event, and not before", + &trace.violations_appeared, + ), + ( + "wrong before this event, and not after", + &trace.violations_resolved, + ), + ] { + if list.is_empty() { + continue; + } + ui.add_space(6.0); + ui.label(RichText::new(heading).strong()); + for violation in list { + ui.horizontal_wrapped(|ui| { + chip( + ui, + &format!("{:?}", violation.severity).to_lowercase(), + theme::severity(violation.severity), + ); + ui.label(&violation.message); + }); + } + } + + ui.add_space(8.0); + ui.label( + RichText::new(format!("what the handler logged ({})", trace.handler.len())) + .strong(), + ); + for line in &trace.handler { + log_line_ui(ui, line, wants); + } + if !trace.ambient.is_empty() { + ui.add_space(6.0); + ui.label( + RichText::new(format!( + "logged by other threads meanwhile ({})", + trace.ambient.len() + )) + .strong(), + ); + for line in &trace.ambient { + log_line_ui(ui, line, wants); + } + } + + if let Some(os) = &os_trace { + ui.add_space(8.0); + os_trace_ui(ui, &self.loaded.dir, os, wants); + } + }); + } + + fn findings_tab(&mut self, ui: &mut egui::Ui, wants: &mut Wants) { + ui.label( + RichText::new(format!( + "{} things that look wrong or unusual, most worth looking at first", + self.loaded.findings.len() + )) + .small() + .color(theme::TEXT_DIM), + ); + egui::ScrollArea::vertical().show(ui, |ui| { + for (index, finding) in self.loaded.findings.iter().enumerate() { + let selected = self.selected_finding == Some(index); + let frame = egui::Frame::new() + .fill(if selected { + Color32::from_rgb(38, 42, 56) + } else { + theme::LANE + }) + .corner_radius(4.0) + .inner_margin(egui::Margin::same(6)); + let response = frame + .show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + chip( + ui, + &format!("{:?}", finding.severity).to_lowercase(), + theme::severity(finding.severity), + ); + ui.label( + RichText::new(timecode::format(finding.start_video_s)).monospace(), + ); + ui.label(RichText::new(&finding.kind).small().color(theme::TEXT_DIM)); + if !finding.bugs.is_empty() { + chip(ui, "near the bug", theme::BUG); + } + }); + ui.label(&finding.summary); + }) + .response + .interact(egui::Sense::click()); + if response.clicked() { + wants.select_finding = Some(index); + } + ui.add_space(3.0); + } + }); + } + + fn bugs_tab(&mut self, ui: &mut egui::Ui, wants: &mut Wants) { + if ui + .add( + egui::Button::new(RichText::new("Mark a bug region…").color(Color32::WHITE)) + .fill(Color32::from_rgb(150, 40, 40)), + ) + .clicked() + { + wants.mark = true; + } + ui.label( + RichText::new( + "The region you mark, and what you say is wrong, is where an investigation starts.", + ) + .small() + .color(theme::TEXT_DIM), + ); + ui.add_space(6.0); + + egui::ScrollArea::vertical().show(ui, |ui| { + let mut any = false; + for kind in [Kind::Bug, Kind::Finding, Kind::Note] { + for annotation in self.loaded.annotations.iter().filter(|annotation| annotation.kind == kind) { + any = true; + let selected = self.selected_bug.as_deref() == Some(annotation.id.as_str()); + egui::Frame::new() + .fill(if selected { Color32::from_rgb(52, 32, 34) } else { theme::LANE }) + .corner_radius(4.0) + .inner_margin(egui::Margin::same(8)) + .show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + let colour = match kind { + Kind::Bug => theme::BUG, + Kind::Finding => theme::OK, + Kind::Note => theme::TEXT_DIM, + }; + chip(ui, &format!("{}", annotation.kind), colour); + ui.label( + RichText::new(format!( + "{} – {}{}", + timecode::format(annotation.start_video_s), + timecode::format(annotation.end_video_s), + if annotation.open_ended { " (open-ended)" } else { "" } + )) + .monospace(), + ); + ui.label(RichText::new(format!("by {}", annotation.author)).small().color(theme::TEXT_DIM)); + }); + if !annotation.title.is_empty() { + ui.label(RichText::new(&annotation.title).strong()); + } + if annotation.needs_description { + ui.colored_label(Color32::from_rgb(235, 185, 60), "needs a description: an investigator reads what you wrote here"); + } else { + ui.label(&annotation.text); + } + if let Some(expected) = &annotation.expected { + ui.label(RichText::new(format!("expected: {expected}")).color(theme::TEXT_DIM)); + } + if !annotation.refs.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new("evidence").small().color(theme::TEXT_DIM)); + for reference in &annotation.refs { + let text = reference.to_string(); + if let crate::annotations::Ref::Event { seq } = reference { + if ui.link(&text).clicked() { + wants.select_event = Some(*seq); + } + } else if let crate::annotations::Ref::Frame { video_s } = reference { + if ui.link(&text).clicked() { + wants.seek = Some(*video_s); + } + } else { + ui.label(RichText::new(text).monospace().small()); + } + } + }); + } + ui.horizontal(|ui| { + if ui.small_button("go to").clicked() { + wants.select_bug = Some(annotation.id.clone()); + } + if ui.small_button("loop it").clicked() { + wants.loop_region = Some((annotation.start_video_s, annotation.end_video_s)); + } + if kind == Kind::Bug && ui.small_button("edit").clicked() { + wants.edit_bug = Some(annotation.id.clone()); + } + if ui.small_button("delete").clicked() { + wants.delete_bug = Some(annotation.id.clone()); + } + }); + }); + ui.add_space(4.0); + } + } + + if !any { + ui.label(RichText::new("Nothing marked yet. Press B, or the Mark bug button.").color(theme::TEXT_DIM)); + } + + if self.loaded.bugs().next().is_none() { + return; + } + ui.add_space(8.0); + if ui.button("Copy a prompt for an agent").on_hover_text("a ready-to-paste instruction that starts an investigation from what you marked").clicked() { + wants.copy = Some(agent_prompt(&self.loaded.dir)); + } + }); + } + + fn log_tab(&mut self, ui: &mut egui::Ui, wants: &mut Wants) { + let log = self.loaded.analysis.log(); + let times = &self.loaded.log_times; + if log.lines.is_empty() { + ui.label(RichText::new("komorebi's log was not recorded").color(theme::TEXT_DIM)); + return; + } + + // the line the playhead is at: the last one at or before it + let position = self.position(); + let current = times + .partition_point(|time| time.is_nan() || *time <= position + 1e-3) + .saturating_sub(1); + + let row_height = 15.0; + let area = egui::ScrollArea::vertical().auto_shrink([false, false]); + let area = if self.playback.is_playing() { + // follow the playhead while playing + area.vertical_scroll_offset((current as f32 - 12.0).max(0.0) * row_height) + } else { + area + }; + area.show_rows(ui, row_height, log.lines.len(), |ui, range| { + for index in range { + let line = &log.lines[index]; + let time = times.get(index).copied().unwrap_or(f64::NAN); + let colour = line.level.map_or(theme::TEXT_DIM, |level| match level { + crate::analysis::logparse::Level::Error + | crate::analysis::logparse::Level::Warn => theme::level(level), + _ => Color32::from_gray(190), + }); + let text = format!( + "{} {:>5} {}", + if time.is_nan() { + " ".to_string() + } else { + timecode::format(time) + }, + line.level + .map_or(String::new(), |level| format!("{level:?}").to_uppercase()), + line.message + ); + let label = RichText::new(text).monospace().size(10.5).color(colour); + let response = ui.selectable_label(index == current, label); + if response.clicked() && !time.is_nan() { + wants.seek = Some(time); + } + } + }); + } +} + +fn log_line_ui(ui: &mut egui::Ui, line: &crate::analysis::trace::TraceLine, wants: &mut Wants) { + let colour = match line.level.as_deref() { + Some("ERROR") => theme::level(crate::analysis::logparse::Level::Error), + Some("WARN") => theme::level(crate::analysis::logparse::Level::Warn), + _ => Color32::from_gray(190), + }; + ui.horizontal_wrapped(|ui| { + if let Some(time) = line.video_s + && ui + .link(RichText::new(timecode::format(time)).monospace().size(10.5)) + .on_hover_text("go there") + .clicked() + { + wants.seek = Some(time); + } + ui.label( + RichText::new(format!( + "{} {}", + line.level.as_deref().unwrap_or(""), + line.message + )) + .monospace() + .size(10.5) + .color(colour), + ); + }); + if let Some(source) = &line.source { + let mut text = format!(" {} in {}", source.location, source.function); + if source.file_changed { + text.push_str(" [file differs from the recorded komorebi]"); + } + if line.changes_state_silently { + text.push_str(" [changes state without a notification]"); + } + let response = ui.label( + RichText::new(text) + .monospace() + .size(10.0) + .color(theme::TEXT_DIM), + ); + if response.clicked() { + wants.copy = Some(source.location.clone()); + } + response.on_hover_text("source of this log line"); + } +} + +/// What the rest of the system did around an event, one collapsible group per source. +fn os_trace_ui(ui: &mut egui::Ui, dir: &std::path::Path, os: &OsTraceData, wants: &mut Wants) { + ui.label(RichText::new(format!("the system around it ({})", os.total)).strong()); + ui.label( + RichText::new(format!( + "from {} (its handler began) to {}", + timecode::format(os.started_s), + timecode::format(os.until_s) + )) + .small() + .color(theme::TEXT_DIM), + ); + for note in &os.notes { + ui.label( + RichText::new(format!("• {note}")) + .small() + .color(Color32::from_rgb(235, 185, 60)), + ); + } + + for group in &os.groups { + let colour = match group.kind { + GroupKind::Komorebi => theme::ACCENT, + GroupKind::System => theme::INCIDENT, + GroupKind::App => theme::OK, + GroupKind::Other => theme::TEXT_DIM, + }; + let title = format!( + "{} {} during, {} after", + group.label, group.during, group.after + ); + egui::CollapsingHeader::new(RichText::new(title).color(colour)) + .id_salt((os.seq, &group.source)) + .default_open(group.kind == GroupKind::Komorebi && group.total() <= 12) + .show(ui, |ui| { + for record in &group.records { + ui.horizontal_wrapped(|ui| { + if ui + .link( + RichText::new(timecode::format(record.video_s)) + .monospace() + .size(10.5), + ) + .on_hover_text("go there") + .clicked() + { + wants.seek = Some(record.video_s); + } + ui.label( + RichText::new(match record.phase { + Phase::During => " ", + Phase::After => "+", + }) + .monospace() + .small() + .color(theme::TEXT_DIM), + ) + .on_hover_text(match record.phase { + Phase::During => "while komorebi's handler was running", + Phase::After => "after the notification was sent", + }); + ui.label( + RichText::new(&record.text) + .monospace() + .size(10.5) + .color(Color32::from_gray(190)), + ); + }); + } + + if group.omitted() > 0 { + ui.horizontal(|ui| { + ui.label( + RichText::new(format!("… {} more", group.omitted())) + .small() + .color(theme::TEXT_DIM), + ); + if ui.small_button("copy command").clicked() { + wants.copy = Some(format!( + "komorebi-recorder at '{}' {:.3} --window 1s --source '{}'", + dir.display(), + os.received_s, + group.source + )); + } + }); + } + }); + } + + if !os.overlapping_events.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new("other events in this window:") + .small() + .color(theme::TEXT_DIM), + ); + for seq in &os.overlapping_events { + if ui.small_button(format!("#{seq}")).clicked() { + wants.select_event = Some(*seq); + } + } + }); + } +} + +/// Returns a prompt that starts an agent's investigation of the session in `dir` from what the user +/// marked. +/// +/// The prompt names the session and tells the agent to begin with `komorebi-recorder brief` on it +/// (where the user's description of the bug is the ground truth) and to read `komorebi-recorder +/// guide` for how to work from there to the cause. The Bugs tab copies it to the clipboard. +/// +/// This lives in a module that is not public, so it has no example; the test +/// `the_agent_prompt_names_the_session_and_the_commands_to_start_with` in `viewer::app` pins what it +/// contains. +#[must_use] +pub fn agent_prompt(dir: &std::path::Path) -> String { + let dir = dir.display(); + format!( + "Investigate the komorebi bug recorded in this session: {dir}\n\n\ + Start with `komorebi-recorder brief '{dir}'`: the user marked where the bug starts and ends \ + and described what is wrong, and that description is the ground truth. Read \ + `komorebi-recorder guide` for how to work from there to the cause, then propose a fix \ + grounded in what the recording shows, citing evidence by event, log line and source line." + ) +} diff --git a/komorebi-recorder/src/viewer/keymap.rs b/komorebi-recorder/src/viewer/keymap.rs new file mode 100644 index 00000000..efbc7c43 --- /dev/null +++ b/komorebi-recorder/src/viewer/keymap.rs @@ -0,0 +1,366 @@ +//! The key map: what each key of the viewer does. +//! +//! Kept apart from the window so the whole map can be read, listed in the help and tested. A key +//! becomes an [`Action`] through [`action`]; the window decides how to carry it out. Nothing here +//! needs a window or a [`Context`](eframe::egui::Context): the keys and modifiers are plain egui +//! values. +//! +//! The keys follow a video editor: `Space` plays and pauses, `J`, `K` and `L` shuttle (see +//! [`shuttle`]), the arrow keys step by a frame or, with `Shift`, by a second. [`BINDINGS`] is the +//! list the help window shows, kept next to the map so the two are edited together. +//! +//! Three things are not in the map. Keys with `Command`, `Ctrl` or `Alt` held belong to the +//! system and give no action; the window handles `Command`-`Z` (bring back a deleted annotation) +//! itself. While a text box wants the keyboard, the window reads no keys at all. And the symbol +//! keys are matched by what they type, not by which physical key they are, since that varies with +//! the keyboard layout. + +use eframe::egui::Key; +use eframe::egui::Modifiers; + +/// An action a key asks the window to carry out. +/// +/// [`action`] makes one from a key press, and +/// [`Open::apply`](super::Open::apply) carries it out. The variants are the things the viewer's +/// keyboard can do, so adding one is how a new key gets an effect. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Action { + /// Play if paused, pause if playing (`Space`). + TogglePlay, + /// Pause where the playhead is (`K`). + Pause, + /// Play forwards, faster each time it is pressed while already playing forwards (`L`). + PlayForwards, + /// Play backwards, faster each time (`J`). + PlayBackwards, + /// Step one frame, and pause: `-1` for back and `1` for forward (`←` and `→`). + StepFrame(i32), + /// Jump this many seconds, negative for back (`Shift` with `←` and `→`: `-1` and `1`). + Skip(i32), + /// Go to the start of the recording (`Home`). + ToStart, + /// Go to the end of the recording (`End`). + ToEnd, + /// Go to the event before the playhead and select it (`,`). + PreviousEvent, + /// Go to the event after the playhead and select it (`.`). + NextEvent, + /// Go to the start of the bug region before the playhead (`{`). + PreviousBug, + /// Go to the start of the bug region after the playhead (`}`). + NextBug, + /// Mark the start of a selection on the timeline at the playhead (`[`). + SetIn, + /// Mark the end of a selection on the timeline at the playhead (`]`). + SetOut, + /// Clear the selection and stop looping. [`action`] never returns it: no key is bound to it, + /// and [`Escape`](Action::Escape) is what `Esc` gives. + ClearSelection, + /// Open the composer for a bug region, from the selection if there is one (`B`). + MarkBug, + /// Loop the selection, or stop looping (`\`). + ToggleLoop, + /// Show or hide komorebi's state over the video (`O`). + ToggleOverlay, + /// Zoom the timeline in around the playhead (`+` or `=`). + ZoomIn, + /// Zoom the timeline out around the playhead (`-` or `_`). + ZoomOut, + /// Show the whole recording on the timeline (`0`). + FitTimeline, + /// Make the display with this index among the displays that have video (counting from `0`, so + /// `1` to `9` give `0` to `8`) the one that stepping acts on. + FocusDisplay(usize), + /// Show or hide the list of keys (`?`). + Help, + /// Close the list of keys if it is open, else close the form for a bug region if it is open, + /// else clear the selection and stop looping (`Esc`). + Escape, +} + +/// Every binding, for the help screen: the keys and what they do, as text to show a person. +/// +/// Each entry is `(keys, what they do)`, for example `("Space", "play / pause")`. The text is +/// written by hand, not generated from [`action`], and nothing checks the two against each other +/// beyond the unit test `every_binding_in_the_help_is_real`, which looks for a few of the keys. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::keymap::BINDINGS; +/// +/// let (keys, does) = BINDINGS[0]; +/// assert_eq!((keys, does), ("Space", "play / pause")); +/// assert!(BINDINGS.iter().any(|(keys, _)| keys.starts_with("J"))); +/// ``` +pub const BINDINGS: &[(&str, &str)] = &[ + ("Space", "play / pause"), + ( + "J K L", + "play backwards / pause / play forwards (again = faster)", + ), + ("← →", "back / forward one frame"), + ("Shift ← →", "back / forward one second"), + ("Home End", "to the start / end"), + (", .", "previous / next event"), + ("{ }", "previous / next bug region"), + ("[ ]", "set the start / end of a selection"), + ("B", "mark a bug region (from the selection)"), + ("\\", "loop the selection"), + ("O", "show komorebi's state over the video"), + ("+ -", "zoom the timeline"), + ("0", "fit the whole recording"), + ("1 – 9", "step by that display"), + ("Esc", "clear the selection / close a panel"), + ("?", "this help"), +]; + +/// Returns the action for a key pressed with `modifiers`, if it is bound. +/// +/// `text` is what the key typed, if anything: the symbol keys (`,` `.` `{` `}` `[` `]` `\` `+` `=` +/// `-` `_` `?`) are read from it, since where they are on the keyboard varies with the layout. When +/// `text` is one of them it decides the action whatever `key` is. Otherwise the action comes from +/// `key`: the letters `J`, `K`, `L`, `B` and `O`, `Space`, the arrow keys (with `Shift` for a +/// second at a time), `Home`, `End`, `Esc` and the digits (`0` fits the timeline, `1` to `9` pick a +/// display). +/// +/// Anything pressed with `Command`, `Ctrl` or `Alt` gives `None`, as does any key that is not +/// bound. [`Action::ClearSelection`] is never returned. +/// +/// # Example +/// +/// ```rust +/// use eframe::egui::{Key, Modifiers}; +/// use komorebi_recorder::viewer::keymap::{action, Action}; +/// +/// assert_eq!(action(Key::Space, Modifiers::NONE, None), Some(Action::TogglePlay)); +/// assert_eq!(action(Key::ArrowRight, Modifiers::NONE, None), Some(Action::StepFrame(1))); +/// assert_eq!(action(Key::ArrowRight, Modifiers::SHIFT, None), Some(Action::Skip(1))); +/// assert_eq!(action(Key::Num2, Modifiers::NONE, None), Some(Action::FocusDisplay(1))); +/// +/// // symbols are read from what they type, not from where they are on the keyboard +/// assert_eq!( +/// action(Key::Comma, Modifiers::NONE, Some(",")), +/// Some(Action::PreviousEvent), +/// ); +/// assert_eq!(action(Key::Equals, Modifiers::NONE, Some("=")), Some(Action::ZoomIn)); +/// +/// // the command key is left to the system, and an unbound key does nothing +/// assert_eq!(action(Key::B, Modifiers::COMMAND, None), None); +/// assert_eq!(action(Key::Q, Modifiers::NONE, None), None); +/// ``` +#[must_use] +pub fn action(key: Key, modifiers: Modifiers, text: Option<&str>) -> Option { + if modifiers.command || modifiers.ctrl || modifiers.alt { + return None; + } + + // symbols by what they type, since where they are on the keyboard differs + match text { + Some(",") => return Some(Action::PreviousEvent), + Some(".") => return Some(Action::NextEvent), + Some("{") => return Some(Action::PreviousBug), + Some("}") => return Some(Action::NextBug), + Some("[") => return Some(Action::SetIn), + Some("]") => return Some(Action::SetOut), + Some("\\") => return Some(Action::ToggleLoop), + Some("+" | "=") => return Some(Action::ZoomIn), + Some("-" | "_") => return Some(Action::ZoomOut), + Some("?") => return Some(Action::Help), + _ => {} + } + + Some(match key { + Key::Space => Action::TogglePlay, + Key::J => Action::PlayBackwards, + Key::K => Action::Pause, + Key::L => Action::PlayForwards, + Key::ArrowLeft if modifiers.shift => Action::Skip(-1), + Key::ArrowRight if modifiers.shift => Action::Skip(1), + Key::ArrowLeft => Action::StepFrame(-1), + Key::ArrowRight => Action::StepFrame(1), + Key::Home => Action::ToStart, + Key::End => Action::ToEnd, + Key::B => Action::MarkBug, + Key::O => Action::ToggleOverlay, + Key::Num0 => Action::FitTimeline, + Key::Num1 => Action::FocusDisplay(0), + Key::Num2 => Action::FocusDisplay(1), + Key::Num3 => Action::FocusDisplay(2), + Key::Num4 => Action::FocusDisplay(3), + Key::Num5 => Action::FocusDisplay(4), + Key::Num6 => Action::FocusDisplay(5), + Key::Num7 => Action::FocusDisplay(6), + Key::Num8 => Action::FocusDisplay(7), + Key::Num9 => Action::FocusDisplay(8), + Key::Escape => Action::Escape, + _ => return None, + }) +} + +/// The speeds `J` and `L` step through, as multiples of real time. The last is the fastest +/// [`shuttle`] gives, which is the fastest the playhead goes +/// ([`MAX_RATE`](crate::playback::transport::MAX_RATE)). +pub const SHUTTLE_RATES: [f64; 4] = [1.0, 2.0, 4.0, 8.0]; + +/// Returns the rate to play at after a shuttle key (`J` or `L`). +/// +/// The first press plays at normal speed, each further press in the same direction takes the next +/// of [`SHUTTLE_RATES`], and pressing the other direction starts over at normal speed. +/// +/// `current` is the signed rate now (negative for backwards), `playing` is whether the playhead +/// is moving, and `forwards` is the key pressed (`L` is forwards). The result is signed: +/// negative for backwards. From a stop, or when turning round, it is `1.0` or `-1.0`; a current +/// speed already at the last of the rates stays there; and a speed between two of them (the +/// speed list in the window offers `0.25` and `0.5`) goes to the next one above it. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::keymap::shuttle; +/// +/// // from a stop, the first press plays at normal speed +/// assert_eq!(shuttle(1.0, false, true), 1.0); +/// // each press in the same direction goes faster, up to the limit +/// assert_eq!(shuttle(1.0, true, true), 2.0); +/// assert_eq!(shuttle(4.0, true, true), 8.0); +/// assert_eq!(shuttle(8.0, true, true), 8.0); +/// // backwards is the same, with a sign +/// assert_eq!(shuttle(-1.0, true, false), -2.0); +/// // turning round starts over at normal speed +/// assert_eq!(shuttle(4.0, true, false), -1.0); +/// assert_eq!(shuttle(-4.0, true, true), 1.0); +/// // between two of the rates, it goes to the next one above +/// assert_eq!(shuttle(0.25, true, true), 1.0); +/// ``` +#[must_use] +pub fn shuttle(current: f64, playing: bool, forwards: bool) -> f64 { + let direction = if forwards { 1.0 } else { -1.0 }; + if !playing || current.signum() != direction { + return direction; + } + + let faster = SHUTTLE_RATES + .iter() + .copied() + .find(|rate| *rate > current.abs() + 1e-9) + .unwrap_or(SHUTTLE_RATES[SHUTTLE_RATES.len() - 1]); + direction * faster +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plain() -> Modifiers { + Modifiers::NONE + } + + #[test] + fn the_transport_keys_do_what_video_players_do() { + assert_eq!(action(Key::Space, plain(), None), Some(Action::TogglePlay)); + assert_eq!(action(Key::J, plain(), None), Some(Action::PlayBackwards)); + assert_eq!(action(Key::K, plain(), None), Some(Action::Pause)); + assert_eq!(action(Key::L, plain(), None), Some(Action::PlayForwards)); + assert_eq!( + action(Key::ArrowLeft, plain(), None), + Some(Action::StepFrame(-1)) + ); + assert_eq!( + action(Key::ArrowRight, plain(), None), + Some(Action::StepFrame(1)) + ); + assert_eq!( + action(Key::ArrowRight, Modifiers::SHIFT, None), + Some(Action::Skip(1)) + ); + assert_eq!(action(Key::Home, plain(), None), Some(Action::ToStart)); + } + + #[test] + fn symbols_are_read_from_what_they_type_not_where_they_are() { + assert_eq!( + action(Key::Comma, plain(), Some(",")), + Some(Action::PreviousEvent) + ); + assert_eq!( + action(Key::Period, plain(), Some(".")), + Some(Action::NextEvent) + ); + assert_eq!( + action(Key::OpenBracket, plain(), Some("[")), + Some(Action::SetIn) + ); + assert_eq!( + action(Key::CloseBracket, plain(), Some("]")), + Some(Action::SetOut) + ); + assert_eq!( + action(Key::Questionmark, plain(), Some("?")), + Some(Action::Help) + ); + assert_eq!( + action(Key::Equals, plain(), Some("=")), + Some(Action::ZoomIn) + ); + assert_eq!( + action(Key::Minus, plain(), Some("-")), + Some(Action::ZoomOut) + ); + } + + #[test] + fn the_command_key_is_left_to_the_system() { + assert_eq!(action(Key::B, Modifiers::COMMAND, None), None); + assert_eq!(action(Key::Space, Modifiers::CTRL, None), None); + assert_eq!(action(Key::Q, plain(), None), None); + } + + #[test] + fn the_number_keys_pick_a_display() { + assert_eq!( + action(Key::Num1, plain(), None), + Some(Action::FocusDisplay(0)) + ); + assert_eq!( + action(Key::Num9, plain(), None), + Some(Action::FocusDisplay(8)) + ); + assert_eq!(action(Key::Num0, plain(), None), Some(Action::FitTimeline)); + } + + #[test] + fn shuttling_speeds_up_in_a_direction_and_starts_over_in_the_other() { + assert_eq!(shuttle(1.0, false, true), 1.0); + assert_eq!(shuttle(1.0, true, true), 2.0); + assert_eq!(shuttle(2.0, true, true), 4.0); + assert_eq!(shuttle(4.0, true, true), 8.0); + assert_eq!(shuttle(8.0, true, true), 8.0, "no faster than the limit"); + + assert_eq!(shuttle(-1.0, true, false), -2.0); + assert_eq!( + shuttle(4.0, true, false), + -1.0, + "turning round starts at normal speed" + ); + assert_eq!(shuttle(-4.0, true, true), 1.0); + assert_eq!( + shuttle(-4.0, false, false), + -1.0, + "from a stop it starts at normal speed" + ); + } + + #[test] + fn every_binding_in_the_help_is_real() { + // the help lists a key for each of these; if one stops working the list must change + let listed: String = BINDINGS + .iter() + .map(|(keys, _)| *keys) + .collect::>() + .join(" "); + for key in ["Space", "J", "Home", "B", "Esc"] { + assert!(listed.contains(key), "{key}"); + } + } +} diff --git a/komorebi-recorder/src/viewer/lanes.rs b/komorebi-recorder/src/viewer/lanes.rs new file mode 100644 index 00000000..277f53af --- /dev/null +++ b/komorebi-recorder/src/viewer/lanes.rs @@ -0,0 +1,1048 @@ +//! The timeline: the whole recording as lanes of what happened, with the playhead on it. +//! +//! [`Open::timeline_panel`] draws the bottom panel: a bar of playing controls, and under it the +//! lanes. The arithmetic (which stretch is visible, where a time falls, where the ruler's marks go, +//! how to bin a dense lane) is in [`timeline`](super::timeline) and is tested there; this file +//! draws it and turns the mouse into actions. The lanes, and what the mouse does on them, are +//! described on [`Open::timeline_panel`], whose documentation is public. +//! +//! It needs an `egui::Context`, so there are no examples; the tests in `viewer::app` draw it with +//! real input. + +use super::app::Open; +use super::app::Tab; +use super::theme; +use super::timeline; +use super::timeline::Bin; +use crate::timecode; +use eframe::egui; +use eframe::egui::Color32; +use eframe::egui::Pos2; +use eframe::egui::Rect; +use eframe::egui::Stroke; +use eframe::egui::vec2; + +const LABEL_WIDTH: f32 = 84.0; +const RULER: f32 = 22.0; +const BUGS: f32 = 22.0; +const EVENTS: f32 = 38.0; +const LOG: f32 = 16.0; +const MACHINE: f32 = 16.0; +const FINDINGS: f32 = 16.0; +const SCREEN: f32 = 16.0; +const VIDEO: f32 = 12.0; +const GAP: f32 = 2.0; + +/// More events than this in view are drawn as columns rather than one by one. +const INDIVIDUAL_EVENTS: usize = 1500; + +/// A drag that is going on across the lanes. +/// +/// A press picks which it is, and the drag carries on as that until the pointer is released: +/// a press near an edge of a bug region in the bugs lane takes hold of the edge, else a press +/// with `Shift` held picks a range, else it scrubs. +#[derive(Debug, Clone, PartialEq)] +pub enum Drag { + /// Moving the playhead. + Scrub, + /// Picking a range, from where the drag began. + Select { + /// Where the drag began, in session video seconds. The selection runs between there and the + /// pointer, in time order. + from: f64, + }, + /// Moving the start or the end of a bug region. + Edge { + /// The id of the bug region. + id: String, + /// `true` to move the start of the region, `false` to move its end. + moving_start: bool, + }, +} + +/// How close, in pixels, a press must be to the edge of a bug region to take hold of it. +const GRAB_PX: f32 = 8.0; + +/// Which lane a point is in. The names of the lanes are in the module documentation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Lane { + Ruler, + Bugs, + Events, + Log, + Machine, + Findings, + /// When the picture changed. + Screen, + Video(usize), +} + +/// Where each lane sits down the panel: the lane, its top and its height, in points from the top +/// of the lanes. Lanes are stacked in the order of [`Lane`], with [`GAP`] between them, and one +/// `Video` lane for each display after the others. +struct Layout { + lanes: Vec<(Lane, f32, f32)>, +} + +impl Layout { + fn new(displays: usize) -> Self { + let mut heights = vec![ + (Lane::Ruler, RULER), + (Lane::Bugs, BUGS), + (Lane::Events, EVENTS), + (Lane::Log, LOG), + (Lane::Machine, MACHINE), + (Lane::Findings, FINDINGS), + (Lane::Screen, SCREEN), + ]; + heights.extend((0..displays).map(|index| (Lane::Video(index), VIDEO))); + + let mut top = 0.0; + Self { + lanes: heights + .into_iter() + .map(|(lane, height)| { + let entry = (lane, top, height); + top += height + GAP; + entry + }) + .collect(), + } + } + + fn height(&self) -> f32 { + self.lanes + .last() + .map_or(0.0, |(_, top, height)| top + height) + } + + fn at(&self, y: f32) -> Option { + self.lanes + .iter() + .find(|(_, top, height)| y >= *top && y <= top + height + GAP) + .map(|(lane, _, _)| *lane) + } + + fn rect(&self, lane: Lane, area: Rect) -> Rect { + let (_, top, height) = self + .lanes + .iter() + .find(|(candidate, _, _)| *candidate == lane) + .copied() + .unwrap_or((lane, 0.0, 0.0)); + Rect::from_min_size( + Pos2::new(area.left(), area.top() + top), + vec2(area.width(), height), + ) + } +} + +impl Open { + /// Draws the bottom panel: the bar of playing controls, and under it the timeline. + /// + /// The bar has the buttons for the transport, the playhead's time and the length of the + /// recording, a menu of speeds (0.25, 0.5, 1, 2, 4 and 8 times; choosing one keeps the + /// direction), a "loop" toggle that repeats the selection, the selection if there is one, and + /// the "fit" and "Mark bug" buttons. Each acts by [`Open::apply`] with the + /// [`Action`](super::keymap::Action) of the key that does the same. + /// + /// Needs an `egui::Context`, so a window is needed. The panel has a fixed height: that of the + /// lanes plus 46 points for the bar. + /// + /// # The lanes + /// + /// From the top, each lane is 12 to 38 points tall with 2 points between them. The names of the + /// lanes are at the left, and one lane is added at the bottom for each display that has video. + /// + /// | lane | what is drawn | a click | + /// |---|---|---| + /// | ruler | marks and times ([`ruler`](super::timeline::ruler), labels at least 70 points apart) | seeks | + /// | bugs | the bug regions the user marked, labeled with the title or the first line of the text; an open-ended one ends in "…" | selects the region under it, shows the Bugs tab and seeks to its start; elsewhere seeks | + /// | events | komorebi's events, one mark each, colored by class and taller the louder the class | selects the event within 6 points, else seeks | + /// | log | the errors and warnings of komorebi's log, as columns (red for an error) | seeks | + /// | machine | incidents: a display going away, sleep, lock (a diamond each) | seeks to the incident within 6 points, else to the click | + /// | findings | what looks wrong, as bars colored by severity | selects the finding under it, shows the Findings tab and seeks to its start; elsewhere seeks | + /// | screen | where the picture changed, brighter the more of the screen did; "looking for changes in the picture…" until the scan has run | seeks | + /// | video *N* | the stretches with video from display *N* | seeks | + /// + /// Over the lanes under the ruler the bug regions are tinted faintly and the selection is + /// shaded, and the playhead is a line with a handle at the top, over all of them. When more + /// than 1500 events are in view they are drawn as columns that count them (the height is the + /// logarithm of the count, the color the loudest class in the column) instead of one by one. + /// + /// # The mouse + /// + /// | gesture | effect | + /// |---|---| + /// | click | as in the table above | + /// | drag | scrubs: the playhead follows the pointer | + /// | `Shift` and drag | picks a range, which becomes the selection | + /// | drag from within 8 points of an edge of a bug region in the bugs lane | moves that edge (an open-ended region has no end to take hold of); the region is saved when the drag ends | + /// | pinch, or `Command` and scroll | zooms around the pointer | + /// | scroll | pans | + /// | hover | a tooltip about what is under the pointer (an event, an incident, a finding, a bug region, a change in the picture, an error or warning in the log); elsewhere, the time | + /// + /// Dragging an edge saves through the same append-only file the command line reads, and a region + /// cannot be made to end before it starts (a refusal is shown in the top bar). + /// + /// The arithmetic is in [`timeline`](super::timeline) and is tested there. + pub fn timeline_panel(&mut self, ctx: &egui::Context) { + let layout = Layout::new(self.loaded.displays.len()); + egui::TopBottomPanel::bottom("timeline") + .frame( + egui::Frame::new() + .fill(theme::BACKGROUND) + .inner_margin(egui::Margin::symmetric(10, 6)), + ) + .exact_height(layout.height() + 46.0) + .show(ctx, |ui| { + self.transport_ui(ui); + ui.add_space(4.0); + self.lanes_ui(ui, &layout); + }); + } + + fn transport_ui(&mut self, ui: &mut egui::Ui) { + let playing = self.playback.is_playing(); + let rate = self.playback.rate(); + let position = self.position(); + + ui.horizontal(|ui| { + if icon_button(ui, Icon::Start, "to the start (Home)") { + self.apply(super::keymap::Action::ToStart); + } + if icon_button(ui, Icon::StepBack, "back one frame (←)") { + self.apply(super::keymap::Action::StepFrame(-1)); + } + if icon_button(ui, Icon::Reverse, "play backwards (J)") { + self.apply(super::keymap::Action::PlayBackwards); + } + if icon_button( + ui, + if playing { Icon::Pause } else { Icon::Play }, + "play / pause (Space)", + ) { + self.apply(super::keymap::Action::TogglePlay); + } + if icon_button(ui, Icon::Forward, "play forwards (L)") { + self.apply(super::keymap::Action::PlayForwards); + } + if icon_button(ui, Icon::StepForward, "forward one frame (→)") { + self.apply(super::keymap::Action::StepFrame(1)); + } + if icon_button(ui, Icon::End, "to the end (End)") { + self.apply(super::keymap::Action::ToEnd); + } + + ui.add_space(10.0); + ui.label( + egui::RichText::new(format!( + "{} / {}", + timecode::format(position), + timecode::format(self.loaded.duration_s) + )) + .monospace() + .size(15.0), + ); + + ui.add_space(8.0); + let mut magnitude = rate.abs(); + egui::ComboBox::from_id_salt("rate") + .width(64.0) + .selected_text(format!("{}{magnitude}×", if rate < 0.0 { "−" } else { "" })) + .show_ui(ui, |ui| { + for choice in [0.25, 0.5, 1.0, 2.0, 4.0, 8.0] { + ui.selectable_value(&mut magnitude, choice, format!("{choice}×")); + } + }); + if (magnitude - rate.abs()).abs() > 1e-9 { + self.playback + .set_rate(magnitude * if rate < 0.0 { -1.0 } else { 1.0 }); + } + + ui.add_space(8.0); + let looping = self.playback.looping().is_some(); + if ui + .selectable_label(looping, "loop") + .on_hover_text("repeat the selection (\\)") + .clicked() + { + self.apply(super::keymap::Action::ToggleLoop); + } + + if let Some((from, to)) = self.selection { + ui.add_space(8.0); + ui.label( + egui::RichText::new(format!( + "selected {} – {} ({:.2} s)", + timecode::format(from), + timecode::format(to), + to - from + )) + .color(theme::SELECTION), + ); + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .add( + egui::Button::new(egui::RichText::new("Mark bug").color(Color32::WHITE)) + .fill(Color32::from_rgb(150, 40, 40)), + ) + .on_hover_text("mark where the bug starts and ends (B)") + .clicked() + { + self.apply(super::keymap::Action::MarkBug); + } + if ui + .small_button("fit") + .on_hover_text("show the whole recording (0)") + .clicked() + { + self.apply(super::keymap::Action::FitTimeline); + } + }); + }); + } + + fn lanes_ui(&mut self, ui: &mut egui::Ui, layout: &Layout) { + let (area, response) = ui.allocate_exact_size( + vec2(ui.available_width(), layout.height()), + egui::Sense::click_and_drag(), + ); + let painter = ui.painter_at(area); + let time_area = Rect::from_min_max( + Pos2::new(area.left() + LABEL_WIDTH, area.top()), + area.right_bottom(), + ); + let (left, width) = (time_area.left(), time_area.width()); + let view = self.view; + let duration = self.loaded.duration_s; + let position = self.position(); + + // stripes and their names + for (index, (lane, _, _)) in layout.lanes.iter().enumerate() { + let strip = layout.rect(*lane, area); + if *lane != Lane::Ruler { + painter.rect_filled( + strip, + 2.0, + if index % 2 == 0 { + theme::LANE + } else { + theme::LANE_ALT + }, + ); + } + let name = match lane { + Lane::Ruler => String::new(), + Lane::Bugs => "bugs".to_string(), + Lane::Events => "events".to_string(), + Lane::Log => "log".to_string(), + Lane::Machine => "machine".to_string(), + Lane::Findings => "findings".to_string(), + Lane::Screen => "screen".to_string(), + Lane::Video(display) => format!("video {}", self.loaded.displays[*display].id), + }; + painter.text( + Pos2::new(strip.left() + 4.0, strip.center().y), + egui::Align2::LEFT_CENTER, + name, + egui::FontId::proportional(10.5), + theme::TEXT_DIM, + ); + } + + // the ruler + let ruler = layout.rect(Lane::Ruler, area); + for tick in timeline::ruler(&view, width, 70.0) { + let x = view.x(tick.time, left, width); + painter.line_segment( + [ + Pos2::new(x, ruler.bottom() - if tick.major { 9.0 } else { 4.0 }), + Pos2::new(x, ruler.bottom()), + ], + Stroke::new(1.0_f32, theme::TEXT_DIM), + ); + if tick.major { + painter.text( + Pos2::new(x + 3.0, ruler.top() + 1.0), + egui::Align2::LEFT_TOP, + tick.label, + egui::FontId::monospace(10.0), + theme::TEXT_DIM, + ); + } + } + + // video coverage + for (index, display) in self.loaded.displays.iter().enumerate() { + let strip = layout.rect(Lane::Video(index), area); + for (from, to) in &display.segments { + let (x0, x1) = ( + view.x(*from, left, width).max(left), + view.x(*to, left, width).min(area.right()), + ); + if x1 > x0 { + painter.rect_filled( + Rect::from_min_max( + Pos2::new(x0, strip.top() + 2.0), + Pos2::new(x1, strip.bottom() - 2.0), + ), + 1.0, + theme::VIDEO, + ); + } + } + } + + // what the user marked as the bug, over its own lane and faintly over the rest + let bugs_strip = layout.rect(Lane::Bugs, area); + for bug in self.loaded.bugs() { + // while an edge is being dragged, show where it would land + let (start_s, end_s) = match &self.edge_preview { + Some((id, start, end)) if *id == bug.id => (*start, *end), + _ => (bug.start_video_s, bug.end_video_s), + }; + let (x0, x1) = ( + view.x(start_s, left, width).clamp(left, area.right()), + view.x(end_s, left, width).clamp(left, area.right()), + ); + if x1 < left || x0 > area.right() { + continue; + } + let selected = self.selected_bug.as_deref() == Some(bug.id.as_str()); + painter.rect_filled( + Rect::from_min_max( + Pos2::new(x0, bugs_strip.top() + 1.0), + Pos2::new(x1.max(x0 + 2.0), bugs_strip.bottom() - 1.0), + ), + 2.0, + Color32::from_rgba_unmultiplied(230, 70, 60, if selected { 200 } else { 130 }), + ); + painter.rect_filled( + Rect::from_min_max( + Pos2::new(x0, area.top() + RULER), + Pos2::new(x1.max(x0 + 2.0), area.bottom()), + ), + 0.0, + Color32::from_rgba_unmultiplied(230, 70, 60, 22), + ); + let label = if bug.title.is_empty() { + bug.text.lines().next().unwrap_or("").to_string() + } else { + bug.title.clone() + }; + if x1 - x0 > 30.0 { + painter + .with_clip_rect(Rect::from_min_max( + Pos2::new(x0, bugs_strip.top()), + Pos2::new(x1, bugs_strip.bottom()), + )) + .text( + Pos2::new(x0 + 4.0, bugs_strip.center().y), + egui::Align2::LEFT_CENTER, + label, + egui::FontId::proportional(11.0), + Color32::WHITE, + ); + } + if bug.open_ended { + painter.text( + Pos2::new(x1 - 2.0, bugs_strip.center().y), + egui::Align2::RIGHT_CENTER, + "…", + egui::FontId::proportional(13.0), + Color32::WHITE, + ); + } + } + + // the range being picked + if let Some((from, to)) = self.selection { + let (x0, x1) = (view.x(from, left, width), view.x(to, left, width)); + painter.rect_filled( + Rect::from_min_max( + Pos2::new(x0.max(left), area.top() + RULER), + Pos2::new(x1.min(area.right()), area.bottom()), + ), + 0.0, + Color32::from_rgba_unmultiplied(90, 150, 240, 45), + ); + for x in [x0, x1] { + painter.line_segment( + [ + Pos2::new(x, area.top() + RULER), + Pos2::new(x, area.bottom()), + ], + Stroke::new(1.0_f32, theme::SELECTION), + ); + } + } + + // events: one mark each while they are few enough to tell apart, columns when not + let events_strip = layout.rect(Lane::Events, area); + let visible = self + .loaded + .event_times + .iter() + .filter(|time| **time >= view.start_s && **time <= view.end_s) + .count(); + if visible <= INDIVIDUAL_EVENTS { + for event in &self.loaded.events { + if event.video_s < view.start_s || event.video_s > view.end_s { + continue; + } + let x = view.x(event.video_s, left, width); + let weight = theme::class_weight(event.class); + let reach = 8.0 + f32::from(weight) * 3.0; + let selected = self.selected_event == Some(event.seq); + painter.line_segment( + [ + Pos2::new(x, events_strip.center().y - reach / 2.0), + Pos2::new(x, events_strip.center().y + reach / 2.0), + ], + Stroke::new( + if selected { 3.0 } else { 1.5_f32 }, + if selected { + Color32::WHITE + } else { + theme::class(event.class) + }, + ), + ); + } + } else { + let columns = timeline::bin( + self.loaded + .events + .iter() + .map(|event| (event.video_s, theme::class_weight(event.class))), + &view, + width as usize, + ); + let peak = columns.iter().map(|bin| bin.count).max().unwrap_or(1) as f32; + for Bin { + column, + count, + weight, + } in columns + { + let x = left + column as f32 + 0.5; + let height = (events_strip.height() - 4.0) + * ((count as f32).ln_1p() / peak.ln_1p()).clamp(0.12, 1.0); + painter.line_segment( + [ + Pos2::new(x, events_strip.bottom() - 2.0), + Pos2::new(x, events_strip.bottom() - 2.0 - height), + ], + Stroke::new(1.0_f32, class_colour_of_weight(weight)), + ); + } + } + + // errors and warnings in komorebi's log + let log_strip = layout.rect(Lane::Log, area); + let marks = timeline::bin( + self.loaded.log_marks.iter().map(|mark| { + ( + mark.video_s, + u8::from(mark.level == crate::analysis::logparse::Level::Error) + 1, + ) + }), + &view, + width as usize, + ); + for Bin { + column, + count, + weight, + } in marks + { + let x = left + column as f32 + 0.5; + let height = (2.0 + (count as f32).ln_1p() * 3.0).min(log_strip.height() - 2.0); + painter.line_segment( + [ + Pos2::new(x, log_strip.bottom() - 1.0), + Pos2::new(x, log_strip.bottom() - 1.0 - height), + ], + Stroke::new( + 1.0_f32, + if weight > 1 { + theme::level(crate::analysis::logparse::Level::Error) + } else { + theme::level(crate::analysis::logparse::Level::Warn) + }, + ), + ); + } + + // what happened to the machine + let machine_strip = layout.rect(Lane::Machine, area); + for incident in &self.loaded.incidents { + let x = view.x(incident.video_s, left, width); + if x < left || x > area.right() { + continue; + } + let centre = Pos2::new(x, machine_strip.center().y); + painter.add(egui::Shape::convex_polygon( + vec![ + centre + vec2(0.0, -5.0), + centre + vec2(5.0, 0.0), + centre + vec2(0.0, 5.0), + centre + vec2(-5.0, 0.0), + ], + theme::INCIDENT, + Stroke::NONE, + )); + } + + // what looked wrong + let findings_strip = layout.rect(Lane::Findings, area); + for (index, finding) in self.loaded.findings.iter().enumerate() { + if finding.end_video_s < view.start_s || finding.start_video_s > view.end_s { + continue; + } + let (x0, x1) = ( + view.x(finding.start_video_s, left, width).max(left), + view.x(finding.end_video_s, left, width).min(area.right()), + ); + let colour = theme::severity(finding.severity); + let selected = self.selected_finding == Some(index); + painter.rect_filled( + Rect::from_min_max( + Pos2::new( + x0, + findings_strip.center().y - if selected { 4.0 } else { 2.5 }, + ), + Pos2::new( + x1.max(x0 + 3.0), + findings_strip.center().y + if selected { 4.0 } else { 2.5 }, + ), + ), + 1.0, + colour, + ); + } + + // when the picture changed, once the scan has found it + let screen_strip = layout.rect(Lane::Screen, area); + if let Some(changes) = &self.changes { + for span in &changes.spans { + let (x0, x1) = ( + view.x(span.start_video_s, left, width).max(left), + view.x(span.end_video_s, left, width).min(area.right()), + ); + if x1 < left || x0 > area.right() { + continue; + } + let strength = (span.peak_share * 40.0).clamp(0.25, 1.0) as f32; + painter.rect_filled( + Rect::from_min_max( + Pos2::new(x0, screen_strip.top() + 3.0), + Pos2::new(x1.max(x0 + 2.0), screen_strip.bottom() - 3.0), + ), + 1.0, + Color32::from_rgba_unmultiplied(120, 200, 190, (90.0 + 150.0 * strength) as u8), + ); + } + } else if self.changes_result.is_some() { + painter.text( + Pos2::new(left + 6.0, screen_strip.center().y), + egui::Align2::LEFT_CENTER, + "looking for changes in the picture…", + egui::FontId::proportional(10.0), + theme::TEXT_DIM, + ); + } + + // the playhead + let x = view.x(position, left, width); + if x >= left - 1.0 && x <= area.right() + 1.0 { + painter.line_segment( + [Pos2::new(x, area.top()), Pos2::new(x, area.bottom())], + Stroke::new(1.5_f32, theme::PLAYHEAD), + ); + painter.add(egui::Shape::convex_polygon( + vec![ + Pos2::new(x - 5.0, area.top()), + Pos2::new(x + 5.0, area.top()), + Pos2::new(x, area.top() + 8.0), + ], + theme::PLAYHEAD, + Stroke::NONE, + )); + } + + self.lanes_interaction(ui, &response, layout, area, time_area, duration); + } + + fn lanes_interaction( + &mut self, + ui: &egui::Ui, + response: &egui::Response, + layout: &Layout, + area: Rect, + time_area: Rect, + duration: f64, + ) { + let (left, width) = (time_area.left(), time_area.width()); + let pointer = response + .interact_pointer_pos() + .or_else(|| response.hover_pos()); + let shift = ui.input(|input| input.modifiers.shift); + + // zoom with a pinch or with Command-scroll, pan with scrolling + if response.hovered() + && let Some(hover) = response.hover_pos() + { + let (scroll, zoom, command) = ui.input(|input| { + ( + input.smooth_scroll_delta, + input.zoom_delta(), + input.modifiers.command, + ) + }); + let anchor = self.view.time(hover.x, left, width); + if (zoom - 1.0).abs() > 1e-4 { + self.view.zoom(anchor, f64::from(zoom), duration); + } else if command && scroll.y.abs() > 0.0 { + self.view.zoom( + anchor, + (1.0 + f64::from(scroll.y) * 0.01).max(0.1), + duration, + ); + } else if scroll.x.abs() > 0.0 || scroll.y.abs() > 0.0 { + let pixels = if scroll.x.abs() > scroll.y.abs() { + scroll.x + } else { + scroll.y + }; + self.view.pan( + -f64::from(pixels) / f64::from(width) * self.view.span(), + duration, + ); + } + } + + // a press picks scrubbing, selecting or taking hold of the edge of a bug region; the drag + // then carries on + if response.drag_started() + && let Some(point) = pointer + && point.x >= left + { + let time = self.view.time(point.x, left, width).clamp(0.0, duration); + let reach = f64::from(GRAB_PX / width) * self.view.span(); + let in_bugs_lane = layout.at(point.y - area.top()) == Some(Lane::Bugs); + + let edge = in_bugs_lane + .then(|| { + self.loaded.bugs().find_map(|bug| { + if (bug.start_video_s - time).abs() <= reach { + Some((bug.id.clone(), true, bug.start_video_s, bug.end_video_s)) + } else if !bug.open_ended && (bug.end_video_s - time).abs() <= reach { + Some((bug.id.clone(), false, bug.start_video_s, bug.end_video_s)) + } else { + None + } + }) + }) + .flatten(); + + self.drag = Some(if let Some((id, moving_start, start, end)) = edge { + self.edge_preview = Some((id.clone(), start, end)); + Drag::Edge { id, moving_start } + } else if shift { + Drag::Select { from: time } + } else { + Drag::Scrub + }); + } + + if response.dragged() + && let Some(point) = pointer + { + let time = self.view.time(point.x, left, width).clamp(0.0, duration); + match self.drag.clone() { + Some(Drag::Scrub) => { + self.playback.seek(time); + self.view.reveal(time, duration); + } + Some(Drag::Select { from }) => { + self.selection = Some((from.min(time), from.max(time))); + } + Some(Drag::Edge { id, moving_start }) => { + if let Some((_, start, end)) = &mut self.edge_preview { + if moving_start { + *start = time.min(*end); + } else { + *end = time.max(*start); + } + } + let _ = id; + } + None => {} + } + } + if response.drag_stopped() { + if let Some(Drag::Edge { id, moving_start }) = self.drag.take() + && let Some((_, start, end)) = self.edge_preview.take() + { + let result = + self.move_bug_edge(&id, moving_start, if moving_start { start } else { end }); + match result { + Ok(()) => self.say("region changed"), + Err(message) => self.say(message), + } + } + self.edge_preview = None; + self.drag = None; + } + + // a click goes to what is under it, else to the time + if response.clicked() + && let Some(point) = response.interact_pointer_pos() + && point.x >= left + { + let time = self.view.time(point.x, left, width).clamp(0.0, duration); + let reach = f64::from(6.0 / width) * self.view.span(); + match layout.at(point.y - area.top()) { + Some(Lane::Events) => { + if let Some(index) = timeline::nearest(&self.loaded.event_times, time, reach) { + self.select_event(index); + } else { + self.playback.seek(time); + } + } + Some(Lane::Bugs) => { + let hit = self + .loaded + .bugs() + .find(|bug| { + time >= bug.start_video_s - reach && time <= bug.end_video_s + reach + }) + .map(|bug| (bug.id.clone(), bug.start_video_s)); + match hit { + Some((id, start)) => { + self.selected_bug = Some(id); + self.tab = Tab::Bugs; + self.playback.seek(start); + } + None => self.playback.seek(time), + } + } + Some(Lane::Findings) => { + let hit = self.loaded.findings.iter().position(|finding| { + time >= finding.start_video_s - reach && time <= finding.end_video_s + reach + }); + if let Some(index) = hit { + self.selected_finding = Some(index); + self.tab = Tab::Findings; + self.playback + .seek(self.loaded.findings[index].start_video_s); + } else { + self.playback.seek(time); + } + } + Some(Lane::Machine) => { + let times: Vec = self + .loaded + .incidents + .iter() + .map(|incident| incident.video_s) + .collect(); + let target = + timeline::nearest(×, time, reach).map_or(time, |index| times[index]); + self.playback.seek(target); + } + _ => self.playback.seek(time), + } + } + + // what is under the pointer + if let Some(hover) = response.hover_pos() + && hover.x >= left + { + let time = self.view.time(hover.x, left, width); + let reach = f64::from(5.0 / width) * self.view.span(); + let text = match layout.at(hover.y - area.top()) { + Some(Lane::Events) => timeline::nearest(&self.loaded.event_times, time, reach) + .and_then(|index| self.loaded.events.get(index)) + .map(|event| { + format!( + "#{} {} · {}\n{}", + event.seq, + timecode::format(event.video_s), + format!("{:?}", event.class).to_lowercase(), + event.summary + ) + }), + Some(Lane::Machine) => self + .loaded + .incidents + .iter() + .find(|incident| (incident.video_s - time).abs() <= reach) + .map(|incident| { + format!( + "{} · {}\n{}", + timecode::format(incident.video_s), + incident.kind, + incident.detail + ) + }), + Some(Lane::Findings) => self + .loaded + .findings + .iter() + .find(|finding| { + time >= finding.start_video_s - reach && time <= finding.end_video_s + reach + }) + .map(|finding| { + format!( + "{} · {}\n{}", + timecode::format(finding.start_video_s), + finding.kind, + finding.summary + ) + }), + Some(Lane::Bugs) => self + .loaded + .bugs() + .find(|bug| { + time >= bug.start_video_s - reach && time <= bug.end_video_s + reach + }) + .map(|bug| { + format!( + "bug {} – {}\n{}", + timecode::format(bug.start_video_s), + timecode::format(bug.end_video_s), + bug.text + ) + }), + Some(Lane::Screen) => self.changes.as_ref().and_then(|changes| { + changes + .spans + .iter() + .find(|span| time >= span.start_video_s - reach && time <= span.end_video_s + reach) + .map(|span| { + format!( + "display {} · {} – {}\nthe picture changed here: up to {:.1}% of the screen", + span.display, + timecode::format(span.start_video_s), + timecode::format(span.end_video_s), + span.peak_share * 100.0 + ) + }) + }), + Some(Lane::Log) => { + let times: Vec = self + .loaded + .log_marks + .iter() + .map(|mark| mark.video_s) + .collect(); + timeline::nearest(×, time, reach * 2.0).map(|index| { + format!( + "{} · {:?} in komorebi's log", + timecode::format(times[index]), + self.loaded.log_marks[index].level + ) + }) + } + _ => Some(timecode::format(time)), + }; + + if let Some(text) = text { + response.clone().on_hover_ui_at_pointer(|ui| { + ui.label(text); + }); + } + } + } +} + +fn class_colour_of_weight(weight: u8) -> Color32 { + match weight { + 6 => Color32::from_rgb(205, 130, 240), + 5 => Color32::from_rgb(110, 180, 255), + 4 => Color32::from_rgb(120, 205, 145), + 3 => Color32::from_rgb(245, 170, 90), + 2 => Color32::from_rgb(170, 170, 200), + _ => Color32::from_rgb(88, 88, 100), + } +} + +/// The pictures on the buttons. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Icon { + Start, + StepBack, + Reverse, + Play, + Pause, + Forward, + StepForward, + End, +} + +/// A button drawn with shapes, since the fonts may not have the symbols. +fn icon_button(ui: &mut egui::Ui, icon: Icon, tip: &str) -> bool { + let (rect, response) = ui.allocate_exact_size(vec2(30.0, 24.0), egui::Sense::click()); + let painter = ui.painter_at(rect); + if response.hovered() { + painter.rect_filled(rect, 4.0, Color32::from_gray(48)); + } + + let colour = if response.hovered() { + Color32::WHITE + } else { + Color32::from_gray(200) + }; + let centre = rect.center(); + let triangle = |direction: f32, offset: f32| { + painter.add(egui::Shape::convex_polygon( + vec![ + Pos2::new(centre.x + offset - 4.0 * direction, centre.y - 6.0), + Pos2::new(centre.x + offset - 4.0 * direction, centre.y + 6.0), + Pos2::new(centre.x + offset + 5.0 * direction, centre.y), + ], + colour, + Stroke::NONE, + )); + }; + let bar = |offset: f32| { + painter.rect_filled( + Rect::from_center_size(Pos2::new(centre.x + offset, centre.y), vec2(2.5, 12.0)), + 0.0, + colour, + ); + }; + + match icon { + Icon::Start => { + bar(-6.0); + triangle(-1.0, 3.0); + } + Icon::StepBack => { + triangle(-1.0, -2.0); + bar(6.0); + } + Icon::Reverse => triangle(-1.0, 0.0), + Icon::Play => triangle(1.0, 0.0), + Icon::Pause => { + bar(-4.0); + bar(4.0); + } + Icon::Forward => triangle(1.0, 0.0), + Icon::StepForward => { + bar(-6.0); + triangle(1.0, 2.0); + } + Icon::End => { + triangle(1.0, -3.0); + bar(6.0); + } + } + + response.on_hover_text(tip).clicked() +} diff --git a/komorebi-recorder/src/viewer/loaded.rs b/komorebi-recorder/src/viewer/loaded.rs new file mode 100644 index 00000000..b7c46043 --- /dev/null +++ b/komorebi-recorder/src/viewer/loaded.rs @@ -0,0 +1,342 @@ +//! A session opened in the viewer: everything the window draws, gathered once off the UI thread. +//! +//! [`Loaded::load`] opens the session through [`Analysis`] and turns what it reads into the plain +//! lists the window draws every frame (events, incidents, findings, log marks, displays and +//! annotations), all of them already on the session's video time. Reading takes noticeable time +//! on a long recording, which is why [`ViewerApp::open`](super::ViewerApp::open) does it on a +//! thread. A [`Loaded`] does not change after it is made, except that +//! [`Loaded::reload_annotations`] reads the annotations again after the window changed them. +//! +//! Which komorebi produced the session (the flavor) and which host recorded it are already +//! decided by [`Analysis`]; nothing here depends on either. + +use crate::analysis::Analysis; +use crate::analysis::catalog::Skew; +use crate::analysis::logparse::Level; +use crate::analysis::overview::Finding; +use crate::analysis::overview::IncidentView; +use crate::analysis::views::EventView; +use crate::annotations; +use crate::annotations::AnnotationView; +use color_eyre::eyre; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; + +/// A display and the stretches of the recording that have video from it. +/// +/// A display that was unplugged or slept and came back has more than one stretch: one `DisplayMeta` +/// per display, however many segments of video it has. +#[derive(Debug, Clone, PartialEq)] +pub struct DisplayMeta { + /// The display's id, as the recorder and the manifest name it. + pub id: u32, + /// `[x, y, width, height]` in global points: where its picture sits among the monitors. + pub frame: [f64; 4], + /// The stretches with video from this display, as `(start, end)` in session video seconds, + /// one for each segment of its video in the order the manifest lists them. A segment with no + /// recorded end runs to the end of the recording. + pub segments: Vec<(f64, f64)>, +} + +/// An error or warning in komorebi's log, placed on the timeline. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct LogMark { + /// When the line was written, in session video seconds. + pub video_s: f64, + /// [`Level::Error`] or [`Level::Warn`]: no other level is marked. + pub level: Level, +} + +/// A session opened in the viewer: everything the window draws, read once. +/// +/// All times are session video seconds, the same timeline as +/// [`Transport`](crate::playback::Transport): seconds from the start of the recording's video. A +/// line of komorebi's log that the session's clock cannot place on it has no [`LogMark`] and a +/// `NaN` in [`Loaded::log_times`]. +/// +/// A `Loaded` is made by [`Loaded::load`], which needs a finished session on disk, so it has no +/// example here: `a_session_loads_with_everything_the_window_draws` in this module's tests builds +/// one. +pub struct Loaded { + /// The session, analyzed. Shared with the background threads that read more of it (the scan for + /// changes in the picture). + pub analysis: Arc, + /// The session directory, as it was given to [`Loaded::load`]. + pub dir: PathBuf, + /// The length of the video in session video seconds: the end of + /// [`Manifest::video_span`](crate::session::Manifest::video_span). + pub duration_s: f64, + /// komorebi's events as a reader sees them, in the order they were recorded. + pub events: Vec, + /// Video time of each event, for finding the one nearest a point. It has one entry for each of + /// `events`, in the same order, so the two can be indexed together. + pub event_times: Vec, + /// Incidents in the recording environment (a display went away, the machine slept...). + pub incidents: Vec, + /// Ranked, most worth looking at first. + pub findings: Vec, + /// The errors and warnings in komorebi's log that have a time, for the log lane. + pub log_marks: Vec, + /// Video time of each line of komorebi's log (NaN where a line has no time). It has one entry + /// for each line of the log, in order. + pub log_times: Vec, + /// The displays that have video, in ascending order of id. + pub displays: Vec, + /// Bug regions, notes and findings, in the order of their start. + pub annotations: Vec, + /// Things the analysis noticed that a reader should be told, and the warnings from reading the + /// annotations file. + pub warnings: Vec, + /// How the komorebi source this build indexed compares with the komorebi that was recorded. + pub skew: Skew, +} + +impl Loaded { + /// Opens the session in `dir` and reads everything the window needs. + /// + /// This takes noticeable time on a long recording: call it off the UI thread. + /// + /// # Errors + /// + /// Returns an error if + /// + /// - `dir` does not exist or is not a session directory (it has no session manifest), + /// - the manifest cannot be read, is not valid, or was written by a newer komorebi-recorder + /// than this build, + /// - the session is still being recorded ("is still being recorded; stop the recording first"), + /// - the session was left unfinished because its recorder was killed or crashed (the error + /// says to run `komorebi-recorder reindex` on it), or + /// - the annotations file cannot be read, or the bug regions or the findings cannot be worked + /// out (a file they are read from cannot be read). + /// + /// Everything else that can be wrong with a session (a missing log, an event that cannot be + /// read) is not an error: it becomes an entry of [`Loaded::warnings`]. + /// + /// Covered by `a_session_loads_with_everything_the_window_draws` and + /// `a_session_that_cannot_be_analyzed_says_why`. + pub fn load(dir: &Path) -> eyre::Result { + let analysis = Arc::new(Analysis::open(dir)?); + let duration_s = analysis.manifest.video_span().1; + + let events: Vec = (0..analysis.events().len()) + .filter_map(|index| analysis.event_view(index)) + .collect(); + let event_times = events.iter().map(|event| event.video_s).collect(); + + let bugs = analysis.bugs()?; + let bug_refs: Vec<&annotations::Annotation> = bugs.iter().collect(); + let findings = analysis.rank(analysis.findings()?, &bug_refs); + + let log_marks = analysis + .log() + .lines + .iter() + .filter_map(|line| { + let level = line + .level + .filter(|level| matches!(level, Level::Error | Level::Warn))?; + let mach_ns = analysis.clock().wall_to_mach(line.wall_us?)?; + Some(LogMark { + video_s: analysis.video_s(mach_ns), + level, + }) + }) + .collect(); + + let log_times: Vec = analysis + .log() + .lines + .iter() + .map(|line| { + line.wall_us + .and_then(|wall_us| analysis.clock().wall_to_mach(wall_us)) + .map_or(f64::NAN, |mach_ns| analysis.video_s(mach_ns)) + }) + .collect(); + + let mut displays: Vec = Vec::new(); + for entry in analysis + .manifest + .displays + .iter() + .filter(|entry| entry.result.frames > 0) + { + let id = entry.result.display.id; + let end = entry.end_s.unwrap_or(duration_s); + match displays.iter_mut().find(|meta| meta.id == id) { + Some(meta) => meta.segments.push((entry.offset_s, end)), + None => displays.push(DisplayMeta { + id, + frame: entry.result.display.frame, + segments: vec![(entry.offset_s, end)], + }), + } + } + displays.sort_by_key(|meta| meta.id); + + let loaded_annotations = annotations::load(dir)?; + let mut warnings = analysis.warnings(); + warnings.extend(loaded_annotations.warnings.clone()); + let skew = analysis.skew(); + + Ok(Self { + incidents: analysis.incidents(), + annotations: loaded_annotations + .annotations + .iter() + .map(|annotation| annotation.view(&analysis.manifest)) + .collect(), + analysis, + dir: dir.to_path_buf(), + duration_s, + events, + event_times, + findings, + log_marks, + log_times, + displays, + warnings, + skew, + }) + } + + /// Reads the annotations again, after one was added, changed or removed. + /// + /// # Errors + /// + /// Returns an error if the annotations file cannot be read. [`Loaded::annotations`] is then + /// unchanged. + pub fn reload_annotations(&mut self) -> eyre::Result<()> { + let loaded = annotations::load(&self.dir)?; + self.annotations = loaded + .annotations + .iter() + .map(|annotation| annotation.view(&self.analysis.manifest)) + .collect(); + Ok(()) + } + + /// Returns the bug regions (the annotations of kind [`Kind::Bug`](annotations::Kind::Bug)), in + /// time order. + pub fn bugs(&self) -> impl Iterator { + self.annotations + .iter() + .filter(|annotation| annotation.kind == annotations::Kind::Bug) + } + + /// Returns the event with sequence number `seq`, if there is one. + /// + /// The search is linear in the number of events. + #[must_use] + pub fn event(&self, seq: u64) -> Option<&EventView> { + self.events.iter().find(|event| event.seq == seq) + } +} + +/// Returns a name for a session in a list: the name of the folder it is in. +/// +/// Sessions are folders named for when they began, so the name is a timestamp. A path with no final +/// name (a root) is shown whole. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::loaded::name_of; +/// use std::path::Path; +/// +/// assert_eq!(name_of(Path::new("/recordings/20261026T120000Z")), "20261026T120000Z"); +/// assert_eq!(name_of(Path::new("/")), "/"); +/// ``` +#[must_use] +pub fn name_of(dir: &Path) -> String { + dir.file_name().map_or_else( + || dir.display().to_string(), + |name| name.to_string_lossy().into_owned(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testkit::SessionBuilder; + use serde_json::json; + + #[test] + fn a_session_loads_with_everything_the_window_draws() { + let (session, _) = SessionBuilder::new("viewer-loaded") + .event( + 2.0, + json!({"type": "Retile"}), + Some(crate::testkit::state_with_windows(&[(1, "a")])), + ) + .log( + 2.0, + "ERROR", + "komorebi::macos_api: failed to get window position: AXError::InvalidUIElement", + ) + .incident(3.0, "display-disconnected", "display 3 went away") + .build(); + + let loaded = Loaded::load(&session.dir).expect("load"); + assert_eq!(loaded.events.len(), 1); + assert_eq!(loaded.event_times.len(), 1); + assert!((loaded.event_times[0] - 2.0).abs() < 1e-6); + assert_eq!(loaded.incidents.len(), 1); + assert_eq!(loaded.log_marks.len(), 1); + assert_eq!(loaded.log_marks[0].level, Level::Error); + assert_eq!(loaded.log_times.len(), 1); + assert!((loaded.log_times[0] - 2.0).abs() < 1e-6); + assert!((loaded.duration_s - 10.0).abs() < 1e-6); + assert!(loaded.displays.is_empty(), "no video was recorded"); + assert!(!loaded.findings.is_empty()); + } + + #[test] + fn annotations_are_read_again_after_a_change() { + let (session, manifest) = SessionBuilder::new("viewer-reload").build(); + let mut loaded = Loaded::load(&session.dir).expect("load"); + assert_eq!(loaded.bugs().count(), 0); + + annotations::add( + &session.dir, + annotations::New { + kind: Some(annotations::Kind::Bug), + start_mach_ns: manifest.mach_at_video_seconds(1.0), + end_mach_ns: Some(manifest.mach_at_video_seconds(2.0)), + text: "wrong".to_string(), + ..annotations::New::default() + }, + ) + .expect("add"); + + loaded.reload_annotations().expect("reload"); + assert_eq!(loaded.bugs().count(), 1); + assert!((loaded.bugs().next().expect("bug").start_video_s - 1.0).abs() < 1e-6); + } + + #[test] + fn a_session_that_cannot_be_analyzed_says_why() { + let (session, mut manifest) = SessionBuilder::new("viewer-live").build(); + manifest.status = "recording".to_string(); + session.write_manifest(&manifest).expect("manifest"); + + let error = Loaded::load(&session.dir) + .err() + .expect("refused") + .to_string(); + assert!( + error.contains("left unfinished") || error.contains("still being recorded"), + "{error}" + ); + assert!(Loaded::load(&session.dir.join("nope")).is_err()); + } + + #[test] + fn a_session_is_named_for_its_folder() { + assert_eq!( + name_of(Path::new("/a/b/20261026T000000Z")), + "20261026T000000Z" + ); + } +} diff --git a/komorebi-recorder/src/viewer/mod.rs b/komorebi-recorder/src/viewer/mod.rs new file mode 100644 index 00000000..1655eeab --- /dev/null +++ b/komorebi-recorder/src/viewer/mod.rs @@ -0,0 +1,156 @@ +//! The viewer: a window for playing and scrubbing a recording with everything that happened in it +//! laid out on a timeline. +//! +//! It is started by `komorebi-recorder view [SESSION]` ([`crate::cli::ViewArgs`]), which calls +//! [`run`], and by the "Open session..." and "Open last" buttons of the recorder window +//! ([`crate::app`]), which start that command in a process of its own so that reviewing a +//! recording cannot disturb one being made. It is an `egui` application run by `eframe`. +//! +//! ```text +//! +-------------------------------------------------+ +//! | Open... session name counts and warnings | top bar +//! +----------------------------------+--------------+ +//! | | Now | +//! | the video of every display, | Event | +//! | side by side, with komorebi's | Findings | inspector +//! | layout drawn over it | Bugs | +//! | | Log | +//! +----------------------------------+--------------+ +//! | transport controls, then the lanes: ruler, bugs,| +//! | events, log, machine, findings, screen, video | timeline +//! +-------------------------------------------------+ +//! ``` +//! +//! # What plays and what is read +//! +//! The viewer reads a *finished* session; one that is still being recorded does not open. A +//! session opens in the background ([`loaded::Loaded::load`]) while the window shows a spinner, and +//! a session that cannot be opened is shown on the start screen with the reason. Playing is +//! done by [`Playback`](crate::playback::Playback), whose worker thread decodes the video; the +//! window only asks it for the frame to show. Where the picture changed is found by a scan on yet +//! another thread after the session opens. +//! +//! The session may have been recorded on either host and by either flavor of komorebi: the viewer +//! shows whatever [`Analysis`](crate::analysis::Analysis) reads from it, and the video plays on +//! any host that has a decoder (macOS and Windows). +//! +//! # Modules +//! +//! | module | what it is | +//! |---|---| +//! | [`keymap`] | the keys: a key press becomes an [`Action`](keymap::Action) | +//! | [`timeline`] | the arithmetic of the timeline: the visible stretch, the ruler, dense lanes | +//! | [`loaded`] | the session as the window draws it, read once | +//! | [`prefs`] | what the viewer remembers between runs | +//! | [`theme`] | colors | +//! | `app` | [`ViewerApp`], [`Screen`] and [`Open`], the state of the window and how it is kept in step | +//! | `lanes` | the transport bar and the timeline lanes, and what a mouse does on them | +//! | `inspector` | the panel on the right and its five tabs | +//! | `video` | the pictures and the state overlay drawn over them | +//! | `composer` | the form for marking a bug region, and editing, deleting and bringing one back | +//! +//! The first five are public, because they are plain values and arithmetic that need no window. The +//! rest draw, so they need an `egui::Context`: their items are documented, and there are no +//! examples for them. They are covered by the tests in `viewer::app`, which drive the whole window +//! headlessly with real key events. +//! +//! # Staying out of the way of what is being investigated +//! +//! The viewer is used on the machine whose behavior is being investigated, so it must neither be +//! tiled by komorebi nor appear in a recording being made. +//! +//! - **Not tiled.** The window has an empty title ([`run`] builds it with `with_title("")`), and +//! komorebi leaves windows with no title alone: komorebi for Mac does not manage a window that +//! has none. The three settings that also hide the title bar apply on macOS only. Whether +//! komorebi for Windows leaves the window alone is checked on a real machine rather than assumed: +//! with `KOMOREBI_RECORDER_PROBE_WINDOW=1` set, the window asks komorebi whether it would manage +//! it and writes the answer to `komorebi-recorder-window-probe.txt` in the temp directory +//! (see [`crate::platform::window::PROBE_VARIABLE`]). +//! - **Not in the video.** On macOS the recorder's capture filter excludes by name every process +//! called `komorebi-recorder` (and its own), which includes the viewer. On Windows a whole +//! monitor is captured, so about once a second the window asks Windows to leave it out of captures +//! (`WDA_EXCLUDEFROMCAPTURE`) through [`crate::platform::window::Chrome`], which it ticks on +//! every frame. + +mod app; +mod composer; +mod inspector; +pub mod keymap; +mod lanes; +pub mod loaded; +pub mod prefs; +pub mod theme; +pub mod timeline; +mod video; + +use color_eyre::eyre; +use eframe::egui; +use std::path::PathBuf; + +pub use app::Open; +pub use app::Screen; +pub use app::ViewerApp; + +/// Opens the viewer window, with `session` open if given, and runs it until it is closed. +/// +/// This blocks the calling thread: the window's event loop runs on it. `session` is the folder of a +/// recording. It opens in the background, so a session that cannot be opened does not make this +/// fail: the window comes up and shows why. With no `session` the window shows a start screen with +/// the recent sessions that still exist ([`prefs::Prefs::existing`]) and a button to choose one. +/// +/// The window is 1500 by 920 points (at least 900 by 600), dark, and untitled: see the [module +/// documentation](self#staying-out-of-the-way-of-what-is-being-investigated) for why. Needs a +/// window, so there is no example; the tests in `viewer::app` drive the same [`ViewerApp`] +/// headlessly. +/// +/// # Errors +/// +/// Returns an error saying "the viewer window failed" if the window cannot be created or its event +/// loop fails (for example, there is no display or no usable graphics adapter). +pub fn run(session: Option) -> eyre::Result<()> { + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + // no title: komorebi leaves untitled windows alone, so opening the viewer does not + // move the layout of the machine whose behavior is being investigated + .with_title("") + .with_title_shown(false) + .with_titlebar_shown(false) + .with_fullsize_content_view(true) + .with_inner_size([1500.0, 920.0]) + .with_min_inner_size([900.0, 600.0]), + ..Default::default() + }; + + eframe::run_native( + "komorebi-recorder", + options, + Box::new(move |creation| { + let mut visuals = egui::Visuals::dark(); + visuals.panel_fill = theme::BACKGROUND; + visuals.window_fill = theme::BACKGROUND; + creation.egui_ctx.set_visuals(visuals); + + let mut app = ViewerApp::new(prefs::directory()); + if let Some(dir) = &session { + app.open(dir); + } + Ok(Box::new(Shell( + app, + crate::platform::window::Chrome::default(), + ))) + }), + ) + .map_err(|error| eyre::Report::msg(format!("the viewer window failed: {error}"))) +} + +/// Adapts [`ViewerApp`] to eframe. +struct Shell(ViewerApp, crate::platform::window::Chrome); + +impl eframe::App for Shell { + fn update(&mut self, context: &egui::Context, _frame: &mut eframe::Frame) { + // keeps the window out of any recording being made (on Windows) and, if asked, finds out + // whether komorebi would tile it + self.1.tick(); + self.0.ui(context); + } +} diff --git a/komorebi-recorder/src/viewer/prefs.rs b/komorebi-recorder/src/viewer/prefs.rs new file mode 100644 index 00000000..42bd575a --- /dev/null +++ b/komorebi-recorder/src/viewer/prefs.rs @@ -0,0 +1,253 @@ +//! The viewer's preferences, kept between runs: which sessions were opened and how it was left. +//! +//! The preferences are one small JSON file, `viewer-prefs.json`, in [`directory`] (komorebi's data +//! directory). They are conveniences and never worth refusing to start over, so a missing or +//! damaged file reads as the defaults and a failure to write one is ignored. Nothing here needs a +//! window. [`ViewerApp`](super::ViewerApp) loads them when it is made and saves them when a +//! session is opened and when the state overlay is switched. + +use serde::Deserialize; +use serde::Serialize; +use std::path::Path; +use std::path::PathBuf; + +const FILE: &str = "viewer-prefs.json"; +const RECENT: usize = 12; + +/// The viewer's preferences, kept between runs. +/// +/// A field missing from the file takes its default, so a file written by an older build with fewer +/// fields still reads. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::prefs::Prefs; +/// use std::path::Path; +/// +/// let mut prefs = Prefs::default(); +/// assert!(prefs.overlay); +/// +/// prefs.opened(Path::new("/recordings/a")); +/// prefs.opened(Path::new("/recordings/b")); +/// prefs.opened(Path::new("/recordings/a")); +/// assert_eq!(prefs.recent, ["/recordings/a", "/recordings/b"]); +/// ``` +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Prefs { + /// The sessions opened, as the text of their paths, most recent first. Each is listed once and + /// at most the twelve most recent are kept. + pub recent: Vec, + /// Whether komorebi's state is drawn over the video. The default is `true`. + pub overlay: bool, +} + +impl Default for Prefs { + fn default() -> Self { + Self { + recent: Vec::new(), + overlay: true, + } + } +} + +impl Prefs { + /// Returns the preferences kept in `dir`, or the defaults if there are none or they are damaged. + /// + /// They are only conveniences, never worth refusing to start over, so this has no error: a + /// missing directory, a file that cannot be read and a file that is not valid JSON of this + /// shape all give [`Prefs::default`]. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::prefs::Prefs; + /// + /// let name = format!("komorebi-recorder-doc-load-{}", std::process::id()); + /// let dir = std::env::temp_dir().join(name); + /// std::fs::create_dir_all(&dir)?; + /// + /// // nothing saved yet + /// assert_eq!(Prefs::load(&dir), Prefs::default()); + /// + /// // damaged + /// std::fs::write(dir.join("viewer-prefs.json"), "not json {")?; + /// assert_eq!(Prefs::load(&dir), Prefs::default()); + /// + /// // an older file with fewer fields still reads + /// std::fs::write(dir.join("viewer-prefs.json"), r#"{"overlay": false}"#)?; + /// assert!(!Prefs::load(&dir).overlay); + /// # std::fs::remove_dir_all(&dir)?; + /// # Ok::<(), Box>(()) + /// ``` + #[must_use] + pub fn load(dir: &Path) -> Self { + std::fs::read_to_string(dir.join(FILE)) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_default() + } + + /// Writes the preferences to `viewer-prefs.json` in `dir`, creating `dir` if it is missing. + /// + /// A failure to create the directory or to write the file is ignored, for the reason given at + /// [`Prefs::load`]: the preferences are not worth interrupting anyone for. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::prefs::Prefs; + /// use std::path::Path; + /// + /// let name = format!("komorebi-recorder-doc-save-{}", std::process::id()); + /// let dir = std::env::temp_dir().join(name); + /// + /// let mut prefs = Prefs { overlay: false, ..Prefs::default() }; + /// prefs.opened(Path::new("/recordings/a")); + /// prefs.save(&dir); + /// assert_eq!(Prefs::load(&dir), prefs); + /// # std::fs::remove_dir_all(&dir)?; + /// # Ok::<(), Box>(()) + /// ``` + pub fn save(&self, dir: &Path) { + if let Ok(text) = serde_json::to_string_pretty(self) { + let _ = std::fs::create_dir_all(dir); + let _ = std::fs::write(dir.join(FILE), text); + } + } + + /// Notes that `session` was opened, moving it to the front of [`Prefs::recent`]. + /// + /// It is listed once, however often it is opened, and the list keeps the twelve most recent. + /// The path is stored as it is given, not made absolute or resolved. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::prefs::Prefs; + /// use std::path::Path; + /// + /// let mut prefs = Prefs::default(); + /// for index in 0..30 { + /// prefs.opened(Path::new(&format!("/recordings/s{index}"))); + /// } + /// assert_eq!(prefs.recent.len(), 12); + /// assert_eq!(prefs.recent[0], "/recordings/s29"); + /// ``` + pub fn opened(&mut self, session: &Path) { + let text = session.display().to_string(); + self.recent.retain(|recent| *recent != text); + self.recent.insert(0, text); + self.recent.truncate(RECENT); + } + + /// Returns the recent sessions that still exist, most recent first. + /// + /// A recent session still exists if its directory has a session manifest + /// ([`MANIFEST_FILE`](crate::session::MANIFEST_FILE)). Nothing else about it is checked, so a + /// session that exists may still fail to open. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::session::MANIFEST_FILE; + /// use komorebi_recorder::viewer::prefs::Prefs; + /// use std::path::Path; + /// + /// let name = format!("komorebi-recorder-doc-existing-{}", std::process::id()); + /// let session = std::env::temp_dir().join(name); + /// std::fs::create_dir_all(&session)?; + /// std::fs::write(session.join(MANIFEST_FILE), "{}")?; + /// + /// let mut prefs = Prefs::default(); + /// prefs.opened(&session); + /// prefs.opened(Path::new("/gone/forever")); + /// assert_eq!(prefs.existing(), [session.clone()]); + /// # std::fs::remove_dir_all(&session)?; + /// # Ok::<(), Box>(()) + /// ``` + #[must_use] + pub fn existing(&self) -> Vec { + self.recent + .iter() + .map(PathBuf::from) + .filter(|path| path.join(crate::session::MANIFEST_FILE).is_file()) + .collect() + } +} + +/// Returns where preferences live: komorebi's data directory, `/komorebi` (see +/// [`komorebi_link::data_dir`](crate::komorebi_link::data_dir)). +/// +/// It depends on the machine, so it is not shown with an example: the viewer passes it to +/// [`Prefs::load`] and [`Prefs::save`]. +#[must_use] +pub fn directory() -> PathBuf { + crate::komorebi_link::data_dir().to_path_buf() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "komorebi-recorder-prefs-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + dir + } + + #[test] + fn preferences_round_trip_and_default_when_missing() { + let dir = temp("round"); + assert_eq!(Prefs::load(&dir), Prefs::default()); + + let mut prefs = Prefs { + overlay: false, + ..Prefs::default() + }; + prefs.opened(Path::new("/a")); + prefs.save(&dir); + assert_eq!(Prefs::load(&dir), prefs); + } + + #[test] + fn damaged_preferences_are_ignored_not_fatal() { + let dir = temp("damaged"); + std::fs::create_dir_all(&dir).expect("dir"); + std::fs::write(dir.join(FILE), "not json {").expect("write"); + assert_eq!(Prefs::load(&dir), Prefs::default()); + + // an older file with fewer fields still reads + std::fs::write(dir.join(FILE), r#"{"overlay": false}"#).expect("write"); + assert!(!Prefs::load(&dir).overlay); + } + + #[test] + fn the_most_recent_session_is_first_and_each_is_listed_once() { + let mut prefs = Prefs::default(); + prefs.opened(Path::new("/a")); + prefs.opened(Path::new("/b")); + prefs.opened(Path::new("/a")); + assert_eq!(prefs.recent, ["/a", "/b"]); + + for index in 0..30 { + prefs.opened(Path::new(&format!("/s{index}"))); + } + assert_eq!(prefs.recent.len(), RECENT); + assert_eq!(prefs.recent[0], "/s29"); + } + + #[test] + fn only_sessions_that_still_exist_are_offered() { + let (session, _) = crate::testkit::SessionBuilder::new("prefs-existing").build(); + let mut prefs = Prefs::default(); + prefs.opened(&session.dir); + prefs.opened(Path::new("/gone/forever")); + + assert_eq!(prefs.existing(), [session.dir]); + } +} diff --git a/komorebi-recorder/src/viewer/theme.rs b/komorebi-recorder/src/viewer/theme.rs new file mode 100644 index 00000000..aacd6bb0 --- /dev/null +++ b/komorebi-recorder/src/viewer/theme.rs @@ -0,0 +1,146 @@ +//! Colors: what each kind of thing looks like wherever it is drawn. +//! +//! The constants are the palette of the window (dark, with one accent), and the functions map the +//! analysis types the viewer shows ([`Class`], [`Severity`], [`Level`]) to a color, so that an +//! event class has the same color on the timeline and in its chip in the inspector. Nothing here +//! needs a window: a [`Color32`] is a plain value. + +use crate::analysis::classify::Class; +use crate::analysis::invariants::Severity; +use crate::analysis::logparse::Level; +use eframe::egui::Color32; + +/// The fill of the window and of its panels. +pub const BACKGROUND: Color32 = Color32::from_rgb(22, 22, 27); +/// The fill of a lane of the timeline (every other lane), and of a card in the inspector. +pub const LANE: Color32 = Color32::from_rgb(30, 30, 37); +/// The fill of the lanes of the timeline that alternate with [`LANE`]. +pub const LANE_ALT: Color32 = Color32::from_rgb(34, 34, 42); +/// Secondary text: captions, the names of lanes and the labels of the ruler. +pub const TEXT_DIM: Color32 = Color32::from_rgb(140, 140, 152); +/// The playhead on the timeline. +pub const PLAYHEAD: Color32 = Color32::from_rgb(255, 214, 90); +/// The color of what is wrong and of what the user marked as the bug: bug regions, errors, windows +/// that break an invariant in the state overlay. +pub const BUG: Color32 = Color32::from_rgb(230, 70, 60); +/// The range picked on the timeline. +pub const SELECTION: Color32 = Color32::from_rgb(90, 150, 240); +/// The stretches of a display's video in its lane of the timeline. +pub const VIDEO: Color32 = Color32::from_rgb(70, 110, 160); +/// The accent: the outline of the display the keys act on, the focused window in the state +/// overlay, and komorebi's own handler and process. +pub const ACCENT: Color32 = Color32::from_rgb(110, 170, 255); +/// Good news and confirmations: nothing looks wrong, the note after an action. +pub const OK: Color32 = Color32::from_rgb(110, 200, 140); + +/// Returns the color of an event of `class`, on the timeline and in its chip in the inspector. +/// +/// [`Class::Echo`], [`Class::Manual`] and [`Class::Other`] share one dim color, and so do +/// [`Class::Monitor`] and [`Class::Lock`]. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::classify::Class; +/// use komorebi_recorder::viewer::theme; +/// +/// assert_eq!(theme::class(Class::Echo), theme::class(Class::Other)); +/// assert_eq!(theme::class(Class::Monitor), theme::class(Class::Lock)); +/// assert_ne!(theme::class(Class::Command), theme::class(Class::Focus)); +/// ``` +#[must_use] +pub fn class(class: Class) -> Color32 { + match class { + Class::Command => Color32::from_rgb(110, 180, 255), + Class::Focus => Color32::from_rgb(170, 170, 200), + Class::Lifecycle => Color32::from_rgb(120, 205, 145), + Class::Drag => Color32::from_rgb(245, 170, 90), + Class::Echo | Class::Manual | Class::Other => Color32::from_rgb(88, 88, 100), + Class::Monitor | Class::Lock => Color32::from_rgb(205, 130, 240), + } +} + +/// Returns how much an event of `class` matters when many share a column of pixels: the loudest +/// wins. +/// +/// The weights, from loudest to quietest, are [`Class::Monitor`] and [`Class::Lock`] (`6`), +/// [`Class::Command`], [`Class::Lifecycle`], [`Class::Drag`], [`Class::Focus`] and, quietest, +/// [`Class::Echo`], [`Class::Manual`] and [`Class::Other`] (`1`). A weight is also what a dense +/// lane of the timeline uses to pick the color of a column: see +/// [`bin`](super::timeline::bin). +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::classify::Class; +/// use komorebi_recorder::viewer::theme::class_weight; +/// +/// assert_eq!(class_weight(Class::Monitor), 6); +/// assert!(class_weight(Class::Monitor) > class_weight(Class::Command)); +/// assert!(class_weight(Class::Command) > class_weight(Class::Lifecycle)); +/// assert!(class_weight(Class::Lifecycle) > class_weight(Class::Drag)); +/// assert!(class_weight(Class::Drag) > class_weight(Class::Focus)); +/// assert!(class_weight(Class::Focus) > class_weight(Class::Echo)); +/// assert_eq!(class_weight(Class::Echo), class_weight(Class::Other)); +/// ``` +#[must_use] +pub fn class_weight(class: Class) -> u8 { + match class { + Class::Monitor | Class::Lock => 6, + Class::Command => 5, + Class::Lifecycle => 4, + Class::Drag => 3, + Class::Focus => 2, + Class::Echo | Class::Manual | Class::Other => 1, + } +} + +/// Returns the color of a finding or a violation of `severity`: red for an error, amber for a +/// warning, gray for information. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::invariants::Severity; +/// use komorebi_recorder::viewer::theme; +/// +/// assert_ne!(theme::severity(Severity::Error), theme::severity(Severity::Warn)); +/// assert_ne!(theme::severity(Severity::Warn), theme::severity(Severity::Info)); +/// ``` +#[must_use] +pub fn severity(severity: Severity) -> Color32 { + match severity { + Severity::Error => Color32::from_rgb(235, 85, 75), + Severity::Warn => Color32::from_rgb(235, 185, 60), + Severity::Info => Color32::from_rgb(130, 130, 150), + } +} + +/// Returns the color of a line of komorebi's log at `level`. +/// +/// An error and a warning are drawn in the colors [`severity`] gives [`Severity::Error`] and +/// [`Severity::Warn`]; every other level is [`TEXT_DIM`]. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::invariants::Severity; +/// use komorebi_recorder::analysis::logparse::Level; +/// use komorebi_recorder::viewer::theme::{self, TEXT_DIM}; +/// +/// assert_eq!(theme::level(Level::Error), theme::severity(Severity::Error)); +/// assert_eq!(theme::level(Level::Warn), theme::severity(Severity::Warn)); +/// assert_eq!(theme::level(Level::Debug), TEXT_DIM); +/// ``` +#[must_use] +pub fn level(level: Level) -> Color32 { + match level { + Level::Error => Color32::from_rgb(235, 85, 75), + Level::Warn => Color32::from_rgb(235, 185, 60), + _ => TEXT_DIM, + } +} + +/// The color of what happened to the machine: an incident on its lane of the timeline, and the +/// system's records in the list of what surrounded an event. +pub const INCIDENT: Color32 = Color32::from_rgb(170, 160, 255); diff --git a/komorebi-recorder/src/viewer/timeline.rs b/komorebi-recorder/src/viewer/timeline.rs new file mode 100644 index 00000000..8d2c5f9f --- /dev/null +++ b/komorebi-recorder/src/viewer/timeline.rs @@ -0,0 +1,679 @@ +//! The arithmetic of the timeline, with no drawing. +//! +//! This is the maths under the lanes the viewer draws: which stretch of the recording is visible +//! ([`View`]), where a time falls on the screen and the other way round, where the ruler's marks go +//! ([`ruler`]), how to squeeze thousands of events into a few hundred pixels ([`bin`]), and how to +//! find the item nearest a point ([`nearest`], [`next_after`], [`previous_before`]). No drawing +//! happens here and nothing needs a window, so all of it is tested and the examples run. +//! +//! Times are session video seconds, the same timeline as +//! [`Transport`](crate::playback::Transport). Pixels are `f32` x positions across a lane: a lane +//! `width` pixels wide whose left edge is at `left`. +//! +//! The drawing that uses it is in the private `lanes` module of the viewer. + +/// The stretch of the recording that is on screen: `start_s` to `end_s`, in session video seconds. +/// +/// A `View` is a plain pair of times. The methods that change it ([`View::zoom`], [`View::pan`], +/// [`View::reveal`] and [`View::centre`]) take the duration of the recording and keep the view +/// within `0.0..=duration_s` and no shorter than [`MIN_SPAN_S`] (a recording shorter than +/// [`MIN_SPAN_S`] is treated as [`MIN_SPAN_S`] long). Building one by hand, with the fields, is not +/// checked. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::timeline::View; +/// +/// // a 500 px wide lane whose left edge is at x = 100, showing 10 s to 20 s +/// let view = View { start_s: 10.0, end_s: 20.0 }; +/// assert_eq!(view.x(15.0, 100.0, 500.0), 350.0); +/// assert_eq!(view.time(350.0, 100.0, 500.0), 15.0); +/// ``` +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct View { + /// The time at the left edge of the lane, in session video seconds. + pub start_s: f64, + /// The time at the right edge of the lane, in session video seconds. + pub end_s: f64, +} + +/// The shortest stretch the timeline will zoom in to, in seconds (50 ms). +pub const MIN_SPAN_S: f64 = 0.05; + +impl View { + /// Returns the view of all of a recording of `duration_s` seconds. + /// + /// A duration shorter than [`MIN_SPAN_S`] gives a view [`MIN_SPAN_S`] long. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::timeline::{View, MIN_SPAN_S}; + /// + /// let view = View::whole(60.0); + /// assert_eq!((view.start_s, view.end_s), (0.0, 60.0)); + /// assert_eq!(View::whole(0.0).span(), MIN_SPAN_S); + /// ``` + #[must_use] + pub fn whole(duration_s: f64) -> Self { + Self { + start_s: 0.0, + end_s: duration_s.max(MIN_SPAN_S), + } + } + + /// Returns how many seconds the view covers: `end_s - start_s`. + #[must_use] + pub fn span(&self) -> f64 { + self.end_s - self.start_s + } + + /// Returns the x position where `time` falls across `width` pixels starting at `left`. + /// + /// A time outside the view gives a position outside `left..left + width`: it is not clamped. + /// [`View::time`] is the inverse, to the precision of an `f32`. + #[must_use] + pub fn x(&self, time: f64, left: f32, width: f32) -> f32 { + left + ((time - self.start_s) / self.span()) as f32 * width + } + + /// Returns the time at pixel `x`, across `width` pixels starting at `left`. + /// + /// A `width` under one pixel is taken as one pixel. A position outside the lane gives a time + /// outside the view: it is not clamped. + #[must_use] + pub fn time(&self, x: f32, left: f32, width: f32) -> f64 { + self.start_s + f64::from((x - left) / width.max(1.0)) * self.span() + } + + /// Zooms by `factor` (above `1.0` zooms in), keeping the time `anchor_s` where it is on the + /// screen, without leaving `0.0..=duration_s`. + /// + /// `factor` is limited to `0.01..=100.0`, and the span to [`MIN_SPAN_S`] at the least and the + /// whole recording at the most, so zooming out of a view that shows everything does nothing and + /// zooming in stops at the closest zoom. The anchor keeps the same share of the window + /// (`0.3` of the way across stays `0.3` of the way across), unless that would push the window + /// past an end of the recording, which wins. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::timeline::{View, MIN_SPAN_S}; + /// + /// let mut view = View::whole(100.0); + /// view.zoom(30.0, 4.0, 100.0); + /// assert_eq!(view.span(), 25.0); + /// // 30 s was 30% of the way across and still is + /// assert!(((30.0 - view.start_s) / view.span() - 0.3).abs() < 1e-9); + /// + /// // zooming out all the way shows everything again + /// view.zoom(30.0, 0.25, 100.0); + /// assert_eq!((view.start_s, view.end_s), (0.0, 100.0)); + /// + /// // and zooming in stops at the closest zoom + /// for _ in 0..50 { + /// view.zoom(30.0, 2.0, 100.0); + /// } + /// assert!((view.span() - MIN_SPAN_S).abs() < 1e-9); + /// ``` + pub fn zoom(&mut self, anchor_s: f64, factor: f64, duration_s: f64) { + let factor = factor.clamp(0.01, 100.0); + let span = (self.span() / factor).clamp(MIN_SPAN_S, duration_s.max(MIN_SPAN_S)); + // the anchor keeps its place in the window + let share = ((anchor_s - self.start_s) / self.span()).clamp(0.0, 1.0); + self.start_s = anchor_s - share * span; + self.end_s = self.start_s + span; + self.clamp(duration_s); + } + + /// Moves the view by `delta_s` (negative for earlier), stopping at the ends of the recording. + /// + /// The span is kept. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::timeline::View; + /// + /// let mut view = View { start_s: 20.0, end_s: 30.0 }; + /// view.pan(-50.0, 100.0); + /// assert_eq!((view.start_s, view.end_s), (0.0, 10.0)); + /// view.pan(500.0, 100.0); + /// assert_eq!((view.start_s, view.end_s), (90.0, 100.0)); + /// ``` + pub fn pan(&mut self, delta_s: f64, duration_s: f64) { + self.start_s += delta_s; + self.end_s += delta_s; + self.clamp(duration_s); + } + + /// Makes sure `time` is on screen, moving the window the least that does it. + /// + /// "On screen" leaves a margin of a tenth of the span at each edge, so a time that is only just + /// inside an edge moves the window and the playhead is never drawn against the edge. A time + /// that is already within the margins moves nothing, and the zoom is always kept. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::timeline::View; + /// + /// let mut view = View { start_s: 20.0, end_s: 30.0 }; + /// view.reveal(25.0, 100.0); + /// assert_eq!(view.start_s, 20.0, "already visible: unmoved"); + /// + /// view.reveal(40.0, 100.0); + /// assert!(view.end_s >= 40.0); + /// assert!((view.span() - 10.0).abs() < 1e-9, "the zoom is kept"); + /// ``` + pub fn reveal(&mut self, time: f64, duration_s: f64) { + let margin = self.span() * 0.1; + if time < self.start_s + margin { + self.pan(time - margin - self.start_s, duration_s); + } else if time > self.end_s - margin { + self.pan(time + margin - self.end_s, duration_s); + } + } + + /// Centers the view on `time`, keeping the zoom and the ends of the recording. + /// + /// Near an end of the recording the view stops at the end rather than centering. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::viewer::timeline::View; + /// + /// let mut view = View { start_s: 0.0, end_s: 10.0 }; + /// view.centre(50.0, 100.0); + /// assert_eq!((view.start_s, view.end_s), (45.0, 55.0)); + /// view.centre(2.0, 100.0); + /// assert_eq!((view.start_s, view.end_s), (0.0, 10.0)); + /// ``` + pub fn centre(&mut self, time: f64, duration_s: f64) { + let half = self.span() / 2.0; + self.start_s = time - half; + self.end_s = time + half; + self.clamp(duration_s); + } + + fn clamp(&mut self, duration_s: f64) { + let duration = duration_s.max(MIN_SPAN_S); + let span = self.span().min(duration); + if self.start_s < 0.0 { + self.start_s = 0.0; + } + self.end_s = self.start_s + span; + if self.end_s > duration { + self.end_s = duration; + self.start_s = duration - span; + } + } +} + +/// A mark on the ruler: [`ruler`] makes them. +#[derive(Debug, Clone, PartialEq)] +pub struct Tick { + /// Where the mark is, in session video seconds. + pub time: f64, + /// Whether the mark is labeled with a time. A major tick is every fifth mark, counting from + /// time zero (not from where the view starts), and is drawn longer. + pub major: bool, + /// The text of the label: empty for a minor tick. It reads `m:ss` when the labeled marks are + /// at least a second apart, `m:ss.s` when they are at least a tenth of a second apart and + /// `m:ss.ss` when they are closer than that. + pub label: String, +} + +/// The steps a ruler counts in, in seconds. +const STEPS: [f64; 15] = [ + 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0, 300.0, 600.0, 1800.0, +]; + +fn label(time: f64, step: f64) -> String { + let total = time.max(0.0); + let minutes = (total / 60.0) as u64; + let seconds = total - (minutes * 60) as f64; + if step >= 1.0 { + format!("{minutes}:{:02}", seconds.round() as u64 % 60) + } else if step >= 0.1 { + format!("{minutes}:{seconds:04.1}") + } else { + format!("{minutes}:{seconds:05.2}") + } +} + +/// Returns the marks of a ruler across `width` pixels: a labeled one at least every +/// `min_label_px`, and minor ones between them. +/// +/// The labeled marks count in a round step: the smallest of 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, +/// 5, 10, 30 and 60 seconds, 5, 10 and 30 minutes that is at least `min_label_px` wide on screen, +/// or an hour if even that is not. There are four minor marks between labeled ones. Only marks +/// within the view are returned, in time order. A `width` of zero or less, or a view with no span, +/// gives no marks. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::timeline::{ruler, View}; +/// +/// // 60 s over 1200 px is 0.05 s per pixel: 80 px is 4 s, so labels every 5 s +/// let ticks = ruler(&View::whole(60.0), 1200.0, 80.0); +/// let labels: Vec<&str> = ticks +/// .iter() +/// .filter(|tick| tick.major) +/// .take(3) +/// .map(|tick| tick.label.as_str()) +/// .collect(); +/// assert_eq!(labels, ["0:00", "0:05", "0:10"]); +/// assert!(ticks.iter().any(|tick| !tick.major), "minor marks sit between"); +/// +/// // zoomed in, labels show fractions of a second +/// let view = View { start_s: 12.0, end_s: 12.5 }; +/// let ticks = ruler(&view, 1000.0, 80.0); +/// let labels: Vec<&str> = ticks +/// .iter() +/// .filter(|tick| tick.major) +/// .map(|tick| tick.label.as_str()) +/// .collect(); +/// assert_eq!(labels.len(), 11); +/// assert_eq!((labels[0], labels[2], labels[10]), ("0:12.00", "0:12.10", "0:12.50")); +/// +/// // nothing to count across: no marks, not a panic +/// assert!(ruler(&View::whole(10.0), 0.0, 80.0).is_empty()); +/// ``` +#[must_use] +pub fn ruler(view: &View, width: f32, min_label_px: f32) -> Vec { + if width <= 0.0 || view.span() <= 0.0 { + return Vec::new(); + } + + let seconds_per_px = view.span() / f64::from(width); + let step = STEPS + .iter() + .copied() + .find(|step| step / seconds_per_px >= f64::from(min_label_px)) + .unwrap_or(3600.0); + let minor = step / 5.0; + + let mut ticks = Vec::new(); + let first = (view.start_s / minor).floor() as i64; + let last = (view.end_s / minor).ceil() as i64; + for index in first..=last { + let time = index as f64 * minor; + if time < view.start_s - 1e-9 || time > view.end_s + 1e-9 { + continue; + } + let major = index % 5 == 0; + ticks.push(Tick { + time, + major, + label: if major { + label(time, step) + } else { + String::new() + }, + }); + } + + ticks +} + +/// A column of pixels in a dense lane: how many things fall in it and the most important kind. +/// [`bin`] makes them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Bin { + /// The index of the column, counting from `0` at the left of the lane. + pub column: usize, + /// How many items fell in the column. + pub count: usize, + /// The largest weight of anything in the column. + pub weight: u8, +} + +/// Counts items into one-pixel columns across `width` pixels of the view. +/// +/// `items` yields `(time, weight)`. Items outside the view are dropped, and the instant at the end +/// of the view belongs to the last column. Only columns that something fell in are returned, in +/// order from the left, so a lane with thousands of items makes at most `width` entries. A `width` +/// of zero gives none. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::timeline::{bin, Bin, View}; +/// +/// // ten seconds across ten columns: each column is one second +/// let view = View { start_s: 0.0, end_s: 10.0 }; +/// let items = [(0.05, 1), (0.06, 3), (0.07, 2), (5.0, 1), (10.0, 2), (11.0, 9), (-1.0, 9)]; +/// let columns = bin(items.into_iter(), &view, 10); +/// +/// assert_eq!(columns, [ +/// Bin { column: 0, count: 3, weight: 3 }, // the loudest of the three +/// Bin { column: 5, count: 1, weight: 1 }, +/// Bin { column: 9, count: 1, weight: 2 }, // the last instant: the last column +/// ]); +/// ``` +#[must_use] +pub fn bin(items: impl Iterator, view: &View, width: usize) -> Vec { + if width == 0 { + return Vec::new(); + } + + let mut columns: Vec> = vec![None; width]; + for (time, weight) in items { + if time < view.start_s || time > view.end_s { + continue; + } + + let column = + (((time - view.start_s) / view.span()) * width as f64).min(width as f64 - 1.0) as usize; + let slot = columns[column].get_or_insert(Bin { + column, + count: 0, + weight: 0, + }); + slot.count += 1; + slot.weight = slot.weight.max(weight); + } + + columns.into_iter().flatten().collect() +} + +/// Returns the index of the item nearest `time` among `times`, if it is within `reach_s`. +/// +/// `times` must be sorted in ascending order; with any other order the result is unspecified (but +/// not a panic). When two items are equally near, the earlier one is returned. `None` means no +/// item is within `reach_s` of `time`, or there are none. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::timeline::nearest; +/// +/// let times = [1.0, 2.0, 4.0, 8.0]; +/// assert_eq!(nearest(×, 2.2, 0.5), Some(1)); +/// assert_eq!(nearest(×, 3.1, 1.5), Some(2)); +/// assert_eq!(nearest(×, 5.0, 0.5), None, "nothing within reach"); +/// assert_eq!(nearest(&[], 1.0, 5.0), None); +/// ``` +#[must_use] +pub fn nearest(times: &[f64], time: f64, reach_s: f64) -> Option { + if times.is_empty() { + return None; + } + + let after = times.partition_point(|candidate| *candidate < time); + let candidates = [after.checked_sub(1), (after < times.len()).then_some(after)]; + candidates + .into_iter() + .flatten() + .min_by(|a, b| { + (times[*a] - time) + .abs() + .total_cmp(&(times[*b] - time).abs()) + }) + .filter(|index| (times[*index] - time).abs() <= reach_s) +} + +/// Returns the first of the sorted `times` strictly after `time`. +/// +/// "Strictly" allows a microsecond: a time within a microsecond after `time` is the one you are on +/// and is skipped, so stepping to the next event from an event does not land on it again. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::timeline::next_after; +/// +/// let times = [1.0, 2.0, 4.0]; +/// assert_eq!(next_after(×, 2.0), Some(4.0), "skips the one it is on"); +/// assert_eq!(next_after(×, 1.5), Some(2.0)); +/// assert_eq!(next_after(×, 4.0), None); +/// ``` +#[must_use] +pub fn next_after(times: &[f64], time: f64) -> Option { + let index = times.partition_point(|candidate| *candidate <= time + 1e-6); + times.get(index).copied() +} + +/// Returns the last of the sorted `times` strictly before `time`. +/// +/// "Strictly" allows a microsecond, as in [`next_after`]: a time within a microsecond before `time` +/// is the one you are on and is skipped. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::viewer::timeline::previous_before; +/// +/// let times = [1.0, 2.0, 4.0]; +/// assert_eq!(previous_before(×, 2.0), Some(1.0), "skips the one it is on"); +/// assert_eq!(previous_before(×, 2.5), Some(2.0)); +/// assert_eq!(previous_before(×, 1.0), None); +/// ``` +#[must_use] +pub fn previous_before(times: &[f64], time: f64) -> Option { + let index = times.partition_point(|candidate| *candidate < time - 1e-6); + index + .checked_sub(1) + .and_then(|index| times.get(index).copied()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 + } + + #[test] + fn times_and_pixels_convert_both_ways() { + let view = View { + start_s: 10.0, + end_s: 20.0, + }; + assert!((view.x(15.0, 100.0, 500.0) - 350.0).abs() < 1e-3); + assert!(close(view.time(350.0, 100.0, 500.0), 15.0)); + for time in [10.0, 12.5, 19.9] { + let x = view.x(time, 40.0, 800.0); + assert!(close(view.time(x, 40.0, 800.0), time)); + } + } + + #[test] + fn zooming_keeps_the_time_under_the_cursor_where_it_is() { + let mut view = View::whole(100.0); + view.zoom(30.0, 4.0, 100.0); + + assert!(close(view.span(), 25.0)); + // 30 s was 30% of the way across and still is + assert!(close((30.0 - view.start_s) / view.span(), 0.3)); + + view.zoom(30.0, 0.25, 100.0); + assert!(close(view.span(), 100.0)); + assert!(close(view.start_s, 0.0)); + } + + #[test] + fn zooming_stops_at_the_ends_and_at_the_closest_zoom() { + let mut view = View::whole(10.0); + view.zoom(0.0, 0.1, 10.0); + assert!(close(view.span(), 10.0), "cannot show more than there is"); + + for _ in 0..50 { + view.zoom(5.0, 2.0, 10.0); + } + assert!(close(view.span(), MIN_SPAN_S)); + assert!(view.start_s >= 0.0 && view.end_s <= 10.0); + } + + #[test] + fn panning_stops_at_the_ends() { + let mut view = View { + start_s: 20.0, + end_s: 30.0, + }; + view.pan(-50.0, 100.0); + assert!(close(view.start_s, 0.0) && close(view.end_s, 10.0)); + + view.pan(500.0, 100.0); + assert!(close(view.start_s, 90.0) && close(view.end_s, 100.0)); + } + + #[test] + fn revealing_moves_the_window_only_when_the_time_is_off_screen() { + let mut view = View { + start_s: 20.0, + end_s: 30.0, + }; + view.reveal(25.0, 100.0); + assert!(close(view.start_s, 20.0), "already visible: unmoved"); + + view.reveal(40.0, 100.0); + assert!(view.end_s >= 40.0 && view.start_s > 20.0); + assert!(close(view.span(), 10.0), "the zoom is kept"); + + view.reveal(2.0, 100.0); + assert!(view.start_s <= 2.0); + } + + #[test] + fn centring_keeps_the_zoom_and_the_ends() { + let mut view = View { + start_s: 0.0, + end_s: 10.0, + }; + view.centre(50.0, 100.0); + assert!(close(view.start_s, 45.0) && close(view.end_s, 55.0)); + view.centre(2.0, 100.0); + assert!(close(view.start_s, 0.0) && close(view.end_s, 10.0)); + } + + #[test] + fn the_ruler_counts_in_round_steps_that_are_never_too_close() { + let ticks = ruler(&View::whole(60.0), 1200.0, 80.0); + let majors: Vec<&Tick> = ticks.iter().filter(|tick| tick.major).collect(); + + // 60 s over 1200 px is 0.05 s per pixel: 80 px is 4 s, so labels every 5 s + assert!(close(majors[1].time - majors[0].time, 5.0), "{majors:?}"); + for pair in majors.windows(2) { + let pixels = (pair[1].time - pair[0].time) / (60.0 / 1200.0); + assert!(pixels >= 80.0 - 1e-6, "labels {pixels} px apart"); + } + assert_eq!(majors[0].label, "0:00"); + assert_eq!(majors[1].label, "0:05"); + assert_eq!(majors[2].label, "0:10"); + // minor marks sit between + assert!(ticks.iter().any(|tick| !tick.major)); + } + + #[test] + fn zoomed_in_the_ruler_labels_fractions_of_a_second() { + let view = View { + start_s: 12.0, + end_s: 12.5, + }; + let ticks = ruler(&view, 1000.0, 80.0); + let labels: Vec<&str> = ticks + .iter() + .filter(|tick| tick.major) + .map(|tick| tick.label.as_str()) + .collect(); + // 0.5 s over 1000 px with labels 80 px apart: a label every 0.05 s, to two places + assert_eq!(labels.len(), 11, "{labels:?}"); + assert_eq!(labels[0], "0:12.00"); + assert_eq!(labels[2], "0:12.10"); + assert_eq!(labels[10], "0:12.50"); + assert!( + ticks + .iter() + .all(|tick| tick.time >= 12.0 - 1e-9 && tick.time <= 12.5 + 1e-9) + ); + } + + #[test] + fn a_degenerate_ruler_is_empty_not_a_panic() { + assert!(ruler(&View::whole(10.0), 0.0, 80.0).is_empty()); + assert!( + ruler( + &View { + start_s: 5.0, + end_s: 5.0 + }, + 100.0, + 80.0 + ) + .is_empty() + ); + } + + #[test] + fn many_items_become_columns_counting_what_fell_in_them() { + let view = View { + start_s: 0.0, + end_s: 10.0, + }; + let items = vec![ + (0.05, 1), + (0.06, 3), + (0.07, 2), + (5.0, 1), + (9.99, 2), + (11.0, 9), + (-1.0, 9), + ]; + let columns = bin(items.into_iter(), &view, 10); + + assert_eq!(columns.len(), 3, "{columns:?}"); + assert_eq!( + columns[0], + Bin { + column: 0, + count: 3, + weight: 3 + } + ); + assert_eq!( + columns[1], + Bin { + column: 5, + count: 1, + weight: 1 + } + ); + // the last instant belongs to the last column, and things off screen to none + assert_eq!( + columns[2], + Bin { + column: 9, + count: 1, + weight: 2 + } + ); + } + + #[test] + fn the_nearest_item_must_be_within_reach() { + let times = [1.0, 2.0, 4.0, 8.0]; + assert_eq!(nearest(×, 2.2, 0.5), Some(1)); + assert_eq!(nearest(×, 3.1, 1.5), Some(2)); + assert_eq!(nearest(×, 5.0, 0.5), None); + assert_eq!(nearest(×, 0.9, 0.5), Some(0)); + assert_eq!(nearest(×, 9.0, 2.0), Some(3)); + assert_eq!(nearest(&[], 1.0, 5.0), None); + } + + #[test] + fn next_and_previous_skip_the_one_you_are_on() { + let times = [1.0, 2.0, 4.0]; + assert_eq!(next_after(×, 2.0), Some(4.0)); + assert_eq!(next_after(×, 1.5), Some(2.0)); + assert_eq!(next_after(×, 4.0), None); + assert_eq!(previous_before(×, 2.0), Some(1.0)); + assert_eq!(previous_before(×, 2.5), Some(2.0)); + assert_eq!(previous_before(×, 1.0), None); + } +} diff --git a/komorebi-recorder/src/viewer/video.rs b/komorebi-recorder/src/viewer/video.rs new file mode 100644 index 00000000..1c9785d3 --- /dev/null +++ b/komorebi-recorder/src/viewer/video.rs @@ -0,0 +1,458 @@ +//! The pictures: each display's frame at the playhead, with komorebi's idea of the layout drawn +//! over it if asked. +//! +//! [`Open::video_ui`] draws one picture for each display that has video, side by side +//! ([`arrange`]), and, with the overlay on, komorebi's state over them. What is drawn is described +//! on [`Open::video_ui`], whose documentation is public. [`arrange`] and [`on_tile`] are plain +//! arithmetic, covered by the unit tests in this module +//! (`one_picture_fills_the_space_it_fits_and_is_centred`, +//! `several_pictures_sit_side_by_side_at_one_height`, `nothing_to_arrange_is_nothing` and +//! `global_points_map_onto_the_picture_of_their_display`); the module is not public, so they have +//! no examples. Drawing needs an `egui::Context`. + +use super::app::Open; +use super::app::Tile; +use super::theme; +use crate::analysis::state::Snapshot; +use crate::playback::DisplayView; +use eframe::egui; +use eframe::egui::Color32; +use eframe::egui::Pos2; +use eframe::egui::Rect; +use eframe::egui::Stroke; +use eframe::egui::StrokeKind; +use eframe::egui::vec2; +use std::sync::Arc; + +/// Returns how the pictures of several displays share the space: side by side, each as tall as +/// fits and as wide as its shape needs. There is one rectangle for each of `aspects`, in order. +/// +/// `aspects` are the width over the height of each picture and `gap` is the space between +/// neighboring pictures. All the pictures have one height: the largest at which the row, gaps +/// included, fits the width of `available` and the picture fits its height (and at least one +/// point). The row is centered in `available`, both ways. No pictures give no rectangles. +#[must_use] +pub fn arrange(available: Rect, aspects: &[f32], gap: f32) -> Vec { + if aspects.is_empty() { + return Vec::new(); + } + + let total_aspect: f32 = aspects.iter().sum(); + let gaps = gap * (aspects.len() as f32 - 1.0); + let height = ((available.width() - gaps) / total_aspect) + .min(available.height()) + .max(1.0); + let used = total_aspect * height + gaps; + + let mut x = available.left() + (available.width() - used) / 2.0; + let top = available.top() + (available.height() - height) / 2.0; + aspects + .iter() + .map(|aspect| { + let rect = Rect::from_min_size(Pos2::new(x, top), vec2(aspect * height, height)); + x += aspect * height + gap; + rect + }) + .collect() +} + +/// Returns where a rectangle in global points falls on a picture of the display whose frame is +/// `frame` (`[x, y, width, height]` in the same points), drawn into `tile`. +/// +/// The rectangle is `left`, `top`, `width` and `height` in global points, as komorebi reports +/// windows and layouts. The result is in the coordinates of `tile`: the display's top-left corner +/// is the tile's, and a rectangle half the display's width is half the tile's. It is not clipped, +/// so a window partly or wholly off the display gives a rectangle that sticks out of the tile. A +/// frame with a width or height under one point is taken as one point. +#[must_use] +pub fn on_tile(tile: Rect, frame: [f64; 4], left: i64, top: i64, width: i64, height: i64) -> Rect { + let [x, y, frame_width, frame_height] = frame; + let scale_x = f64::from(tile.width()) / frame_width.max(1.0); + let scale_y = f64::from(tile.height()) / frame_height.max(1.0); + Rect::from_min_size( + Pos2::new( + tile.left() + ((left as f64 - x) * scale_x) as f32, + tile.top() + ((top as f64 - y) * scale_y) as f32, + ), + vec2( + (width as f64 * scale_x) as f32, + (height as f64 * scale_y) as f32, + ), + ) +} + +impl Open { + /// Draws the displays into `ui`, which is the middle of the window. + /// + /// One picture is drawn for each display that has video, side by side and each as tall as fits. + /// Each has a label (`display N`, and, when it shows a frame, when that frame was on screen) and + /// is outlined more heavily if it is the focused display ([`Open::focus`]). Clicking a picture + /// focuses its display. A recording with no video at all shows a note to that effect instead. + /// + /// What a picture shows comes from [`Playback::view`](crate::playback::Playback::view): + /// + /// | [`DisplayView`] | drawn as | + /// |---|---| + /// | `Frame` | the frame, uploaded to the graphics card once for each new frame | + /// | `Gap` | a placeholder saying the display has no video there and, when the recording shows why, the reason | + /// | `Loading` | "decoding…" | + /// | `Failed` | "could not decode:" and the reason | + /// + /// A gap says why from the machine's incidents when it can: the last display-disconnected, + /// display-asleep, capture-stopped, capture-failed or display-reconfigured incident for that + /// display, up to half a second ahead of the playhead; failing that, when the display's next + /// video begins; failing that, "unplugged, asleep, or not yet recorded". + /// + /// # The state overlay + /// + /// With the overlay on ([`Open::overlay`]: the "state overlay" box, and `O`), komorebi's state at + /// the playhead ([`Open::state_at`]) is drawn over each picture that shows a frame. A dashed + /// rectangle is where komorebi meant each tiled window of the display's focused workspace to + /// be, and a solid one is where each visible window really was. A solid rectangle is red if the + /// window breaks an invariant of the state ([`crate::analysis::invariants::check`]), the accent + /// color if it has focus and green otherwise. Windows komorebi has parked out of sight are not + /// drawn. A display is matched to komorebi's monitor of the same id, and positions are in the + /// global points komorebi uses. + /// + /// `ctx` is used to upload frames as textures. Needs an `egui::Context`, so a window is needed. + pub fn video_ui(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { + if self.loaded.displays.is_empty() { + ui.centered_and_justified(|ui| { + ui.label( + egui::RichText::new("this recording has no video") + .color(theme::TEXT_DIM) + .size(16.0), + ); + }); + return; + } + + let ids: Vec = self + .loaded + .displays + .iter() + .map(|display| display.id) + .collect(); + let area = ui.available_rect_before_wrap(); + ui.allocate_rect(area, egui::Sense::hover()); + + // the shape of each picture: from the frame on screen, else from the display + let aspects: Vec = ids + .iter() + .map(|id| match self.playback.view(*id) { + DisplayView::Frame(frame) if frame.height > 0 => { + frame.width as f32 / frame.height as f32 + } + _ => { + let frame = self + .loaded + .displays + .iter() + .find(|d| d.id == *id) + .map_or([0.0, 0.0, 16.0, 9.0], |d| d.frame); + (frame[2] / frame[3].max(1.0)) as f32 + } + }) + .collect(); + + let snapshot = if self.overlay { + self.state_at(self.position()) + } else { + None + }; + + let rects = arrange(area, &aspects, 10.0); + for (id, rect) in ids.iter().zip(rects) { + let view = self.playback.view(*id); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 4.0, Color32::BLACK); + + match &view { + DisplayView::Frame(frame) => { + let pointer = Arc::as_ptr(frame) as usize; + let stale = self.tiles.get(id).is_none_or(|tile| tile.frame != pointer); + if stale { + let image = egui::ColorImage::from_rgba_unmultiplied( + [frame.width as usize, frame.height as usize], + &frame.rgba, + ); + match self.tiles.get_mut(id) { + Some(tile) => { + tile.texture.set(image, egui::TextureOptions::LINEAR); + tile.frame = pointer; + } + None => { + let texture = ctx.load_texture( + format!("display-{id}"), + image, + egui::TextureOptions::LINEAR, + ); + self.tiles.insert( + *id, + Tile { + texture, + frame: pointer, + }, + ); + } + } + } + + if let Some(tile) = self.tiles.get(id) { + painter.image( + tile.texture.id(), + rect, + Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)), + Color32::WHITE, + ); + } + } + DisplayView::Gap => self.gap_placeholder(&painter, rect, *id), + DisplayView::Loading => { + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + "decoding…", + egui::FontId::proportional(14.0), + theme::TEXT_DIM, + ); + } + DisplayView::Failed(message) => { + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + format!("could not decode: {message}"), + egui::FontId::proportional(13.0), + theme::BUG, + ); + } + } + + if let Some(snapshot) = &snapshot + && matches!(view, DisplayView::Frame(_)) + && let Some(meta) = self.loaded.displays.iter().find(|meta| meta.id == *id) + { + self.draw_overlay(&painter, rect, meta.frame, *id, snapshot); + } + + // which picture this is, and which one the keys act on + let focused = self.focus == Some(*id); + painter.rect_stroke( + rect, + 4.0, + Stroke::new( + if focused { 2.0 } else { 1.0_f32 }, + if focused { + theme::ACCENT + } else { + Color32::from_gray(60) + }, + ), + StrokeKind::Inside, + ); + let shown = match &view { + DisplayView::Frame(frame) => { + format!(" · frame from {}", crate::timecode::format(frame.shown_s)) + } + _ => String::new(), + }; + painter.text( + rect.left_bottom() + vec2(8.0, -6.0), + egui::Align2::LEFT_BOTTOM, + format!("display {id}{shown}"), + egui::FontId::monospace(11.0), + Color32::from_rgba_unmultiplied(255, 255, 255, 200), + ); + + let response = ui.interact(rect, ui.id().with(("tile", *id)), egui::Sense::click()); + if response.clicked() { + self.focus = Some(*id); + } + } + } + + /// What to show where a display has no video: why, if the recording says. + fn gap_placeholder(&self, painter: &egui::Painter, rect: Rect, display: u32) { + painter.rect_filled(rect, 4.0, Color32::from_rgb(18, 18, 22)); + let now = self.position(); + // why it has none: what happened to this display most recently, or that it had not begun + let ended = self + .loaded + .incidents + .iter() + .rfind(|incident| { + incident.display == Some(display) + && incident.video_s <= now + 0.5 + && matches!( + incident.kind.as_str(), + "display-disconnected" + | "display-asleep" + | "capture-stopped" + | "capture-failed" + | "display-reconfigured" + ) + }) + .map(|incident| format!("{}: {}", incident.kind, incident.detail)); + let begins = self + .loaded + .displays + .iter() + .find(|meta| meta.id == display) + .and_then(|meta| { + meta.segments + .iter() + .map(|(from, _)| *from) + .find(|from| *from > now) + }) + .map(|from| format!("its video begins at {}", crate::timecode::format(from))); + let why = ended.or(begins); + + painter.text( + rect.center() - vec2(0.0, 10.0), + egui::Align2::CENTER_CENTER, + format!("display {display} has no video here"), + egui::FontId::proportional(15.0), + theme::TEXT_DIM, + ); + painter.text( + rect.center() + vec2(0.0, 12.0), + egui::Align2::CENTER_CENTER, + why.unwrap_or_else(|| "unplugged, asleep, or not yet recorded".to_string()), + egui::FontId::proportional(12.0), + Color32::from_gray(110), + ); + } + + /// komorebi's idea of the layout, over the display it is about: where it meant each tiled + /// window to be (dashed) and where the window really was (solid). + fn draw_overlay( + &self, + painter: &egui::Painter, + tile: Rect, + frame: [f64; 4], + display: u32, + snapshot: &Snapshot, + ) { + let Some(monitor) = snapshot + .monitors + .iter() + .find(|monitor| u32::try_from(monitor.id).ok() == Some(display)) + else { + return; + }; + let Some(workspace) = monitor.focused_workspace() else { + return; + }; + + let focus = snapshot.focus(); + let focused_window = focus.as_ref().and_then(|focus| focus.window_id); + let violating: Vec = crate::analysis::invariants::check(snapshot) + .into_iter() + .flat_map(|violation| violation.window_ids) + .collect(); + + for rect in &workspace.layout_rects { + let drawn = on_tile(tile, frame, rect.left, rect.top, rect.width, rect.height); + painter.add(egui::Shape::dashed_line( + &[ + drawn.left_top(), + drawn.right_top(), + drawn.right_bottom(), + drawn.left_bottom(), + drawn.left_top(), + ], + Stroke::new(1.0_f32, Color32::from_rgba_unmultiplied(240, 200, 80, 190)), + 5.0, + 4.0, + )); + } + + for (location, window) in snapshot.windows() { + if location.monitor_id != monitor.id || !location.workspace_visible { + continue; + } + let Some(rect) = &window.rect else { + continue; + }; + if snapshot.is_hidden_position(rect, monitor) { + continue; + } + + let drawn = on_tile(tile, frame, rect.left, rect.top, rect.width, rect.height); + let wrong = violating.contains(&window.id); + let is_focused = focused_window == Some(window.id); + let colour = if wrong { + theme::BUG + } else if is_focused { + theme::ACCENT + } else { + Color32::from_rgba_unmultiplied(110, 220, 150, 200) + }; + painter.rect_stroke( + drawn, + 0.0, + Stroke::new(if wrong || is_focused { 2.0 } else { 1.0_f32 }, colour), + StrokeKind::Inside, + ); + painter.text( + drawn.left_top() + vec2(4.0, 3.0), + egui::Align2::LEFT_TOP, + format!("{} {}", window.exe, window.id), + egui::FontId::monospace(10.0), + colour, + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rect(width: f32, height: f32) -> Rect { + Rect::from_min_size(Pos2::ZERO, vec2(width, height)) + } + + #[test] + fn one_picture_fills_the_space_it_fits_and_is_centred() { + let rects = arrange(rect(1000.0, 400.0), &[2.0], 10.0); + assert_eq!(rects.len(), 1); + // 400 tall at 2:1 is 800 wide, centred in 1000 + assert!( + (rects[0].width() - 800.0).abs() < 0.01 && (rects[0].height() - 400.0).abs() < 0.01 + ); + assert!((rects[0].left() - 100.0).abs() < 0.01); + } + + #[test] + fn several_pictures_sit_side_by_side_at_one_height() { + let rects = arrange(rect(1200.0, 1000.0), &[1.5, 2.5], 20.0); + assert_eq!(rects.len(), 2); + assert!((rects[0].height() - rects[1].height()).abs() < 0.01); + assert!((rects[1].left() - rects[0].right() - 20.0).abs() < 0.01); + // wide screens are wide: the whole row uses the width (1180 / 4) + assert!((rects[0].height() - 295.0).abs() < 0.01); + assert!(rects[1].right() <= 1200.0 + 0.01); + } + + #[test] + fn nothing_to_arrange_is_nothing() { + assert!(arrange(rect(100.0, 100.0), &[], 10.0).is_empty()); + } + + #[test] + fn global_points_map_onto_the_picture_of_their_display() { + // a display at (1000, 0), 2000 x 1000 points, drawn into a 400 x 200 tile at (50, 30) + let tile = Rect::from_min_size(Pos2::new(50.0, 30.0), vec2(400.0, 200.0)); + let frame = [1000.0, 0.0, 2000.0, 1000.0]; + + // its top-left corner is the tile's + let corner = on_tile(tile, frame, 1000, 0, 0, 0); + assert!((corner.left() - 50.0).abs() < 0.01 && (corner.top() - 30.0).abs() < 0.01); + + // a window 500 x 250 at (2000, 500) is a fifth of the tile's size, in the middle + let window = on_tile(tile, frame, 2000, 500, 500, 250); + assert!((window.left() - 250.0).abs() < 0.01 && (window.top() - 130.0).abs() < 0.01); + assert!((window.width() - 100.0).abs() < 0.01 && (window.height() - 50.0).abs() < 0.01); + } +}