diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4b279292..8e3fa4ec 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -93,6 +93,12 @@ reactions: a display that is gone has its video finalized at once, one that retu stream is started afresh after a wake. The capture backend is a trait, so that these policies are tested with a scripted backend that docks and undocks without hardware. +## Investigating + +Reading a session never needs a window: `analysis` answers each question as a plain serializable value, and the command +line and the viewer present the same answers. Every command takes `--json`, which prints an envelope with the data, its +schema, warnings, whether it was truncated and a cursor, and failures exit with a code that says what kind they were. + ## Rules and the layer that enforces them | Rule | Enforced by | diff --git a/docs/usage/recording-a-bug-repro.md b/docs/usage/recording-a-bug-repro.md index 7b966303..474a8128 100644 --- a/docs/usage/recording-a-bug-repro.md +++ b/docs/usage/recording-a-bug-repro.md @@ -136,6 +136,14 @@ recorder is built so that **nothing already captured is put at risk by any of it process. komorebi not running when recording starts is not an error either. All of this is recorded in `recorder.jsonl`. +It is shown as the `recorder` source, right next to the log lines and trace around it: + +``` +komorebi-recorder at 12.5 --source recorder +``` + +`summary` marks a second in which something changed with `recorder=N`, `locate` says which segment of each display covers +a moment (and which displays had no video then), and `frames` extracts from the right segment. ### If the recorder dies @@ -151,6 +159,35 @@ This closes the segments that were still open (using the video files themselves the timeline, and marks the session `recovered`. The queries tell you to do this if you point them at an unfinished session. +## Asking questions of a session + +Times are video timecodes: `12.5`, `00:12.500` or `1:02:03`. Video `00:00.000` is the first captured frame. + +``` +# everything within +-1s of 12.5s, grouped by source +komorebi-recorder at 12.5 + +# one app's OS trace only, or one source +komorebi-recorder at 12.5 --app Ghostty +komorebi-recorder at 12.5 --source events + +# a span, and a per-second digest of the whole recording +komorebi-recorder range 10 15 +komorebi-recorder summary + +# reverse: where in the video was this? +komorebi-recorder locate --log-line 120 +komorebi-recorder locate --event-seq 7 +komorebi-recorder locate --utc 2026-10-26T19:43:35.062613Z + +# look at the exact frame +komorebi-recorder frames 12.5 14.0 +``` + +Add `--json` to any query for machine-readable output, which is also what makes a session easy to hand to an LLM: the +generated `README.md` in every session directory explains each file and contains these commands with the session path +filled in. + ## The session directory ``` diff --git a/komorebi-recorder/src/analysis/diff.rs b/komorebi-recorder/src/analysis/diff.rs new file mode 100644 index 00000000..f4044327 --- /dev/null +++ b/komorebi-recorder/src/analysis/diff.rs @@ -0,0 +1,809 @@ +//! The differences between two komorebi states, described the way a person would. +//! +//! A raw JSON diff of komorebi's `State` is mostly noise: a window that moved from the second +//! container to the first is a dozen changed paths. [`diff`] compares two [`Snapshot`]s and reports +//! [`Change`]s instead: a window appeared, went away, moved to another workspace or was really +//! somewhere else on screen; focus moved; a layout or a workspace changed; a monitor came or went. +//! It is a pure function of the two states: nothing is read from a session, so any two snapshots +//! can be compared, from any recording. The `diff` command, `trace` and the viewer all call it. +//! +//! # What counts as a change +//! +//! - **Windows are followed by id.** A window has moved only if its monitor, its workspace or the +//! container it is in changes, or it goes from one kind of place to another (tiled, monocle, +//! maximized, floating). Containers are compared by their id, not their index, so a container +//! that slides from index 1 to index 0 because the one before it closed is not a move, and +//! neither is switching to another tab of the same container. If one id appears in more than one +//! place in a state (see `window-in-two-places` in `crate::analysis::invariants`), the first place +//! found is the one used. +//! - **A rect must move by more than 2 points** in any of left, top, width and height to be a +//! [`Change::WindowRect`]: the accessibility API rounds, and some applications snap to whole +//! points. A window whose rect is missing from either state is never reported as having moved +//! on screen. +//! - **A reorder is one change.** If the same containers are in a different order, the result is a +//! single [`Change::ContainerOrder`] rather than a series of moves. +//! - **Monitors are matched by id** and workspaces by name, within a monitor present in both +//! states. A workspace that exists in only one of the states has no layout or order to compare. +//! +//! # Flavor +//! +//! komorebi for Mac parks a hidden window in a corner of its monitor, so a window's rect shows +//! whether it is hidden. komorebi for Windows cloaks a window where it is, so it does not. The +//! `hidden_before` and `hidden_after` flags of [`Change::WindowRect`] are therefore decided by the +//! rules of the flavor that wrote the state ([`Snapshot::is_hidden_position`]), and are always +//! `false` for a komorebi for Windows state. Nothing else here depends on the flavor. + +use super::state::Focus; +use super::state::Location; +use super::state::Monitor; +use super::state::Rect; +use super::state::Snapshot; +use super::state::Window; +use schemars::JsonSchema; +use serde::Serialize; +use std::collections::BTreeMap; + +/// A window rect that moved by no more than this is treated as not having moved: the accessibility +/// API rounds, and some applications snap to whole points. +const RECT_TOLERANCE: i64 = 2; + +/// A window, named so that a reader can tell which one a [`Change`] is about. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct WindowRef { + /// The window's id in komorebi's state: a window id on a Mac, a window handle on Windows. + pub id: u64, + /// The window's title when the state was serialized. + pub title: String, + /// The program the window belongs to, as komorebi names it. + pub exe: String, +} + +impl WindowRef { + fn of(window: &Window) -> Self { + Self { + id: window.id, + title: window.title.clone(), + exe: window.exe.clone(), + } + } + + /// Returns the window as `exe "title" (window id)`. + #[must_use] + pub fn describe(&self) -> String { + format!("{} \"{}\" (window {})", self.exe, self.title, self.id) + } +} + +/// One difference between two states, as [`diff`] reports it. +/// +/// In JSON a change is an object with a `kind` field naming the variant in kebab case +/// ([`Change::kind`]) and the variant's fields beside it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(tag = "kind", rename_all = "kebab-case")] +pub enum Change { + /// A monitor is in the second state and was not in the first. + MonitorAdded { + /// The display id of the monitor ([`Monitor::id`]). + monitor_id: u64, + /// The monitor's device name. + device: String, + /// The monitor's area, in global display points. + size: Rect, + }, + /// A monitor was in the first state and is not in the second. + MonitorRemoved { + /// The display id of the monitor ([`Monitor::id`]). + monitor_id: u64, + /// The monitor's device name. + device: String, + }, + /// A monitor is in both states but its area differs (by any amount: there is no tolerance). + MonitorResized { + /// The display id of the monitor ([`Monitor::id`]). + monitor_id: u64, + /// The area in the first state, in global display points. + from: Rect, + /// The area in the second state, in global display points. + to: Rect, + }, + /// The workspace showing on a monitor changed. + WorkspaceFocus { + /// The display id of the monitor. + monitor_id: u64, + /// The name of the workspace that was showing; empty if the monitor had none. + from: String, + /// The name of the workspace that is showing; empty if the monitor has none. + to: String, + }, + /// The keyboard focus moved (see [`Snapshot::focus`] for what has it). + Focus { + /// The focus before: a monitor, workspace and window; `None` if nothing had it. + from: Option, + /// The focus after, in the same terms; `None` if nothing has it. + to: Option, + }, + /// A workspace's layout changed. + Layout { + /// The display id of the monitor the workspace is on. + monitor_id: u64, + /// The name of the workspace. + workspace: String, + /// The layout's name before, e.g. `Columns` or `BSP`. + from: String, + /// The layout's name after. + to: String, + }, + /// The containers of a workspace are in a different order (window ids by container). + ContainerOrder { + /// The display id of the monitor the workspace is on. + monitor_id: u64, + /// The name of the workspace. + workspace: String, + /// The id of the first window of each container, in container order, before. + from: Vec, + /// The same list after: the same ids in another order. + to: Vec, + }, + /// A window is in the second state and was not in the first. + WindowAdded { + /// The window. + window: WindowRef, + /// Where it is in the second state. + at: Location, + }, + /// A window was in the first state and is not in the second. + WindowRemoved { + /// The window. + window: WindowRef, + /// Where it was in the first state. + from: Location, + }, + /// Moved to another container, another kind of place, another workspace or another monitor. + WindowMoved { + /// The window. + window: WindowRef, + /// Where it was in the first state. + from: Location, + /// Where it is in the second state. + to: Location, + }, + /// Really somewhere else on screen. + WindowRect { + /// The window. + window: WindowRef, + /// Where the window was in the first state, as read live from the OS. + from: Rect, + /// Where the window is in the second state, as read live from the OS. + to: Rect, + /// Whether `from` is where komorebi parks a hidden window. Always `false` for komorebi + /// for Windows, which hides a window without moving it. + hidden_before: bool, + /// Whether `to` is where komorebi parks a hidden window. Always `false` for komorebi for + /// Windows. + hidden_after: bool, + }, + /// komorebi was paused or resumed. + Paused { + /// Whether komorebi is paused in the second state. + paused: bool, + }, +} + +impl Change { + /// Returns the kind name of the change, the same as the `kind` field of its JSON: for example + /// `window-added`. + #[must_use] + pub fn kind(&self) -> &'static str { + match self { + Self::MonitorAdded { .. } => "monitor-added", + Self::MonitorRemoved { .. } => "monitor-removed", + Self::MonitorResized { .. } => "monitor-resized", + Self::WorkspaceFocus { .. } => "workspace-focus", + Self::Focus { .. } => "focus", + Self::Layout { .. } => "layout", + Self::ContainerOrder { .. } => "container-order", + Self::WindowAdded { .. } => "window-added", + Self::WindowRemoved { .. } => "window-removed", + Self::WindowMoved { .. } => "window-moved", + Self::WindowRect { .. } => "window-rect", + Self::Paused { .. } => "paused", + } + } + + /// Returns one line a person can read, such as `Safari "window 2" appeared on monitor 1 + /// workspace one (container 1)`. + #[must_use] + pub fn describe(&self) -> String { + let focus = |focus: &Option| { + focus.as_ref().map_or_else( + || "nothing".to_string(), + |focus| { + format!( + "window {} on monitor {} workspace {}", + focus + .window_id + .map_or_else(|| "(none)".to_string(), |id| id.to_string()), + focus.monitor_id, + focus.workspace + ) + }, + ) + }; + + match self { + Self::MonitorAdded { + monitor_id, + device, + size, + } => { + format!( + "monitor {monitor_id} \"{device}\" appeared, {}", + size.describe() + ) + } + Self::MonitorRemoved { monitor_id, device } => { + format!("monitor {monitor_id} \"{device}\" went away") + } + Self::MonitorResized { + monitor_id, + from, + to, + } => format!( + "monitor {monitor_id} changed from {} to {}", + from.describe(), + to.describe() + ), + Self::WorkspaceFocus { + monitor_id, + from, + to, + } => { + format!("monitor {monitor_id} switched from workspace {from} to {to}") + } + Self::Focus { from, to } => { + format!("focus moved from {} to {}", focus(from), focus(to)) + } + Self::Layout { + monitor_id, + workspace, + from, + to, + } => format!( + "monitor {monitor_id} workspace {workspace} layout changed from {from} to {to}" + ), + Self::ContainerOrder { + monitor_id, + workspace, + from, + to, + } => format!( + "monitor {monitor_id} workspace {workspace} containers reordered from {from:?} to {to:?}" + ), + Self::WindowAdded { window, at } => { + format!("{} appeared on {}", window.describe(), at.describe()) + } + Self::WindowRemoved { window, from } => { + format!("{} went away from {}", window.describe(), from.describe()) + } + Self::WindowMoved { window, from, to } => format!( + "{} moved from {} to {}", + window.describe(), + from.describe(), + to.describe() + ), + Self::WindowRect { + window, + from, + to, + hidden_before, + hidden_after, + } => { + let note = match (hidden_before, hidden_after) { + (false, true) => " (now hidden)", + (true, false) => " (now shown)", + _ => "", + }; + format!( + "{} is really at {} instead of {}{note}", + window.describe(), + to.describe(), + from.describe() + ) + } + Self::Paused { paused } => { + format!("komorebi {}", if *paused { "paused" } else { "resumed" }) + } + } + } +} + +/// Where a window sits, coarsely: it only counts as having moved if this changes. Container +/// *indexes* shift whenever a container before it comes or goes, so containers are compared by id. +fn anchor(snapshot: &Snapshot) -> BTreeMap { + let mut anchors = BTreeMap::new(); + for monitor in &snapshot.monitors { + for (index, workspace) in monitor.workspaces.iter().enumerate() { + let visible = index == monitor.focused; + let mut put = |window: &Window, slot: String, place: super::state::Place| { + anchors.entry(window.id).or_insert_with(|| { + ( + monitor.id, + workspace.name.clone(), + slot, + Location { + monitor_id: monitor.id, + workspace: workspace.name.clone(), + place, + workspace_visible: visible, + }, + window.clone(), + ) + }); + }; + + for (container_index, container) in workspace.containers.iter().enumerate() { + for (tab, window) in container.windows.iter().enumerate() { + put( + window, + format!("container {}", container.id), + super::state::Place::Container { + index: container_index, + tab, + }, + ); + } + } + if let Some(monocle) = &workspace.monocle { + for (tab, window) in monocle.windows.iter().enumerate() { + put( + window, + "monocle".to_string(), + super::state::Place::Monocle { tab }, + ); + } + } + if let Some(window) = &workspace.maximized { + put( + window, + "maximized".to_string(), + super::state::Place::Maximized, + ); + } + for (index, window) in workspace.floating.iter().enumerate() { + put( + window, + "floating".to_string(), + super::state::Place::Floating { index }, + ); + } + } + } + + anchors +} + +fn is_hidden(snapshot: &Snapshot, window: &Window) -> bool { + window.rect.as_ref().is_some_and(|rect| { + snapshot + .monitor_under(rect) + .or_else(|| snapshot.monitors.first()) + .is_some_and(|monitor| snapshot.is_hidden_position(rect, monitor)) + }) +} + +fn monitor_by_id(snapshot: &Snapshot, id: u64) -> Option<&Monitor> { + snapshot.monitors.iter().find(|monitor| monitor.id == id) +} + +/// Returns what changed from the state `before` to the state `after`, empty if nothing did. +/// +/// The changes come in a fixed order, which tests and the text output rely on: +/// +/// 1. [`Change::Paused`]; +/// 2. [`Change::MonitorRemoved`] and [`Change::MonitorResized`], by monitor of `before`, then +/// [`Change::MonitorAdded`]; +/// 3. for each monitor in both states, [`Change::WorkspaceFocus`], then for each of its workspaces +/// [`Change::Layout`] and [`Change::ContainerOrder`]; +/// 4. [`Change::Focus`]; +/// 5. for each window of `after`, in order of window id, [`Change::WindowAdded`], or else +/// [`Change::WindowMoved`] followed by [`Change::WindowRect`]; +/// 6. [`Change::WindowRemoved`], for each window of `before` that is not in `after`, in order of +/// window id. +/// +/// What counts as a change is described in the [module](self) documentation. The comparison cannot +/// fail and does not panic. +/// +/// # Example +/// +/// A second window is opened beside the first, so the first is squeezed to half the screen: +/// +/// ```rust +/// use komorebi_recorder::analysis::diff::Change; +/// use komorebi_recorder::analysis::diff::diff; +/// use komorebi_recorder::analysis::flavor::Flavor; +/// use komorebi_recorder::analysis::state::Snapshot; +/// use komorebi_recorder::testkit::state_with_windows; +/// +/// let before = Snapshot::parse(Flavor::Macos, &state_with_windows(&[(1, "Ghostty")])); +/// let after = Snapshot::parse( +/// Flavor::Macos, +/// &state_with_windows(&[(1, "Ghostty"), (2, "Safari")]), +/// ); +/// +/// let changes = diff(&before, &after); +/// let kinds: Vec<_> = changes.iter().map(Change::kind).collect(); +/// assert_eq!(kinds, ["window-rect", "window-added"]); +/// assert_eq!( +/// changes[0].describe(), +/// "Ghostty \"window 1\" (window 1) is really at 500x800 at (0, 0) instead of 1000x800 at (0, 0)" +/// ); +/// assert_eq!( +/// changes[1].describe(), +/// "Safari \"window 2\" (window 2) appeared on monitor 1 workspace one (container 1)" +/// ); +/// +/// // the same state twice has nothing to report +/// assert!(diff(&after, &after.clone()).is_empty()); +/// ``` +/// +/// Covered in detail by the unit tests of this module, among them +/// `container_indexes_shifting_is_not_a_move`, `reordered_containers_are_one_change` and +/// `rect_jitter_within_the_tolerance_is_not_a_change`. +#[must_use] +pub fn diff(before: &Snapshot, after: &Snapshot) -> Vec { + let mut changes = Vec::new(); + + if before.paused != after.paused { + changes.push(Change::Paused { + paused: after.paused, + }); + } + + for monitor in &before.monitors { + match monitor_by_id(after, monitor.id) { + None => changes.push(Change::MonitorRemoved { + monitor_id: monitor.id, + device: monitor.device.clone(), + }), + Some(now) if now.size != monitor.size => changes.push(Change::MonitorResized { + monitor_id: monitor.id, + from: monitor.size, + to: now.size, + }), + Some(_) => {} + } + } + for monitor in &after.monitors { + if monitor_by_id(before, monitor.id).is_none() { + changes.push(Change::MonitorAdded { + monitor_id: monitor.id, + device: monitor.device.clone(), + size: monitor.size, + }); + } + } + + for monitor in &after.monitors { + let Some(was) = monitor_by_id(before, monitor.id) else { + continue; + }; + + let name = |monitor: &Monitor| { + monitor + .focused_workspace() + .map_or_else(String::new, |workspace| workspace.name.clone()) + }; + if name(was) != name(monitor) { + changes.push(Change::WorkspaceFocus { + monitor_id: monitor.id, + from: name(was), + to: name(monitor), + }); + } + + for workspace in &monitor.workspaces { + let Some(old) = was.workspaces.iter().find(|old| old.name == workspace.name) else { + continue; + }; + + if old.layout != workspace.layout { + changes.push(Change::Layout { + monitor_id: monitor.id, + workspace: workspace.name.clone(), + from: old.layout.clone(), + to: workspace.layout.clone(), + }); + } + + let order = |workspace: &super::state::Workspace| -> Vec { + workspace + .containers + .iter() + .filter_map(|container| container.windows.first().map(|window| window.id)) + .collect() + }; + let (old_order, new_order) = (order(old), order(workspace)); + let mut old_sorted = old_order.clone(); + let mut new_sorted = new_order.clone(); + old_sorted.sort_unstable(); + new_sorted.sort_unstable(); + // the same containers, in another order: a reorder rather than adds and removes + if old_order != new_order && old_sorted == new_sorted { + changes.push(Change::ContainerOrder { + monitor_id: monitor.id, + workspace: workspace.name.clone(), + from: old_order, + to: new_order, + }); + } + } + } + + let (focus_before, focus_after) = (before.focus(), after.focus()); + if focus_before != focus_after { + changes.push(Change::Focus { + from: focus_before, + to: focus_after, + }); + } + + let (was, now) = (anchor(before), anchor(after)); + for (id, (monitor, workspace, slot, location, window)) in &now { + match was.get(id) { + None => changes.push(Change::WindowAdded { + window: WindowRef::of(window), + at: location.clone(), + }), + Some((old_monitor, old_workspace, old_slot, old_location, old_window)) => { + if (old_monitor, old_workspace, old_slot) != (monitor, workspace, slot) { + changes.push(Change::WindowMoved { + window: WindowRef::of(window), + from: old_location.clone(), + to: location.clone(), + }); + } + + if let (Some(from), Some(to)) = (&old_window.rect, &window.rect) + && from.max_delta(to) > RECT_TOLERANCE + { + changes.push(Change::WindowRect { + window: WindowRef::of(window), + from: *from, + to: *to, + hidden_before: is_hidden(before, old_window), + hidden_after: is_hidden(after, window), + }); + } + } + } + } + for (id, (_, _, _, location, window)) in &was { + if !now.contains_key(id) { + changes.push(Change::WindowRemoved { + window: WindowRef::of(window), + from: location.clone(), + }); + } + } + + changes +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::Value; + use serde_json::json; + + fn window(id: u64, rect: Option<[i64; 4]>) -> Value { + let mut value = json!({"id": id, "details": {"title": format!("w{id}"), "exe": "app"}}); + if let Some([left, top, width, height]) = rect { + value["rect"] = json!({"left": left, "top": top, "right": width, "bottom": height}); + } + value + } + + fn container(id: &str, windows: Vec) -> Value { + json!({"id": id, "windows": {"elements": windows, "focused": 0}}) + } + + fn state(workspaces: Vec<(&str, Vec, usize)>, focused_workspace: usize) -> Snapshot { + let workspaces: Vec = workspaces + .into_iter() + .map(|(name, containers, focused)| { + json!({"name": name, "layer": "Tiling", "layout": {"Default": "Columns"}, + "containers": {"elements": containers, "focused": focused}}) + }) + .collect(); + Snapshot::from_value(&json!({ + "monitors": {"elements": [{ + "id": 1, "device": "d", + "size": {"left": 0, "top": 0, "right": 1000, "bottom": 800}, + "window_hiding_position": "BottomLeft", + "workspaces": {"elements": workspaces, "focused": focused_workspace}, + }], "focused": 0} + })) + } + + fn kinds(changes: &[Change]) -> Vec<&'static str> { + changes.iter().map(Change::kind).collect() + } + + #[test] + fn identical_states_have_no_changes() { + let a = state( + vec![( + "one", + vec![container("a", vec![window(1, Some([0, 0, 500, 800]))])], + 0, + )], + 0, + ); + assert!(diff(&a, &a.clone()).is_empty()); + } + + #[test] + fn a_window_appearing_and_focus_moving_are_described_as_such() { + let before = state( + vec![("one", vec![container("a", vec![window(1, None)])], 0)], + 0, + ); + let after = state( + vec![( + "one", + vec![ + container("a", vec![window(1, None)]), + container("b", vec![window(2, None)]), + ], + 1, + )], + 0, + ); + + let changes = diff(&before, &after); + assert_eq!(kinds(&changes), ["focus", "window-added"]); + let Change::WindowAdded { window, at } = &changes[1] else { + panic!("{changes:?}") + }; + assert_eq!(window.id, 2); + assert_eq!(at.workspace, "one"); + assert!(changes[1].describe().contains("w2")); + } + + #[test] + fn a_window_leaving_a_workspace_is_a_move_not_an_add_and_remove() { + let before = state( + vec![ + ("one", vec![container("a", vec![window(1, None)])], 0), + ("two", vec![], 0), + ], + 0, + ); + let after = state( + vec![ + ("one", vec![], 0), + ("two", vec![container("a", vec![window(1, None)])], 0), + ], + 0, + ); + + let changes = diff(&before, &after); + assert!(kinds(&changes).contains(&"window-moved"), "{changes:?}"); + assert!(!kinds(&changes).contains(&"window-added")); + assert!(!kinds(&changes).contains(&"window-removed")); + } + + #[test] + fn container_indexes_shifting_is_not_a_move() { + let before = state( + vec![( + "one", + vec![ + container("a", vec![window(1, None)]), + container("b", vec![window(2, None)]), + ], + 0, + )], + 0, + ); + // container "a" is closed: "b" moves from index 1 to 0 but is not moved + let after = state( + vec![("one", vec![container("b", vec![window(2, None)])], 0)], + 0, + ); + + assert_eq!(kinds(&diff(&before, &after)), ["focus", "window-removed"]); + } + + #[test] + fn reordered_containers_are_one_change() { + let a = container("a", vec![window(1, None)]); + let b = container("b", vec![window(2, None)]); + let before = state(vec![("one", vec![a.clone(), b.clone()], 0)], 0); + let after = state(vec![("one", vec![b, a], 0)], 0); + + let changes = diff(&before, &after); + assert!(kinds(&changes).contains(&"container-order"), "{changes:?}"); + assert!(!kinds(&changes).contains(&"window-moved")); + } + + #[test] + fn a_window_really_moving_on_screen_is_reported_with_hiding() { + let on = window(1, Some([0, 0, 500, 800])); + // hidden at the bottom-left sliver: right edge one point inside the monitor + let hidden = window(1, Some([-499, 790, 500, 800])); + let before = state(vec![("one", vec![container("a", vec![on])], 0)], 0); + let after = state(vec![("one", vec![container("a", vec![hidden])], 0)], 0); + + let changes = diff(&before, &after); + let Change::WindowRect { + hidden_before, + hidden_after, + .. + } = &changes[0] + else { + panic!("{changes:?}") + }; + assert!(!hidden_before && *hidden_after); + assert!(changes[0].describe().contains("now hidden")); + } + + #[test] + fn rect_jitter_within_the_tolerance_is_not_a_change() { + let before = state( + vec![( + "one", + vec![container("a", vec![window(1, Some([0, 0, 500, 800]))])], + 0, + )], + 0, + ); + let after = state( + vec![( + "one", + vec![container("a", vec![window(1, Some([1, 0, 499, 800]))])], + 0, + )], + 0, + ); + assert!(diff(&before, &after).is_empty()); + } + + #[test] + fn workspace_switches_and_monitor_changes_are_reported() { + let before = state(vec![("one", vec![], 0), ("two", vec![], 0)], 0); + let after = state(vec![("one", vec![], 0), ("two", vec![], 0)], 1); + let changes = diff(&before, &after); + assert!(matches!( + &changes[0], + Change::WorkspaceFocus { from, to, .. } if from == "one" && to == "two" + )); + + let docked = Snapshot::from_value(&json!({ + "monitors": {"elements": [ + {"id": 1, "device": "a", "size": {"left": 0, "top": 0, "right": 10, "bottom": 10}}, + {"id": 2, "device": "b", "size": {"left": 10, "top": 0, "right": 10, "bottom": 10}}, + ], "focused": 0} + })); + let undocked = Snapshot::from_value(&json!({ + "monitors": {"elements": [ + {"id": 1, "device": "a", "size": {"left": 0, "top": 0, "right": 20, "bottom": 10}}, + ], "focused": 0} + })); + let changes = diff(&docked, &undocked); + assert_eq!(kinds(&changes), ["monitor-resized", "monitor-removed"]); + assert_eq!( + kinds(&diff(&undocked, &docked)), + ["monitor-resized", "monitor-added"] + ); + } + + #[test] + fn pausing_is_reported() { + let mut paused = state(vec![], 0); + paused.paused = true; + let changes = diff(&state(vec![], 0), &paused); + assert_eq!(changes, [Change::Paused { paused: true }]); + assert_eq!(changes[0].describe(), "komorebi paused"); + } +} diff --git a/komorebi-recorder/src/analysis/flavor/mac.rs b/komorebi-recorder/src/analysis/flavor/mac.rs index 9c0072de..1da907bb 100644 --- a/komorebi-recorder/src/analysis/flavor/mac.rs +++ b/komorebi-recorder/src/analysis/flavor/mac.rs @@ -34,6 +34,8 @@ use crate::analysis::events::EventInfo; use crate::analysis::events::EventRecord; use crate::analysis::events::Family; use crate::analysis::logparse::Line; +use crate::analysis::state::Monitor; +use crate::analysis::state::Rect; use serde_json::Value; /// The [`Rules`] of komorebi for Mac: what its events, `State`, log and modules say. @@ -213,6 +215,20 @@ impl Rules for MacRules { } } + /// Whether `rect` is where komorebi parks a window it has hidden on `monitor`: with a + /// one-point sliver still inside the display, so the window stays "on screen" to macOS. The + /// vertical position is not checked, because macOS pulls a window up to keep its title bar + /// reachable. + fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool { + let tolerance = 2; + let bottom_right = monitor.hiding_position == "BottomRight"; + if bottom_right { + (rect.left - (monitor.size.left + monitor.size.width - 1)).abs() <= tolerance + } else { + (rect.right_edge() - (monitor.size.left + 1)).abs() <= tolerance + } + } + fn block_header(&self, line: &Line, _open: Option<&Block>) -> Option { match line.root_span() { Some("process_event") if line.message.starts_with(EVENT_HEADER) => { diff --git a/komorebi-recorder/src/analysis/flavor/mod.rs b/komorebi-recorder/src/analysis/flavor/mod.rs index 6015f950..bcb7692a 100644 --- a/komorebi-recorder/src/analysis/flavor/mod.rs +++ b/komorebi-recorder/src/analysis/flavor/mod.rs @@ -40,6 +40,7 @@ //! | [`window_id`](Rules::window_id) | the id a window has in `State` | `Snapshot::parse` | `id` | `hwnd` | //! | [`window_is_unreadable`](Rules::window_is_unreadable) | whether komorebi failed to read a window | `Snapshot::parse` | the default: never | the title starts with `could not get window` | //! | [`hides_windows_by_position`](Rules::hides_windows_by_position) | whether a window's position shows that it is hidden | `Snapshot::hides_windows_by_position` | yes: parked at a corner | no: cloaked where it is | +//! | [`is_hidden_position`](Rules::is_hidden_position) | whether a rect is where a hidden window is parked | `Snapshot::is_hidden_position` | a one-point sliver inside the display | never | //! | [`block_header`](Rules::block_header) | whether a log line starts a handler's block | `blocks::build` | the `processing event:` and `processing command:` lines | the first line of a `process_event{...}` or `process_command{...}` span whose fields differ from the open block's | //! | [`is_block_end`](Rules::is_block_end) | whether a log line ends a handler's block | `blocks::build` | `processed command: ...`, for commands only | `processed: ...` for events, `processed` for commands | //! | [`slow_handler_cause`](Rules::slow_handler_cause) | what a slow handler was probably doing | the `overview` and `trace` answers | accessibility calls | Win32 calls | @@ -78,6 +79,10 @@ //! that komorebi made up ended a real drag. //! 1. `blocks::build` walks the log: `block_header` for every line, and //! `is_block_end` for every line inside an open block. +//! 1. `Snapshot::parse` reads each `State`, asking [`window_id`](Rules::window_id) and +//! [`window_is_unreadable`](Rules::window_is_unreadable) for every window. The snapshot keeps +//! its flavor for [`hides_windows_by_position`](Rules::hides_windows_by_position) and +//! `is_hidden_position`. //! //! [`MacRules`]: mac::MacRules //! [`WindowsRules`]: windows::WindowsRules @@ -94,6 +99,8 @@ use super::classify::Class; use super::events::EventInfo; use super::events::EventRecord; use super::logparse::Line; +use super::state::Monitor; +use super::state::Rect; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -340,6 +347,7 @@ pub struct BlockHeader { /// # use komorebi_recorder::analysis::flavor::mac::MacRules; /// # use komorebi_recorder::analysis::flavor::{BlockHeader, Flavor, Rules}; /// # use komorebi_recorder::analysis::logparse::Line; +/// # use komorebi_recorder::analysis::state::{Monitor, Rect}; /// # use serde_json::Value; /// struct Unchecked; /// @@ -353,6 +361,9 @@ pub struct BlockHeader { /// fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) { /// MacRules.classify_window_manager(event) /// } +/// fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool { +/// MacRules.is_hidden_position(rect, monitor) +/// } /// fn block_header(&self, line: &Line, open: Option<&Block>) -> Option { /// MacRules.block_header(line, open) /// } @@ -382,6 +393,7 @@ pub struct BlockHeader { /// # use komorebi_recorder::analysis::flavor::mac::MacRules; /// # use komorebi_recorder::analysis::flavor::{BlockHeader, Flavor, Rules}; /// # use komorebi_recorder::analysis::logparse::Line; +/// # use komorebi_recorder::analysis::state::{Monitor, Rect}; /// # use serde_json::Value; /// struct Unchecked; /// @@ -395,6 +407,9 @@ pub struct BlockHeader { /// fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) { /// MacRules.classify_window_manager(event) /// } +/// fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool { +/// MacRules.is_hidden_position(rect, monitor) +/// } /// fn block_header(&self, line: &Line, open: Option<&Block>) -> Option { /// MacRules.block_header(line, open) /// } @@ -515,6 +530,14 @@ pub trait Rules: Sync { /// komorebi acted, into an echo itself. fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str); + /// Returns whether `rect` is where komorebi parks a window it has hidden on `monitor`. + /// + /// `rect` is the window's rect as the `State` has it and `monitor` is the monitor the window is + /// on. komorebi for Mac parks a hidden window with a one-point sliver still inside the + /// display and the rules compare the horizontal position only, within 2 points. komorebi for + /// Windows does not park windows, so its answer is always `false`. + fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool; + /// Returns the header of the handler's block that `line` starts, or `None` if `line` does not /// start one. /// diff --git a/komorebi-recorder/src/analysis/flavor/windows.rs b/komorebi-recorder/src/analysis/flavor/windows.rs index ca40e4eb..5377f4d6 100644 --- a/komorebi-recorder/src/analysis/flavor/windows.rs +++ b/komorebi-recorder/src/analysis/flavor/windows.rs @@ -35,6 +35,8 @@ use crate::analysis::events::EventInfo; use crate::analysis::events::EventRecord; use crate::analysis::events::Family; use crate::analysis::logparse::Line; +use crate::analysis::state::Monitor; +use crate::analysis::state::Rect; use serde_json::Value; /// The [`Rules`] of komorebi for Windows: what its events, `State`, log and modules say. @@ -244,6 +246,11 @@ impl Rules for WindowsRules { false } + fn is_hidden_position(&self, _rect: &Rect, _monitor: &Monitor) -> bool { + // a cloaked window is exactly where it was; nothing in the state says it is hidden + false + } + fn block_header(&self, line: &Line, open: Option<&Block>) -> Option { let kind = match line.root_span()? { "process_event" => BlockKind::Event, diff --git a/komorebi-recorder/src/analysis/lookup.rs b/komorebi-recorder/src/analysis/lookup.rs new file mode 100644 index 00000000..9f5c1148 --- /dev/null +++ b/komorebi-recorder/src/analysis/lookup.rs @@ -0,0 +1,123 @@ +//! [`Lookup`] over the files of a session, without opening it for analysis. +//! +//! A `TimeSpec` such as `event:12+1s` or `bug:a-3f9c1e02.end` names a moment by pointing at +//! something the session recorded, and resolving it asks a [`Lookup`] when that thing happened. +//! `Analysis` is one, but opening an `Analysis` refuses a session that is still being recorded +//! and parses the events and the log up front. [`SessionLookup`] reads only the file each question +//! needs, so it works on a session that is still recording: `annotate` uses it to mark a bug region +//! while the recording goes on. +//! +//! It answers differently from `Analysis` about the start of an event: see [`SessionLookup`]. + +use super::envelope; +use super::timespec::Edge; +use super::timespec::Lookup; +use crate::annotations; +use crate::incidents::INCIDENTS_FILE; +use crate::incidents::Incident; +use crate::session::Manifest; +use crate::session::Session; +use crate::timeline; +use crate::timeline::Locator; +use color_eyre::eyre; + +/// A [`Lookup`] that reads the files of a session as they are asked about. +/// +/// Every question reads its file again from the start (`events.jsonl`, `komorebi.log`, +/// `recorder.jsonl` or the annotations), which suits resolving the handful of times a command line +/// names, and not resolving many. Every failure to find what is asked for is reported with the +/// not-found exit kind and a message saying what is missing. +/// +/// # Difference from `Analysis` +/// +/// [`Edge`] is ignored for an event: `event:12` and `event:12.end` both resolve to the moment the +/// notification was received, which is when komorebi had finished handling it. `Analysis` +/// resolves `event:12` (the start edge) to when the handler began, where komorebi's log shows it. +/// +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::lookup::SessionLookup; +/// use komorebi_recorder::analysis::timespec::Edge; +/// use komorebi_recorder::analysis::timespec::Lookup; +/// use komorebi_recorder::analysis::timespec::TimeSpec; +/// use komorebi_recorder::testkit::SessionBuilder; +/// use serde_json::json; +/// +/// let (session, manifest) = SessionBuilder::new("doc-session-lookup") +/// .event(2.0, json!({"type": "Retile"}), None) +/// .incident(4.0, "display-disconnected", "display 2") +/// .build(); +/// let lookup = SessionLookup::new(&session, &manifest); +/// +/// // one second after event 1 was received +/// let moment = "event:1+1s".parse::()?.resolve(&manifest, &lookup)?; +/// assert!((moment.video_s - 3.0).abs() < 1e-6); +/// +/// // both edges of an event are when it was received +/// assert_eq!( +/// lookup.event_mach_ns(1, Edge::Start)?, +/// lookup.event_mach_ns(1, Edge::End)? +/// ); +/// +/// // incidents are numbered from 1 +/// assert!(lookup.incident_mach_ns(1).is_ok()); +/// assert!(lookup.incident_mach_ns(2).is_err()); +/// assert!(lookup.event_mach_ns(99, Edge::End).is_err()); +/// # Ok::<(), Box>(()) +/// ``` +/// +/// Used end to end, against real files, by +/// `tests/annotate.rs::a_bug_can_be_marked_relative_to_an_event_and_edited_and_deleted` and +/// `tests/annotate.rs::annotating_works_on_a_session_that_is_still_recording`. +pub struct SessionLookup<'a> { + /// The session whose files are read. + pub session: &'a Session, + /// The session's manifest, which maps the master clock to video time. + pub manifest: &'a Manifest, +} + +impl<'a> SessionLookup<'a> { + /// Returns a lookup over `session`, whose manifest is `manifest`. + #[must_use] + pub fn new(session: &'a Session, manifest: &'a Manifest) -> Self { + Self { session, manifest } + } + + fn located(&self, locator: &Locator) -> eyre::Result { + timeline::locate(self.session, self.manifest, locator) + .map(|located| located.mach_ns) + .map_err(|error| envelope::not_found(format!("{error:#}"))) + } +} + +impl Lookup for SessionLookup<'_> { + fn event_mach_ns(&self, seq: u64, _edge: Edge) -> eyre::Result { + self.located(&Locator::EventSeq(seq)) + } + + fn log_mach_ns(&self, line: u64) -> eyre::Result { + self.located(&Locator::LogLine(line)) + } + + fn incident_mach_ns(&self, number: u64) -> eyre::Result { + let text = std::fs::read_to_string(self.session.path(INCIDENTS_FILE)) + .map_err(|_| envelope::not_found("the session recorded no incidents"))?; + let index = usize::try_from(number.saturating_sub(1)).unwrap_or(usize::MAX); + text.lines() + .nth(index) + .filter(|_| number >= 1) + .and_then(|line| serde_json::from_str::(line).ok()) + .map(|incident| incident.mach_ns) + .ok_or_else(|| envelope::not_found(format!("there is no incident {number}"))) + } + + fn annotation_span(&self, id: &str) -> eyre::Result<(u64, Option)> { + let loaded = annotations::load(&self.session.dir)?; + loaded + .get(id) + .map(|annotation| (annotation.start_mach_ns, annotation.end_mach_ns)) + .ok_or_else(|| envelope::not_found(format!("there is no annotation {id}"))) + } +} diff --git a/komorebi-recorder/src/analysis/mod.rs b/komorebi-recorder/src/analysis/mod.rs index eb34aa44..2edc8338 100644 --- a/komorebi-recorder/src/analysis/mod.rs +++ b/komorebi-recorder/src/analysis/mod.rs @@ -8,10 +8,13 @@ pub mod blocks; pub mod classify; +pub mod diff; pub mod envelope; pub mod events; pub mod flavor; pub mod guard; pub mod ids; pub mod logparse; +pub mod lookup; +pub mod state; pub mod timespec; diff --git a/komorebi-recorder/src/analysis/state.rs b/komorebi-recorder/src/analysis/state.rs new file mode 100644 index 00000000..dddc67e5 --- /dev/null +++ b/komorebi-recorder/src/analysis/state.rs @@ -0,0 +1,876 @@ +//! komorebi's `State`, as a model that can be asked questions. +//! +//! Every subscriber notification carries the whole `State` serialized as JSON, and the recorder +//! stores each distinct one. The JSON is read tolerantly into a [`Snapshot`]: unknown fields are +//! ignored and missing ones default, so a komorebi newer than this recorder still reads. +//! +//! Two facts about it that matter when reading it: +//! +//! - A window's `rect` is **not** komorebi's bookkeeping. It is read live from the accessibility +//! API at the moment the state is serialized, so it says where the window *really* was. +//! Comparing it with where komorebi's layout says it should be (`layout_rects`) finds windows +//! that are in the wrong place. +//! - komorebi's `Rect` is `{left, top, right, bottom}` where `right` is the **width** and `bottom` +//! the **height**, in global display points. [`Rect`] uses honest names. komorebi for Windows +//! writes its `Rect` the same way. +//! +//! The two flavors of komorebi do not write a window the same way. A Mac window is keyed by `id` +//! and keeps its title and program under `details`; a Windows window is keyed by its handle, +//! `hwnd`, with its title and program beside it. The flavor's [`Rules`] know which, and +//! [`Snapshot::parse`] asks them, so the rest of the analysis sees one model: a [`Snapshot`] of +//! [`Monitor`]s, [`Workspace`]s, [`Container`]s and [`Window`]s. +//! +//! This module reads and does not judge. Whether the state is consistent (a window in two places, a +//! layout that was not applied) is for the invariant checks of the analysis, which are built on +//! these types. +//! +//! # Example +//! +//! A one-window state as each flavor writes it, read into the same model: +//! +//! ```rust +//! use komorebi_recorder::analysis::flavor::Flavor; +//! use komorebi_recorder::analysis::state::{Place, Rect, Snapshot}; +//! use serde_json::json; +//! +//! // a workspace with one container, containing the given window, on monitor 1 +//! let state = |window: serde_json::Value| json!({ +//! "monitors": {"elements": [{ +//! "id": 1, +//! "workspaces": {"elements": [{ +//! "name": "one", +//! "containers": {"elements": [ +//! {"id": "c", "windows": {"elements": [window], "focused": 0}} +//! ], "focused": 0} +//! }], "focused": 0} +//! }], "focused": 0} +//! }); +//! +//! let mac = Snapshot::parse(Flavor::Macos, &state(json!({ +//! "id": 59, +//! "details": {"title": "Notes", "exe": "Notes"}, +//! "rect": {"left": 10, "top": 10, "right": 1686, "bottom": 1420} +//! }))); +//! let (location, window) = mac.find(59).expect("the window"); +//! assert_eq!(window.exe, "Notes"); +//! // komorebi's `right` and `bottom` are a width and a height +//! assert_eq!( +//! window.rect, +//! Some(Rect { left: 10, top: 10, width: 1686, height: 1420 }) +//! ); +//! assert_eq!(location.place, Place::Container { index: 0, tab: 0 }); +//! assert_eq!(location.describe(), "monitor 1 workspace one (container 0)"); +//! +//! let windows = Snapshot::parse(Flavor::Windows, &state(json!({ +//! "hwnd": 131072, "title": "Notes", "exe": "notepad.exe", +//! "rect": {"left": 0, "top": 0, "right": 100, "bottom": 100} +//! }))); +//! assert_eq!(windows.find(131_072).expect("the window").1.exe, "notepad.exe"); +//! +//! // only komorebi for Mac hides windows by position +//! assert!(mac.hides_windows_by_position()); +//! assert!(!windows.hides_windows_by_position()); +//! ``` + +use super::flavor::Flavor; +use super::flavor::Rules; +use schemars::JsonSchema; +use serde::Serialize; +use serde_json::Value; + +/// A rectangle in komorebi's display coordinates, with names that say what the numbers are. +/// +/// komorebi writes a rectangle as `{left, top, right, bottom}`, where `right` and `bottom` are a +/// width and a height. A `Rect` stores those two as [`Rect::width`] and [`Rect::height`], and +/// [`Rect::right_edge`] and [`Rect::bottom_edge`] give the edges. +/// +/// A rect is not guaranteed to have a positive size: komorebi for Windows writes zeros for a window +/// it could not read. [`Rect::area`] counts a width or height below 0 as 0. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::state::Rect; +/// +/// let a = Rect { left: 0, top: 0, width: 10, height: 10 }; +/// let b = Rect { left: 5, top: 5, width: 10, height: 10 }; +/// +/// assert_eq!(a.right_edge(), 10); +/// assert_eq!(a.overlap_area(&b), 25); +/// assert_eq!(a.max_delta(&b), 5); +/// assert_eq!(a.describe(), "10x10 at (0, 0)"); +/// +/// // rects that only touch share no area +/// let c = Rect { left: 10, top: 0, width: 5, height: 5 }; +/// assert_eq!(a.overlap_area(&c), 0); +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Rect { + /// The x coordinate of the left edge. + pub left: i64, + /// The y coordinate of the top edge. + pub top: i64, + /// The width: komorebi's `right`. + pub width: i64, + /// The height: komorebi's `bottom`. + pub height: i64, +} + +impl Rect { + /// Returns the x coordinate of the right edge: `left + width`. + #[must_use] + pub fn right_edge(&self) -> i64 { + self.left + self.width + } + + /// Returns the y coordinate of the bottom edge: `top + height`. + #[must_use] + pub fn bottom_edge(&self) -> i64 { + self.top + self.height + } + + /// Returns the area the two rectangles share, or 0 if they do not overlap (touching edges do + /// not overlap). + #[must_use] + pub fn overlap_area(&self, other: &Rect) -> i64 { + let width = self.right_edge().min(other.right_edge()) - self.left.max(other.left); + let height = self.bottom_edge().min(other.bottom_edge()) - self.top.max(other.top); + if width <= 0 || height <= 0 { + 0 + } else { + width * height + } + } + + /// Returns the rectangle's area. A width or height below 0 counts as 0. + #[must_use] + pub fn area(&self) -> i64 { + self.width.max(0) * self.height.max(0) + } + + /// Returns the largest difference in any of the four numbers (`left`, `top`, `width`, + /// `height`) between the two rectangles: 0 if they are equal. + #[must_use] + pub fn max_delta(&self, other: &Rect) -> i64 { + [ + (self.left - other.left).abs(), + (self.top - other.top).abs(), + (self.width - other.width).abs(), + (self.height - other.height).abs(), + ] + .into_iter() + .max() + .unwrap_or(0) + } + + /// Returns the rectangle as text for a reader: `1686x1420 at (10, 10)`, the size and then the + /// position of the top left corner. + #[must_use] + pub fn describe(&self) -> String { + format!( + "{}x{} at ({}, {})", + self.width, self.height, self.left, self.top + ) + } + + fn from_value(value: &Value) -> Option { + let number = |key: &str| { + let field = value.get(key)?; + field + .as_i64() + .or_else(|| field.as_f64().map(|float| float.round() as i64)) + }; + + Some(Self { + left: number("left")?, + top: number("top")?, + // komorebi's `right` and `bottom` are a width and a height + width: number("right")?, + height: number("bottom")?, + }) + } +} + +/// A window that appears in komorebi's state, as the state describes it. +/// +/// Fields that the state does not have (a komorebi that does not write them, or one newer than this +/// recorder) are empty text, not an error. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Window { + /// The window's id in the state: a window id on a Mac, a handle on Windows + /// ([`Rules::window_id`]). + pub id: u64, + /// The window's title. Empty if the state has none. For a window komorebi for Windows could not + /// read, it is komorebi's error text (`could not get window title`), not a title. + pub title: String, + /// The program: an application name on a Mac, an executable file name on Windows. Empty if the + /// state has none, and komorebi's error text for a window it could not read. + pub exe: String, + /// Where the window really was when the state was serialized (a live read from the OS, not + /// komorebi's bookkeeping). `None` if the state has no rect for it, or if komorebi could not read + /// the window ([`Rules::window_is_unreadable`]), so that a rect of zeros is not mistaken for a + /// window parked at a corner. + pub rect: Option, +} + +/// A container: one tile of a workspace, holding one window or a stack of tabbed ones. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Container { + /// komorebi's identifier for the container. + pub id: String, + /// The windows in the container, one tile's worth: more than one when they are tabbed or + /// stacked. + pub windows: Vec, + /// Which of `windows` is in front: an index into `windows`. 0 if the state does not say. + pub focused: usize, + /// Whether the state has the container as locked (`locked`); `false` if it does not say. + pub locked: bool, +} + +impl Container { + /// Returns the window in front, or `None` if `focused` is not an index of `windows` (an empty + /// container, for one). + #[must_use] + pub fn focused_window(&self) -> Option<&Window> { + self.windows.get(self.focused) + } +} + +/// A workspace of a monitor: its tiled containers, and its monocle, maximized and floating windows. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Workspace { + /// The workspace's name; empty if it has none. + pub name: String, + /// The tiled containers, in komorebi's order. + pub containers: Vec, + /// Which of `containers` has focus: an index into `containers`. 0 if the state does not say. + pub focused: usize, + /// A container filling the workspace on its own. + pub monocle: Option, + /// The window maximized on the workspace, if there is one. + pub maximized: Option, + /// The windows floating above the tiles. + pub floating: Vec, + /// Which of `floating` has focus: an index into `floating`. 0 if the state does not say. + pub floating_focused: usize, + /// `Tiling` or `Floating`: which layer has the focus. + pub layer: String, + /// The layout's short name: `Columns`, `BSP`, ... Empty if the state has none. + pub layout: String, + /// Where komorebi's last layout pass put each container, by container index. + pub layout_rects: Vec, + /// Whether tiling is on for the workspace. `true` if the state does not say. + pub tiling: bool, +} + +/// A monitor and its workspaces. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Monitor { + /// The display id: the same number as the `--display` of the recording. + pub id: u64, + /// The display's name, as komorebi has it (`Built-in Retina Display`). + pub device: String, + /// The monitor's whole area. + pub size: Rect, + /// The monitor's work area, from `work_area_size`. + pub work_area: Rect, + /// The monitor's workspaces, in komorebi's order. + pub workspaces: Vec, + /// Which of `workspaces` is showing: an index into `workspaces`. 0 if the state does not say. + pub focused: usize, + /// `BottomLeft` or `BottomRight`: the corner komorebi hides windows in. Empty if the state does + /// not say. + pub hiding_position: String, +} + +impl Monitor { + /// Returns the workspace that is showing, or `None` if `focused` is not an index of + /// `workspaces`. + #[must_use] + pub fn focused_workspace(&self) -> Option<&Workspace> { + self.workspaces.get(self.focused) + } +} + +/// Where a window is in the tree: on which monitor and workspace, and in which place on it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Location { + /// The [`Monitor::id`] of the monitor. + pub monitor_id: u64, + /// The name of the workspace. + pub workspace: String, + /// Where on the workspace. + pub place: Place, + /// Whether that workspace is the one showing on its monitor. + pub workspace_visible: bool, +} + +/// Where on a workspace a window is. +/// +/// Serialized as an object with the kebab-case variant name in `kind`: `{"kind": "container", +/// "index": 2, "tab": 0}`, `{"kind": "maximized"}`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(tag = "kind", rename_all = "kebab-case")] +pub enum Place { + /// In a tiled container. + Container { + /// Which of the workspace's containers: an index into [`Workspace::containers`]. + index: usize, + /// Which of the container's windows: an index into [`Container::windows`], 0 for the + /// first. + tab: usize, + }, + /// In the container that fills the workspace. + Monocle { + /// Which of the container's windows. + tab: usize, + }, + /// The window maximized on the workspace. + Maximized, + /// Floating above the tiles. + Floating { + /// Which of the workspace's floating windows: an index into [`Workspace::floating`]. + index: usize, + }, +} + +impl Place { + /// Returns the place as text for a reader: `container 2`, `container 2 tab 1` (the tab only + /// when it is not the first), `monocle`, `maximized` or `floating 0`. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::state::Place; + /// + /// assert_eq!(Place::Container { index: 2, tab: 0 }.describe(), "container 2"); + /// assert_eq!(Place::Container { index: 2, tab: 1 }.describe(), "container 2 tab 1"); + /// assert_eq!(Place::Maximized.describe(), "maximized"); + /// ``` + #[must_use] + pub fn describe(&self) -> String { + match self { + Self::Container { index, tab } if *tab > 0 => format!("container {index} tab {tab}"), + Self::Container { index, .. } => format!("container {index}"), + Self::Monocle { .. } => "monocle".to_string(), + Self::Maximized => "maximized".to_string(), + Self::Floating { index } => format!("floating {index}"), + } + } +} + +impl Location { + /// Returns the location as text for a reader: `monitor 3 workspace one (container 0)`. + #[must_use] + pub fn describe(&self) -> String { + format!( + "monitor {} workspace {} ({})", + self.monitor_id, + self.workspace, + self.place.describe() + ) + } +} + +/// The monitor, workspace and window that have the keyboard focus, as komorebi's state has them. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Focus { + /// The [`Monitor::id`] of the focused monitor. + pub monitor_id: u64, + /// The name of its focused workspace. + pub workspace: String, + /// The focused window's [`Window::id`]; `None` if the workspace has no window to focus. + pub window_id: Option, + /// Where the focused window is on the workspace; `None` when there is none. + pub place: Option, +} + +/// komorebi's whole `State` at one moment, read into a model. +/// +/// A snapshot is built with [`Snapshot::parse`], which never fails: a state with fields missing or +/// unknown reads with what is there, and what is not is empty or a default. It records which +/// [`Flavor`] wrote it, because what a window's position says depends on that (see +/// [`Snapshot::hides_windows_by_position`]); the flavor is not part of the serialized form. +/// +/// See the [module documentation](self) for an example. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Snapshot { + /// Which komorebi wrote this state, and so how to read the parts of it that mean different + /// things in each. Not part of the state itself. + #[serde(skip)] + #[schemars(skip)] + pub flavor: Flavor, + /// The monitors, in komorebi's order. + pub monitors: Vec, + /// Which of `monitors` has focus: an index into `monitors`. 0 if the state does not say. + pub focused_monitor: usize, + /// Whether komorebi was paused (`is_paused`); `false` if the state does not say. + pub paused: bool, +} + +fn array<'a>(value: &'a Value, key: &str) -> &'a [Value] { + value + .get(key) + .and_then(|ring| ring.get("elements")) + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice) +} + +fn focused(value: &Value, key: &str) -> usize { + value + .get(key) + .and_then(|ring| ring.get("focused")) + .and_then(Value::as_u64) + .map_or(0, |index| index as usize) +} + +fn text(value: &Value, key: &str) -> String { + value + .get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() +} + +fn window(rules: &dyn Rules, value: &Value) -> Option { + let id = rules.window_id(value)?; + // a mac window keeps its title and program under `details`, a Windows one beside the rest + let details = value.get("details").unwrap_or(value); + // what komorebi could not read it does not guess: its rect is a zero and its title an error + // message, which would read as a window parked at the corner of the screen + let unreadable = rules.window_is_unreadable(value); + Some(Window { + id, + title: text(details, "title"), + exe: text(details, "exe"), + rect: value + .get("rect") + .and_then(Rect::from_value) + .filter(|_| !unreadable), + }) +} + +fn container(rules: &dyn Rules, value: &Value) -> Container { + Container { + id: text(value, "id"), + windows: array(value, "windows") + .iter() + .filter_map(|value| window(rules, value)) + .collect(), + focused: focused(value, "windows"), + locked: value + .get("locked") + .and_then(Value::as_bool) + .unwrap_or(false), + } +} + +/// `{"Default": "Columns"}` or `"BSP"` or `{"Custom": ...}` as a short name. +fn layout_name(value: Option<&Value>) -> String { + match value { + Some(Value::String(name)) => name.clone(), + Some(Value::Object(object)) => { + object + .iter() + .next() + .map_or_else(String::new, |(key, inner)| match inner.as_str() { + Some(name) => name.to_string(), + None => key.clone(), + }) + } + _ => String::new(), + } +} + +fn workspace(rules: &dyn Rules, value: &Value) -> Workspace { + Workspace { + name: text(value, "name"), + containers: array(value, "containers") + .iter() + .map(|value| container(rules, value)) + .collect(), + focused: focused(value, "containers"), + monocle: value + .get("monocle_container") + .filter(|monocle| monocle.is_object()) + .map(|monocle| container(rules, monocle)), + maximized: value + .get("maximized_window") + .and_then(|value| window(rules, value)), + floating: array(value, "floating_windows") + .iter() + .filter_map(|value| window(rules, value)) + .collect(), + floating_focused: focused(value, "floating_windows"), + layer: text(value, "layer"), + layout: layout_name(value.get("layout")), + layout_rects: value + .get("latest_layout") + .and_then(Value::as_array) + .map(|rects| rects.iter().filter_map(Rect::from_value).collect()) + .unwrap_or_default(), + tiling: value.get("tile").and_then(Value::as_bool).unwrap_or(true), + } +} + +fn monitor(rules: &dyn Rules, value: &Value) -> Monitor { + let rect = |key: &str| { + value.get(key).and_then(Rect::from_value).unwrap_or(Rect { + left: 0, + top: 0, + width: 0, + height: 0, + }) + }; + + Monitor { + id: value + .get("id") + .and_then(|id| id.as_u64().or_else(|| id.as_i64().map(|id| id as u64))) + .unwrap_or(0), + device: text(value, "device"), + size: rect("size"), + work_area: rect("work_area_size"), + workspaces: array(value, "workspaces") + .iter() + .map(|value| workspace(rules, value)) + .collect(), + focused: focused(value, "workspaces"), + hiding_position: text(value, "window_hiding_position"), + } +} + +impl Snapshot { + /// Returns the model of a `State` as the komorebi of `flavor` serialized it. + /// + /// This never fails. The JSON is read tolerantly: unknown fields are ignored, and a missing one + /// is an empty list, empty text, 0 or `false` (`tiling` is `true`). A window the flavor's + /// [`Rules::window_id`] does not recognize as one is left out. Numbers in a rect may be floats; + /// they are rounded. + /// + /// `state` is what komorebi sent in a notification, or what the recorder stored in + /// `states/.json`. See the [module documentation](self) for an example. + #[must_use] + pub fn parse(flavor: Flavor, state: &Value) -> Self { + Self { + flavor, + monitors: array(state, "monitors") + .iter() + .map(|value| monitor(flavor.rules(), value)) + .collect(), + focused_monitor: focused(state, "monitors"), + paused: state + .get("is_paused") + .and_then(Value::as_bool) + .unwrap_or(false), + } + } + + /// A macOS state, for the tests, whose states all are. + #[cfg(test)] + #[must_use] + pub fn from_value(state: &Value) -> Self { + Self::parse(Flavor::Macos, state) + } + + /// Returns every window with where it is, in order: by monitor, then workspace, then the + /// tiled containers (each tab in turn), the monocle container, the maximized window and the + /// floating windows. + /// + /// A window that the state lists in two places appears twice. + #[must_use] + pub fn windows(&self) -> Vec<(Location, &Window)> { + let mut found = Vec::new(); + for monitor in &self.monitors { + for (index, workspace) in monitor.workspaces.iter().enumerate() { + let visible = index == monitor.focused; + let at = |place: Place| Location { + monitor_id: monitor.id, + workspace: workspace.name.clone(), + place, + workspace_visible: visible, + }; + + for (container_index, container) in workspace.containers.iter().enumerate() { + for (tab, window) in container.windows.iter().enumerate() { + found.push(( + at(Place::Container { + index: container_index, + tab, + }), + window, + )); + } + } + if let Some(monocle) = &workspace.monocle { + for (tab, window) in monocle.windows.iter().enumerate() { + found.push((at(Place::Monocle { tab }), window)); + } + } + if let Some(window) = &workspace.maximized { + found.push((at(Place::Maximized), window)); + } + for (floating_index, window) in workspace.floating.iter().enumerate() { + found.push(( + at(Place::Floating { + index: floating_index, + }), + window, + )); + } + } + } + + found + } + + /// Returns the first place a window with this id is, in the order of [`Snapshot::windows`], or + /// `None` if there is none. + #[must_use] + pub fn find(&self, window_id: u64) -> Option<(Location, &Window)> { + self.windows() + .into_iter() + .find(|(_, window)| window.id == window_id) + } + + /// Returns what has focus: the focused monitor's focused workspace's focused window, where a + /// floating layer beats the tiled containers and a monocle container beats the rest. + /// + /// The layer wins only when the workspace's `layer` is `Floating` and it has floating windows. + /// A `focused_monitor` that is not an index of `monitors` falls back to the first monitor. The + /// result is `None` if there is no monitor or the monitor has no focused workspace; a focused + /// workspace with nothing to focus is a [`Focus`] with no `window_id` and no `place`. + #[must_use] + pub fn focus(&self) -> Option { + let monitor = self + .monitors + .get(self.focused_monitor) + .or_else(|| self.monitors.first())?; + let workspace = monitor.focused_workspace()?; + + let (window, place) = if workspace.layer == "Floating" && !workspace.floating.is_empty() { + let index = workspace + .floating_focused + .min(workspace.floating.len().saturating_sub(1)); + ( + workspace.floating.get(index), + Some(Place::Floating { index }), + ) + } else if let Some(monocle) = &workspace.monocle { + ( + monocle.focused_window(), + Some(Place::Monocle { + tab: monocle.focused, + }), + ) + } else if let Some(container) = workspace.containers.get(workspace.focused) { + ( + container.focused_window(), + Some(Place::Container { + index: workspace.focused, + tab: container.focused, + }), + ) + } else { + (None, None) + }; + + Some(Focus { + monitor_id: monitor.id, + workspace: workspace.name.clone(), + window_id: window.map(|window| window.id), + place, + }) + } + + /// Returns whether a window's position says if it is hidden: komorebi for Mac parks a hidden + /// window in a corner, and komorebi for Windows by default cloaks it where it is, so there a + /// hidden window is not told from a visible one by where it is. + /// + /// This is [`Rules::hides_windows_by_position`] of the snapshot's flavor. Checks that depend on + /// where hidden windows are skip a snapshot for which it is `false`. + #[must_use] + pub fn hides_windows_by_position(&self) -> bool { + self.flavor.rules().hides_windows_by_position() + } + + /// Returns whether `rect` is where komorebi parks a window it has hidden on `monitor`. What that + /// looks like is up to the flavor of komorebi that recorded the state: it is + /// [`Rules::is_hidden_position`] of the snapshot's flavor. + #[must_use] + pub fn is_hidden_position(&self, rect: &Rect, monitor: &Monitor) -> bool { + self.flavor.rules().is_hidden_position(rect, monitor) + } + + /// Returns the monitor whose area holds most of `rect`, or `None` if `rect` overlaps none. On a + /// tie, the monitor later in `monitors` is returned. + #[must_use] + pub fn monitor_under(&self, rect: &Rect) -> Option<&Monitor> { + self.monitors + .iter() + .map(|monitor| (monitor.size.overlap_area(rect), monitor)) + .filter(|(area, _)| *area > 0) + .max_by_key(|(area, _)| *area) + .map(|(_, monitor)| monitor) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fixture() -> Snapshot { + let state: Value = + serde_json::from_str(include_str!("../../tests/fixtures/state.json")).expect("fixture"); + Snapshot::from_value(&state) + } + + #[test] + fn a_real_state_reads_into_monitors_workspaces_and_windows() { + let snapshot = fixture(); + + assert_eq!(snapshot.monitors.len(), 2); + assert_eq!(snapshot.monitors[0].id, 1); + assert_eq!(snapshot.monitors[0].device, "Built-in Retina Display"); + assert_eq!(snapshot.monitors[1].workspaces.len(), 10); + assert!(!snapshot.paused); + + let windows = snapshot.windows(); + assert!(windows.len() > 15); + let (location, slack) = snapshot.find(59).expect("window 59"); + assert_eq!(slack.exe, "Slack"); + assert_eq!(slack.title, "window 59"); + assert_eq!(location.monitor_id, 3); + assert_eq!(location.workspace, "one"); + assert_eq!(location.place, Place::Container { index: 0, tab: 0 }); + } + + #[test] + fn komorebis_right_and_bottom_are_read_as_width_and_height() { + let snapshot = fixture(); + let layout = &snapshot.monitors[1].workspaces[0].layout_rects; + // {"left": 10, "top": 10, "right": 1686, "bottom": 1420} + assert_eq!( + layout[0], + Rect { + left: 10, + top: 10, + width: 1686, + height: 1420 + } + ); + assert_eq!(layout[0].right_edge(), 1696); + } + + #[test] + fn layouts_have_short_names() { + assert_eq!(fixture().monitors[1].workspaces[0].layout, "Columns"); + assert_eq!(layout_name(Some(&serde_json::json!("BSP"))), "BSP"); + assert_eq!(layout_name(None), ""); + } + + #[test] + fn hidden_windows_sit_on_the_sliver_and_visible_ones_do_not() { + let snapshot = fixture(); + let monitor = &snapshot.monitors[1]; + let (_, hidden) = snapshot + .find(59) + .expect("a window on a workspace that is not showing"); + assert!(snapshot.is_hidden_position(hidden.rect.as_ref().expect("rect"), monitor)); + + let visible = Rect { + left: 10, + top: 10, + width: 1686, + height: 1420, + }; + assert!(!snapshot.is_hidden_position(&visible, monitor)); + } + + #[test] + fn focus_follows_the_focused_monitor_workspace_and_container() { + let focus = fixture().focus().expect("focus"); + // the second monitor (display 3) is focused, on workspace "ten", at its third container + assert_eq!(focus.monitor_id, 3); + assert_eq!(focus.workspace, "ten"); + assert_eq!(focus.window_id, Some(8550)); + assert_eq!(focus.place, Some(Place::Container { index: 2, tab: 0 })); + } + + fn workspace_state(extra: Value) -> Snapshot { + let mut workspace = serde_json::json!({ + "name": "w", "layer": "Tiling", + "containers": {"elements": [ + {"id": "a", "windows": {"elements": [{"id": 1, "rect": null}], "focused": 0}}, + {"id": "b", "windows": {"elements": [{"id": 2}], "focused": 0}} + ], "focused": 1}, + "floating_windows": {"elements": [{"id": 3}], "focused": 0}, + }); + for (key, value) in extra.as_object().expect("object") { + workspace[key] = value.clone(); + } + Snapshot::from_value(&serde_json::json!({ + "monitors": {"elements": [{"id": 1, "workspaces": {"elements": [workspace], "focused": 0}}], "focused": 0} + })) + } + + #[test] + fn a_monocle_container_beats_the_containers_and_a_floating_layer_beats_both() { + let plain = workspace_state(serde_json::json!({})); + assert_eq!(plain.focus().expect("focus").window_id, Some(2)); + + let monocle = workspace_state(serde_json::json!({ + "monocle_container": {"id": "m", "windows": {"elements": [{"id": 9}], "focused": 0}} + })); + assert_eq!(monocle.focus().expect("focus").window_id, Some(9)); + + let floating = workspace_state(serde_json::json!({ + "layer": "Floating", + "monocle_container": {"id": "m", "windows": {"elements": [{"id": 9}], "focused": 0}} + })); + assert_eq!(floating.focus().expect("focus").window_id, Some(3)); + } + + #[test] + fn missing_and_unknown_fields_do_not_break_reading() { + let snapshot = Snapshot::from_value(&serde_json::json!({"brand_new": 1})); + assert!(snapshot.monitors.is_empty()); + assert!(snapshot.focus().is_none()); + + let odd = Snapshot::from_value(&serde_json::json!({ + "monitors": {"elements": [{"id": 1, "future_field": [1, 2], "workspaces": {"elements": [{"name": "x", "monocle_container": null}]}}]} + })); + assert_eq!(odd.monitors[0].workspaces[0].name, "x"); + assert!(odd.monitors[0].workspaces[0].monocle.is_none()); + } + + #[test] + fn a_window_without_a_rect_has_none_and_overlap_is_computed() { + let snapshot = workspace_state(serde_json::json!({})); + assert!(snapshot.find(1).expect("window").1.rect.is_none()); + + let a = Rect { + left: 0, + top: 0, + width: 10, + height: 10, + }; + let b = Rect { + left: 5, + top: 5, + width: 10, + height: 10, + }; + assert_eq!(a.overlap_area(&b), 25); + assert_eq!( + a.overlap_area(&Rect { + left: 20, + top: 0, + width: 5, + height: 5 + }), + 0 + ); + assert_eq!(a.max_delta(&b), 5); + } +} diff --git a/komorebi-recorder/src/cli/mod.rs b/komorebi-recorder/src/cli/mod.rs index ecd24ad5..a0dc00f4 100644 --- a/komorebi-recorder/src/cli/mod.rs +++ b/komorebi-recorder/src/cli/mod.rs @@ -6,8 +6,11 @@ //! `--json` on a command also decides how a failure is reported (see [`Command::wants_json`]). mod doctor; +mod query; mod record; +use crate::analysis::envelope::unusable; +use crate::analysis::envelope::with_hint; use crate::session::Session; use clap::Args; use clap::Parser; @@ -17,6 +20,12 @@ use serde::Serialize; use std::path::PathBuf; pub use doctor::DoctorArgs; +pub use query::AtArgs; +pub use query::FilterArgs; +pub use query::FramesArgs; +pub use query::LocateArgs; +pub use query::RangeArgs; +pub use query::SummaryArgs; pub use record::RecordArgs; /// The command line of `komorebi-recorder`. @@ -49,6 +58,16 @@ pub enum Command { Displays, /// What this machine can do for a recording, and probes that measure what one leans on Doctor(DoctorArgs), + /// Everything recorded around a video timecode: komorebi log, events and OS trace + At(AtArgs), + /// Everything recorded between two video timecodes + Range(RangeArgs), + /// A per-bucket digest of the whole recording + Summary(SummaryArgs), + /// Reverse lookup: a UTC time, log line or event number to a video timecode + Locate(LocateArgs), + /// Extract PNG frames at video timecodes (needs ffmpeg) + Frames(FramesArgs), /// Rebuild a session's timeline from its raw files, recovering it first if the recorder died Reindex(ReindexArgs), /// Check the video-to-clock alignment against a rendered on-screen clock @@ -85,11 +104,20 @@ pub(crate) fn print_json(value: &impl Serialize) -> eyre::Result<()> { Ok(()) } +pub(crate) fn limit(value: usize) -> Option { + (value != 0).then_some(value) +} + impl Command { /// Whether this command was asked for JSON, which also decides how a failure is reported. #[must_use] pub fn wants_json(&self) -> bool { match self { + Self::At(args) => args.filter.json, + Self::Range(args) => args.filter.json, + Self::Summary(args) => args.json, + Self::Locate(args) => args.json, + Self::Frames(args) => args.json, Self::Doctor(args) => args.json, _ => false, } @@ -130,6 +158,11 @@ pub fn run(command: Command) -> eyre::Result<()> { Command::Record(args) => record::record(&args), Command::Displays => record::displays(), Command::Doctor(args) => doctor::doctor(&args), + Command::At(args) => query::at(&args), + Command::Range(args) => query::range(&args), + Command::Summary(args) => query::summary(&args), + Command::Locate(args) => query::locate(&args), + Command::Frames(args) => query::frames_command(&args), Command::Reindex(args) => reindex(&args), Command::Selftest(args) => crate::selftest::run(&args), Command::SelftestClock => crate::selftest::run_clock(), @@ -157,6 +190,28 @@ pub fn main() -> eyre::Result { )) } +pub(crate) fn load(session: &std::path::Path) -> eyre::Result<(Session, crate::session::Manifest)> { + let session = Session::open(session)?; + let manifest = session.manifest()?; + + if manifest.status == crate::session::STATUS_RECORDING { + let dir = session.dir.display(); + return Err(match crate::lock::recorder(&session.dir) { + crate::lock::Recorder::Running(_) => unusable(format!( + "{dir} is still being recorded; stop the recording first" + )), + crate::lock::Recorder::NotRunning | crate::lock::Recorder::Unknown => with_hint( + unusable(format!( + "{dir} was left unfinished: its recorder was killed or crashed" + )), + format!("recover it with `komorebi-recorder reindex {dir}`"), + ), + }); + } + + Ok((session, manifest)) +} + fn reindex(args: &ReindexArgs) -> eyre::Result<()> { let session = Session::open(&args.session)?; let reindexed = crate::recovery::reindex_session(&session)?; diff --git a/komorebi-recorder/src/cli/query.rs b/komorebi-recorder/src/cli/query.rs new file mode 100644 index 00000000..d665f318 --- /dev/null +++ b/komorebi-recorder/src/cli/query.rs @@ -0,0 +1,330 @@ +//! Reading a session back: `at`, `range`, `summary`, `locate` and `frames`. +//! +//! These read the session's timeline directly (see [`crate::timeline`]), not through an `Analysis`, +//! so they say what was recorded without interpreting it as the output of one komorebi or the +//! other. Times are video timecodes ([`crate::timecode`]). +//! +//! | Command | Asks | Prints | +//! |---|---|---| +//! | `at