feat(viewer): open sessions as tabs of one window

The viewer is now one window with a tab per session. Opening a session
(Open..., recents, the recorder window's buttons, `view SESSION...`) follows
one rule: focus the tab that has it, else load into the current start-screen
or failed tab, else add a tab. Only the tab in view plays; closing a tab
cancels its scan and stops its playback. Keys: Cmd/Ctrl T, W, 1-9,
Ctrl+Tab (and Cmd+Shift+[ ] on a Mac).

`view` and the recorder window hand sessions to a running viewer over a
local socket (komorebi-recorder-viewer.sock in the data dir, one JSON line
each way) and only start a process when none answers; `view --new-window`
opts out. The socket uses komorebi_link's cfg pattern (std unix sockets, or
uds_windows on Windows). The unix/macOS branches could not be compiled
here, only the Windows one.
This commit is contained in:
LGUG2Z committed 2026-10-28 16:58:55 -07:00
1 parent 19886f96fe
commit 72d600c8f6
10 files changed
+1786 -94

No files matched your search

+3 -1
View File
@@ -82,7 +82,9 @@ 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.
`komorebi-recorder view ./repro` opens the recording in the viewer, which is where you mark where the bug is. There is
one viewer window: running `view` again (or **Open session…** in the recorder window) opens another recording as a tab
of it, and `view --new-window` makes a window of its own.
Every command takes `--json` (including `record`, `displays`, `reindex` and `selftest`), 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.
+9 -1
View File
@@ -22,9 +22,16 @@ budget, 6 an `assert` check did not hold.
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.
opens the recording in the viewer 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.
There is only ever one viewer window. Each recording is a tab of it: `komorebi-recorder view <session>...` (from another
terminal, or from the recorder window) adds tabs to the window that is already open and brings it to the front, so
several recordings can be loaded side by side. A recording that is already open is just switched to. **+** (or ⌘/Ctrl-T)
adds a start tab with your recent recordings and **Open…**, × (or middle-click, or ⌘/Ctrl-W) closes a tab, Ctrl-Tab and
⌘/Ctrl-1 to 9 move between them, and only the tab you are looking at plays. `view --new-window` skips all of this and
opens a window of its own.
- 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).
@@ -130,6 +137,7 @@ and `event:12.end` when it finished.
| `assert --check "KIND ARGS METRIC<=N"` | Pass/fail checks for a scripted scenario, repeatable. Kinds: `findings kind=K [severity=S] count<=N`, `log "<logq query>" count==N`, `motion [region=x,y,w,h] [from=T] [to=T] segments\|active_ms\|peak_share<=N`, `blank region=x,y,w,h [from=T] [to=T] [color=white] ms<=N`, `annotations kind=note\|bug\|finding count>=N`. Operators `== != <= >= < >`. Prints `PASS`/`FAIL` per check; exit 0 if all pass, 6 if one fails, 4 if one cannot be measured (no video), 2 if malformed. `--json` gives `assert/1` |
| `annotate`, `annotations` | Add, change and list bug regions, notes and findings |
| `mark TEXT` | While recording: drop a named point note (author `script`) onto the timeline from a script; it then appears in `annotations`, `brief` and the viewer like any note |
| `view [SESSION...] [--new-window]` | Open recordings in the viewer window, each as a tab of the one window that is running (it is started if there is none and brought to the front if there is); `--new-window` makes a window of its own instead |
### Who changed it
+19 -5
View File
@@ -10,7 +10,7 @@
//! |---|---|
//! | Record | starts a recording on a thread named `recorder` ([`recorder::record`]), with the options the window was started with, the displays ticked below and the predicate typed under Advanced |
//! | Stop | asks the recording to finish ([`Live::request_stop`]); it indexes and finalizes the session, which the window shows as "finalizing..." |
//! | Open session..., Open last | open the viewer on a recording, in a process of its own |
//! | Open session..., Open last | open a recording as a tab of the viewer window, which is started in a process of its own if it is not running ([`crate::viewer::ipc`]) |
//! | Copy path, Open in the file manager | after a recording: copy where the session was saved, or show it (Finder or Explorer) |
//!
//! While idle the list of displays is read again every second, so a display that was docked or
@@ -112,10 +112,24 @@ pub fn latest_session_in(recordings: &std::path::Path) -> Option<PathBuf> {
.max()
}
/// Open the viewer, in its own process, on `session` if given. A separate process, so that
/// reviewing a recording can never disturb one being made, and kept out of the video (by name on
/// macOS, and by each of its windows asking on Windows).
/// Open `session` (or just a start-screen tab, with none) in the viewer.
///
/// If a viewer is already running it is asked, over its socket, to open the session as a tab and
/// to come to the front: no process is started. Only when none answers is `komorebi-recorder view`
/// started, in a process of its own, so that reviewing a recording can never disturb one being
/// made, and kept out of the video (by name on macOS, and by each of its windows asking on
/// Windows). It then becomes the one viewer window.
fn open_viewer(session: Option<&std::path::Path>) -> std::io::Result<()> {
use crate::viewer::ipc;
let request = ipc::Request {
open: session.map(ipc::absolute).into_iter().collect(),
focus: true,
};
if ipc::send(&ipc::default_socket(), &request)? == ipc::Delivery::Delivered {
return Ok(());
}
// on Windows the viewer is the build without a console, so that no console window opens with it
let this = std::env::current_exe()?;
let gui = this.with_file_name(format!(
@@ -133,7 +147,7 @@ fn open_viewer(session: Option<&std::path::Path>) -> std::io::Result<()> {
crate::platform::process::isolate(&mut command);
command.arg("view");
if let Some(session) = session {
command.arg(session);
command.arg(crate::viewer::ipc::absolute(session));
}
command.spawn().map(|_| ())
}
+4 -1
View File
@@ -298,7 +298,10 @@ 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::View(args) => {
let socket = (!args.new_window).then(crate::viewer::ipc::default_socket);
crate::viewer::run(args.session, socket.as_deref())
}
Command::Sheet(args) => video::sheet(&args),
Command::Motion(args) => video::motion(&args),
Command::Framediff(args) => video::framediff(&args),
+7 -3
View File
@@ -5,9 +5,13 @@
use clap::Args;
use std::path::PathBuf;
/// The arguments of `view`: the session to open, if one is given.
/// The arguments of `view`: the sessions to open, if any are given.
#[derive(Args, Debug)]
pub struct ViewArgs {
/// The recording's folder [default: choose one in the window]
pub session: Option<PathBuf>,
/// The recordings' folders, each opened as a tab of the one viewer window [default: choose
/// one in the window]
pub session: Vec<PathBuf>,
/// Open a window of its own, instead of a tab of the viewer that is already running
#[arg(long)]
pub new_window: bool,
}
File diff suppressed because it is too large. Load diff
+648
View File
@@ -0,0 +1,648 @@
//! One viewer window, however many times a recording is opened: the viewer's local socket.
//!
//! The first viewer to start listens on a unix domain socket in the per-user data directory
//! ([`default_socket`]); every later `komorebi-recorder view SESSION...`, and the recorder
//! window's "Open session..." and "Open last", connect to it, ask it to open the sessions as tabs
//! and exit, instead of making a window of their own. The socket types are the ones
//! [`crate::komorebi_link`] uses (std's on unix, the `uds_windows` crate's on Windows), so there is
//! one place where the two hosts differ.
//!
//! # Protocol
//!
//! A request is one line of JSON, [`Request`], for example
//! `{"open":["/recordings/20261028T154619Z"],"focus":true}`. The server answers with one line,
//! [`Reply`] (`{"ok":true}`, or `{"ok":false,"error":"..."}`), and closes the connection. An empty
//! `open` asks only for the window to be raised and a start-screen tab to be there. Paths must be
//! absolute: the viewer runs somewhere else, so a relative path would mean nothing to it
//! ([`absolute`] makes them so before they are sent).
//!
//! The server reads at most [`MAX_LINE`] bytes of a request and waits at most [`TIMEOUT`] for
//! it, ignores what is not a request (answering with an error) and never panics on input.
//!
//! # Who becomes the server
//!
//! [`claim`] does it all: it tries to hand the request to a running viewer; if none answers it
//! binds the socket, removing a stale socket file (left by a viewer that did not exit normally)
//! when nothing is listening on it, and the caller becomes the viewer. Two viewers started at the
//! same moment resolve as one binding and the other finding the bind taken and forwarding. A viewer
//! that dies between accepting and answering looks like no viewer, so the request is served by the
//! caller instead of being lost. The one race left is two viewers both finding a *stale* file at
//! the same moment, which can leave two windows; it is harmless and cannot lose a request.
//!
//! The server's socket file is removed when the [`Server`] is dropped, which is when the viewer
//! exits normally.
//!
//! Every function takes the socket path as a parameter, so tests use a temporary one and never the
//! user's real socket.
use crate::komorebi_link::UnixListener;
use crate::komorebi_link::UnixStream;
use serde::Deserialize;
use serde::Serialize;
use std::io::BufRead;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
/// The name of the viewer's socket, inside komorebi's data directory.
pub const SOCKET_NAME: &str = "komorebi-recorder-viewer.sock";
/// The environment variable that replaces the socket path ([`default_socket`]). It exists so
/// that a viewer can be tried out, or tested end to end, without touching the user's real one.
pub const SOCKET_VARIABLE: &str = "KOMOREBI_RECORDER_VIEWER_SOCKET";
/// The longest request line the server reads, in bytes. A longer one is refused.
pub const MAX_LINE: u64 = 1 << 20;
/// How long either side waits on the other for one read or write.
pub const TIMEOUT: Duration = Duration::from_secs(2);
/// What to ask the viewer to do.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::viewer::ipc::Request;
///
/// let request = Request { open: vec!["/recordings/a".into()], focus: true };
/// assert_eq!(
/// serde_json::to_string(&request)?,
/// r#"{"open":["/recordings/a"],"focus":true}"#
/// );
///
/// // both fields may be left out
/// let empty: Request = serde_json::from_str("{}")?;
/// assert!(empty.open.is_empty() && empty.focus);
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Request {
/// The sessions to open, as absolute paths. Empty means: open a start-screen tab (unless the
/// current one is already one) and raise the window.
#[serde(default)]
pub open: Vec<PathBuf>,
/// Whether to raise the window and un-minimise it. The default is `true`.
#[serde(default = "yes")]
pub focus: bool,
}
fn yes() -> bool {
true
}
impl Default for Request {
fn default() -> Self {
Self {
open: Vec::new(),
focus: true,
}
}
}
/// The server's one-line answer to a [`Request`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Reply {
/// Whether the request was understood and handed to the window.
pub ok: bool,
/// Why not, when `ok` is false.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl Reply {
fn accepted() -> Self {
Self {
ok: true,
error: None,
}
}
fn refused(error: impl Into<String>) -> Self {
Self {
ok: false,
error: Some(error.into()),
}
}
}
/// Returns the socket path to use: `$KOMOREBI_RECORDER_VIEWER_SOCKET` if it is set and not
/// empty, else [`SOCKET_NAME`] in komorebi's data directory
/// ([`data_dir`](crate::komorebi_link::data_dir)).
///
/// Only the edges of the program call this (the `view` command and the recorder window); everything
/// else takes the path as a parameter.
#[must_use]
pub fn default_socket() -> PathBuf {
match std::env::var_os(SOCKET_VARIABLE) {
Some(path) if !path.is_empty() => PathBuf::from(path),
_ => crate::komorebi_link::socket_path(SOCKET_NAME),
}
}
/// Makes `path` absolute against the current directory, without looking at the disk, so a request
/// means the same thing in the viewer's process as in this one.
#[must_use]
pub fn absolute(path: &Path) -> PathBuf {
std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
}
/// What came of handing a request to a viewer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Delivery {
/// A viewer took it and said so.
Delivered,
/// Nothing is listening on the socket (no file, or nobody behind it).
NoViewer,
/// Something was listening but went away before answering: treated as no viewer.
Died,
}
/// Hands `request` to the viewer listening on `socket`, if there is one.
///
/// # Errors
///
/// Returns an error if a viewer answered that it refused the request (kind `InvalidInput`, with its
/// reason), or if writing the request failed for a reason other than the viewer going away.
pub fn send(socket: &Path, request: &Request) -> std::io::Result<Delivery> {
use std::io::ErrorKind;
let mut stream = match UnixStream::connect(socket) {
Ok(stream) => stream,
// no file, a refusal, or a file that is not a socket at all: nobody is there to answer
Err(_) => return Ok(Delivery::NoViewer),
};
stream.set_read_timeout(Some(TIMEOUT))?;
stream.set_write_timeout(Some(TIMEOUT))?;
let mut line = serde_json::to_string(request).map_err(std::io::Error::other)?;
line.push('\n');
if let Err(error) = stream
.write_all(line.as_bytes())
.and_then(|()| stream.flush())
{
return match error.kind() {
ErrorKind::BrokenPipe
| ErrorKind::ConnectionReset
| ErrorKind::ConnectionAborted
| ErrorKind::TimedOut
| ErrorKind::WouldBlock => Ok(Delivery::Died),
_ => Err(error),
};
}
let mut answer = String::new();
let read = std::io::BufReader::new(&stream)
.take(MAX_LINE)
.read_line(&mut answer);
match read {
Ok(0) => Ok(Delivery::Died),
Ok(_) => match serde_json::from_str::<Reply>(answer.trim()) {
Ok(Reply { ok: true, .. }) => Ok(Delivery::Delivered),
Ok(Reply { error, .. }) => Err(std::io::Error::new(
ErrorKind::InvalidInput,
error.unwrap_or_else(|| "the viewer refused the request".to_string()),
)),
// something that is not our viewer is on the socket
Err(_) => Ok(Delivery::Died),
},
Err(error)
if matches!(
error.kind(),
ErrorKind::ConnectionReset
| ErrorKind::ConnectionAborted
| ErrorKind::TimedOut
| ErrorKind::WouldBlock
| ErrorKind::UnexpectedEof
) =>
{
Ok(Delivery::Died)
}
Err(error) => Err(error),
}
}
/// A bound socket that is not being served yet: the result of [`claim`] when this process is
/// the viewer.
///
/// It is made before the window is, and started with [`Bound::serve`] once the window's context
/// exists.
pub struct Bound {
listener: UnixListener,
path: PathBuf,
}
/// The outcome of [`claim`].
pub enum Claim {
/// A running viewer took the request: there is nothing more to do.
Forwarded,
/// Nobody answered and the socket is now ours: be the viewer.
Serving(Bound),
}
/// Hands `request` to a running viewer, or becomes the viewer: see the [module
/// documentation](self#who-becomes-the-server).
///
/// # Errors
///
/// Returns an error if a viewer refused the request (see [`send`]), or if the socket can neither
/// be answered nor bound (for example, its directory cannot be written to).
pub fn claim(socket: &Path, request: &Request) -> std::io::Result<Claim> {
use std::io::ErrorKind;
if let Some(parent) = socket.parent() {
let _ = std::fs::create_dir_all(parent);
}
let mut last = None;
for _ in 0..4 {
if send(socket, request)? == Delivery::Delivered {
return Ok(Claim::Forwarded);
}
match UnixListener::bind(socket) {
Ok(listener) => {
return Ok(Claim::Serving(Bound {
listener,
path: socket.to_path_buf(),
}));
}
Err(error)
if matches!(
error.kind(),
ErrorKind::AddrInUse | ErrorKind::AlreadyExists | ErrorKind::PermissionDenied
) && socket.exists() =>
{
// either another viewer bound it a moment ago, or the file is left over from one
// that died: ask again, and only if nobody answers, clear it and go round
if send(socket, request)? == Delivery::Delivered {
return Ok(Claim::Forwarded);
}
let _ = std::fs::remove_file(socket);
last = Some(error);
}
Err(error) => return Err(error),
}
}
Err(last.unwrap_or_else(|| std::io::Error::other("could not claim the viewer's socket")))
}
impl Bound {
/// Starts answering requests on a thread of its own and returns the [`Server`] to drain them
/// from.
///
/// `notify` is called, from that thread, after each request is queued: the window uses it to ask
/// for a repaint, so a request is taken up even when the window is idle.
#[must_use]
pub fn serve(self, notify: impl Fn() + Send + Sync + 'static) -> Server {
let (sender, receiver) = crossbeam_channel::unbounded();
let stopping = Arc::new(AtomicBool::new(false));
let notify = Arc::new(notify);
let flag = stopping.clone();
let Bound { listener, path } = self;
let thread = std::thread::Builder::new()
.name("viewer-ipc".to_string())
.spawn(move || {
for stream in listener.incoming() {
if flag.load(Ordering::Acquire) {
break;
}
let Ok(stream) = stream else {
continue;
};
let sender = sender.clone();
let notify = notify.clone();
// a client that stalls must not hold up the next one
let _ = std::thread::Builder::new()
.name("viewer-ipc-client".to_string())
.spawn(move || handle(stream, &sender, &*notify));
}
})
.ok();
Server {
path,
receiver,
stopping,
thread,
}
}
}
/// Reads one request from `stream`, queues it and answers. Never panics on what it reads.
fn handle(
mut stream: UnixStream,
queue: &crossbeam_channel::Sender<Request>,
notify: &(dyn Fn() + Send + Sync),
) {
let _ = stream.set_read_timeout(Some(TIMEOUT));
let _ = stream.set_write_timeout(Some(TIMEOUT));
let mut line = Vec::new();
let read = std::io::BufReader::new(&stream)
.take(MAX_LINE + 1)
.read_until(b'\n', &mut line);
let reply = match read {
Err(_) | Ok(0) => return,
Ok(_) if line.len() as u64 > MAX_LINE => Reply::refused("the request is too long"),
Ok(_) => match parse(&line) {
Err(why) => Reply::refused(why),
Ok(request) => {
if queue.send(request).is_ok() {
notify();
Reply::accepted()
} else {
Reply::refused("the viewer is closing")
}
}
},
};
if let Ok(mut text) = serde_json::to_string(&reply) {
text.push('\n');
let _ = stream.write_all(text.as_bytes());
let _ = stream.flush();
}
}
/// Reads a request line, refusing what is not one and any path that is not absolute.
fn parse(line: &[u8]) -> Result<Request, String> {
let text = std::str::from_utf8(line).map_err(|_| "the request is not text".to_string())?;
let request: Request =
serde_json::from_str(text.trim()).map_err(|error| format!("not a request: {error}"))?;
if let Some(path) = request.open.iter().find(|path| !path.is_absolute()) {
return Err(format!("{} is not an absolute path", path.display()));
}
Ok(request)
}
/// The viewer's end of the socket: requests arrive on [`Server::requests`].
///
/// Dropping it stops the listener thread and removes the socket file.
pub struct Server {
path: PathBuf,
receiver: crossbeam_channel::Receiver<Request>,
stopping: Arc<AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl Server {
/// Returns the requests that have arrived and not yet been taken, oldest first.
#[must_use]
pub fn requests(&self) -> Vec<Request> {
self.receiver.try_iter().collect()
}
/// Returns the path of the socket being served.
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for Server {
fn drop(&mut self) {
self.stopping.store(true, Ordering::Release);
// a connection wakes the listener, which is waiting in accept
let _ = UnixStream::connect(&self.path);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
let _ = std::fs::remove_file(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;
use std::time::Instant;
fn socket(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("kr-ipc-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("dir");
dir.join("v.sock")
}
fn serving(path: &Path) -> Server {
match claim(path, &Request::default()).expect("claim") {
Claim::Serving(bound) => bound.serve(|| {}),
Claim::Forwarded => panic!("a viewer was already there"),
}
}
fn wait_for(server: &Server, count: usize) -> Vec<Request> {
let mut got = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
while got.len() < count && Instant::now() < deadline {
got.extend(server.requests());
std::thread::sleep(Duration::from_millis(5));
}
got
}
fn abs(name: &str) -> PathBuf {
absolute(Path::new(name))
}
#[test]
fn a_request_goes_to_the_server_and_is_acknowledged() {
let path = socket("round");
let woken = Arc::new(AtomicUsize::new(0));
let counter = woken.clone();
let Claim::Serving(bound) = claim(&path, &Request::default()).expect("claim") else {
panic!("nobody is serving yet");
};
let server = bound.serve(move || {
counter.fetch_add(1, Ordering::SeqCst);
});
let request = Request {
open: vec![abs("a"), abs("b")],
focus: true,
};
assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered);
assert_eq!(wait_for(&server, 1), [request]);
assert_eq!(woken.load(Ordering::SeqCst), 1);
// a second claim forwards instead of binding
let more = Request {
open: vec![abs("c")],
focus: false,
};
assert!(matches!(
claim(&path, &more).expect("claim"),
Claim::Forwarded
));
assert_eq!(wait_for(&server, 1), [more]);
}
#[test]
fn nothing_is_delivered_when_nobody_listens() {
let path = socket("nobody");
assert_eq!(
send(&path, &Request::default()).expect("sent"),
Delivery::NoViewer
);
}
#[test]
fn the_socket_file_goes_when_the_server_does() {
let path = socket("cleanup");
let server = serving(&path);
assert!(path.exists());
drop(server);
assert!(!path.exists());
assert_eq!(
send(&path, &Request::default()).expect("sent"),
Delivery::NoViewer
);
}
#[test]
fn a_stale_socket_file_is_cleared_and_claimed() {
let path = socket("stale");
// a listener that is dropped without removing its file leaves one behind
drop(UnixListener::bind(&path).expect("bind"));
assert!(path.exists(), "the file is left behind");
let server = serving(&path);
let request = Request {
open: vec![abs("x")],
focus: true,
};
assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered);
assert_eq!(wait_for(&server, 1), [request]);
}
#[test]
fn a_file_that_is_not_a_socket_is_replaced() {
let path = socket("regular");
std::fs::write(&path, "left by something else").expect("write");
let server = serving(&path);
drop(server);
}
#[test]
fn two_viewers_starting_together_make_one_server() {
let path = socket("race");
let mut threads = Vec::new();
for index in 0..6 {
let path = path.clone();
threads.push(std::thread::spawn(move || {
let request = Request {
open: vec![abs(&format!("s{index}"))],
focus: true,
};
match claim(&path, &request).expect("claim") {
Claim::Forwarded => None,
Claim::Serving(bound) => Some((bound.serve(|| {}), request)),
}
}));
}
let results: Vec<_> = threads
.into_iter()
.map(|thread| thread.join().expect("thread"))
.collect();
let servers: Vec<_> = results.into_iter().flatten().collect();
assert_eq!(servers.len(), 1, "exactly one of them is the viewer");
// every other request reached it; the server's own was not sent to itself
let (server, own) = &servers[0];
let got = wait_for(server, 5);
assert_eq!(got.len(), 5, "{got:?}");
assert!(!got.contains(own));
}
#[test]
fn what_is_not_a_request_is_refused_and_the_server_carries_on() {
let path = socket("garbage");
let server = serving(&path);
let ask = |bytes: &[u8]| -> Option<Reply> {
let mut stream = UnixStream::connect(&path).expect("connect");
stream.set_read_timeout(Some(TIMEOUT)).expect("timeout");
// the server may answer and close before everything is written
let _ = stream.write_all(bytes);
let mut answer = String::new();
std::io::BufReader::new(&stream)
.read_line(&mut answer)
.ok()?;
serde_json::from_str(answer.trim()).ok()
};
for garbage in [
&b"not json at all\n"[..],
b"{\"open\": 7}\n",
b"\xff\xfe\n",
b"42\n",
b"\"open\"\n",
b"{\"open\":[\"relative/path\"]}\n",
] {
let reply = ask(garbage).expect("an answer");
assert!(!reply.ok, "{}", String::from_utf8_lossy(garbage));
assert!(reply.error.is_some());
}
// far too long, with no end of line
let long = vec![b'a'; usize::try_from(MAX_LINE).expect("fits") + 10];
if let Some(reply) = ask(&long) {
assert!(!reply.ok);
}
// a client that connects and says nothing, or hangs up, changes nothing
drop(UnixStream::connect(&path).expect("connect"));
assert!(server.requests().is_empty());
// and a good request still works afterwards
let request = Request {
open: vec![abs("fine")],
focus: true,
};
assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered);
assert_eq!(wait_for(&server, 1), [request]);
}
#[test]
fn a_refused_request_is_an_error_to_the_sender() {
let path = socket("refused");
let _server = serving(&path);
let relative = Request {
open: vec![PathBuf::from("relative")],
focus: true,
};
let error = send(&path, &relative).expect_err("refused");
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
assert!(error.to_string().contains("absolute"), "{error}");
}
#[test]
fn a_server_that_dies_mid_request_looks_like_no_viewer() {
let path = socket("died");
let listener = UnixListener::bind(&path).expect("bind");
let thread = std::thread::spawn(move || {
// accepts, reads the request, and hangs up without answering
let (stream, _) = listener.accept().expect("accept");
let mut line = String::new();
let _ = std::io::BufReader::new(&stream).read_line(&mut line);
drop(stream);
});
let outcome = send(&path, &Request::default()).expect("no error");
assert_eq!(outcome, Delivery::Died);
thread.join().expect("thread");
}
#[test]
fn the_default_socket_is_in_the_data_dir_unless_overridden() {
// only the pure parts: the environment is shared by every test
assert!(
default_socket().ends_with(SOCKET_NAME) || std::env::var_os(SOCKET_VARIABLE).is_some()
);
assert!(abs("a").is_absolute());
}
}
+158 -4
View File
@@ -9,7 +9,9 @@
//! [`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
//! The tab keys (`Cmd`/`Ctrl` with `T`, `W` and the digits, `Ctrl` `Tab`) are in the map, and are
//! carried out by the window rather than by a session. Otherwise 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
@@ -76,6 +78,37 @@ pub enum Action {
/// 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,
/// Open a new start-screen tab (`Cmd`/`Ctrl` `T`). Carried out by the window, not by an open
/// session ([`ViewerApp::apply_tab_action`](super::ViewerApp::apply_tab_action)).
NewTab,
/// Close the current tab (`Cmd`/`Ctrl` `W`).
CloseTab,
/// Go to the next tab, from the last to the first (`Ctrl` `Tab`, and `Cmd` `Shift` `]`).
NextTab,
/// Go to the previous tab, from the first to the last (`Ctrl` `Shift` `Tab`, and `Cmd` `Shift`
/// `[`).
PreviousTab,
/// Go to this tab, counting from `0` (`Cmd`/`Ctrl` with `1` to `8`). One beyond the tabs there
/// are does nothing.
GoToTab(usize),
/// Go to the last tab (`Cmd`/`Ctrl` `9`).
LastTab,
}
impl Action {
/// Whether this action is about the window's tabs rather than the session in the current one.
#[must_use]
pub fn is_tab_action(self) -> bool {
matches!(
self,
Self::NewTab
| Self::CloseTab
| Self::NextTab
| Self::PreviousTab
| Self::GoToTab(_)
| Self::LastTab
)
}
}
/// Every binding, for the help screen: the keys and what they do, as text to show a person.
@@ -113,6 +146,13 @@ pub const BINDINGS: &[(&str, &str)] = &[
("1 – 9", "step by that display"),
("Esc", "clear the selection / close a panel"),
("?", "this help"),
("Cmd/Ctrl T", "a new tab"),
("Cmd/Ctrl W", "close the tab"),
(
"Ctrl Tab Ctrl Shift Tab",
"next / previous tab (on a Mac also Cmd Shift ] [)",
),
("Cmd/Ctrl 1 – 9", "go to that tab (9 is the last)"),
];
/// Returns the action for a key pressed with `modifiers`, if it is bound.
@@ -124,8 +164,10 @@ pub const BINDINGS: &[(&str, &str)] = &[
/// 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.
/// The tab keys hold `Command` (`Cmd` on a Mac, `Ctrl` elsewhere): `T` opens a tab, `W` closes
/// one, `1` to `9` go to a tab. `Ctrl` `Tab` (with `Shift`, backwards) and, on a Mac, `Command`
/// `Shift` `]` and `[` move between tabs. Anything else pressed with `Command`, `Ctrl` or `Alt`
/// gives `None`, as does any key that is not bound. [`Action::ClearSelection`] is never returned.
///
/// # Example
///
@@ -147,10 +189,15 @@ pub const BINDINGS: &[(&str, &str)] = &[
///
/// // 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::T, Modifiers::COMMAND, None), Some(Action::NewTab));
/// assert_eq!(action(Key::Num9, Modifiers::COMMAND, None), Some(Action::LastTab));
/// assert_eq!(action(Key::Q, Modifiers::NONE, None), None);
/// ```
#[must_use]
pub fn action(key: Key, modifiers: Modifiers, text: Option<&str>) -> Option<Action> {
if let Some(tab) = tab_action(key, modifiers) {
return Some(tab);
}
if modifiers.command || modifiers.ctrl || modifiers.alt {
return None;
}
@@ -198,6 +245,43 @@ pub fn action(key: Key, modifiers: Modifiers, text: Option<&str>) -> Option<Acti
})
}
fn tab_action(key: Key, modifiers: Modifiers) -> Option<Action> {
if modifiers.alt {
return None;
}
if modifiers.ctrl && key == Key::Tab {
return Some(if modifiers.shift {
Action::PreviousTab
} else {
Action::NextTab
});
}
if !modifiers.command {
return None;
}
if modifiers.shift {
return match key {
Key::CloseBracket | Key::CloseCurlyBracket => Some(Action::NextTab),
Key::OpenBracket | Key::OpenCurlyBracket => Some(Action::PreviousTab),
_ => None,
};
}
Some(match key {
Key::T => Action::NewTab,
Key::W => Action::CloseTab,
Key::Num1 => Action::GoToTab(0),
Key::Num2 => Action::GoToTab(1),
Key::Num3 => Action::GoToTab(2),
Key::Num4 => Action::GoToTab(3),
Key::Num5 => Action::GoToTab(4),
Key::Num6 => Action::GoToTab(5),
Key::Num7 => Action::GoToTab(6),
Key::Num8 => Action::GoToTab(7),
Key::Num9 => Action::LastTab,
_ => 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)).
@@ -351,6 +435,76 @@ mod tests {
);
}
#[test]
fn the_tab_keys_hold_command_and_do_not_clash_with_the_plain_ones() {
assert_eq!(
action(Key::T, Modifiers::COMMAND, None),
Some(Action::NewTab)
);
assert_eq!(
action(Key::W, Modifiers::COMMAND, None),
Some(Action::CloseTab)
);
assert_eq!(
action(Key::Tab, Modifiers::CTRL, None),
Some(Action::NextTab)
);
assert_eq!(
action(
Key::Tab,
Modifiers {
ctrl: true,
shift: true,
..Modifiers::NONE
},
None
),
Some(Action::PreviousTab)
);
let command_shift = Modifiers {
command: true,
shift: true,
..Modifiers::NONE
};
assert_eq!(
action(Key::CloseBracket, command_shift, None),
Some(Action::NextTab)
);
assert_eq!(
action(Key::OpenCurlyBracket, command_shift, None),
Some(Action::PreviousTab)
);
assert_eq!(
action(Key::Num1, Modifiers::COMMAND, None),
Some(Action::GoToTab(0))
);
assert_eq!(
action(Key::Num9, Modifiers::COMMAND, None),
Some(Action::LastTab)
);
// the plain digit still picks a display, the plain letters still do what they did
assert_eq!(
action(Key::Num1, plain(), None),
Some(Action::FocusDisplay(0))
);
assert_eq!(action(Key::T, plain(), None), None);
assert_eq!(action(Key::W, plain(), None), None);
assert_eq!(action(Key::Tab, plain(), None), None);
// Alt makes them something else again
assert_eq!(
action(
Key::T,
Modifiers {
command: true,
alt: true,
..Modifiers::NONE
},
None
),
None
);
}
#[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
@@ -359,7 +513,7 @@ mod tests {
.map(|(keys, _)| *keys)
.collect::<Vec<_>>()
.join(" ");
for key in ["Space", "J", "Home", "B", "Esc"] {
for key in ["Space", "J", "Home", "B", "Esc", "Cmd/Ctrl T", "Ctrl Tab"] {
assert!(listed.contains(key), "{key}");
}
}
+20
View File
@@ -274,6 +274,26 @@ pub fn name_of(dir: &Path) -> String {
)
}
/// Returns the short name of a session for a tab: the time of day it began, when its folder is named
/// for when it began (`20261026T154619Z` is `15:46:19`, in UTC as the folder is), else the folder's
/// name as [`name_of`] gives it.
///
/// # Example
///
/// ```rust
/// use komorebi_recorder::viewer::loaded::tab_name;
/// use std::path::Path;
///
/// assert_eq!(tab_name(Path::new("/recordings/20261026T154619Z")), "15:46:19");
/// assert_eq!(tab_name(Path::new("/recordings/repro")), "repro");
/// ```
#[must_use]
pub fn tab_name(dir: &Path) -> String {
let name = name_of(dir);
chrono::NaiveDateTime::parse_from_str(&name, "%Y%m%dT%H%M%SZ")
.map_or(name, |time| time.format("%H:%M:%S").to_string())
}
#[cfg(test)]
mod tests {
use super::*;
+78 -12
View File
@@ -1,14 +1,20 @@
//! 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
//! 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`.
//!
//! There is one viewer window. Each session is a tab of it, and opening another session (from
//! the window, from the command line or from the recorder window) adds a tab to the window that
//! is already open instead of making a new one: see [`ipc`] and
//! [Tabs and one window](self#tabs-and-one-window).
//!
//! ```text
//! +-------------------------------------------------+
//! | Open... session name counts and warnings | top bar
//! | [15:46:19 x] [15:51:02 x] [+] Open... | tab bar
//! | session name counts and warnings | top bar
//! +----------------------------------+--------------+
//! | | Now |
//! | the video of every display, | Event |
@@ -21,6 +27,28 @@
//! +-------------------------------------------------+
//! ```
//!
//! # Tabs and one window
//!
//! A tab is one session ([`Open`]), or a start screen with the recent sessions, or a session that
//! failed to open with the reason. A tab is named for when its session began (`15:46:19`, from the
//! folder's name), with the whole path on hover; `x` (or a middle click) closes it and `+` adds a
//! start screen. Closing the last tab leaves a start screen: the window itself is closed
//! with the system's close button. Opening a session follows one rule, whatever asked for it: if a
//! tab has the session, that tab is shown; else if the current tab is a start screen or a failure
//! the session loads into it; else it goes in a new tab. Only the tab in view plays: the others
//! are paused (their scan for changes carries on), and closing one stops its scan and its decoding.
//! The keys are in [`keymap`] (`Cmd`/`Ctrl` `T`, `W`, `Tab`, and `1` to `9`). Tabs are not
//! restored when the viewer is started again; the recent sessions are shared by all of them.
//!
//! `komorebi-recorder view` finds out whether a viewer is running by connecting to a socket in
//! komorebi's data directory, `komorebi-recorder-viewer.sock`. If one answers, it is sent the
//! sessions (as absolute paths) and asked to come to the front, and the command exits without a
//! window; if not, the command becomes the viewer and listens there. `view --new-window` skips
//! the socket and makes an independent window. The recorder window talks to the socket directly and
//! starts `view` only if nobody answers. The protocol, the start-up race and a stale socket
//! are covered in [`ipc`]. `KOMOREBI_RECORDER_VIEWER_SOCKET` names another socket, for trying the
//! viewer out without touching a real one.
//!
//! # What plays and what is read
//!
//! The viewer reads a *finished* session; one that is still being recorded does not open. A
@@ -38,18 +66,19 @@
//!
//! | module | what it is |
//! |---|---|
//! | [`ipc`] | the viewer's local socket: how one window takes sessions from other processes |
//! | [`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 |
//! | `app` | [`ViewerApp`] (the tabs), [`Screen`] (what a tab shows) 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
//! The first six 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.
@@ -78,6 +107,7 @@
mod app;
mod composer;
mod inspector;
pub mod ipc;
pub mod keymap;
mod lanes;
pub mod loaded;
@@ -89,18 +119,27 @@ mod video;
use color_eyre::eyre;
use eframe::egui;
use std::path::Path;
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.
/// Opens the viewer window, with each of `sessions` open in a tab, 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.
/// This blocks the calling thread: the window's event loop runs on it. Each of `sessions` is the
/// folder of a recording. They open in the background, so a session that cannot be opened does not
/// make this fail: the window comes up and shows why. With no sessions the window shows a start
/// screen with the recent sessions that still exist ([`prefs::Prefs::existing`]) and a button to
/// choose one.
///
/// `socket` is the path of the viewer's socket ([`ipc::default_socket`]), or `None` for a window
/// of its own that no other process can reach (`view --new-window`). With a socket, if a viewer is
/// already running it is asked to open `sessions` as tabs (an empty list raises it) and this
/// returns `Ok` at once without making a window; otherwise this window listens on the socket and
/// opens what arrives as tabs. If the socket cannot be used, a message is printed and the window
/// is made without it.
///
/// The window is 1500 by 920 points (at least 900 by 600), dark, and titled only when komorebi ignores it: see the [module
/// documentation](self#staying-out-of-the-way-of-what-is-being-investigated) for why. Needs a
@@ -111,9 +150,32 @@ pub use app::ViewerApp;
///
/// 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<()> {
// before the window exists, so komorebi never sees a titled window it was not told to ignore
pub fn run(sessions: Vec<PathBuf>, socket: Option<&Path>) -> eyre::Result<()> {
let bound = match socket {
Some(socket) => {
let sessions: Vec<PathBuf> = sessions.iter().map(|path| ipc::absolute(path)).collect();
let request = ipc::Request {
open: sessions,
focus: true,
};
match ipc::claim(socket, &request) {
// a viewer is running and has taken the sessions as tabs
Ok(ipc::Claim::Forwarded) => return Ok(()),
Ok(ipc::Claim::Serving(bound)) => Some(bound),
// not being able to share a window is no reason not to show the recording
Err(error) => {
eprintln!("could not reach or start the viewer's socket: {error}");
None
}
}
}
None => None,
};
// only a viewer that is going to open a window needs komorebi to ignore it, and it must be
// told before the window exists, so komorebi never sees a titled window it was not told to ignore
let title = crate::komorebi_ignore::prepare_window().title;
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
// titled only when komorebi ignores it (or is not running), so opening the viewer does
@@ -139,9 +201,13 @@ pub fn run(session: Option<PathBuf>) -> eyre::Result<()> {
creation.egui_ctx.set_visuals(visuals);
let mut app = ViewerApp::new(prefs::directory());
if let Some(dir) = &session {
for dir in &sessions {
app.open(dir);
}
if let Some(bound) = bound {
let ctx = creation.egui_ctx.clone();
app.listen(bound.serve(move || ctx.request_repaint()));
}
Ok(Box::new(Shell(
app,
crate::platform::window::Chrome::default(),