feat(viewer): view a recording

`komorebi-recorder view <session>` 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.
This commit is contained in:
LGUG2Z committed 2026-10-27 22:22:56 -07:00
1 parent 278fde6650
commit 28cfdaa463
17 files changed
+6173 -2

No files matched your search

+1
View File
@@ -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.
+32 -2
View File
@@ -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 <session>
```
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 <session> add --kind bug --start 12.5 --end 18 \
+11
View File
@@ -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 <session>` 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
+5
View File
@@ -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),
@@ -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<PathBuf>,
}
+2
View File
@@ -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;
File diff suppressed because it is too large. Load diff
+512
View File
@@ -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<String>,
/// 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<String>,
/// 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<u32> = 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<u32> = 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<f64, String> {
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<u32> = 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<String> = 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);
}
}
}
+882
View File
@@ -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<f64>,
select_event: Option<u64>,
select_finding: Option<usize>,
select_bug: Option<String>,
edit_bug: Option<String>,
delete_bug: Option<String>,
loop_region: Option<(f64, f64)>,
copy: Option<String>,
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::<u64>().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<Arc<OsTraceData>> {
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<Arc<TraceData>> {
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<usize> = (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<String> = 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."
)
}
+366
View File
@@ -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<Action> {
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::<Vec<_>>()
.join(" ");
for key in ["Space", "J", "Home", "B", "Esc"] {
assert!(listed.contains(key), "{key}");
}
}
}
File diff suppressed because it is too large. Load diff
+342
View File
@@ -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<Analysis>,
/// 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<EventView>,
/// 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<f64>,
/// Incidents in the recording environment (a display went away, the machine slept...).
pub incidents: Vec<IncidentView>,
/// Ranked, most worth looking at first.
pub findings: Vec<Finding>,
/// The errors and warnings in komorebi's log that have a time, for the log lane.
pub log_marks: Vec<LogMark>,
/// 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<f64>,
/// The displays that have video, in ascending order of id.
pub displays: Vec<DisplayMeta>,
/// Bug regions, notes and findings, in the order of their start.
pub annotations: Vec<AnnotationView>,
/// Things the analysis noticed that a reader should be told, and the warnings from reading the
/// annotations file.
pub warnings: Vec<String>,
/// 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<Self> {
let analysis = Arc::new(Analysis::open(dir)?);
let duration_s = analysis.manifest.video_span().1;
let events: Vec<EventView> = (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<f64> = 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<DisplayMeta> = 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<Item = &AnnotationView> {
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"
);
}
}
+156
View File
@@ -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<PathBuf>) -> 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);
}
}
+253
View File
@@ -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<String>,
/// 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<dyn std::error::Error>>(())
/// ```
#[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<dyn std::error::Error>>(())
/// ```
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<dyn std::error::Error>>(())
/// ```
#[must_use]
pub fn existing(&self) -> Vec<PathBuf> {
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, `<local data dir>/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]);
}
}
+146
View File
@@ -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);
+679
View File
@@ -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<Tick> {
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<Item = (f64, u8)>, view: &View, width: usize) -> Vec<Bin> {
if width == 0 {
return Vec::new();
}
let mut columns: Vec<Option<Bin>> = 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(&times, 2.2, 0.5), Some(1));
/// assert_eq!(nearest(&times, 3.1, 1.5), Some(2));
/// assert_eq!(nearest(&times, 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<usize> {
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(&times, 2.0), Some(4.0), "skips the one it is on");
/// assert_eq!(next_after(&times, 1.5), Some(2.0));
/// assert_eq!(next_after(&times, 4.0), None);
/// ```
#[must_use]
pub fn next_after(times: &[f64], time: f64) -> Option<f64> {
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(&times, 2.0), Some(1.0), "skips the one it is on");
/// assert_eq!(previous_before(&times, 2.5), Some(2.0));
/// assert_eq!(previous_before(&times, 1.0), None);
/// ```
#[must_use]
pub fn previous_before(times: &[f64], time: f64) -> Option<f64> {
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(&times, 2.2, 0.5), Some(1));
assert_eq!(nearest(&times, 3.1, 1.5), Some(2));
assert_eq!(nearest(&times, 5.0, 0.5), None);
assert_eq!(nearest(&times, 0.9, 0.5), Some(0));
assert_eq!(nearest(&times, 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(&times, 2.0), Some(4.0));
assert_eq!(next_after(&times, 1.5), Some(2.0));
assert_eq!(next_after(&times, 4.0), None);
assert_eq!(previous_before(&times, 2.0), Some(1.0));
assert_eq!(previous_before(&times, 2.5), Some(2.0));
assert_eq!(previous_before(&times, 1.0), None);
}
}
+458
View File
@@ -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<Rect> {
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<u32> = 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<f32> = 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<u64> = 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);
}
}