diff --git a/README.md b/README.md index b8f1661f..71c8d33e 100644 --- a/README.md +++ b/README.md @@ -82,9 +82,10 @@ 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. 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. +`komorebi-recorder view ./repro` opens the recording in the window, which is where you mark where the bug is. There is +only ever one window, for recording and for reviewing: its first tab is **Record** and each recording is a tab after it. +Running `komorebi-recorder` or `view` again (or **Open session…** in the Record tab) raises that window instead of +making another, and `--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/DESIGN.md b/docs/DESIGN.md index b3158ace..5cf27fe8 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -83,13 +83,20 @@ recorded in the manifest, and everything that reads a session asks the manifest. ## Why can a bug only be marked in the viewer? -The recorder window has no button for marking a bug, and the viewer has one. I found it confusing to have two places to do -the same thing, so a bug is marked in the viewer only. `komorebi-recorder annotate` writes the same annotations for a +The Record tab has no button for marking a bug, and a session's tab has one. I found it confusing to have two places to do +the same thing, so a bug is marked in a session's tab only. `komorebi-recorder annotate` writes the same annotations for a script or an agent that has no window. -## Why is the recorder window untitled? +## Why is there one window? -komorebi does not manage windows with an empty title, so a borderless untitled window is never tiled: opening the recorder +Recording and reviewing used to be two windows, and the recorder's buttons for opening a recording started the other one. +Now the recorder is the pinned first tab of the one window and each recording is a tab after it, so there is one thing to +keep out of the video and out of komorebi's layout. It starts small, always on top, with only the Record tab, which is what +the old recorder window was for, and grows when a recording is opened. + +## Why is the window untitled? + +komorebi does not manage windows with an empty title, so an untitled window is never tiled: opening the recorder does not move the layout of the machine whose bug is being recorded. ## Why is ffmpeg not part of the program? diff --git a/docs/PLATFORM.md b/docs/PLATFORM.md index b5792fa8..9777476c 100644 --- a/docs/PLATFORM.md +++ b/docs/PLATFORM.md @@ -127,7 +127,10 @@ that a contact sheet never decodes more pixels than it shows. ### The program's own windows -The recorder window and the viewer must not be in the video they are recording, and komorebi must not tile them. +The program has one window, with the recorder as its first tab and the recordings as the others. It must not be in the +video it is recording, in either of its sizes (the small always-on-top one and the full one), and komorebi must not tile +it. Every `komorebi-recorder` launch (`gui`, `view`, no command, and `komorebi-recorder-gui.exe`) shares one local socket, +so there is never a second window to exclude. | | macOS | Windows | |---|---|---| diff --git a/docs/usage/investigating-a-recording.md b/docs/usage/investigating-a-recording.md index cd0ced8c..bc09a7f0 100644 --- a/docs/usage/investigating-a-recording.md +++ b/docs/usage/investigating-a-recording.md @@ -22,14 +22,15 @@ budget, 6 an `assert` check did not hold. komorebi-recorder view ``` -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. +opens the recording in the window, for the person who made it (or anyone with the folder) to play, scrub and mark. +The Record tab of the same 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 +There is only ever one window, for recording and for reviewing: its first tab is **Record** (see [Recording a bug +repro](recording-a-bug-repro.md#the-window)) and each recording is a tab after it. `komorebi-recorder view +...` (from another terminal, or from the Record tab) 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 (closing the +last one shows the Record tab), Ctrl-Tab and ⌘/Ctrl-1 to 9 move between them, ⌘/Ctrl-0 goes to the Record tab, 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, @@ -137,7 +138,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 | +| `view [SESSION...] [--new-window]` | Open recordings in the 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/docs/usage/recording-a-bug-repro.md b/docs/usage/recording-a-bug-repro.md index da3f619f..225da8cb 100644 --- a/docs/usage/recording-a-bug-repro.md +++ b/docs/usage/recording-a-bug-repro.md @@ -6,7 +6,7 @@ was the OS doing, at 00:12.5 in the video?" and the other way around. ``` komorebi-recorder record --duration 30 # record without a window -komorebi-recorder # or open the Record / Stop window +komorebi-recorder # or open the window, with its Record / Stop tab ``` It is built for the situations where komorebi bugs actually show up: laptops that get docked and undocked, woken with the @@ -46,7 +46,7 @@ Start komorebi with `komorebi.exe --log-level debug` before recording a bug. (`R prints every dependency's log; `RUST_LOG=komorebi=debug` does not.) `komorebi-recorder doctor` says what the machine can do, and `komorebi-recorder record --no-video` records without the screen. -The recorder window keeps itself out of the video (Windows 10 version 2004 or later). +The window keeps itself out of the video (Windows 10 version 2004 or later). ## Before you record @@ -58,9 +58,11 @@ The recorder window keeps itself out of the video (Windows 10 version 2004 or la - **`ffmpeg`** is only needed for `frames` and `selftest`. It is never used to capture. The `nix develop` shell provides it; otherwise `brew install ffmpeg`. -The recorder window is borderless, and on Windows is named `komorebi-recorder` only once komorebi is told to ignore it: +There is one window for everything. It opens small (the Record tab alone, always on top, to leave over the application +you are reproducing a bug in) and grows when you open a recording; see [The window](#the-window). On Windows it is named +`komorebi-recorder` only once komorebi is told to ignore it: at start the recorder runs `komorebic ignore-rule exe komorebi-recorder.exe` (and the same for -`komorebi-recorder-gui.exe`, which opens the viewer) against the running komorebi, a live rule that is not saved. If +`komorebi-recorder-gui.exe`, the build with no console window) against the running komorebi, a live rule that is not saved. If komorebi is not running the window is named too; if `komorebic` is not found or fails, and on a Mac, the window stays untitled, because komorebi does not manage windows without a title, and the recorder says so on standard error and in the window. Either way opening it does not move your layout around while you are trying to reproduce a layout bug. @@ -89,14 +91,33 @@ the same match is an `ignore_rules` entry with `kind: Exe`, `id: komorebi-record } ``` It is also excluded from the video, as is any other `komorebi-recorder` process. -The viewer is one such process. +The window is one such process, in either size. ## Recording -Press **Record**, reproduce the problem, press **Stop**. The window shows live counters, recent events (a display being -unplugged, a wake) and any warnings. The session is written to +Press **Record**, reproduce the problem, press **Stop**. The Record tab shows live counters, recent events (a display +being unplugged, a wake) and any warnings. The session is written to `~/Library/Application Support/komorebi/recordings//` unless you pass `--out`. +The **Review** row of the tab has **Open session…** (choose a recording's folder) and **Open last** (the newest one); +each opens the recording as a new tab of this same window, and the window grows to show it. + +### The window + +`komorebi-recorder` (or `komorebi-recorder gui`) opens one window, and there is never a second: starting it again, or +running `komorebi-recorder view `, raises the window that is already open instead. The first tab, **Record**, +cannot be closed, and says `REC` and the time in the tab bar while a recording is going, so you can look at another tab +and see that it still is (the recording carries on whichever tab is showing, and closing the window while recording +finishes the session first). The recordings you open follow it as tabs, and **+**, ⌘/Ctrl-T and ⌘/Ctrl-0 (the Record +tab) work as in a browser. + +Started plainly, the window is _compact_: 420 by 380, always on top, showing the Record tab and nothing else, the small +control window you leave over the application you are reproducing the bug in. **Expand** (on the Record tab) makes it +the full window with the tab bar, and opening a recording does that for you; **Compact** goes back, and the choice is +remembered. While recording, the full window has a **pin on top** checkbox. Options such as `--fps` or `--no-komorebi` +given to `komorebi-recorder`/`gui` set up the Record tab of the window that gets started; if a window is already open +they are ignored. `--new-window` opens a window of its own instead of raising the open one. + With every display ticked, the recorder follows _all_ displays, including ones connected while it is recording. Untick a display to record only the others. @@ -148,9 +169,10 @@ Useful options: ### Marking where the bug is -A bug is marked in one place, the viewer, after the recording: `komorebi-recorder view ` opens it, and **Mark -bug** (or **B**) takes a stretch of the recording and what went wrong in it. That marks a _region_, not a single moment. -The recorder window has no button for it, so while recording there is nothing to do but reproduce the problem. +A bug is marked in one place, a session's tab, after the recording: `komorebi-recorder view ` opens it (the +Record tab's **Open last** does too), and **Mark bug** (or **B**) takes a stretch of the recording and what went wrong in +it. That marks a _region_, not a single moment. The Record tab has no button for it, so while recording there is nothing +to do but reproduce the problem. This is what makes the recording useful to whoever investigates it, person or agent: your description is the ground truth of _what_ went wrong, and everything else in the session is evidence of _why_. See diff --git a/komorebi-recorder/src/app.rs b/komorebi-recorder/src/app.rs index f7103a07..17412b89 100644 --- a/komorebi-recorder/src/app.rs +++ b/komorebi-recorder/src/app.rs @@ -1,56 +1,64 @@ -//! The recorder window: Record / Stop, live counters and warnings. +//! The recorder tab: Record / Stop, live counters and warnings. //! -//! This is what `komorebi-recorder` opens when it is run with no subcommand, and with `gui`: [`run`] -//! shows a small window and keeps it until it is closed. It is the same recorder as -//! `komorebi-recorder record`, with a window instead of Ctrl-C. +//! The recorder is not a window of its own. It is the pinned first tab of the one window of the +//! program ([`crate::viewer`]), which `komorebi-recorder` (with no command) and `komorebi-recorder +//! gui` open, and which also holds a tab for every session being reviewed. This module is the +//! recorder itself, [`RecorderApp`]: the host window draws it into the Record tab with +//! [`RecorderApp::ui`] and, on every frame whichever tab is showing, calls [`RecorderApp::poll`], so +//! that a recording carries on, and is finalized, while a session is being looked at. [`run`] opens +//! the window; it is the same recorder as `komorebi-recorder record`, with a window instead of +//! Ctrl-C. //! -//! # What the window does +//! # What the tab does //! //! | control | effect | //! |---|---| //! | 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 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`]) | +//! | Stop | asks the recording to finish ([`Live::request_stop`]); it indexes and finalizes the session, which the tab shows as "finalizing..." | +//! | Open session..., Open last | open a recording as a new tab of this same window (a folder dialog, or the newest session); the window expands if it was compact | +//! | Compact / Expand | switches the window between the small control window and the full one ([`crate::viewer`]) | //! | 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 //! undocked appears or disappears and a new one starts ticked. With every display ticked the //! recorder follows all of them, including any connected while recording; with one unticked it -//! records only the ticked ones. While recording the window shows counters (video frames and the +//! records only the ticked ones. While recording the tab shows counters (video frames and the //! frames dropped, the size of komorebi's log, the number of komorebi events, the OS trace and each -//! of its streams), the most recent incidents to the recording environment, and any warnings. +//! of its streams), the most recent incidents to the recording environment, and any warnings, and +//! the tab's label in the tab bar says `REC` and the time. //! -//! The window does not mark where a bug is: that is done afterwards, in the viewer. +//! The tab does not mark where a bug is: that is done afterwards, in a session's tab. //! //! Closing the window while recording, or delivering SIGINT or SIGTERM to the process (the handler //! also runs on SIGHUP on Unix, and on Ctrl-C on Windows), finishes and indexes the session first -//! rather than leaving it half-written, and only then closes the window. +//! rather than leaving it half-written, and only then closes the window. With no recording the +//! window closes at once. //! //! # Staying out of the video and out of the layout //! //! The window is for use on the machine whose behavior is being recorded, so it must not appear in -//! the video and must not be tiled by komorebi. +//! the video and must not be tiled by komorebi. Both hold for the one window, in either size. //! //! - **Not in the video.** On macOS the capture filter excludes this whole application (this -//! process and every process named `komorebi-recorder`), so the controls never appear in the +//! process and every process named `komorebi-recorder`), so the window never appears in the //! video. On Windows a whole monitor is captured, so about once a second the window asks Windows //! to leave it out of captures (`WDA_EXCLUDEFROMCAPTURE`) through //! [`crate::platform::window::Chrome`]. -//! - **Not tiled.** The window is borderless, with its own drag handle and close button, and always -//! on top. It is named only when it is safely ignored ([`crate::komorebi_ignore`]): on Windows, -//! [`run`] first asks a running komorebi, with `komorebic ignore-rule exe`, to ignore the -//! recorder's executables (komorebi's live rule, nothing is written to `komorebi.json`), and +//! - **Not tiled.** The window is named only when it is safely ignored ([`crate::komorebi_ignore`]): +//! on Windows, [`run`] first asks a running komorebi, with `komorebic ignore-rule exe`, to ignore +//! the recorder's executables (komorebi's live rule, nothing is written to `komorebi.json`), and //! then titles the window `komorebi-recorder`; with no komorebi running it is titled too. If //! `komorebic` cannot be found or fails, and always on macOS (komorebi for Mac manages any window //! with a title, in `Window::should_manage`), the window stays untitled so that opening the //! recorder does not perturb the very layout being observed, and one line on standard error and -//! the window's message area say how to add the rule by hand. On Windows +//! the tab's message area say how to add the rule by hand. On Windows //! `KOMOREBI_RECORDER_PROBE_WINDOW=1` makes the window ask komorebi whether it would manage it //! (see [`crate::platform::window::PROBE_VARIABLE`]). //! -//! The window needs an `egui::Context` to draw and a screen to record, so it has no example. Its -//! logic that does not need either is covered by this module's unit test -//! (`the_latest_session_is_the_last_by_name_and_must_be_a_session`). +//! The tab needs an `egui::Ui` to draw and a screen to record, so it has no example. Its logic that +//! does not need either is covered by this module's unit test +//! (`the_latest_session_is_the_last_by_name_and_must_be_a_session`), and the tests of +//! `viewer::app` drive it inside the window. use crate::capture::DisplayDescriptor; use crate::cli::RecordArgs; @@ -112,25 +120,32 @@ pub fn latest_session_in(recordings: &std::path::Path) -> Option { .max() } -/// Open `session` (or just a start-screen tab, with none) in the viewer. +/// Open `session` (or just a start-screen tab, with none) in the program's window, from another +/// process. /// -/// 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<()> { +/// This is for a process that is not the window, such as a script or another tool: the window +/// itself opens sessions as tabs without any of this. If a window 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, and kept out +/// of the video (by name on macOS, and by each of its windows asking on Windows). It then becomes +/// the one window. +/// +/// # Errors +/// +/// Returns an error if the window refused the request, or none was running and `view` could not be +/// started. +pub 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, + ..ipc::Request::default() }; 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 + // on Windows the window 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!( "komorebi-recorder-gui{}", @@ -147,7 +162,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(crate::viewer::ipc::absolute(session)); + command.arg(ipc::absolute(session)); } command.spawn().map(|_| ()) } @@ -155,67 +170,57 @@ fn open_viewer(session: Option<&std::path::Path>) -> std::io::Result<()> { /// Set by SIGINT/SIGTERM: the window finishes any recording in progress, then closes. static QUIT: AtomicBool = AtomicBool::new(false); +/// Installs the handler that sets the quit flag on SIGINT and SIGTERM (it also runs on SIGHUP on +/// Unix, and on Ctrl-C on Windows), so that killing the window, or logging out, still finalizes a +/// recording in progress. Failing to install it (another is already installed) is ignored. +pub(crate) fn install_quit_handler() { + let _ = ctrlc::set_handler(|| QUIT.store(true, Ordering::SeqCst)); +} + /// How often the list of attached displays is refreshed while idle. const DISPLAY_REFRESH: Duration = Duration::from_secs(1); -/// Opens the recorder window and runs it until it is closed. +/// Opens the program's one window on the Record tab, in the small control window, and runs it +/// until it is closed. /// -/// `args` are the options of `komorebi-recorder record` that the window starts from, such as -/// `--fps`, `--codec` and `--no-komorebi`. Each recording uses them, except that the displays ticked in -/// the window replace `--display` (every display ticked means every display, including any +/// `args` are the options of `komorebi-recorder record` that the Record tab starts from, such as +/// `--fps`, `--codec` and `--no-komorebi`. Each recording uses them, except that the displays ticked +/// in the tab replace `--display` (every display ticked means every display, including any /// connected while recording) and a predicate typed under Advanced replaces `--predicate`. /// -/// This blocks the calling thread: the window's event loop runs on it. It installs a handler for -/// SIGINT and SIGTERM (it also runs on SIGHUP on Unix, and on Ctrl-C on Windows) that asks the -/// window to finish any recording in progress and close, so that killing the window, or logging -/// out, still finalizes the session. Failing to install the handler (another is already -/// installed) is ignored. +/// `socket` is the path of the window's socket ([`crate::viewer::ipc::default_socket`]), or `None` +/// for a window of its own that no other process can reach (`gui --new-window`). With a socket, if +/// a window is already running it is asked to show its Record tab and this returns `Ok` at once +/// without making a window, and `args` are ignored: they only seed the window that is started. /// -/// A recording that fails does not make this fail: the window shows why, and can record again. -/// -/// The window is 420 by 380 points (at least 360 by 260), borderless and always on top, titled `komorebi-recorder` only when komorebi ignores it: -/// see the [module documentation](self#staying-out-of-the-video-and-out-of-the-layout). Needs a -/// window, so there is no example. +/// This blocks the calling thread: the window's event loop runs on it. A recording that fails does +/// not make this fail: the tab shows why, and can record again. The window is described in +/// [`crate::viewer::run_with`]; whether it starts small comes from the preferences +/// ([`crate::viewer::prefs::Prefs::compact`]). Needs a window, so there is no example. /// /// # Errors /// -/// Returns an error saying "the recorder 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(args: RecordArgs) -> eyre::Result<()> { - // killing the window (or logging out) must still finalize a recording in progress - let _ = ctrlc::set_handler(|| QUIT.store(true, Ordering::SeqCst)); - - // before the window exists, so komorebi never sees a titled window it was not told to ignore - let setup = crate::komorebi_ignore::prepare_window(); - let options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - // titled only when komorebi ignores it (or is not running); see `komorebi_ignore` - .with_title(setup.title) - .with_app_id("komorebi-recorder") - .with_icon(crate::icon::window_icon()) - .with_decorations(false) - .with_inner_size([420.0, 380.0]) - .with_min_inner_size([360.0, 260.0]) - .with_always_on_top(), - ..Default::default() - }; - - eframe::run_native( - "komorebi-recorder", - options, - Box::new(move |_creation_context| { - let mut app = RecorderApp::new(args); - app.last = setup.note.map(Err); - Ok(Box::new(app)) - }), +/// Returns an error saying "the 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(args: RecordArgs, socket: Option<&std::path::Path>) -> eyre::Result<()> { + crate::viewer::run_with( + crate::viewer::Launch { + sessions: Vec::new(), + record: args, + show: crate::viewer::Show::Record, + }, + socket, ) - .map_err(|error| eyre::Report::msg(format!("the recorder window failed: {error}"))) } type Worker = JoinHandle>; -struct RecorderApp { - chrome: crate::platform::window::Chrome, +/// The recorder: what is needed to record, and the Record tab that shows it. +/// +/// The host window makes one with [`RecorderApp::new`], calls [`RecorderApp::poll`] on every frame +/// and [`RecorderApp::ui`] on the frames the Record tab is showing. It owns the recording's thread, +/// so dropping it without stopping leaves that thread to finish on its own. +pub struct RecorderApp { args: RecordArgs, live: Arc, worker: Option, @@ -226,12 +231,26 @@ struct RecorderApp { closing: bool, predicate: String, show_streams: bool, + quit: &'static AtomicBool, +} + +/// What the Record tab asks of the window in one frame. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct RecorderOutput { + /// "Open session…" was pressed: ask for a folder and open it in a tab. + pub choose: bool, + /// "Open last" was pressed: open this session in a tab. + pub open: Option, + /// "Compact" or "Expand" was pressed. + pub toggle_compact: bool, } impl RecorderApp { - fn new(args: RecordArgs) -> Self { + /// Returns a recorder that starts from `args`: see [`run`] for how they are used. It reads the + /// attached displays and whether the screen may be recorded, and records nothing. + #[must_use] + pub fn new(args: RecordArgs) -> Self { let mut app = Self { - chrome: crate::platform::window::Chrome::default(), predicate: args.predicate.clone().unwrap_or_default(), args, live: Live::new(), @@ -242,6 +261,7 @@ impl RecorderApp { last: None, closing: false, show_streams: false, + quit: &QUIT, }; app.refresh_displays(); @@ -275,10 +295,45 @@ impl RecorderApp { .collect(); } - fn recording(&self) -> bool { + /// Whether a recording is going: from pressing Record until its thread has been joined, + /// including while it finalizes. + #[must_use] + pub fn recording(&self) -> bool { self.worker.is_some() } + /// Says `note` in the tab as a message (as an error, in red), for something the window learned + /// before it was shown. + pub fn say(&mut self, note: String) { + self.last = Some(Err(note)); + } + + /// Returns the session the last recording saved, or `None` if none has finished since the + /// window was started, or one is going. + #[must_use] + pub fn saved(&self) -> Option<&std::path::Path> { + match &self.last { + Some(Ok(dir)) => Some(dir), + _ => None, + } + } + + /// Returns the text of the Record tab in the tab bar, and whether it is marking a recording + /// (so the window can draw it in red): `Record` when idle, `● REC 00:12` while recording. + #[must_use] + pub fn tab_label(&self) -> (String, bool) { + let snapshot = self.live.snapshot(); + if !self.recording() { + return ("Record".to_string(), false); + } + let text = match snapshot.phase { + Phase::Starting => "● starting…".to_string(), + Phase::Stopping => "● finalizing…".to_string(), + _ => format!("● REC {}", timecode::format(snapshot.elapsed_s)), + }; + (text, true) + } + fn start(&mut self) { let mut args = self.args.clone(); // with every display ticked, record *every* display including ones connected while @@ -309,7 +364,18 @@ impl RecorderApp { } } - fn poll(&mut self, context: &egui::Context) { + /// Does what the recorder has to do on every frame, whichever tab is showing: refreshes the + /// displays while idle, joins a recording that has finished (its session becomes + /// [`RecorderApp::saved`], or the reason it failed is shown), and honours a close request or + /// SIGINT/SIGTERM. While recording, those cancel the close, ask the recording to stop and close + /// the window once it has finalized; with none going they close it. It also asks `context` to + /// draw again soon, so the label of the tab keeps time. + pub fn poll(&mut self, context: &egui::Context) { + context.request_repaint_after(if self.recording() { + Duration::from_millis(200) + } else { + Duration::from_millis(500) + }); if !self.recording() && self.displays_refreshed.elapsed() >= DISPLAY_REFRESH { self.refresh_displays(); } @@ -325,7 +391,7 @@ impl RecorderApp { self.live.reset(); } - let quit_signalled = QUIT.load(Ordering::SeqCst); + let quit_signalled = self.quit.load(Ordering::SeqCst); if (quit_signalled || context.input(|input| input.viewport().close_requested())) && self.recording() { @@ -339,6 +405,230 @@ impl RecorderApp { context.send_viewport_cmd(egui::ViewportCommand::Close); } } + + /// Draws the Record tab into `ui`: the content of the tab, with no window chrome of its own. + /// + /// `compact` says whether the window is the small control window, which changes the label of + /// the button that switches it. It returns what the tab asked the window to do. + pub fn ui(&mut self, ui: &mut egui::Ui, compact: bool) -> RecorderOutput { + let mut output = RecorderOutput::default(); + let snapshot = self.live.snapshot(); + let recording = self.recording(); + let busy = matches!(snapshot.phase, Phase::Starting | Phase::Stopping); + + egui::ScrollArea::vertical() + .id_salt("record-tab") + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(egui::RichText::new("komorebi-recorder").strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (label, tip) = if compact { + ("Expand", "the full window, with tabs for sessions") + } else { + ("Compact", "the small window that stays on top") + }; + if ui.button(label).on_hover_text(tip).clicked() { + output.toggle_compact = true; + } + }); + }); + ui.separator(); + ui.horizontal(|ui| { + let can_record = !recording && self.permission && !self.displays.is_empty(); + if ui + .add_enabled( + can_record, + egui::Button::new("Record").min_size([110.0, 32.0].into()), + ) + .clicked() + { + self.start(); + } + + if ui + .add_enabled( + recording && !busy && !self.live.stop_requested(), + egui::Button::new("Stop").min_size([110.0, 32.0].into()), + ) + .clicked() + { + self.live.request_stop(); + } + + let state = match snapshot.phase { + Phase::Starting => "starting...".to_string(), + Phase::Recording => format!("REC {}", timecode::format(snapshot.elapsed_s)), + Phase::Stopping => "finalizing...".to_string(), + _ => "ready".to_string(), + }; + ui.label(egui::RichText::new(state).size(18.0).monospace()); + }); + + ui.separator(); + + // reviewing: open a recording in the viewer, which is its own window + ui.horizontal(|ui| { + ui.label(egui::RichText::new("Review").small().weak()); + if ui + .button("Open session…") + .on_hover_text("play and scrub a recording") + .clicked() + && let Err(error) = open_viewer(None) + { + self.last = Some(Err(format!("could not open the viewer: {error}"))); + } + + let last = match &self.last { + Some(Ok(dir)) => Some(dir.clone()), + _ => latest_session_in(&crate::session::default_recordings_dir()), + }; + if ui + .add_enabled(last.is_some(), egui::Button::new("Open last")) + .on_hover_text("the most recent recording") + .clicked() + && let Some(dir) = last + && let Err(error) = open_viewer(Some(&dir)) + { + self.last = Some(Err(format!("could not open the viewer: {error}"))); + } + }); + + ui.separator(); + + if !self.permission { + ui.colored_label( + egui::Color32::YELLOW, + "Screen Recording permission is needed to record the screen.", + ); + if ui.button("Grant permission").clicked() { + match capture::ensure_permission() { + Ok(()) => self.permission = true, + Err(error) => self.last = Some(Err(format!("{error:#}"))), + } + } + } else { + ui.add_enabled_ui(!recording, |ui| { + ui.horizontal_wrapped(|ui| { + ui.label("Displays:"); + for (display, selected) in &mut self.displays { + ui.checkbox( + selected, + format!( + "{} ({}×{})", + display.id, display.width_points, display.height_points + ), + ); + } + }); + }); + } + + if recording { + ui.add_space(6.0); + egui::Grid::new("counters").num_columns(2).show(ui, |ui| { + ui.label("displays"); + ui.label(if snapshot.displays_retrying.is_empty() { + format!("{} recording", snapshot.displays_recording) + } else { + format!( + "{} recording, waiting to retry {:?}", + snapshot.displays_recording, snapshot.displays_retrying + ) + }); + ui.end_row(); + ui.label("video frames"); + ui.label(format!( + "{} ({} dropped)", + snapshot.frames, snapshot.dropped + )); + ui.end_row(); + ui.label("komorebi log"); + ui.label(human_bytes(snapshot.log_bytes)); + ui.end_row(); + ui.label("komorebi events"); + ui.label(snapshot.events.to_string()); + ui.end_row(); + ui.label("OS trace"); + ui.label(format!( + "{} events, {} across {} streams", + snapshot.oslog_events, + human_bytes(snapshot.oslog_bytes), + snapshot.streams.len() + )); + ui.end_row(); + }); + + ui.collapsing("OS trace streams", |ui| { + self.show_streams = true; + for stream in &snapshot.streams { + ui.label(format!( + "{}: {} events, {}", + stream.name, + stream.events, + human_bytes(stream.bytes) + )); + } + }); + } else { + ui.collapsing("Advanced", |ui| { + ui.label("`system` OS trace predicate (blank for the default):"); + ui.text_edit_singleline(&mut self.predicate); + }); + } + + if !snapshot.incidents.is_empty() { + ui.add_space(6.0); + ui.label(egui::RichText::new("Recent events").small().weak()); + for incident in snapshot.incidents.iter().rev().take(4) { + ui.label(egui::RichText::new(incident).small().weak()); + } + } + + if !snapshot.warnings.is_empty() { + ui.add_space(6.0); + egui::ScrollArea::vertical() + .max_height(110.0) + .id_salt("warnings") + .show(ui, |ui| { + for warning in &snapshot.warnings { + ui.colored_label(egui::Color32::YELLOW, format!("! {warning}")); + } + }); + } + + match &self.last { + Some(Ok(dir)) => { + ui.add_space(8.0); + ui.separator(); + ui.label("Saved session:"); + ui.monospace(dir.display().to_string()); + ui.horizontal(|ui| { + if ui.button("Copy path").clicked() { + ui.ctx().copy_text(dir.display().to_string()); + } + + if ui + .button(format!("Open in {}", shell::FILE_MANAGER)) + .clicked() + { + shell::reveal(dir); + } + }); + ui.label(format!( + "Investigate it: komorebi-recorder brief {}", + dir.display() + )); + } + Some(Err(error)) => { + ui.add_space(8.0); + ui.colored_label(egui::Color32::LIGHT_RED, error); + } + None => {} + } + }); + output + } } fn human_bytes(bytes: u64) -> String { @@ -357,230 +647,43 @@ fn human_bytes(bytes: u64) -> String { } } -impl eframe::App for RecorderApp { - fn update(&mut self, context: &egui::Context, _frame: &mut eframe::Frame) { - self.chrome.tick(); - self.poll(context); - context.request_repaint_after(Duration::from_millis(200)); +#[cfg(test)] +impl RecorderApp { + /// A recorder that touches no screen: no permission check, no displays, and its own quit flag, + /// for the tests of the window. + pub(crate) fn quiet(quit: &'static AtomicBool) -> Self { + Self { + args: RecordArgs::default(), + live: Live::new(), + worker: None, + permission: true, + displays: Vec::new(), + displays_refreshed: Instant::now(), + last: None, + closing: false, + predicate: String::new(), + show_streams: false, + quit, + } + } - let snapshot = self.live.snapshot(); - let recording = self.recording(); - let busy = matches!(snapshot.phase, Phase::Starting | Phase::Stopping); - - egui::CentralPanel::default().show(context, |ui| { - // drag handle and close button, since there is no title bar - let header = egui::Rect::from_min_size( - ui.min_rect().min, - egui::vec2(ui.available_width(), 24.0), - ); - let drag = ui.interact(header, ui.id().with("drag"), egui::Sense::drag()); - if drag.drag_started() { - context.send_viewport_cmd(egui::ViewportCommand::StartDrag); - } - - ui.horizontal(|ui| { - ui.label(egui::RichText::new("komorebi-recorder").strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("×").on_hover_text("Close").clicked() { - context.send_viewport_cmd(egui::ViewportCommand::Close); - } - }); - }); - ui.separator(); - - ui.horizontal(|ui| { - let can_record = !recording && self.permission && !self.displays.is_empty(); - if ui - .add_enabled( - can_record, - egui::Button::new("Record").min_size([110.0, 32.0].into()), - ) - .clicked() - { - self.start(); - } - - if ui - .add_enabled( - recording && !busy && !self.live.stop_requested(), - egui::Button::new("Stop").min_size([110.0, 32.0].into()), - ) - .clicked() - { - self.live.request_stop(); - } - - let state = match snapshot.phase { - Phase::Starting => "starting...".to_string(), - Phase::Recording => format!("REC {}", timecode::format(snapshot.elapsed_s)), - Phase::Stopping => "finalizing...".to_string(), - _ => "ready".to_string(), - }; - ui.label(egui::RichText::new(state).size(18.0).monospace()); - }); - - ui.separator(); - - // reviewing: open a recording in the viewer, which is its own window - ui.horizontal(|ui| { - ui.label(egui::RichText::new("Review").small().weak()); - if ui - .button("Open session…") - .on_hover_text("play and scrub a recording") - .clicked() - && let Err(error) = open_viewer(None) - { - self.last = Some(Err(format!("could not open the viewer: {error}"))); - } - - let last = match &self.last { - Some(Ok(dir)) => Some(dir.clone()), - _ => latest_session_in(&crate::session::default_recordings_dir()), - }; - if ui - .add_enabled(last.is_some(), egui::Button::new("Open last")) - .on_hover_text("the most recent recording") - .clicked() - && let Some(dir) = last - && let Err(error) = open_viewer(Some(&dir)) - { - self.last = Some(Err(format!("could not open the viewer: {error}"))); - } - }); - - ui.separator(); - - if !self.permission { - ui.colored_label( - egui::Color32::YELLOW, - "Screen Recording permission is needed to record the screen.", - ); - if ui.button("Grant permission").clicked() { - match capture::ensure_permission() { - Ok(()) => self.permission = true, - Err(error) => self.last = Some(Err(format!("{error:#}"))), - } - } - } else { - ui.add_enabled_ui(!recording, |ui| { - ui.horizontal_wrapped(|ui| { - ui.label("Displays:"); - for (display, selected) in &mut self.displays { - ui.checkbox( - selected, - format!( - "{} ({}×{})", - display.id, display.width_points, display.height_points - ), - ); - } - }); - }); - } - - if recording { - ui.add_space(6.0); - egui::Grid::new("counters").num_columns(2).show(ui, |ui| { - ui.label("displays"); - ui.label(if snapshot.displays_retrying.is_empty() { - format!("{} recording", snapshot.displays_recording) - } else { - format!( - "{} recording, waiting to retry {:?}", - snapshot.displays_recording, snapshot.displays_retrying - ) - }); - ui.end_row(); - ui.label("video frames"); - ui.label(format!( - "{} ({} dropped)", - snapshot.frames, snapshot.dropped - )); - ui.end_row(); - ui.label("komorebi log"); - ui.label(human_bytes(snapshot.log_bytes)); - ui.end_row(); - ui.label("komorebi events"); - ui.label(snapshot.events.to_string()); - ui.end_row(); - ui.label("OS trace"); - ui.label(format!( - "{} events, {} across {} streams", - snapshot.oslog_events, - human_bytes(snapshot.oslog_bytes), - snapshot.streams.len() - )); - ui.end_row(); - }); - - ui.collapsing("OS trace streams", |ui| { - self.show_streams = true; - for stream in &snapshot.streams { - ui.label(format!( - "{}: {} events, {}", - stream.name, - stream.events, - human_bytes(stream.bytes) - )); - } - }); - } else { - ui.collapsing("Advanced", |ui| { - ui.label("`system` OS trace predicate (blank for the default):"); - ui.text_edit_singleline(&mut self.predicate); - }); - } - - if !snapshot.incidents.is_empty() { - ui.add_space(6.0); - ui.label(egui::RichText::new("Recent events").small().weak()); - for incident in snapshot.incidents.iter().rev().take(4) { - ui.label(egui::RichText::new(incident).small().weak()); - } - } - - if !snapshot.warnings.is_empty() { - ui.add_space(6.0); - egui::ScrollArea::vertical() - .max_height(110.0) - .id_salt("warnings") - .show(ui, |ui| { - for warning in &snapshot.warnings { - ui.colored_label(egui::Color32::YELLOW, format!("! {warning}")); - } - }); - } - - match &self.last { - Some(Ok(dir)) => { - ui.add_space(8.0); - ui.separator(); - ui.label("Saved session:"); - ui.monospace(dir.display().to_string()); - ui.horizontal(|ui| { - if ui.button("Copy path").clicked() { - context.copy_text(dir.display().to_string()); - } - - if ui - .button(format!("Open in {}", shell::FILE_MANAGER)) - .clicked() - { - shell::reveal(dir); - } - }); - ui.label(format!( - "Investigate it: komorebi-recorder brief {}", - dir.display() - )); - } - Some(Err(error)) => { - ui.add_space(8.0); - ui.colored_label(egui::Color32::LIGHT_RED, error); - } - None => {} - } + /// Makes the recorder look as if `worker` were a recording that has begun, with `phase`. + pub(crate) fn pretend(&mut self, worker: Worker, phase: Phase, elapsed_s: f64) { + self.live.update(|snapshot| { + snapshot.phase = phase; + snapshot.elapsed_s = elapsed_s; }); + self.worker = Some(worker); + } + + /// The handle the recording would publish through. + pub(crate) fn live(&self) -> Arc { + self.live.clone() + } + + /// Whether the recorder has been asked to close the window once the recording is done. + pub(crate) fn closing(&self) -> bool { + self.closing } } diff --git a/komorebi-recorder/src/bin/komorebi-recorder-gui.rs b/komorebi-recorder/src/bin/komorebi-recorder-gui.rs index 5ffbe363..8fcf773c 100644 --- a/komorebi-recorder/src/bin/komorebi-recorder-gui.rs +++ b/komorebi-recorder/src/bin/komorebi-recorder-gui.rs @@ -1,11 +1,13 @@ //! The same program as `komorebi-recorder`, built for the Windows GUI subsystem: it opens no -//! console window, which is what a shortcut or the recorder window launching the viewer wants. +//! console window, which is what a shortcut wants. //! Its output goes nowhere, so use `komorebi-recorder` to run a command and read what it prints. //! (On other systems there is no such distinction and this is the same binary.) //! //! `main` is [`komorebi_recorder::cli::main`], as it is for `komorebi-recorder`: it reads the -//! command line and runs the command, and with no command opens the recorder window -//! ([`komorebi_recorder::app::run`]). The recorder window starts the viewer by running this +//! command line and runs the command, and with no command opens the one window on its Record tab +//! ([`komorebi_recorder::app::run`]). It shares the window's socket with `komorebi-recorder`, so +//! whichever of the two is started second raises the window the first one opened. A process that +//! wants a window to open a recording ([`komorebi_recorder::app::open_viewer`]) starts this //! executable with `view` when it is next to the one that is running (on Windows), so that //! opening a recording does not open a console window beside it. #![cfg_attr(windows, windows_subsystem = "windows")] diff --git a/komorebi-recorder/src/cli/mod.rs b/komorebi-recorder/src/cli/mod.rs index b5ef749c..9963e30f 100644 --- a/komorebi-recorder/src/cli/mod.rs +++ b/komorebi-recorder/src/cli/mod.rs @@ -63,6 +63,7 @@ pub use video::CompareArgs; pub use video::FramediffArgs; pub use video::MotionArgs; pub use video::SheetArgs; +pub use viewer_command::GuiArgs; pub use viewer_command::ViewArgs; /// The command line of `komorebi-recorder`. @@ -76,7 +77,7 @@ pub use viewer_command::ViewArgs; all on one clock, into a session directory. \ Then ask what was happening at any second of the video, or where in the video any \ log line or event is.\n\n\ - Run with no subcommand to open the recorder window." + Run with no subcommand to open the window on its Record tab." )] pub struct Opts { /// The command to run. @@ -87,8 +88,12 @@ pub struct Opts { /// What `komorebi-recorder` was asked to do. #[derive(Subcommand)] pub enum Command { - /// Open the recorder window with Record / Stop buttons (the default) - Gui(RecordArgs), + /// Open the window, on its Record tab, with Record / Stop buttons (the default) + /// + /// There is only ever one window, for recording and for reviewing sessions. If one is already + /// running it is raised and shown on its Record tab, and the options given here are ignored: + /// they only set up the window that is started. + Gui(GuiArgs), /// Record without a window; Ctrl-C (or --duration) stops and finalizes the session Record(RecordArgs), /// List the displays that can be recorded @@ -140,7 +145,7 @@ pub enum Command { Compare(CompareArgs), /// A contact sheet image of frames, with the times, events and bug region marked Sheet(SheetArgs), - /// Open a recording in a window: play and scrub the video with every event on a timeline + /// Open a recording as a tab of the window: play and scrub the video with every event on a timeline View(ViewArgs), /// Which line of komorebi's source wrote a line of its log, with the code around it Code(CodeArgs), @@ -276,7 +281,10 @@ pub fn execute(command: Command) -> std::process::ExitCode { /// Returns whatever error the command fails with; [`execute`] turns it into an exit status. pub fn run(command: Command) -> eyre::Result<()> { match command { - Command::Gui(args) => crate::app::run(args), + Command::Gui(args) => { + let socket = (!args.new_window).then(crate::viewer::ipc::default_socket); + crate::app::run(args.record, socket.as_deref()) + } Command::Record(args) => record::record(&args), Command::Displays(args) => record::displays(&args), Command::Doctor(args) => doctor::doctor(&args), @@ -320,7 +328,7 @@ pub fn run(command: Command) -> eyre::Result<()> { /// What both binaries (`komorebi-recorder` and, on Windows, the no-console /// `komorebi-recorder-gui`) do: read the command line and run it. -/// No command opens the recorder window. +/// No command opens the window on its Record tab. /// /// # Errors /// @@ -335,7 +343,7 @@ pub fn main() -> eyre::Result { let opts = Opts::parse(); Ok(execute( opts.command - .unwrap_or_else(|| Command::Gui(RecordArgs::default())), + .unwrap_or_else(|| Command::Gui(GuiArgs::default())), )) } diff --git a/komorebi-recorder/src/cli/record.rs b/komorebi-recorder/src/cli/record.rs index 40b64b0a..8d6f9413 100644 --- a/komorebi-recorder/src/cli/record.rs +++ b/komorebi-recorder/src/cli/record.rs @@ -1,7 +1,7 @@ //! `record`, `gui` and `displays`: the arguments of a recording and the headless recorder. //! //! [`RecordArgs`] is the one set of options for both ways of recording: `record` runs without a -//! window and `gui` opens the recorder window with the same options as its starting settings. +//! window and `gui` opens the window, on its Record tab, with the same options as its starting settings. //! [`RecordArgs::to_options`] turns them into the [`RecordOptions`] that [`recorder::record`] takes. //! //! `record --until-exit -- ` runs a command while recording and stops when it exits (see diff --git a/komorebi-recorder/src/cli/viewer_command.rs b/komorebi-recorder/src/cli/viewer_command.rs index 67703f3e..e2fa674e 100644 --- a/komorebi-recorder/src/cli/viewer_command.rs +++ b/komorebi-recorder/src/cli/viewer_command.rs @@ -1,17 +1,34 @@ -//! `view`: the arguments of the viewer window. +//! `gui` and `view`: the arguments of the one window. //! -//! The command table runs the command with `crate::viewer::run`; this file holds only its arguments. +//! The command table runs `gui` with `crate::app::run` and `view` with `crate::viewer::run`; this +//! file holds only their arguments. +use super::RecordArgs; use clap::Args; use std::path::PathBuf; +/// The arguments of `gui` (and of running with no command): the options the Record tab starts +/// from, which are those of `record`. +/// +/// If a window is already running they are ignored: the second launch only raises it and shows its +/// Record tab. +#[derive(Args, Clone, Debug, Default)] +pub struct GuiArgs { + /// The options of `record`, which each recording started from the window uses + #[command(flatten)] + pub record: RecordArgs, + /// Open a window of its own, instead of raising the one that is already running + #[arg(long)] + pub new_window: bool, +} + /// The arguments of `view`: the sessions to open, if any are given. #[derive(Args, Debug)] pub struct ViewArgs { - /// The recordings' folders, each opened as a tab of the one viewer window [default: choose + /// The recordings' folders, each opened as a tab of the one 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 + /// Open a window of its own, instead of a tab of the window that is already running #[arg(long)] pub new_window: bool, } diff --git a/komorebi-recorder/src/komorebi_ignore.rs b/komorebi-recorder/src/komorebi_ignore.rs index 0d0c9bc2..6bcea8c1 100644 --- a/komorebi-recorder/src/komorebi_ignore.rs +++ b/komorebi-recorder/src/komorebi_ignore.rs @@ -1,6 +1,6 @@ //! Naming the recorder's windows, and telling komorebi to leave them alone. //! -//! The recorder window and the viewer are used on the machine whose behavior is being investigated, so komorebi +//! The program's one window (the Record tab and the tabs of recordings) is used on the machine whose behavior is being investigated, so komorebi //! must not tile them. For a long time that was done by giving them no title at all, which komorebi does not //! manage. This module lets them have a real title, `komorebi-recorder`, on one condition: _the window is only //! named when it is safely ignored_. @@ -36,7 +36,7 @@ use std::time::Instant; /// The title of the windows when it is safe to give them one. pub const TITLE: &str = "komorebi-recorder"; -/// The executable of the windows that have no console, which the recorder window opens the viewer with. +/// The executable of the windows that have no console, which a process that opens a recording in the window starts it with. pub const GUI_EXE: &str = "komorebi-recorder-gui.exe"; /// How long `komorebic ignore-rule` has before it is killed. @@ -194,7 +194,7 @@ pub fn describe_exit(code: i32) -> String { /// Registers an ignore rule for each of the recorder's executables, if komorebi is running and a `komorebic` is /// found. Pure apart from what `runner` does; `current` is this executable's file name. /// -/// Each `komorebic` that exists is tried in turn ([`candidates`]), and the first that registers every rule +/// Each `komorebic` that exists is tried in turn (`candidates`), and the first that registers every rule /// wins. One that crashes or refuses does not end the attempt while another is left; if none works the /// failure names every one tried and how it failed. pub fn ensure_with(runner: &mut dyn Runner, current: &str, windows: bool) -> Outcome { @@ -350,9 +350,18 @@ fn current_exe_name() -> String { }) } +/// The environment variable that stops [`ensure_self_ignored`] from running `komorebic` at all, for trying the +/// window out (or testing it end to end) on a machine whose real komorebi must not be told anything. The window is +/// then not titled. It is not meant for anything else. +pub const SKIP_VARIABLE: &str = "KOMOREBI_RECORDER_NO_IGNORE_RULE"; + /// Registers the ignore rules for this machine's real komorebi (see the [module documentation](self)). Call it -/// before a window is created. +/// before a window is created. With [`SKIP_VARIABLE`] set it registers nothing and returns +/// [`Outcome::NotApplicable`]. pub fn ensure_self_ignored() -> Outcome { + if std::env::var_os(SKIP_VARIABLE).is_some_and(|value| !value.is_empty()) { + return Outcome::NotApplicable; + } ensure_with(&mut SystemRunner, ¤t_exe_name(), cfg!(windows)) } diff --git a/komorebi-recorder/src/lib.rs b/komorebi-recorder/src/lib.rs index 55c8620a..aad540a2 100644 --- a/komorebi-recorder/src/lib.rs +++ b/komorebi-recorder/src/lib.rs @@ -57,12 +57,12 @@ //! | [`recovery`] | rebuilding a session whose recorder died | //! | [`cli`] | the command line | //! | [`icon`] | the icon of the windows | -//! | [`app`] | the recorder window | +//! | [`app`] | the recorder: the Record tab of the one window | //! | [`av`] and [`selftest`] | decoding the recorded video and checking it against the clocks | //! | [`doctor`] | what a recording leans on, and probes that measure it | //! | [`report`] | answers as text for a terminal | //! | [`playback`] | a clock that runs forwards or backwards, and the decoding that follows it | -//! | [`viewer`] | the window that plays a recording | +//! | [`viewer`] | the one window: the Record tab, and a tab for each recording that is played | //! //! # What is not supported //! diff --git a/komorebi-recorder/src/platform/window.rs b/komorebi-recorder/src/platform/window.rs index 95354038..def424d7 100644 --- a/komorebi-recorder/src/platform/window.rs +++ b/komorebi-recorder/src/platform/window.rs @@ -1,6 +1,6 @@ //! What this program's windows do about being in the video and being tiled, which differs by OS. //! -//! The recorder window ([`crate::app`]) and the viewer must not be in the video they are +//! The program's one window ([`crate::viewer`], with the recorder of [`crate::app`] as a tab) must not be in the video it is //! recording, and komorebi must not tile them. The two hosts get there differently: //! //! | | macOS | Windows | diff --git a/komorebi-recorder/src/recorder.rs b/komorebi-recorder/src/recorder.rs index ba004ef2..4250062e 100644 --- a/komorebi-recorder/src/recorder.rs +++ b/komorebi-recorder/src/recorder.rs @@ -287,7 +287,7 @@ impl Live { *self.snapshot.lock() = LiveSnapshot::default(); } - fn update(&self, change: impl FnOnce(&mut LiveSnapshot)) { + pub(crate) fn update(&self, change: impl FnOnce(&mut LiveSnapshot)) { change(&mut self.snapshot.lock()); } } diff --git a/komorebi-recorder/src/viewer/app.rs b/komorebi-recorder/src/viewer/app.rs index 588cb167..e368ef5b 100644 --- a/komorebi-recorder/src/viewer/app.rs +++ b/komorebi-recorder/src/viewer/app.rs @@ -1,8 +1,10 @@ -//! The viewer window: opening a session and keeping everything on screen in step. +//! The window: the Record tab, opening a session and keeping everything on screen in step. //! -//! [`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 +//! [`ViewerApp`] is the whole application. It holds the recorder ([`RecorderApp`]), which is the +//! pinned first tab and cannot be closed, and after it a tab for each session, 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, @@ -26,6 +28,7 @@ use super::timeline::View; use crate::analysis::guard::SessionPath; use crate::analysis::state::Snapshot; use crate::analysis::trace::TraceData; +use crate::app::RecorderApp; use crate::playback::Playback; use color_eyre::eyre; use crossbeam_channel::Receiver; @@ -184,13 +187,23 @@ impl Screen { } } -/// The viewer application: the preferences and the tabs of the window. +/// The application: the recorder, the preferences and the tabs of the window. /// -/// 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. +/// This is what [`run`](super::run) hands to `eframe`. [`ViewerApp::new`] makes one showing the +/// Record tab with no session tabs, [`ViewerApp::open`] opens a session in a tab, and +/// [`ViewerApp::ui`] draws a frame. The Record tab is always first and cannot be closed; the +/// session tabs ([`ViewerApp::tabs`]) follow it, and closing the last of them leaves the Record +/// tab showing. Exactly one tab is showing; the others keep their state (an open session keeps its +/// playhead, its selection and its scan) but their video is paused, while a recording carries on +/// whichever tab is showing. It needs a window to draw and so has no example. +/// +/// # The two sizes +/// +/// The window is either *compact*, the small always-on-top control window that shows the Record tab +/// alone, or expanded, with the tab bar. Starting with no session to show gives the size the +/// preferences remember ([`Prefs::compact`]); showing any session tab expands it, and the Compact +/// button of the Record tab goes back. The window is resized and pinned on top with viewport +/// commands, by [`ViewerApp::ui`], whenever the mode changed. /// /// # Opening a session /// @@ -204,8 +217,19 @@ pub struct ViewerApp { /// switched. pub prefs: Prefs, prefs_dir: PathBuf, + recorder: RecorderApp, + /// Whether the Record tab, rather than a session tab, is the one showing. + record_active: bool, tabs: Vec, + /// The session tab showing, or the one that was when the Record tab is. active: usize, + compact: bool, + /// Whether the window is kept on top while it is not compact. + pinned: bool, + /// The (compact, on top) the window was last put in, so it is only told when that changes. + applied: (bool, bool), + /// The size of the expanded window, to go back to after being compact. + full_size: egui::Vec2, picker: Option>>, server: Option, release_focus: bool, @@ -228,21 +252,113 @@ fn canonical(dir: &Path) -> PathBuf { } impl ViewerApp { - /// Returns a viewer with one start-screen tab, with the preferences kept in `prefs_dir`. + /// Returns an app showing the Record tab, with the preferences kept in `prefs_dir`, and no + /// session tabs. /// /// The preferences are read with [`Prefs::load`], so a missing or damaged file gives the - /// defaults. Nothing is opened: see [`ViewerApp::open`]. + /// defaults; the window is compact if they say so. Nothing is opened: see [`ViewerApp::open`]. #[must_use] pub fn new(prefs_dir: PathBuf) -> Self { - Self { - prefs: Prefs::load(&prefs_dir), + Self::start( prefs_dir, - tabs: vec![Screen::Empty], + super::Launch::record(crate::cli::RecordArgs::default()), + ) + } + + /// Returns the app a launch asks for: the recorder seeded with its options, and its sessions + /// opened (see [`ViewerApp::open`]). + /// + /// A launch that shows the Record tab is compact if the preferences say so; one that shows + /// sessions is expanded, and with none shows a start screen. The preferences are not changed + /// by that: only the Compact and Expand buttons write them. + #[must_use] + pub fn start(prefs_dir: PathBuf, launch: super::Launch) -> Self { + let prefs = Prefs::load(&prefs_dir); + let compact = launch.starts_compact(&prefs); + let mut app = Self { + prefs, + prefs_dir, + recorder: RecorderApp::new(launch.record), + record_active: true, + tabs: Vec::new(), active: 0, + compact, + pinned: false, + applied: (compact, compact), + full_size: egui::vec2(FULL_SIZE[0], FULL_SIZE[1]), picker: None, server: None, release_focus: false, + }; + if matches!(launch.show, super::Show::Sessions) { + for dir in &launch.sessions { + app.open(dir); + } + if launch.sessions.is_empty() { + app.new_tab(); + } } + app + } + + /// Returns the recorder, the content of the Record tab. + #[must_use] + pub fn recorder(&self) -> &RecorderApp { + &self.recorder + } + + /// Returns the recorder, to change. + pub fn recorder_mut(&mut self) -> &mut RecorderApp { + &mut self.recorder + } + + /// Whether the Record tab, rather than a session tab, is showing. + #[must_use] + pub fn record_active(&self) -> bool { + self.record_active + } + + /// Whether the window is the small control window. + #[must_use] + pub fn is_compact(&self) -> bool { + self.compact + } + + /// Whether the window is on top: always when compact, and when pinned otherwise. + #[must_use] + pub fn is_on_top(&self) -> bool { + self.compact || self.pinned + } + + /// Switches between the small control window and the full one, and remembers which in the + /// preferences. Becoming compact shows the Record tab, which is all a compact window has; + /// expanding shows the tab bar and no longer keeps the window on top. + pub fn toggle_compact(&mut self) { + let compact = !self.compact; + self.set_compact(compact); + self.prefs.compact = compact; + self.prefs.save(&self.prefs_dir); + } + + /// Makes the window compact or not, without touching the preferences: what opening a session + /// does (it expands the window so the session shows). The resizing itself is done by the next + /// [`ViewerApp::ui`]. + pub fn set_compact(&mut self, compact: bool) { + if compact == self.compact { + return; + } + self.compact = compact; + if compact { + self.show_record(); + } else { + self.pinned = false; + } + } + + /// Shows the Record tab. The session tab that was showing is paused. + pub fn show_record(&mut self) { + self.record_active = true; + self.pause_hidden(); } /// Takes requests from other processes through `server` from now on: see @@ -251,27 +367,38 @@ impl ViewerApp { self.server = Some(server); } - /// Returns every tab, in order. + /// Returns every session tab, in order: the ones after the Record tab. #[must_use] pub fn tabs(&self) -> &[Screen] { &self.tabs } - /// Returns the index of the tab being shown. + /// Returns the index, among [`ViewerApp::tabs`], of the session tab being shown, or that of the + /// one that was shown last while the Record tab is. #[must_use] pub fn active_index(&self) -> usize { self.active } - /// Returns what the tab being shown has in it. + /// Returns what the session tab being shown has in it, or `None` while the Record tab is + /// showing. #[must_use] - pub fn screen(&self) -> &Screen { - &self.tabs[self.active] + pub fn screen(&self) -> Option<&Screen> { + if self.record_active { + None + } else { + self.tabs.get(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 what the session tab being shown has in it, to change, or `None` while the Record + /// tab is showing. + pub fn screen_mut(&mut self) -> Option<&mut Screen> { + if self.record_active { + None + } else { + self.tabs.get_mut(self.active) + } } /// Returns the index of the tab that has the session in `dir` (already [`canonical`]) in it. @@ -310,10 +437,10 @@ impl ViewerApp { 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. + /// Returns the tab a session that is not open yet goes in: the current one if it is a free + /// session tab, else a new one at the end. The Record tab is never one. fn slot_for_new_session(&mut self) -> usize { - if self.tabs[self.active].is_free() { + if !self.record_active && self.tabs.get(self.active).is_some_and(Screen::is_free) { self.active } else { self.tabs.push(Screen::Empty); @@ -402,19 +529,22 @@ impl ViewerApp { Ok(open) } - /// Adds a start-screen tab at the end and shows it. + /// Adds a start-screen session 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); } - /// 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. + /// Shows session tab `index`, and expands the window if it was compact, so the session shows. + /// 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.record_active = false; + self.set_compact(false); self.pause_hidden(); if let Screen::Open(open) = &mut self.tabs[index] { // the overlay is one setting for the window, not one per tab @@ -422,11 +552,11 @@ impl ViewerApp { } } - /// Pauses every tab but the active one. Decoding stops with the playhead, and a hidden tab's - /// scan for changes carries on. + /// Pauses every tab but the active one (all of them, with the Record tab showing). 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 + if (index != self.active || self.record_active) && let Screen::Open(open) = tab && open.playback.is_playing() { @@ -435,8 +565,9 @@ impl ViewerApp { } } - /// 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 + /// Closes session tab `index`; the Record tab is not one and cannot be closed. Closing a + /// session stops its scan for changes and its playback; closing the last session tab shows the + /// Record tab (a start screen is only there if `+` adds it). 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() { @@ -445,35 +576,61 @@ impl ViewerApp { // 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); + self.active = 0; + self.show_record(); + return; } if index < self.active { self.active -= 1; } - self.focus_tab(self.active.min(self.tabs.len() - 1)); + self.active = self.active.min(self.tabs.len() - 1); + if !self.record_active { + self.focus_tab(self.active); + } } /// Carries out a tab key: see [`Action::NewTab`] and the others for which are tab actions. Any /// other action does nothing. + /// + /// The Record tab is part of the ring `Next` and `Previous` go round (it comes first), `GoToTab` + /// and `LastTab` count session tabs only, and `CloseTab` does nothing on the Record tab. pub fn apply_tab_action(&mut self, action: Action) { let count = self.tabs.len(); + let position = if self.record_active { + 0 + } else { + self.active + 1 + }; + let total = count + 1; 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::CloseTab if !self.record_active => self.close_tab(self.active), + Action::NextTab => self.focus_position((position + 1) % total), + Action::PreviousTab => self.focus_position((position + total - 1) % total), Action::GoToTab(index) => self.focus_tab(index), - Action::LastTab => self.focus_tab(count - 1), + Action::LastTab if count > 0 => self.focus_tab(count - 1), + Action::LastTab | Action::ShowRecord => self.show_record(), _ => {} } } + /// Shows the tab at `position` of the whole bar: `0` is the Record tab, then the sessions. + fn focus_position(&mut self, position: usize) { + match position.checked_sub(1) { + None => self.show_record(), + Some(index) => self.focus_tab(index), + } + } + /// 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. + /// [`ViewerApp::open`] does, which expands the window if it was compact; for a request with + /// none, shows the Record tab if it asked for that (`gui` does), else a start-screen tab (a new + /// one unless the current tab is one already). A request that names the Record tab shows it + /// after any sessions are opened. Returns whether the window should be raised. pub fn handle_request(&mut self, request: &ipc::Request) -> bool { + let record = request.tab == Some(ipc::TabName::Record); if request.open.is_empty() { - if !matches!(self.tabs[self.active], Screen::Empty) { + if !record && !matches!(self.screen(), Some(Screen::Empty)) { self.new_tab(); } } else { @@ -481,6 +638,9 @@ impl ViewerApp { self.open(dir); } } + if record { + self.show_record(); + } request.focus } @@ -604,67 +764,110 @@ impl ViewerApp { /// 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) { + // whichever tab is showing, a recording goes on and is finished + self.recorder.poll(ctx); self.poll_requests(ctx); self.poll_loading(); self.poll_picker(); let ctrl_tab = self.tab_keys(ctx); + // a session needs the room of the full window + if !self.record_active { + self.set_compact(false); + } self.pause_hidden(); + self.remember_full_size(ctx); let mut to_open: Option = None; let mut choose = false; let mut bar = TabBar::default(); + let (label, recording) = self.recorder.tab_label(); + let record_tab = RecordTab { + label, + recording, + selected: self.record_active, + }; - egui::TopBottomPanel::top("top") - .frame( - egui::Frame::new() - .fill(theme::BACKGROUND) - .inner_margin(egui::Margin::symmetric(10, 6)), - ) - .show(ctx, |ui| { - ui.horizontal(|ui| { - // leave room for the window controls that sit over the content - ui.add_space(70.0); - bar = tab_bar(ui, &self.tabs, self.active); - if ui.button("Open…").clicked() { - choose = true; + // the compact window is the Record tab alone + if !self.compact { + egui::TopBottomPanel::top("top") + .frame( + egui::Frame::new() + .fill(theme::BACKGROUND) + .inner_margin(egui::Margin::symmetric(10, 6)), + ) + .show(ctx, |ui| { + ui.horizontal(|ui| { + // leave room for the window controls that sit over the content + if cfg!(target_os = "macos") { + ui.add_space(70.0); + } + bar = tab_bar(ui, &record_tab, &self.tabs, self.active); + if ui.button("Open…").clicked() { + choose = true; + } + if recording { + ui.checkbox(&mut self.pinned, "pin on top") + .on_hover_text("keep this window above the others while recording"); + } + }); + if !self.record_active { + 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, .. } => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(format!("opening {}…", name_of(dir))); + }); + } + _ => {} + } } }); - 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, .. } => { - ui.horizontal(|ui| { - ui.spinner(); - ui.label(format!("opening {}…", name_of(dir))); - }); - } - _ => {} - } - }); + } let active = self.active; - match &mut self.tabs[active] { - Screen::Open(open) => open.ui(ctx), - Screen::Empty => { - egui::CentralPanel::default().show(ctx, |ui| { - to_open = start_screen(ui, &self.prefs, None); - }); + if self.record_active { + let compact = self.compact; + let mut output = crate::app::RecorderOutput::default(); + egui::CentralPanel::default().show(ctx, |ui| { + // leave room for the window controls that sit over the content + if cfg!(target_os = "macos") && compact { + ui.add_space(24.0); + } + output = self.recorder.ui(ui, compact); + }); + choose |= output.choose; + to_open = output.open; + if output.toggle_compact { + self.toggle_compact(); } - Screen::Failed { dir, message } => { - let (dir, message) = (dir.clone(), message.clone()); - egui::CentralPanel::default().show(ctx, |ui| { - to_open = start_screen(ui, &self.prefs, Some((&dir, &message))); - }); - } - Screen::Loading { .. } => { - egui::CentralPanel::default().show(ctx, |ui| { - ui.centered_and_justified(|ui| ui.spinner()); - }); + } else { + match &mut self.tabs[active] { + Screen::Open(open) => open.ui(ctx), + Screen::Empty => { + egui::CentralPanel::default().show(ctx, |ui| { + to_open = start_screen(ui, &self.prefs, None); + }); + } + Screen::Failed { dir, message } => { + let (dir, message) = (dir.clone(), message.clone()); + egui::CentralPanel::default().show(ctx, |ui| { + to_open = start_screen(ui, &self.prefs, Some((&dir, &message))); + }); + } + Screen::Loading { .. } => { + egui::CentralPanel::default().show(ctx, |ui| { + ui.centered_and_justified(|ui| ui.spinner()); + }); + } } } @@ -685,6 +888,9 @@ impl ViewerApp { if bar.new_tab { self.new_tab(); } + if bar.select_record { + self.show_record(); + } if let Some(index) = bar.select { self.focus_tab(index); } @@ -700,23 +906,81 @@ impl ViewerApp { ctx.request_repaint_after(Duration::from_millis(500)); } - if let Screen::Open(open) = &self.tabs[self.active] + if !self.record_active + && let Some(Screen::Open(open)) = self.tabs.get(self.active) && open.overlay != self.prefs.overlay { self.prefs.overlay = open.overlay; self.prefs.save(&self.prefs_dir); } + self.sync_window(ctx); + } + + /// Notes the size of the window while it is the full one, to go back to after being compact. + fn remember_full_size(&mut self, ctx: &egui::Context) { + if self.compact { + return; + } + if let Some(rect) = ctx.input(|input| input.viewport().inner_rect) { + let size = rect.size(); + // not the middle of a resize from the small window + if size.x >= FULL_MIN[0] && size.y >= FULL_MIN[1] { + self.full_size = size; + } + } + } + + /// Resizes and pins the window if its mode (compact, on top) is not the one it was last put in. + fn sync_window(&mut self, ctx: &egui::Context) { + let want = (self.compact, self.is_on_top()); + if want == self.applied { + return; + } + if want.0 != self.applied.0 { + let (size, min) = if want.0 { + (egui::vec2(COMPACT_SIZE[0], COMPACT_SIZE[1]), COMPACT_MIN) + } else { + (self.full_size, FULL_MIN) + }; + ctx.send_viewport_cmd(egui::ViewportCommand::MinInnerSize(egui::vec2( + min[0], min[1], + ))); + ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size)); + } + ctx.send_viewport_cmd(egui::ViewportCommand::WindowLevel(if want.1 { + egui::WindowLevel::AlwaysOnTop + } else { + egui::WindowLevel::Normal + })); + self.applied = want; } } +/// The size of the expanded window, in points. +pub const FULL_SIZE: [f32; 2] = [1500.0, 920.0]; +/// The least the expanded window can be made, in points. +pub const FULL_MIN: [f32; 2] = [900.0, 600.0]; +/// The size of the compact window, in points. +pub const COMPACT_SIZE: [f32; 2] = [420.0, 380.0]; +/// The least the compact window can be made, in points. +pub const COMPACT_MIN: [f32; 2] = [360.0, 260.0]; + /// What was clicked in the tab bar in one frame. #[derive(Default)] struct TabBar { + select_record: bool, select: Option, close: Option, new_tab: bool, } +/// What the Record tab says about itself in the bar. +struct RecordTab { + label: String, + recording: bool, + selected: 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 { @@ -736,9 +1000,25 @@ fn tab_title(screen: &Screen) -> (String, 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 { +/// Draws the Record tab, which has no close button, then the session tabs with one on each, and +/// the `+` after them. `active` is the session tab showing, if the Record tab is not. +fn tab_bar(ui: &mut egui::Ui, record: &RecordTab, tabs: &[Screen], active: usize) -> TabBar { let mut bar = TabBar::default(); + let text = egui::RichText::new(&record.label); + let text = if record.recording { + text.color(theme::BUG).strong() + } else { + text + }; + if ui + .selectable_label(record.selected, text) + .on_hover_text("Record: start and stop a recording") + .clicked() + { + bar.select_record = true; + } + ui.separator(); + let active = (!record.selected).then_some(active); let room = (ui.available_width() - 110.0).max(120.0); egui::ScrollArea::horizontal() .id_salt("tabs") @@ -749,7 +1029,7 @@ fn tab_bar(ui: &mut egui::Ui, tabs: &[Screen], active: usize) -> TabBar { for (index, tab) in tabs.iter().enumerate() { let (label, tip) = tab_title(tab); let response = ui - .selectable_label(index == active, label) + .selectable_label(Some(index) == active, label) .on_hover_text(tip); if response.clicked() { bar.select = Some(index); @@ -989,7 +1269,8 @@ impl Open { | Action::NextTab | Action::PreviousTab | Action::GoToTab(_) - | Action::LastTab => {} + | Action::LastTab + | Action::ShowRecord => {} Action::Escape => { if self.help { self.help = false; @@ -1258,7 +1539,7 @@ mod tests { fn open(app: &mut ViewerApp) -> &mut Open { match app.screen_mut() { - Screen::Open(open) => open, + Some(Screen::Open(open)) => open, _ => panic!("no session is open"), } } @@ -1288,7 +1569,12 @@ 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!( + app.record_active(), + "the Record tab shows, not a start screen" + ); + assert!(app.tabs().is_empty()); + assert!(app.screen().is_none()); } #[test] @@ -1302,11 +1588,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(), Some(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 Some(Screen::Failed { message, .. }) = app.screen() else { panic!("the unfinished session opened"); }; assert!(message.contains("left unfinished"), "{message}"); @@ -1601,7 +1887,7 @@ mod tests { }); assert!(ctx.wants_keyboard_input()); let _ = ctx.run(input(vec![key(egui::Key::Space)]), |ctx| { - if let Screen::Open(open) = app.screen_mut() { + if let Some(Screen::Open(open)) = app.screen_mut() { open.ui(ctx); } }); @@ -1874,7 +2160,11 @@ mod tests { let ctx = egui::Context::default(); app.open(&a); - assert_eq!(app.tabs().len(), 1, "the start tab was used"); + assert_eq!( + app.tabs().len(), + 1, + "the Record tab is not one a session loads into" + ); settle(&mut app, &ctx); assert_eq!(names(&app), ["viewer-tabs-a"]); @@ -1893,7 +2183,7 @@ mod tests { // 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)); + assert!(matches!(app.screen(), Some(Screen::Empty))); frame(&mut app, &ctx, vec![]); app.open_now(&a).expect("already open"); assert_eq!(app.tabs().len(), 4, "nothing was added"); @@ -1924,7 +2214,10 @@ mod tests { 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"); + assert!( + matches!(app.screen(), Some(Screen::Open(_))), + "not reloaded" + ); } #[test] @@ -1941,7 +2234,7 @@ mod tests { assert_eq!(app.tabs().len(), 2, "the open session is not replaced"); settle(&mut app, &ctx); - let Screen::Failed { message, .. } = app.screen() else { + let Some(Screen::Failed { message, .. }) = app.screen() else { panic!("it should have failed"); }; assert!(message.contains("left unfinished"), "{message}"); @@ -1969,19 +2262,22 @@ mod tests { // 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"); + assert_eq!( + short(app.screen().and_then(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 + // closing the last session tab shows the Record tab, and the window draws it app.close_tab(0); - assert!(matches!(app.screen(), Screen::Empty)); - assert_eq!(app.tabs().len(), 1); + assert!(app.record_active()); + assert!(app.tabs().is_empty()); frame(&mut app, &ctx, vec![]); // an index that is not there does nothing app.close_tab(7); - assert_eq!(app.tabs().len(), 1); + assert!(app.tabs().is_empty()); } #[test] @@ -2008,9 +2304,14 @@ mod tests { frame(&mut app, &ctx, vec![]); frame(&mut app, &ctx, vec![ctrl_tab(false)]); - assert_eq!(app.active_index(), 0, "next wraps round"); + assert!(app.record_active(), "next goes round to the Record tab"); frame(&mut app, &ctx, vec![ctrl_tab(true)]); - assert_eq!(app.active_index(), 2, "previous wraps round"); + assert_eq!( + app.active_index(), + 2, + "previous goes back round to the last" + ); + assert!(!app.record_active()); // 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![]); @@ -2023,6 +2324,10 @@ mod tests { 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::Num0, false)]); + assert!(app.record_active(), "0 is the Record tab"); + frame(&mut app, &ctx, vec![with_command(egui::Key::Num1, false)]); + assert!(!app.record_active()); frame( &mut app, &ctx, @@ -2038,7 +2343,7 @@ mod tests { frame(&mut app, &ctx, vec![with_command(egui::Key::T, false)]); assert_eq!(app.tabs().len(), 4); - assert!(matches!(app.screen(), Screen::Empty)); + assert!(matches!(app.screen(), Some(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); @@ -2068,7 +2373,7 @@ mod tests { let _ = ctx.run(input(vec![with_command(egui::Key::T, false)]), |ctx| { app.ui(ctx); }); - assert_eq!(app.tabs().len(), 1); + assert!(app.tabs().is_empty(), "no new tab was opened"); } #[test] @@ -2116,6 +2421,7 @@ mod tests { let request = ipc::Request { open: vec![a.clone(), b.clone()], focus: true, + ..ipc::Request::default() }; assert!(app.handle_request(&request)); settle(&mut app, &ctx); @@ -2125,6 +2431,7 @@ mod tests { let again = ipc::Request { open: vec![a], focus: false, + ..ipc::Request::default() }; assert!(!app.handle_request(&again)); assert_eq!((app.tabs().len(), app.active_index()), (2, 0)); @@ -2154,13 +2461,14 @@ mod tests { let request = ipc::Request { open: vec![a], focus: true, + ..ipc::Request::default() }; 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 { + while !matches!(app.screen(), Some(Screen::Open(_))) && Instant::now() < deadline { frame(&mut app, &ctx, vec![]); std::thread::sleep(Duration::from_millis(20)); } @@ -2192,6 +2500,373 @@ mod tests { ); } + // ---- the Record tab and the one window ---- + + /// An app whose recorder touches no screen, and the flag that stands for SIGINT. + fn quiet(name: &str) -> (ViewerApp, &'static std::sync::atomic::AtomicBool) { + let quit: &'static std::sync::atomic::AtomicBool = + Box::leak(Box::new(std::sync::atomic::AtomicBool::new(false))); + let mut app = ViewerApp::new(prefs_dir(name)); + *app.recorder_mut() = RecorderApp::quiet(quit); + (app, quit) + } + + /// A recording that is finished when it is asked to stop, and saves `dir`. + fn fake_recording( + live: Arc, + dir: PathBuf, + ) -> std::thread::JoinHandle> { + std::thread::spawn(move || { + while !live.stop_requested() { + std::thread::sleep(Duration::from_millis(2)); + } + Ok(dir) + }) + } + + /// Draws a frame and returns the commands it sent to the window. + fn commands( + app: &mut ViewerApp, + ctx: &egui::Context, + events: Vec, + close_requested: bool, + ) -> Vec { + let mut raw = input(events); + if close_requested { + raw.viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + } + let output = ctx.run(raw, |ctx| app.ui(ctx)); + output + .viewport_output + .get(&egui::ViewportId::ROOT) + .map(|viewport| viewport.commands.clone()) + .unwrap_or_default() + } + + fn start_recording(app: &mut ViewerApp, phase: crate::recorder::Phase) { + let live = app.recorder().live(); + let worker = fake_recording(live, PathBuf::from("saved-session")); + app.recorder_mut().pretend(worker, phase, 12.0); + } + + #[test] + fn the_record_tab_is_first_pinned_and_cannot_be_closed() { + let (a, b) = ( + session("viewer-rec-a", false), + session("viewer-rec-b", false), + ); + let (mut app, _) = quiet("record-first"); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + assert!(app.record_active() && app.tabs().is_empty()); + assert!(app.is_compact(), "a plain start is the small window"); + + // a session is tab 1 (the first session tab), and the window expands to show it + app.open_now(&a).expect("open"); + assert_eq!(app.tabs().len(), 1); + assert!(!app.record_active()); + assert!(!app.is_compact(), "opening a session expands the window"); + app.open_now(&b).expect("open"); + frame(&mut app, &ctx, vec![]); + + // the key for the Record tab, and Cmd/Ctrl W on it does nothing + frame(&mut app, &ctx, vec![with_command(egui::Key::Num0, false)]); + assert!(app.record_active()); + frame(&mut app, &ctx, vec![with_command(egui::Key::W, false)]); + assert!(app.record_active()); + assert_eq!(app.tabs().len(), 2, "no session was closed either"); + // the tab bar and the tab draw with the Record tab showing + frame(&mut app, &ctx, vec![]); + + // `+` after the Record tab is a start screen; closing every session returns to Record + app.new_tab(); + assert!(matches!(app.screen(), Some(Screen::Empty))); + for _ in 0..3 { + app.close_tab(0); + } + assert!(app.tabs().is_empty()); + assert!(app.record_active(), "not an empty start screen"); + frame(&mut app, &ctx, vec![]); + } + + #[test] + fn opening_a_session_expands_the_compact_window_and_asks_the_window_to_resize() { + let a = session("viewer-expand-a", false); + let (mut app, _) = quiet("expand"); + let ctx = egui::Context::default(); + assert!(app.is_compact() && app.is_on_top()); + // nothing to say while the window is as it was made + let sent = commands(&mut app, &ctx, vec![], false); + assert!( + !sent + .iter() + .any(|c| matches!(c, egui::ViewportCommand::InnerSize(_))) + ); + + app.open_now(&a).expect("open"); + assert!(!app.is_compact() && !app.is_on_top()); + let sent = commands(&mut app, &ctx, vec![], false); + assert!( + sent.contains(&egui::ViewportCommand::InnerSize(egui::vec2(1500.0, 920.0))), + "{sent:?}" + ); + assert!(sent.contains(&egui::ViewportCommand::WindowLevel( + egui::WindowLevel::Normal + ))); + + // back to the small window: pinned on top again + app.toggle_compact(); + assert!(app.is_compact() && app.record_active()); + let sent = commands(&mut app, &ctx, vec![], false); + assert!( + sent.contains(&egui::ViewportCommand::InnerSize(egui::vec2(420.0, 380.0))), + "{sent:?}" + ); + assert!(sent.contains(&egui::ViewportCommand::WindowLevel( + egui::WindowLevel::AlwaysOnTop + ))); + // and a key that shows a session expands it again + frame(&mut app, &ctx, vec![with_command(egui::Key::Num1, false)]); + assert!(!app.is_compact() && !app.record_active()); + } + + #[test] + fn the_compact_choice_is_kept_in_the_preferences() { + let dir = prefs_dir("compact-prefs"); + let mut app = ViewerApp::new(dir.clone()); + assert!(app.is_compact(), "the default is the small window"); + app.toggle_compact(); + assert!(!app.is_compact()); + assert!(!Prefs::load(&dir).compact); + // the next start is the full window + assert!(!ViewerApp::new(dir.clone()).is_compact()); + app.toggle_compact(); + assert!(Prefs::load(&dir).compact); + + // showing a session expands without being remembered + let a = session("viewer-compact-a", false); + app.open_now(&a).expect("open"); + assert!(!app.is_compact()); + assert!(Prefs::load(&dir).compact, "only the button writes it"); + + // `view` with sessions starts full, and with none shows a start screen + let launched = ViewerApp::start(dir.clone(), crate::viewer::Launch::sessions(Vec::new())); + assert!(!launched.is_compact()); + assert_eq!(launched.tabs().len(), 1); + assert!(matches!(launched.screen(), Some(Screen::Empty))); + assert!(Prefs::load(&dir).compact); + // an older preferences file has no such field, and keeps the small window + std::fs::write(dir.join("viewer-prefs.json"), r#"{"overlay": true}"#).expect("write"); + assert!(ViewerApp::new(dir).is_compact()); + } + + #[test] + fn the_tab_says_when_a_recording_is_going() { + let a = session("viewer-marker-a", false); + let (mut app, _) = quiet("marker"); + let ctx = egui::Context::default(); + assert_eq!(app.recorder().tab_label(), ("Record".to_string(), false)); + + start_recording(&mut app, crate::recorder::Phase::Recording); + let (label, recording) = app.recorder().tab_label(); + assert!(recording && label.starts_with("● REC "), "{label}"); + // it draws, in the bar and with a session showing, with the pin toggle + app.open_now(&a).expect("open"); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![with_command(egui::Key::Num0, false)]); + + let live = app.recorder().live(); + live.request_stop(); + let deadline = Instant::now() + Duration::from_secs(5); + while app.recorder().recording() && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(app.recorder().tab_label(), ("Record".to_string(), false)); + } + + #[test] + fn a_recording_is_joined_and_saved_while_another_tab_is_showing() { + let a = session("viewer-poll-a", false); + let (mut app, _) = quiet("poll"); + let ctx = egui::Context::default(); + start_recording(&mut app, crate::recorder::Phase::Recording); + app.open_now(&a).expect("open"); + assert!(!app.record_active()); + + let live = app.recorder().live(); + live.request_stop(); + let deadline = Instant::now() + Duration::from_secs(5); + while app.recorder().recording() && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(!app.recorder().recording()); + assert_eq!( + app.recorder().saved(), + Some(Path::new("saved-session")), + "the worker was joined and its session kept, with the Record tab hidden" + ); + assert!(!app.record_active(), "and the tab in view was left alone"); + } + + #[test] + fn closing_the_window_while_recording_stops_the_recording_first() { + let a = session("viewer-close-rec-a", false); + let (mut app, _) = quiet("close-recording"); + let ctx = egui::Context::default(); + start_recording(&mut app, crate::recorder::Phase::Recording); + app.open_now(&a).expect("open"); + + let sent = commands(&mut app, &ctx, vec![], true); + assert!( + sent.contains(&egui::ViewportCommand::CancelClose), + "{sent:?}" + ); + assert!(!sent.contains(&egui::ViewportCommand::Close)); + assert!(app.recorder().live().stop_requested()); + assert!(app.recorder().closing()); + + // once the recording has finalized the window closes + let deadline = Instant::now() + Duration::from_secs(5); + let mut closed = false; + while !closed && Instant::now() < deadline { + closed = + commands(&mut app, &ctx, vec![], false).contains(&egui::ViewportCommand::Close); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(closed, "the window closed after the recording was done"); + assert!(app.recorder().saved().is_some()); + } + + #[test] + fn a_quit_signal_while_recording_is_the_same_as_closing() { + let (mut app, quit) = quiet("quit-recording"); + let ctx = egui::Context::default(); + start_recording(&mut app, crate::recorder::Phase::Recording); + // with a session showing, as the other tests do + app.open_now(&session("viewer-quit-a", false)) + .expect("open"); + quit.store(true, std::sync::atomic::Ordering::SeqCst); + + let sent = commands(&mut app, &ctx, vec![], false); + assert!( + sent.contains(&egui::ViewportCommand::CancelClose), + "{sent:?}" + ); + assert!(app.recorder().live().stop_requested()); + let deadline = Instant::now() + Duration::from_secs(5); + let mut closed = false; + while !closed && Instant::now() < deadline { + closed = + commands(&mut app, &ctx, vec![], false).contains(&egui::ViewportCommand::Close); + std::thread::sleep(Duration::from_millis(5)); + } + assert!(closed); + } + + #[test] + fn with_no_recording_a_close_request_closes_and_a_quit_signal_closes_too() { + let (mut app, quit) = quiet("close-idle"); + let ctx = egui::Context::default(); + let sent = commands(&mut app, &ctx, vec![], true); + assert!( + !sent.contains(&egui::ViewportCommand::CancelClose), + "{sent:?}" + ); + + quit.store(true, std::sync::atomic::Ordering::SeqCst); + let sent = commands(&mut app, &ctx, vec![], false); + assert!(sent.contains(&egui::ViewportCommand::Close), "{sent:?}"); + } + + #[test] + fn a_gui_request_shows_the_record_tab_and_a_view_request_opens_tabs() { + let (a, b) = ( + session("viewer-gui-a", false), + session("viewer-gui-b", false), + ); + let (mut app, _) = quiet("gui-request"); + let ctx = egui::Context::default(); + + // `view SESSION...` forwarded: tabs, in the full window + let view = ipc::Request { + open: vec![a.clone(), b], + ..ipc::Request::default() + }; + assert!(app.handle_request(&view)); + settle(&mut app, &ctx); + assert_eq!(names(&app), ["viewer-gui-a", "viewer-gui-b"]); + assert!(!app.record_active() && !app.is_compact()); + + // `gui` forwarded: the Record tab, and no tab added or closed + let gui = ipc::Request { + tab: Some(ipc::TabName::Record), + ..ipc::Request::default() + }; + assert!(app.handle_request(&gui), "the window is raised"); + assert!(app.record_active()); + assert_eq!(app.tabs().len(), 2); + + // sessions and the Record tab together open the sessions and end on Record + let both = ipc::Request { + open: vec![a], + tab: Some(ipc::TabName::Record), + ..ipc::Request::default() + }; + assert!(app.handle_request(&both)); + assert!(app.record_active() && app.tabs().len() == 2); + + // a request in the old shape is still understood + let old: ipc::Request = + serde_json::from_str(r#"{"open":[],"focus":false}"#).expect("old request"); + assert!(!app.handle_request(&old)); + assert_eq!( + app.tabs().len(), + 3, + "an empty open is a start screen, as it was" + ); + assert!(matches!(app.screen(), Some(Screen::Empty))); + } + + #[test] + fn a_gui_request_over_the_socket_reaches_a_hidden_record_tab() { + let dir = std::env::temp_dir().join(format!("kr-viewer-gui-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-gui-socket-a", false); + + let Ok(ipc::Claim::Serving(bound)) = ipc::claim(&socket, &ipc::Request::default()) else { + panic!("nobody is serving"); + }; + let (mut app, _) = quiet("gui-socket"); + app.listen(bound.serve(|| {})); + app.open_now(&a).expect("open"); + assert!(!app.record_active()); + let ctx = egui::Context::default(); + + let gui = ipc::Request { + tab: Some(ipc::TabName::Record), + ..ipc::Request::default() + }; + assert!(matches!( + ipc::claim(&socket, &gui).expect("claim"), + ipc::Claim::Forwarded + )); + let deadline = Instant::now() + Duration::from_secs(10); + while !app.record_active() && Instant::now() < deadline { + frame(&mut app, &ctx, vec![]); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(app.record_active()); + assert_eq!(app.tabs().len(), 1); + } + #[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 index 673f0bb5..31a10d6f 100644 --- a/komorebi-recorder/src/viewer/ipc.rs +++ b/komorebi-recorder/src/viewer/ipc.rs @@ -1,16 +1,18 @@ -//! One viewer window, however many times a recording is opened: the viewer's local socket. +//! One window, however many times the program is started: the window'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 +//! The first `komorebi-recorder` to start a window (with no command, `gui` or `view`) listens on a +//! unix domain socket in the per-user data directory ([`default_socket`]); every later one connects +//! to it, asks it to open the sessions as tabs or to show the Record tab, and exits, instead of +//! making a window of its 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, +//! `{"open":["/recordings/20261028T154619Z"],"focus":true}`. A request may also say which tab to +//! show, `"tab":"record"` (what `gui` sends: see [`TabName`]); a request without `"tab"`, which is +//! what older programs send, is still accepted. 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 @@ -67,9 +69,9 @@ pub const TIMEOUT: Duration = Duration::from_secs(2); /// # Example /// /// ```rust -/// use komorebi_recorder::viewer::ipc::Request; +/// use komorebi_recorder::viewer::ipc::{Request, TabName}; /// -/// let request = Request { open: vec!["/recordings/a".into()], focus: true }; +/// let request = Request { open: vec!["/recordings/a".into()], ..Request::default() }; /// assert_eq!( /// serde_json::to_string(&request)?, /// r#"{"open":["/recordings/a"],"focus":true}"# @@ -77,7 +79,11 @@ pub const TIMEOUT: Duration = Duration::from_secs(2); /// /// // both fields may be left out /// let empty: Request = serde_json::from_str("{}")?; -/// assert!(empty.open.is_empty() && empty.focus); +/// assert!(empty.open.is_empty() && empty.focus && empty.tab.is_none()); +/// +/// // `gui` asks for the Record tab +/// let record = Request { tab: Some(TabName::Record), ..Request::default() }; +/// assert_eq!(serde_json::to_string(&record)?, r#"{"open":[],"focus":true,"tab":"record"}"#); /// # Ok::<(), serde_json::Error>(()) /// ``` #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -89,6 +95,18 @@ pub struct Request { /// Whether to raise the window and un-minimise it. The default is `true`. #[serde(default = "yes")] pub focus: bool, + /// Which tab to show once the sessions are open. `None`, the default and what `view` sends, + /// shows the last session opened (or a start screen, when there is none). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tab: Option, +} + +/// A tab a [`Request`] can ask for by name. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TabName { + /// The pinned Record tab, first in the window. + Record, } fn yes() -> bool { @@ -100,6 +118,7 @@ impl Default for Request { Self { open: Vec::new(), focus: true, + tab: None, } } } @@ -134,8 +153,8 @@ impl Reply { /// 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. +/// Only the edges of the program call this (the `gui` and `view` commands); everything else takes +/// the path as a parameter. #[must_use] pub fn default_socket() -> PathBuf { match std::env::var_os(SOCKET_VARIABLE) { @@ -464,6 +483,7 @@ mod tests { let request = Request { open: vec![abs("a"), abs("b")], focus: true, + ..Request::default() }; assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered); assert_eq!(wait_for(&server, 1), [request]); @@ -473,6 +493,7 @@ mod tests { let more = Request { open: vec![abs("c")], focus: false, + ..Request::default() }; assert!(matches!( claim(&path, &more).expect("claim"), @@ -481,6 +502,24 @@ mod tests { assert_eq!(wait_for(&server, 1), [more]); } + #[test] + fn the_tab_is_additive_and_old_requests_still_read() { + let old: Request = serde_json::from_str(r#"{"open":["/a"],"focus":false}"#).expect("old"); + assert_eq!(old.tab, None); + let new: Request = serde_json::from_str(r#"{"tab":"record"}"#).expect("new"); + assert_eq!(new.tab, Some(TabName::Record)); + assert!(serde_json::from_str::(r#"{"tab":"nowhere"}"#).is_err()); + + let path = socket("tab"); + let server = serving(&path); + let request = Request { + tab: Some(TabName::Record), + ..Request::default() + }; + assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered); + assert_eq!(wait_for(&server, 1), [request]); + } + #[test] fn nothing_is_delivered_when_nobody_listens() { let path = socket("nobody"); @@ -514,6 +553,7 @@ mod tests { let request = Request { open: vec![abs("x")], focus: true, + ..Request::default() }; assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered); assert_eq!(wait_for(&server, 1), [request]); @@ -537,6 +577,7 @@ mod tests { let request = Request { open: vec![abs(&format!("s{index}"))], focus: true, + ..Request::default() }; match claim(&path, &request).expect("claim") { Claim::Forwarded => None, @@ -602,6 +643,7 @@ mod tests { let request = Request { open: vec![abs("fine")], focus: true, + ..Request::default() }; assert_eq!(send(&path, &request).expect("sent"), Delivery::Delivered); assert_eq!(wait_for(&server, 1), [request]); @@ -614,6 +656,7 @@ mod tests { let relative = Request { open: vec![PathBuf::from("relative")], focus: true, + ..Request::default() }; let error = send(&path, &relative).expect_err("refused"); assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput); diff --git a/komorebi-recorder/src/viewer/keymap.rs b/komorebi-recorder/src/viewer/keymap.rs index f196510c..9d2f679b 100644 --- a/komorebi-recorder/src/viewer/keymap.rs +++ b/komorebi-recorder/src/viewer/keymap.rs @@ -93,6 +93,8 @@ pub enum Action { GoToTab(usize), /// Go to the last tab (`Cmd`/`Ctrl` `9`). LastTab, + /// Go to the pinned Record tab (`Cmd`/`Ctrl` `0`). + ShowRecord, } impl Action { @@ -107,6 +109,7 @@ impl Action { | Self::PreviousTab | Self::GoToTab(_) | Self::LastTab + | Self::ShowRecord ) } } @@ -152,7 +155,8 @@ pub const BINDINGS: &[(&str, &str)] = &[ "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)"), + ("Cmd/Ctrl 1 – 9", "go to that session tab (9 is the last)"), + ("Cmd/Ctrl 0", "go to the Record tab"), ]; /// Returns the action for a key pressed with `modifiers`, if it is bound. @@ -165,7 +169,7 @@ pub const BINDINGS: &[(&str, &str)] = &[ /// display). /// /// 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` +/// one, `1` to `9` go to a session tab and `0` to the Record 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. /// @@ -269,6 +273,7 @@ fn tab_action(key: Key, modifiers: Modifiers) -> Option { Some(match key { Key::T => Action::NewTab, Key::W => Action::CloseTab, + Key::Num0 => Action::ShowRecord, Key::Num1 => Action::GoToTab(0), Key::Num2 => Action::GoToTab(1), Key::Num3 => Action::GoToTab(2), @@ -482,6 +487,11 @@ mod tests { action(Key::Num9, Modifiers::COMMAND, None), Some(Action::LastTab) ); + assert_eq!( + action(Key::Num0, Modifiers::COMMAND, None), + Some(Action::ShowRecord) + ); + assert_eq!(action(Key::Num0, plain(), None), Some(Action::FitTimeline)); // the plain digit still picks a display, the plain letters still do what they did assert_eq!( action(Key::Num1, plain(), None), @@ -513,7 +523,16 @@ mod tests { .map(|(keys, _)| *keys) .collect::>() .join(" "); - for key in ["Space", "J", "Home", "B", "Esc", "Cmd/Ctrl T", "Ctrl Tab"] { + for key in [ + "Space", + "J", + "Home", + "B", + "Esc", + "Cmd/Ctrl T", + "Ctrl Tab", + "Cmd/Ctrl 0", + ] { assert!(listed.contains(key), "{key}"); } } diff --git a/komorebi-recorder/src/viewer/mod.rs b/komorebi-recorder/src/viewer/mod.rs index cc001af2..5d262f2d 100644 --- a/komorebi-recorder/src/viewer/mod.rs +++ b/komorebi-recorder/src/viewer/mod.rs @@ -1,20 +1,22 @@ -//! The viewer: a window for playing and scrubbing a recording with everything that happened in it -//! laid out on a timeline. +//! The program's one window: recording and reviewing, in tabs. //! -//! 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`. +//! `komorebi-recorder` with no command, `komorebi-recorder gui` and `komorebi-recorder view +//! [SESSION...]` ([`crate::cli::GuiArgs`], [`crate::cli::ViewArgs`]) all open this window, with +//! [`run_with`] (the recorder's [`crate::app::run`] and the viewer's [`run`] are the two ways in), +//! or hand their request to the one that is already open. 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). +//! The first tab is **Record**: the recorder ([`crate::app`]) with its Record and Stop buttons. It +//! is pinned, cannot be closed, and shows `REC` and the time in the tab bar while a recording goes +//! on, which it does whichever tab is showing. After it come the session tabs, one for each +//! recording being reviewed. There is only ever one window: opening another session (from the +//! window, from the command line or from the Record tab) 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 //! +-------------------------------------------------+ -//! | [15:46:19 x] [15:51:02 x] [+] Open... | tab bar -//! | session name counts and warnings | top bar +//! | [Record] [15:46:19 x] [15:51:02 x] [+] Open... | tab bar +//! | session name counts and warnings | top bar (a session) //! +----------------------------------+--------------+ //! | | Now | //! | the video of every display, | Event | @@ -27,27 +29,46 @@ //! +-------------------------------------------------+ //! ``` //! +//! # Compact and full +//! +//! Started plainly (`komorebi-recorder`, `gui`), the window is *compact*: the old small recorder +//! window, 420 by 380 points (at least 360 by 260), always on top, showing the Record tab alone +//! with no tab bar, to leave over the application a bug is being reproduced in. The Expand button +//! of the Record tab, and opening any session (the Review buttons, a request from another process, +//! a key), make it the full window: 1500 by 920 points (at least 900 by 600), not on top, with the +//! tab bar; the size it had last is restored. The Compact button goes back, and the choice is +//! kept in the preferences ([`prefs::Prefs::compact`]). `view` with sessions starts full. While +//! recording, the full window has a "pin on top" checkbox. The window uses the system's title bar +//! and frame on Windows; on macOS the title bar is hidden and the content runs under it. +//! //! # 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. +//! A session 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. The Record tab has no `x`. Closing the last session tab +//! shows the Record tab; 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`, `0` for the Record tab, and `1` to `9`). Tabs are not restored when the window +//! 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. +//! Every launch that opens a window finds out whether one is already running by connecting to a +//! socket in komorebi's data directory, `komorebi-recorder-viewer.sock`. If one answers, it is +//! sent what was asked (the sessions as absolute paths, or the Record tab for `gui`) and asked to +//! come to the front, and the command exits without a window; if not, the command becomes the +//! window and listens there. A second `gui` therefore raises the window and shows its Record tab, +//! and its options (`--fps` and the rest) are ignored: they only seed the window that is started. +//! `--new-window` on `gui` and `view` skips the socket and makes an independent window. +//! `komorebi-recorder-gui.exe` (the Windows build with no console) uses the same socket. The +//! protocol, the start-up race and a stale socket are covered in [`ipc`]. +//! +//! Two environment variables point the window somewhere else, for trying it out or testing it end +//! to end without touching the real ones: `KOMOREBI_RECORDER_VIEWER_SOCKET` names another socket +//! ([`ipc::SOCKET_VARIABLE`]) and `KOMOREBI_RECORDER_PREFS_DIR` another directory for the +//! preferences ([`prefs::DIRECTORY_VARIABLE`]). //! //! # What plays and what is read //! @@ -66,13 +87,13 @@ //! //! | module | what it is | //! |---|---| -//! | [`ipc`] | the viewer's local socket: how one window takes sessions from other processes | +//! | [`ipc`] | the window's local socket: how one window takes requests 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 | +//! | [`prefs`] | what the window remembers between runs | //! | [`theme`] | colors | -//! | `app` | [`ViewerApp`] (the tabs), [`Screen`] (what a tab shows) and [`Open`], the state of the window and how it is kept in step | +//! | `app` | [`ViewerApp`] (the Record tab and the session tabs), [`Screen`] (what a session 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 | @@ -85,11 +106,11 @@ //! //! # Staying out of the way of what is being investigated //! -//! The viewer is used on the machine whose behavior is being investigated, so it must neither be -//! tiled by komorebi nor appear in a recording being made. +//! The window is used on the machine whose behavior is being investigated, so it must neither be +//! tiled by komorebi nor appear in a recording being made, in either size. //! //! - **Not tiled.** The window is named `komorebi-recorder` only when it is safely ignored -//! ([`crate::komorebi_ignore`]): [`run`] first registers `komorebic ignore-rule exe` for the +//! ([`crate::komorebi_ignore`]): [`run_with`] first registers `komorebic ignore-rule exe` for the //! recorder's executables with a running komorebi for Windows, or finds none running. When it //! cannot (no `komorebic`, the command fails, or any macOS host, where komorebi manages every //! window with a title) the title is empty, and komorebi leaves windows with no title alone. @@ -99,7 +120,7 @@ //! it and writes the answer to `komorebi-recorder-window-probe.txt` in the temp directory //! (see [`crate::platform::window::PROBE_VARIABLE`]). //! - **Not in the video.** On macOS the recorder's capture filter excludes by name every process -//! called `komorebi-recorder` (and its own), which includes the viewer. On Windows a whole +//! called `komorebi-recorder` (and its own), which includes this window. On Windows a whole //! monitor is captured, so about once a second the window asks Windows to leave it out of captures //! (`WDA_EXCLUDEFROMCAPTURE`) through [`crate::platform::window::Chrome`], which it ticks on //! every frame. @@ -126,68 +147,155 @@ pub use app::Open; pub use app::Screen; pub use app::ViewerApp; -/// Opens the viewer window, with each of `sessions` open in a tab, and runs it until it is closed. +/// What the window is started to show: the Record tab (plain `gui`) or sessions (`view`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Show { + /// The Record tab, in the compact window if the preferences say so. + Record, + /// The sessions in [`Launch::sessions`], in the full window; with none, a start screen. + Sessions, +} + +/// What a launch of the window asks for. +#[derive(Debug, Clone)] +pub struct Launch { + /// The sessions to open as tabs, as given. Only used with [`Show::Sessions`]. + pub sessions: Vec, + /// The options the Record tab starts from (see [`crate::app::run`]). + pub record: crate::cli::RecordArgs, + /// What to show. + pub show: Show, +} + +impl Launch { + /// Returns the launch of plain `gui`: the Record tab, starting from `record`. + #[must_use] + pub fn record(record: crate::cli::RecordArgs) -> Self { + Self { + sessions: Vec::new(), + record, + show: Show::Record, + } + } + + /// Returns the launch of `view`: `sessions` as tabs, in the full window. + #[must_use] + pub fn sessions(sessions: Vec) -> Self { + Self { + sessions, + record: crate::cli::RecordArgs::default(), + show: Show::Sessions, + } + } + + /// Whether the window starts as the small control window: when it shows the Record tab and + /// `prefs` say so. + #[must_use] + pub fn starts_compact(&self, prefs: &prefs::Prefs) -> bool { + self.show == Show::Record && prefs.compact + } + + /// The request that hands this launch to a window that is already running. + fn request(&self) -> ipc::Request { + match self.show { + Show::Record => ipc::Request { + tab: Some(ipc::TabName::Record), + ..ipc::Request::default() + }, + Show::Sessions => ipc::Request { + open: self + .sessions + .iter() + .map(|path| ipc::absolute(path)) + .collect(), + ..ipc::Request::default() + }, + } + } +} + +/// Opens the window with each of `sessions` open in a tab, and runs it until it is closed: what +/// `komorebi-recorder view` does. See [`run_with`], of which this is the launch [`Launch::sessions`]. /// -/// This blocks the calling thread: the window's event loop runs on it. Each of `sessions` is the +/// # Errors +/// +/// As [`run_with`]. +pub fn run(sessions: Vec, socket: Option<&Path>) -> eyre::Result<()> { + run_with(Launch::sessions(sessions), socket) +} + +/// Opens the window as `launch` asks, and runs it until it is closed. +/// +/// This blocks the calling thread: the window's event loop runs on it. Each of the 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. +/// make this fail: the window comes up and shows why. With [`Show::Sessions`] and 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. +/// `socket` is the path of the window's socket ([`ipc::default_socket`]), or `None` for a window of +/// its own that no other process can reach (`--new-window`). With a socket, if a window is already +/// running it is handed the launch (the sessions as tabs, or its Record tab, which raises it) and +/// this returns `Ok` at once without making a window; the options of [`Launch::record`] are then +/// ignored. Otherwise this window listens on the socket and takes 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 -/// window, so there is no example; the tests in `viewer::app` drive the same [`ViewerApp`] +/// The window is 1500 by 920 points (at least 900 by 600), or 420 by 380 (at least 360 by 260) and +/// always on top when compact ([`Launch::starts_compact`]), 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. A SIGINT or SIGTERM while recording finishes the recording and then closes the window. +/// Needs a window, so there is no example; the tests in `viewer::app` drive the same [`ViewerApp`] /// headlessly. /// /// # Errors /// -/// Returns an error saying "the viewer window failed" if the window cannot be created or its event -/// loop fails (for example, there is no display or no usable graphics adapter). -pub fn run(sessions: Vec, socket: Option<&Path>) -> eyre::Result<()> { +/// Returns an error saying "the 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_with(launch: Launch, 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 - } + Some(socket) => match ipc::claim(socket, &launch.request()) { + // a window is running and has taken the request + 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 window'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; + // killing the window (or logging out) must still finalize a recording in progress + crate::app::install_quit_handler(); + // only a window that is really going to open 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 setup = crate::komorebi_ignore::prepare_window(); + + let directory = prefs::directory(); + let compact = launch.starts_compact(&prefs::Prefs::load(&directory)); + let (size, min) = if compact { + (app::COMPACT_SIZE, app::COMPACT_MIN) + } else { + (app::FULL_SIZE, app::FULL_MIN) + }; + let mut viewport = egui::ViewportBuilder::default() + // titled only when komorebi ignores it (or is not running), so opening the window does + // not move the layout of the machine whose behavior is being investigated + .with_title(setup.title) + .with_app_id("komorebi-recorder") + .with_icon(crate::icon::window_icon()) + .with_title_shown(false) + .with_titlebar_shown(false) + .with_fullsize_content_view(true) + .with_inner_size(size) + .with_min_inner_size(min); + if compact { + // the small control window stays over the application being recorded + viewport = viewport.with_always_on_top(); + } let options = eframe::NativeOptions { - viewport: egui::ViewportBuilder::default() - // titled only when komorebi ignores it (or is not running), so opening the viewer does - // not move the layout of the machine whose behavior is being investigated - .with_title(title) - .with_app_id("komorebi-recorder") - .with_icon(crate::icon::window_icon()) - .with_title_shown(false) - .with_titlebar_shown(false) - .with_fullsize_content_view(true) - .with_inner_size([1500.0, 920.0]) - .with_min_inner_size([900.0, 600.0]), + viewport, ..Default::default() }; @@ -200,9 +308,9 @@ pub fn run(sessions: Vec, socket: Option<&Path>) -> eyre::Result<()> { visuals.window_fill = theme::BACKGROUND; creation.egui_ctx.set_visuals(visuals); - let mut app = ViewerApp::new(prefs::directory()); - for dir in &sessions { - app.open(dir); + let mut app = ViewerApp::start(directory, launch); + if let Some(note) = setup.note { + app.recorder_mut().say(note); } if let Some(bound) = bound { let ctx = creation.egui_ctx.clone(); @@ -214,7 +322,7 @@ pub fn run(sessions: Vec, socket: Option<&Path>) -> eyre::Result<()> { ))) }), ) - .map_err(|error| eyre::Report::msg(format!("the viewer window failed: {error}"))) + .map_err(|error| eyre::Report::msg(format!("the window failed: {error}"))) } /// Adapts [`ViewerApp`] to eframe. diff --git a/komorebi-recorder/src/viewer/prefs.rs b/komorebi-recorder/src/viewer/prefs.rs index 42bd575a..5f618d3b 100644 --- a/komorebi-recorder/src/viewer/prefs.rs +++ b/komorebi-recorder/src/viewer/prefs.rs @@ -26,7 +26,7 @@ const RECENT: usize = 12; /// use std::path::Path; /// /// let mut prefs = Prefs::default(); -/// assert!(prefs.overlay); +/// assert!(prefs.overlay && prefs.compact); /// /// prefs.opened(Path::new("/recordings/a")); /// prefs.opened(Path::new("/recordings/b")); @@ -41,6 +41,10 @@ pub struct Prefs { pub recent: Vec, /// Whether komorebi's state is drawn over the video. The default is `true`. pub overlay: bool, + /// Whether the window, when started with no session to show, is the small control window: the + /// Record tab alone, always on top. Switched with the Compact / Expand button. The default is + /// `true`, so a file from a build that did not have it keeps the small window. + pub compact: bool, } impl Default for Prefs { @@ -48,6 +52,7 @@ impl Default for Prefs { Self { recent: Vec::new(), overlay: true, + compact: true, } } } @@ -177,14 +182,23 @@ impl Prefs { } } -/// Returns where preferences live: komorebi's data directory, `/komorebi` (see +/// The environment variable that replaces [`directory`]. It exists so that the window can be tried +/// out, or tested end to end, without reading or writing the user's real preferences; it is not +/// meant for anything else. +pub const DIRECTORY_VARIABLE: &str = "KOMOREBI_RECORDER_PREFS_DIR"; + +/// Returns where preferences live: `$KOMOREBI_RECORDER_PREFS_DIR` if it is set and not empty +/// ([`DIRECTORY_VARIABLE`]), else komorebi's data directory, `/komorebi` (see /// [`komorebi_link::data_dir`](crate::komorebi_link::data_dir)). /// /// It depends on the machine, so it is not shown with an example: the viewer passes it to /// [`Prefs::load`] and [`Prefs::save`]. #[must_use] pub fn directory() -> PathBuf { - crate::komorebi_link::data_dir().to_path_buf() + match std::env::var_os(DIRECTORY_VARIABLE) { + Some(path) if !path.is_empty() => PathBuf::from(path), + _ => crate::komorebi_link::data_dir().to_path_buf(), + } } #[cfg(test)]