From 72d600c8f6e256c24199f8bacbb0014cedc3644b Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 16:49:23 -0700 Subject: [PATCH] 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. --- README.md | 4 +- docs/usage/investigating-a-recording.md | 10 +- komorebi-recorder/src/app.rs | 24 +- komorebi-recorder/src/cli/mod.rs | 5 +- komorebi-recorder/src/cli/viewer_command.rs | 10 +- komorebi-recorder/src/viewer/app.rs | 907 ++++++++++++++++++-- komorebi-recorder/src/viewer/ipc.rs | 648 ++++++++++++++ komorebi-recorder/src/viewer/keymap.rs | 162 +++- komorebi-recorder/src/viewer/loaded.rs | 20 + komorebi-recorder/src/viewer/mod.rs | 90 +- 10 files changed, 1786 insertions(+), 94 deletions(-) create mode 100644 komorebi-recorder/src/viewer/ipc.rs diff --git a/README.md b/README.md index e4c18697..b8f1661f 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/usage/investigating-a-recording.md b/docs/usage/investigating-a-recording.md index 66246e39..cd0ced8c 100644 --- a/docs/usage/investigating-a-recording.md +++ b/docs/usage/investigating-a-recording.md @@ -22,9 +22,16 @@ budget, 6 an `assert` check did not hold. komorebi-recorder view ``` -opens the recording in its own window, for the person who made it (or anyone with the folder) to play, scrub and mark. +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 ...` (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 "" 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 diff --git a/komorebi-recorder/src/app.rs b/komorebi-recorder/src/app.rs index ff1e855d..f7103a07 100644 --- a/komorebi-recorder/src/app.rs +++ b/komorebi-recorder/src/app.rs @@ -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 { .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(|_| ()) } diff --git a/komorebi-recorder/src/cli/mod.rs b/komorebi-recorder/src/cli/mod.rs index 7a57784f..b5ef749c 100644 --- a/komorebi-recorder/src/cli/mod.rs +++ b/komorebi-recorder/src/cli/mod.rs @@ -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), diff --git a/komorebi-recorder/src/cli/viewer_command.rs b/komorebi-recorder/src/cli/viewer_command.rs index dbb6870c..67703f3e 100644 --- a/komorebi-recorder/src/cli/viewer_command.rs +++ b/komorebi-recorder/src/cli/viewer_command.rs @@ -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, + /// The recordings' folders, each opened as a tab of the one viewer window [default: choose + /// one in the window] + pub session: Vec, + /// Open a window of its own, instead of a tab of the viewer that is already running + #[arg(long)] + pub new_window: bool, } diff --git a/komorebi-recorder/src/viewer/app.rs b/komorebi-recorder/src/viewer/app.rs index 9622c7fd..588cb167 100644 --- a/komorebi-recorder/src/viewer/app.rs +++ b/komorebi-recorder/src/viewer/app.rs @@ -1,8 +1,8 @@ //! The viewer window: opening a session and keeping everything on screen in step. //! -//! [`ViewerApp`] is the whole application and holds a [`Screen`]: nothing opened yet, a session -//! loading, a session that failed to open, or an [`Open`] session. [`ViewerApp::ui`] draws one frame -//! of whichever it is. An [`Open`] is where the state of a session being viewed lives (the +//! [`ViewerApp`] is the whole application and holds tabs, each with a [`Screen`]: nothing opened +//! yet, a session loading, a session that failed to open, or an [`Open`] session. +//! [`ViewerApp::ui`] draws one frame of the tab bar and of the tab that is showing. An [`Open`] is where the state of a session being viewed lives (the //! playhead's [`Playback`], the visible stretch of the timeline, the selection, which event or //! finding or bug region is selected, the form being filled in), and its methods are spread //! over the files that draw each part: this file keeps it in step with the keyboard, and the lanes, @@ -13,10 +13,12 @@ //! bottom of this file run [`ViewerApp::ui`] headlessly through `egui::Context::run` with real key //! events, against sessions made by the test kit, and are what covers the behavior. +use super::ipc; use super::keymap; use super::keymap::Action; use super::loaded::Loaded; use super::loaded::name_of; +use super::loaded::tab_name; use super::prefs::Prefs; use super::theme; use super::timeline; @@ -137,12 +139,13 @@ pub struct Open { pub edge_preview: Option<(String, f64, f64)>, } -/// The screen the window is showing: a session, or what stands in for one. +/// What one tab of the window is showing: a session, or what stands in for one. /// -/// A [`ViewerApp`] is always on exactly one of these. [`ViewerApp::open`] moves it from `Empty` -/// (or any screen) to `Loading`, and from there to `Open` or `Failed` when the load finishes. +/// Every tab of a [`ViewerApp`] is on exactly one of these. [`ViewerApp::open`] puts a `Loading` +/// in the tab it opens a session in, and from there it becomes `Open` or `Failed` when the load +/// finishes. pub enum Screen { - /// Nothing opened yet: the start screen, with the recent sessions that still exist. + /// Nothing opened in this tab: the start screen, with the recent sessions that still exist. Empty, /// A session is being read in the background: a spinner. Loading { @@ -162,19 +165,50 @@ pub enum Screen { Open(Box), } -/// The viewer application: the preferences and the screen being shown. +impl Screen { + /// Returns the session this tab is opening, has failed to open or has open, if it has one. + #[must_use] + pub fn dir(&self) -> Option<&Path> { + match self { + Self::Empty => None, + Self::Loading { dir, .. } | Self::Failed { dir, .. } => Some(dir), + Self::Open(open) => Some(&open.loaded.dir), + } + } + + /// Whether a session can be opened into this tab without losing anything: it shows the start + /// screen, or a failure. + #[must_use] + pub fn is_free(&self) -> bool { + matches!(self, Self::Empty | Self::Failed { .. }) + } +} + +/// The viewer application: the preferences and the tabs of the window. /// -/// This is what [`run`](super::run) hands to `eframe`. [`ViewerApp::new`] makes one showing the -/// start screen, [`ViewerApp::open`] opens a session, and [`ViewerApp::ui`] draws a frame. It needs -/// a window to draw and so has no example. +/// This is what [`run`](super::run) hands to `eframe`. [`ViewerApp::new`] makes one with a single +/// start-screen tab, [`ViewerApp::open`] opens a session in a tab, and [`ViewerApp::ui`] draws a +/// frame. There is always at least one tab, and exactly one is active; the others keep their +/// state (an open session keeps its playhead, its selection and its scan) but their video is +/// paused. It needs a window to draw and so has no example. +/// +/// # Opening a session +/// +/// Every way of opening one (the buttons, the recent list, the system's folder dialog, a request +/// from another process: [`ViewerApp::handle_request`]) goes through [`ViewerApp::open`], which +/// follows one rule: if a tab already has the session, that tab is shown; otherwise, if the +/// current tab is a start screen or a failure, the session loads into it; otherwise it loads into a +/// new tab, which is shown. A tab is only ever closed by the user. pub struct ViewerApp { /// The viewer's preferences. Saved when a session is opened and when the state overlay is /// switched. pub prefs: Prefs, prefs_dir: PathBuf, - /// The screen the window is showing. - pub screen: Screen, + tabs: Vec, + active: usize, picker: Option>>, + server: Option, + release_focus: bool, } /// Ask the user for a folder with the system's own dialog, off the UI thread. @@ -186,8 +220,15 @@ fn pick_folder() -> Receiver> { receiver } +/// The path as sessions are told apart by: made absolute, with symbolic links followed, and on +/// Windows without the `\\?\` prefix. A path that cannot be resolved (it does not exist) is kept +/// as given, and then fails to open with the reason. +fn canonical(dir: &Path) -> PathBuf { + dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()) +} + impl ViewerApp { - /// Returns a viewer showing the start screen, with the preferences kept in `prefs_dir`. + /// Returns a viewer with one start-screen tab, with the preferences kept in `prefs_dir`. /// /// The preferences are read with [`Prefs::load`], so a missing or damaged file gives the /// defaults. Nothing is opened: see [`ViewerApp::open`]. @@ -196,47 +237,123 @@ impl ViewerApp { Self { prefs: Prefs::load(&prefs_dir), prefs_dir, - screen: Screen::Empty, + tabs: vec![Screen::Empty], + active: 0, picker: None, + server: None, + release_focus: false, } } - /// Starts opening the session in `dir` in the background. + /// Takes requests from other processes through `server` from now on: see + /// [`ViewerApp::handle_request`]. The socket is removed when the viewer is dropped. + pub fn listen(&mut self, server: ipc::Server) { + self.server = Some(server); + } + + /// Returns every tab, in order. + #[must_use] + pub fn tabs(&self) -> &[Screen] { + &self.tabs + } + + /// Returns the index of the tab being shown. + #[must_use] + pub fn active_index(&self) -> usize { + self.active + } + + /// Returns what the tab being shown has in it. + #[must_use] + pub fn screen(&self) -> &Screen { + &self.tabs[self.active] + } + + /// Returns what the tab being shown has in it, to change. + pub fn screen_mut(&mut self) -> &mut Screen { + &mut self.tabs[self.active] + } + + /// Returns the index of the tab that has the session in `dir` (already [`canonical`]) in it. + fn find(&self, dir: &Path) -> Option { + self.tabs.iter().position(|tab| { + tab.dir() + .is_some_and(|have| have == dir || canonical(have) == dir) + }) + } + + /// Opens the session in `dir` in a tab, in the background: see the [type + /// documentation](ViewerApp#opening-a-session) for which tab. /// - /// The screen becomes [`Screen::Loading`] at once, replacing whatever was showing, and - /// [`ViewerApp::ui`] brings the result in when the load has finished: an [`Open`] session, or - /// [`Screen::Failed`] with the reason. A session that cannot be opened is therefore not an error - /// here; see [`Loaded::load`] for what can go wrong. + /// The tab is shown at once. It is [`Screen::Loading`] and [`ViewerApp::ui`] brings the result + /// in when the load has finished: an [`Open`] session, or [`Screen::Failed`] with the reason. A + /// session that cannot be opened is therefore not an error here; see [`Loaded::load`] for what + /// can go wrong. A session that is already open is not loaded again; one that failed is + /// tried again. pub fn open(&mut self, dir: &Path) { + let dir = canonical(dir); + let slot = match self.find(&dir) { + Some(slot) if matches!(self.tabs[slot], Screen::Failed { .. }) => slot, + Some(slot) => { + self.focus_tab(slot); + return; + } + None => self.slot_for_new_session(), + }; + let (sender, result) = crossbeam_channel::bounded(1); - let target = dir.to_path_buf(); + let target = dir.clone(); std::thread::spawn(move || { let _ = sender.send(Loaded::load(&target)); }); - self.screen = Screen::Loading { - dir: dir.to_path_buf(), - result, - }; + self.tabs[slot] = Screen::Loading { dir, result }; + self.focus_tab(slot); + } + + /// Returns the tab a session that is not open yet goes in: the current one if it is free, else + /// a new one at the end. + fn slot_for_new_session(&mut self) -> usize { + if self.tabs[self.active].is_free() { + self.active + } else { + self.tabs.push(Screen::Empty); + self.tabs.len() - 1 + } } /// Opens the session in `dir` and waits for it: for tests, which have nothing to draw /// meanwhile. /// - /// On success the screen is [`Screen::Open`], the session is at the top of the recent - /// sessions (and the preferences are saved), and the playhead is a second before where the - /// first bug region starts, if there is one. + /// On success the tab is [`Screen::Open`] (found, or made, as [`ViewerApp::open`] does), the + /// session is at the top of the recent sessions (and the preferences are saved), and the + /// playhead is a second before where the first bug region starts, if there is one. A session + /// that is already open is only shown. /// /// # Errors /// /// Returns an error if the session cannot be loaded (see [`Loaded::load`]), if `dir` is not a /// session directory, or if the playback cannot be started (see [`Playback::start`]). The - /// screen is left as it was: unlike [`ViewerApp::open`], a failure is not shown in the window. + /// tabs are left as they were: unlike [`ViewerApp::open`], a failure is not shown in the window. pub fn open_now(&mut self, dir: &Path) -> eyre::Result<()> { - let loaded = Loaded::load(dir)?; - self.finish_open(loaded) + let dir = canonical(dir); + if let Some(slot) = self.find(&dir) + && matches!(self.tabs[slot], Screen::Open(_)) + { + self.focus_tab(slot); + return Ok(()); + } + let loaded = Loaded::load(&dir)?; + let open = self.build_open(loaded)?; + let slot = match self.find(&dir) { + Some(slot) => slot, + None => self.slot_for_new_session(), + }; + self.tabs[slot] = Screen::Open(Box::new(open)); + self.focus_tab(slot); + Ok(()) } - fn finish_open(&mut self, loaded: Loaded) -> eyre::Result<()> { + fn build_open(&mut self, loaded: Loaded) -> eyre::Result { let guard = SessionPath::new(&loaded.dir)?; let playback = Playback::start(loaded.analysis.manifest.clone(), guard, DECODE_WIDTH)?; self.prefs.opened(&loaded.dir); @@ -282,28 +399,130 @@ impl ViewerApp { if let Some(start) = start { open.playback.seek((start - 1.0).max(0.0)); } - self.screen = Screen::Open(Box::new(open)); - Ok(()) + Ok(open) } - /// Bring a finished load into the window, or show why it failed. - fn poll_loading(&mut self) { - let Screen::Loading { dir, result } = &self.screen else { - return; - }; + /// Adds a start-screen tab at the end and shows it. + pub fn new_tab(&mut self) { + self.tabs.push(Screen::Empty); + self.focus_tab(self.tabs.len() - 1); + } - let Ok(outcome) = result.try_recv() else { + /// Shows tab `index`. The tab that was showing is paused, so that only the tab in view decodes + /// video. An index beyond the tabs does nothing. + pub fn focus_tab(&mut self, index: usize) { + if index >= self.tabs.len() { + return; + } + self.active = index; + self.pause_hidden(); + if let Screen::Open(open) = &mut self.tabs[index] { + // the overlay is one setting for the window, not one per tab + open.overlay = self.prefs.overlay; + } + } + + /// Pauses every tab but the active one. Decoding stops with the playhead, and a hidden tab's + /// scan for changes carries on. + fn pause_hidden(&mut self) { + for (index, tab) in self.tabs.iter_mut().enumerate() { + if index != self.active + && let Screen::Open(open) = tab + && open.playback.is_playing() + { + open.playback.pause(); + } + } + } + + /// Closes tab `index`. Closing a session stops its scan for changes and its playback; closing + /// the last tab leaves a start-screen tab, so the window stays. The tab that takes the closed + /// one's place is shown if it was the one showing. An index beyond the tabs does nothing. + pub fn close_tab(&mut self, index: usize) { + if index >= self.tabs.len() { + return; + } + // dropping an Open cancels its scan and stops its playback + drop(self.tabs.remove(index)); + if self.tabs.is_empty() { + self.tabs.push(Screen::Empty); + } + if index < self.active { + self.active -= 1; + } + self.focus_tab(self.active.min(self.tabs.len() - 1)); + } + + /// Carries out a tab key: see [`Action::NewTab`] and the others for which are tab actions. Any + /// other action does nothing. + pub fn apply_tab_action(&mut self, action: Action) { + let count = self.tabs.len(); + match action { + Action::NewTab => self.new_tab(), + Action::CloseTab => self.close_tab(self.active), + Action::NextTab => self.focus_tab((self.active + 1) % count), + Action::PreviousTab => self.focus_tab((self.active + count - 1) % count), + Action::GoToTab(index) => self.focus_tab(index), + Action::LastTab => self.focus_tab(count - 1), + _ => {} + } + } + + /// Carries out a request from another process (see [`ipc::Request`]): opens each session as + /// [`ViewerApp::open`] does, or, for a request with none, shows a start-screen tab (a new one + /// unless the current tab is one already). Returns whether the window should be raised. + pub fn handle_request(&mut self, request: &ipc::Request) -> bool { + if request.open.is_empty() { + if !matches!(self.tabs[self.active], Screen::Empty) { + self.new_tab(); + } + } else { + for dir in &request.open { + self.open(dir); + } + } + request.focus + } + + /// Takes in the requests that arrived from other processes, and raises the window if one asked. + fn poll_requests(&mut self, ctx: &egui::Context) { + let Some(server) = &self.server else { return; }; - let dir = dir.clone(); - match outcome.and_then(|loaded| self.finish_open(loaded)) { - Ok(()) => {} - Err(error) => { - self.screen = Screen::Failed { + let requests = server.requests(); + let mut raise = false; + for request in &requests { + raise |= self.handle_request(request); + } + if raise { + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } + } + + /// Bring finished loads into their tabs, or show why they failed. + fn poll_loading(&mut self) { + for index in 0..self.tabs.len() { + let Screen::Loading { dir, result } = &self.tabs[index] else { + continue; + }; + let dir = dir.clone(); + let outcome = match result.try_recv() { + Ok(outcome) => outcome, + Err(crossbeam_channel::TryRecvError::Empty) => continue, + Err(crossbeam_channel::TryRecvError::Disconnected) => { + Err(eyre::eyre!("the thread reading the session stopped")) + } + }; + self.tabs[index] = match outcome.and_then(|loaded| self.build_open(loaded)) { + Ok(open) => Screen::Open(Box::new(open)), + Err(error) => Screen::Failed { dir, message: format!("{error:#}"), - }; - } + }, + }; + // a session that finished loading in a tab out of view starts paused + self.pause_hidden(); } } @@ -321,21 +540,79 @@ impl ViewerApp { } } + /// Reads the tab keys, unless a text box wants the keyboard. The keys of the session in the tab + /// being shown are read by [`Open::ui`]. + /// + /// Returns whether `Ctrl` `Tab` was pressed: egui also takes that as a request to move the + /// keyboard focus to the next widget, which would make the window think a text box wants the + /// keyboard, so the focus is let go of again at the start of the next frame. + fn tab_keys(&mut self, ctx: &egui::Context) -> bool { + if std::mem::take(&mut self.release_focus) { + // egui moved the focus when the last frame ended + ctx.memory_mut(|memory| { + if let Some(id) = memory.focused() { + memory.surrender_focus(id); + } + }); + } + if ctx.wants_keyboard_input() { + return false; + } + let ctrl_tab = ctx.input(|input| { + input.events.iter().any(|event| { + matches!( + event, + egui::Event::Key { + key: egui::Key::Tab, + pressed: true, + modifiers, + .. + } if modifiers.ctrl + ) + }) + }); + let actions: Vec = ctx.input(|input| { + input + .events + .iter() + .filter_map(|event| match event { + egui::Event::Key { + key, + pressed: true, + modifiers, + .. + } => keymap::action(*key, *modifiers, None), + _ => None, + }) + .filter(|action| action.is_tab_action()) + .collect() + }); + for action in actions { + self.apply_tab_action(action); + } + ctrl_tab + } + /// Draws one frame of the window. /// - /// It first takes in a finished load and a folder chosen in the system's dialog, then draws the - /// top bar and the screen, and saves the preferences if the state overlay was switched. While a - /// session is loading, or the dialog is open, it asks `ctx` to draw again soon, so the result - /// shows without anyone touching the window. An open session draws itself with [`Open::ui`]. + /// It first takes in requests from other processes, finished loads and a folder chosen in the + /// system's dialog, then draws the tab bar, the top bar of the tab being shown and its screen, + /// and saves the preferences if the state overlay was switched. While a session is loading, or + /// the dialog is open, it asks `ctx` to draw again soon, so the result shows without anyone + /// touching the window. An open session draws itself with [`Open::ui`]. /// /// Needs an `egui::Context`, so a window is needed (the tests of this module draw frames /// headlessly with `egui::Context::run`). pub fn ui(&mut self, ctx: &egui::Context) { + self.poll_requests(ctx); self.poll_loading(); self.poll_picker(); + let ctrl_tab = self.tab_keys(ctx); + self.pause_hidden(); let mut to_open: Option = None; let mut choose = false; + let mut bar = TabBar::default(); egui::TopBottomPanel::top("top") .frame( @@ -347,24 +624,31 @@ impl ViewerApp { ui.horizontal(|ui| { // leave room for the window controls that sit over the content ui.add_space(70.0); + bar = tab_bar(ui, &self.tabs, self.active); if ui.button("Open…").clicked() { choose = true; } - match &mut self.screen { - Screen::Open(open) => { + }); + let active = self.active; + match &mut self.tabs[active] { + Screen::Open(open) => { + ui.horizontal(|ui| { ui.label(egui::RichText::new(name_of(&open.loaded.dir)).strong()); open.top_bar(ui, &mut self.prefs); - } - Screen::Loading { dir, .. } => { + }); + } + Screen::Loading { dir, .. } => { + ui.horizontal(|ui| { ui.spinner(); ui.label(format!("opening {}…", name_of(dir))); - } - _ => {} + }); } - }); + _ => {} + } }); - match &mut self.screen { + let active = self.active; + match &mut self.tabs[active] { Screen::Open(open) => open.ui(ctx), Screen::Empty => { egui::CentralPanel::default().show(ctx, |ui| { @@ -381,21 +665,42 @@ impl ViewerApp { egui::CentralPanel::default().show(ctx, |ui| { ui.centered_and_justified(|ui| ui.spinner()); }); - ctx.request_repaint_after(Duration::from_millis(50)); } } + // a load in any tab, shown or not, is brought in by a later frame + if self + .tabs + .iter() + .any(|tab| matches!(tab, Screen::Loading { .. })) + { + ctx.request_repaint_after(Duration::from_millis(50)); + } if choose && self.picker.is_none() { self.picker = Some(pick_folder()); } if let Some(dir) = to_open { self.open(&dir); } + if bar.new_tab { + self.new_tab(); + } + if let Some(index) = bar.select { + self.focus_tab(index); + } + if let Some(index) = bar.close { + self.close_tab(index); + } + self.release_focus = ctrl_tab; if self.picker.is_some() { ctx.request_repaint_after(Duration::from_millis(100)); } + if self.server.is_some() { + // requests wake the window themselves; this is for a window that is minimised + ctx.request_repaint_after(Duration::from_millis(500)); + } - if let Screen::Open(open) = &self.screen + if let Screen::Open(open) = &self.tabs[self.active] && open.overlay != self.prefs.overlay { self.prefs.overlay = open.overlay; @@ -404,6 +709,71 @@ impl ViewerApp { } } +/// What was clicked in the tab bar in one frame. +#[derive(Default)] +struct TabBar { + select: Option, + close: Option, + new_tab: bool, +} + +/// What a tab says about itself: its label and the longer text for hovering over it. +fn tab_title(screen: &Screen) -> (String, String) { + match screen { + Screen::Empty => ("New tab".to_string(), "Open a recording".to_string()), + Screen::Loading { dir, .. } => ( + format!("… {}", tab_name(dir)), + format!("opening {}", dir.display()), + ), + Screen::Failed { dir, message } => ( + format!("⚠ {}", tab_name(dir)), + format!("{} could not be opened: {message}", dir.display()), + ), + Screen::Open(open) => ( + tab_name(&open.loaded.dir), + open.loaded.dir.display().to_string(), + ), + } +} + +/// Draws the tabs, a close button on each, and the `+` after them. +fn tab_bar(ui: &mut egui::Ui, tabs: &[Screen], active: usize) -> TabBar { + let mut bar = TabBar::default(); + let room = (ui.available_width() - 110.0).max(120.0); + egui::ScrollArea::horizontal() + .id_salt("tabs") + .max_width(room) + .auto_shrink([true, true]) + .show(ui, |ui| { + ui.horizontal(|ui| { + for (index, tab) in tabs.iter().enumerate() { + let (label, tip) = tab_title(tab); + let response = ui + .selectable_label(index == active, label) + .on_hover_text(tip); + if response.clicked() { + bar.select = Some(index); + } + if response.middle_clicked() { + bar.close = Some(index); + } + if ui + .small_button("×") + .on_hover_text("Close the tab") + .clicked() + { + bar.close = Some(index); + } + ui.add_space(6.0); + } + }); + }); + if ui.button("+").on_hover_text("A new tab").clicked() { + bar.new_tab = true; + } + bar +} + /// What to show before a session is open (or when it would not open). fn start_screen( ui: &mut egui::Ui, @@ -613,6 +983,13 @@ impl Open { } } Action::Help => self.help = !self.help, + // the tabs belong to the window (`ViewerApp::apply_tab_action`) + Action::NewTab + | Action::CloseTab + | Action::NextTab + | Action::PreviousTab + | Action::GoToTab(_) + | Action::LastTab => {} Action::Escape => { if self.help { self.help = false; @@ -880,7 +1257,7 @@ mod tests { } fn open(app: &mut ViewerApp) -> &mut Open { - match &mut app.screen { + match app.screen_mut() { Screen::Open(open) => open, _ => panic!("no session is open"), } @@ -911,7 +1288,7 @@ mod tests { let mut app = ViewerApp::new(prefs_dir("empty")); let ctx = egui::Context::default(); frame(&mut app, &ctx, vec![]); - assert!(matches!(app.screen, Screen::Empty)); + assert!(matches!(app.screen(), Screen::Empty)); } #[test] @@ -925,11 +1302,11 @@ mod tests { app.open(&session.dir); let deadline = Instant::now() + Duration::from_secs(5); - while matches!(app.screen, Screen::Loading { .. }) && Instant::now() < deadline { + while matches!(app.screen(), Screen::Loading { .. }) && Instant::now() < deadline { frame(&mut app, &ctx, vec![]); std::thread::sleep(Duration::from_millis(20)); } - let Screen::Failed { message, .. } = &app.screen else { + let Screen::Failed { message, .. } = app.screen() else { panic!("the unfinished session opened"); }; assert!(message.contains("left unfinished"), "{message}"); @@ -943,7 +1320,10 @@ mod tests { let mut app = ViewerApp::new(prefs.clone()); app.open_now(&dir).expect("open"); - assert_eq!(Prefs::load(&prefs).recent, [dir.display().to_string()]); + assert_eq!( + Prefs::load(&prefs).recent, + [canonical(&dir).display().to_string()] + ); } #[test] @@ -1221,7 +1601,7 @@ mod tests { }); assert!(ctx.wants_keyboard_input()); let _ = ctx.run(input(vec![key(egui::Key::Space)]), |ctx| { - if let Screen::Open(open) = &mut app.screen { + if let Screen::Open(open) = app.screen_mut() { open.ui(ctx); } }); @@ -1419,6 +1799,399 @@ mod tests { frame(&mut app, &ctx, vec![]); } + fn names(app: &ViewerApp) -> Vec { + app.tabs() + .iter() + .map(|tab| match tab { + Screen::Empty => "empty".to_string(), + Screen::Loading { .. } => "loading".to_string(), + Screen::Failed { .. } => "failed".to_string(), + Screen::Open(open) => short(&open.loaded.dir), + }) + .collect() + } + + /// The name a test gave a session, without what the test kit adds to keep sessions apart. + fn short(dir: &Path) -> String { + let name = name_of(dir); + let name = name + .strip_prefix("komorebi-recorder-testkit-") + .unwrap_or(&name); + name.rsplit_once('-') + .map_or(name.to_string(), |(name, _)| name.to_string()) + } + + fn with_command(key: egui::Key, shift: bool) -> egui::Event { + egui::Event::Key { + key, + physical_key: Some(key), + pressed: true, + repeat: false, + modifiers: egui::Modifiers { + command: true, + ctrl: !cfg!(target_os = "macos"), + shift, + ..egui::Modifiers::NONE + }, + } + } + + fn ctrl_tab(shift: bool) -> egui::Event { + egui::Event::Key { + key: egui::Key::Tab, + physical_key: Some(egui::Key::Tab), + pressed: true, + repeat: false, + modifiers: egui::Modifiers { + ctrl: true, + shift, + ..egui::Modifiers::NONE + }, + } + } + + fn settle(app: &mut ViewerApp, ctx: &egui::Context) { + let deadline = Instant::now() + Duration::from_secs(10); + while app + .tabs() + .iter() + .any(|tab| matches!(tab, Screen::Loading { .. })) + && Instant::now() < deadline + { + frame(app, ctx, vec![]); + std::thread::sleep(Duration::from_millis(20)); + } + } + + #[test] + fn opening_from_a_start_tab_loads_into_it_and_from_a_session_adds_a_tab() { + let (a, b, c) = ( + session("viewer-tabs-a", false), + session("viewer-tabs-b", false), + session("viewer-tabs-c", false), + ); + let mut app = ViewerApp::new(prefs_dir("tabs-open")); + let ctx = egui::Context::default(); + + app.open(&a); + assert_eq!(app.tabs().len(), 1, "the start tab was used"); + settle(&mut app, &ctx); + assert_eq!(names(&app), ["viewer-tabs-a"]); + + app.open(&b); + assert_eq!(app.tabs().len(), 2); + assert_eq!(app.active_index(), 1, "the new tab is shown"); + settle(&mut app, &ctx); + app.open_now(&c).expect("open"); + assert_eq!( + names(&app), + ["viewer-tabs-a", "viewer-tabs-b", "viewer-tabs-c"] + ); + assert_eq!(app.active_index(), 2); + frame(&mut app, &ctx, vec![]); + + // a new tab is a start screen, and a session opened from it goes into it + app.new_tab(); + assert_eq!(app.tabs().len(), 4); + assert!(matches!(app.screen(), Screen::Empty)); + frame(&mut app, &ctx, vec![]); + app.open_now(&a).expect("already open"); + assert_eq!(app.tabs().len(), 4, "nothing was added"); + assert_eq!(app.active_index(), 0, "it focused the tab that has it"); + app.focus_tab(3); + app.open_now(&session("viewer-tabs-d", false)) + .expect("open"); + assert_eq!(app.tabs().len(), 4); + assert_eq!(app.active_index(), 3); + assert_eq!(names(&app)[3], "viewer-tabs-d"); + } + + #[test] + fn a_session_that_is_already_open_is_focused_not_opened_again() { + let a = session("viewer-dedupe-a", false); + let b = session("viewer-dedupe-b", false); + let mut app = ViewerApp::new(prefs_dir("dedupe")); + let ctx = egui::Context::default(); + app.open_now(&a).expect("open"); + app.open_now(&b).expect("open"); + assert_eq!(app.active_index(), 1); + + // by the same path, and by a path that reaches it another way + app.open(&a); + assert_eq!((app.tabs().len(), app.active_index()), (2, 0)); + let roundabout = a.join("..").join(name_of(&a)); + app.focus_tab(1); + app.open(&roundabout); + assert_eq!((app.tabs().len(), app.active_index()), (2, 0)); + settle(&mut app, &ctx); + assert!(matches!(app.screen(), Screen::Open(_)), "not reloaded"); + } + + #[test] + fn a_session_that_fails_keeps_its_tab_and_its_reason() { + let (unfinished, mut manifest) = SessionBuilder::new("viewer-tabs-unfinished").build(); + manifest.status = "recording".to_string(); + unfinished.write_manifest(&manifest).expect("manifest"); + let good = session("viewer-tabs-good", false); + + let mut app = ViewerApp::new(prefs_dir("tabs-failed")); + let ctx = egui::Context::default(); + app.open_now(&good).expect("open"); + app.open(&unfinished.dir); + assert_eq!(app.tabs().len(), 2, "the open session is not replaced"); + settle(&mut app, &ctx); + + let Screen::Failed { message, .. } = app.screen() else { + panic!("it should have failed"); + }; + assert!(message.contains("left unfinished"), "{message}"); + frame(&mut app, &ctx, vec![]); + + // the next session loads into the failed tab, as into any free one + app.open_now(&session("viewer-tabs-next", false)) + .expect("open"); + assert_eq!(app.tabs().len(), 2); + assert_eq!(names(&app), ["viewer-tabs-good", "viewer-tabs-next"]); + } + + #[test] + fn closing_tabs_keeps_one_and_picks_a_neighbour() { + let a = session("viewer-close-a", false); + let b = session("viewer-close-b", false); + let c = session("viewer-close-c", false); + let mut app = ViewerApp::new(prefs_dir("close")); + let ctx = egui::Context::default(); + for dir in [&a, &b, &c] { + app.open_now(dir).expect("open"); + } + assert_eq!(app.active_index(), 2); + + // closing a tab before the active one keeps the same session showing + app.close_tab(0); + assert_eq!(names(&app), ["viewer-close-b", "viewer-close-c"]); + assert_eq!(short(app.screen().dir().expect("dir")), "viewer-close-c"); + // closing the active last tab shows the one before + app.close_tab(1); + assert_eq!(names(&app), ["viewer-close-b"]); + assert_eq!(app.active_index(), 0); + // closing the last tab leaves a start screen, and the window draws it + app.close_tab(0); + assert!(matches!(app.screen(), Screen::Empty)); + assert_eq!(app.tabs().len(), 1); + frame(&mut app, &ctx, vec![]); + // an index that is not there does nothing + app.close_tab(7); + assert_eq!(app.tabs().len(), 1); + } + + #[test] + fn closing_a_session_cancels_its_scan() { + let dir = session("viewer-close-scan", false); + let mut app = ViewerApp::new(prefs_dir("close-scan")); + app.open_now(&dir).expect("open"); + let cancel = open(&mut app).changes_cancel.clone(); + assert!(!cancel.load(std::sync::atomic::Ordering::Relaxed)); + app.close_tab(0); + assert!(cancel.load(std::sync::atomic::Ordering::Relaxed)); + } + + #[test] + fn the_tab_keys_switch_close_and_open_tabs() { + let a = session("viewer-keys-a", false); + let b = session("viewer-keys-b", false); + let c = session("viewer-keys-c", false); + let mut app = ViewerApp::new(prefs_dir("tab-keys")); + let ctx = egui::Context::default(); + for dir in [&a, &b, &c] { + app.open_now(dir).expect("open"); + } + frame(&mut app, &ctx, vec![]); + + frame(&mut app, &ctx, vec![ctrl_tab(false)]); + assert_eq!(app.active_index(), 0, "next wraps round"); + frame(&mut app, &ctx, vec![ctrl_tab(true)]); + assert_eq!(app.active_index(), 2, "previous wraps round"); + // egui moved the focus for the Tab, and the window lets go of it again + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert!(!ctx.wants_keyboard_input()); + frame(&mut app, &ctx, vec![with_command(egui::Key::Num2, false)]); + assert_eq!(app.active_index(), 1); + frame(&mut app, &ctx, vec![with_command(egui::Key::Num9, false)]); + assert_eq!(app.active_index(), 2, "9 is the last"); + frame(&mut app, &ctx, vec![with_command(egui::Key::Num1, false)]); + assert_eq!(app.active_index(), 0); + frame(&mut app, &ctx, vec![with_command(egui::Key::Num8, false)]); + assert_eq!(app.active_index(), 0, "there is no eighth tab"); + frame( + &mut app, + &ctx, + vec![with_command(egui::Key::CloseBracket, true)], + ); + assert_eq!(app.active_index(), 1); + frame( + &mut app, + &ctx, + vec![with_command(egui::Key::OpenBracket, true)], + ); + assert_eq!(app.active_index(), 0); + + frame(&mut app, &ctx, vec![with_command(egui::Key::T, false)]); + assert_eq!(app.tabs().len(), 4); + assert!(matches!(app.screen(), Screen::Empty)); + // the start screen has no keys of its own, and the tab keys work there too + frame(&mut app, &ctx, vec![with_command(egui::Key::W, false)]); + assert_eq!(app.tabs().len(), 3); + frame(&mut app, &ctx, vec![with_command(egui::Key::W, false)]); + assert_eq!(app.tabs().len(), 2); + assert_eq!(names(&app), ["viewer-keys-a", "viewer-keys-b"]); + + // a plain Space still plays, in the active tab only + frame(&mut app, &ctx, vec![key(egui::Key::Space)]); + assert!(open(&mut app).playback.is_playing()); + } + + #[test] + fn typing_in_a_text_box_does_not_press_the_tab_keys() { + let mut app = ViewerApp::new(prefs_dir("tab-keys-typing")); + let ctx = egui::Context::default(); + ctx.memory_mut(|memory| memory.request_focus(egui::Id::new("a text box"))); + let _ = ctx.run(input(vec![]), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| { + let mut text = String::new(); + let response = + ui.add(egui::TextEdit::singleline(&mut text).id(egui::Id::new("a text box"))); + response.request_focus(); + }); + }); + assert!(ctx.wants_keyboard_input()); + let _ = ctx.run(input(vec![with_command(egui::Key::T, false)]), |ctx| { + app.ui(ctx); + }); + assert_eq!(app.tabs().len(), 1); + } + + #[test] + fn only_the_tab_in_view_plays() { + let a = session("viewer-play-a", false); + let b = session("viewer-play-b", false); + let mut app = ViewerApp::new(prefs_dir("play")); + let ctx = egui::Context::default(); + app.open_now(&a).expect("open"); + frame(&mut app, &ctx, vec![key(egui::Key::Space)]); + assert!(open(&mut app).playback.is_playing()); + + // opening another session hides the first, and pauses it + app.open_now(&b).expect("open"); + let Screen::Open(first) = &app.tabs()[0] else { + panic!("the first is open"); + }; + assert!(!first.playback.is_playing()); + + // and one set playing while hidden is stopped by the next frame + if let Screen::Open(first) = &mut app.tabs[0] { + first.playback.play(1.0); + } + frame(&mut app, &ctx, vec![]); + let Screen::Open(first) = &app.tabs()[0] else { + panic!("the first is open"); + }; + assert!(!first.playback.is_playing()); + + // each keeps its own place + app.focus_tab(0); + frame(&mut app, &ctx, vec![key(egui::Key::End)]); + let end = open(&mut app).position(); + app.focus_tab(1); + assert!(open(&mut app).position() < end); + } + + #[test] + fn a_request_from_another_process_opens_tabs_and_raises_the_window() { + let a = session("viewer-request-a", false); + let b = session("viewer-request-b", false); + let mut app = ViewerApp::new(prefs_dir("request")); + let ctx = egui::Context::default(); + + let request = ipc::Request { + open: vec![a.clone(), b.clone()], + focus: true, + }; + assert!(app.handle_request(&request)); + settle(&mut app, &ctx); + assert_eq!(names(&app), ["viewer-request-a", "viewer-request-b"]); + + // asking again for one that is open only focuses it + let again = ipc::Request { + open: vec![a], + focus: false, + }; + assert!(!app.handle_request(&again)); + assert_eq!((app.tabs().len(), app.active_index()), (2, 0)); + + // nothing to open: a start-screen tab, but not a second one + assert!(app.handle_request(&ipc::Request::default())); + assert_eq!(app.tabs().len(), 3); + assert!(app.handle_request(&ipc::Request::default())); + assert_eq!(app.tabs().len(), 3); + } + + #[test] + fn requests_over_the_socket_reach_the_window() { + let dir = std::env::temp_dir().join(format!("kr-viewer-socket-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("dir"); + let socket = dir.join("v.sock"); + let a = session("viewer-socket-a", false); + + let Ok(ipc::Claim::Serving(bound)) = ipc::claim(&socket, &ipc::Request::default()) else { + panic!("nobody is serving"); + }; + let mut app = ViewerApp::new(prefs_dir("socket")); + app.listen(bound.serve(|| {})); + let ctx = egui::Context::default(); + + let request = ipc::Request { + open: vec![a], + focus: true, + }; + assert_eq!( + ipc::send(&socket, &request).expect("sent"), + ipc::Delivery::Delivered + ); + let deadline = Instant::now() + Duration::from_secs(10); + while !matches!(app.screen(), Screen::Open(_)) && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(names(&app), ["viewer-socket-a"]); + + // closing the viewer removes the socket + drop(app); + assert!(!socket.exists()); + } + + #[test] + fn every_kind_of_tab_draws_in_the_bar() { + let (unfinished, mut manifest) = SessionBuilder::new("viewer-bar-unfinished").build(); + manifest.status = "recording".to_string(); + unfinished.write_manifest(&manifest).expect("manifest"); + let mut app = ViewerApp::new(prefs_dir("bar")); + let ctx = egui::Context::default(); + app.open_now(&session("viewer-bar-ok", false)) + .expect("open"); + app.open(&unfinished.dir); + frame(&mut app, &ctx, vec![]); + settle(&mut app, &ctx); + app.new_tab(); + frame(&mut app, &ctx, vec![]); + assert_eq!( + names(&app), + ["viewer-bar-ok", "failed", "empty"], + "open, failed and start tabs" + ); + } + #[test] fn the_agent_prompt_names_the_session_and_the_commands_to_start_with() { let prompt = super::super::inspector::agent_prompt(Path::new("/tmp/a session")); diff --git a/komorebi-recorder/src/viewer/ipc.rs b/komorebi-recorder/src/viewer/ipc.rs new file mode 100644 index 00000000..673f0bb5 --- /dev/null +++ b/komorebi-recorder/src/viewer/ipc.rs @@ -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, + /// 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, +} + +impl Reply { + fn accepted() -> Self { + Self { + ok: true, + error: None, + } + } + + fn refused(error: impl Into) -> 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 { + 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::(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 { + 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, + 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 { + 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, + stopping: Arc, + thread: Option>, +} + +impl Server { + /// Returns the requests that have arrived and not yet been taken, oldest first. + #[must_use] + pub fn requests(&self) -> Vec { + 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 { + 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 { + 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()); + } +} diff --git a/komorebi-recorder/src/viewer/keymap.rs b/komorebi-recorder/src/viewer/keymap.rs index efbc7c43..f196510c 100644 --- a/komorebi-recorder/src/viewer/keymap.rs +++ b/komorebi-recorder/src/viewer/keymap.rs @@ -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 { + 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 Option { + 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::>() .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}"); } } diff --git a/komorebi-recorder/src/viewer/loaded.rs b/komorebi-recorder/src/viewer/loaded.rs index 75b6b8d3..3481ad3c 100644 --- a/komorebi-recorder/src/viewer/loaded.rs +++ b/komorebi-recorder/src/viewer/loaded.rs @@ -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::*; diff --git a/komorebi-recorder/src/viewer/mod.rs b/komorebi-recorder/src/viewer/mod.rs index bccaefd3..cc001af2 100644 --- a/komorebi-recorder/src/viewer/mod.rs +++ b/komorebi-recorder/src/viewer/mod.rs @@ -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) -> eyre::Result<()> { - // before the window exists, so komorebi never sees a titled window it was not told to ignore +pub fn run(sessions: Vec, socket: Option<&Path>) -> eyre::Result<()> { + let bound = match socket { + Some(socket) => { + let sessions: Vec = 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) -> 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(),