From 0de0f8284034bd2f6d539d2b09196d27ce4fb82a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Tue, 27 Oct 2026 06:14:10 -0700 Subject: [PATCH] feat(flavor): read komorebi for Mac and for Windows Which komorebi produced a session is a separate axis from the host the recorder ran on. `Flavor` names the two and `Rules` holds what each knows: what its events look like on the wire, which of them move a window, and which are komorebi making things up. komorebi for Mac and komorebi for Windows each implement it, and a missing method is a compile error. The Windows rules were written from komorebi's source and say so until a recording confirms them. Events are classified through the rules, and the names of things in a session (`event:12`, `log:7`) are parsed here too, with the envelope and exit codes every command will answer in. --- docs/ARCHITECTURE.md | 23 + komorebi-recorder/src/analysis/classify.rs | 406 ++++++++++++++ komorebi-recorder/src/analysis/envelope.rs | 468 ++++++++++++++++ komorebi-recorder/src/analysis/events.rs | 175 ++++++ komorebi-recorder/src/analysis/flavor/mac.rs | 272 ++++++++++ komorebi-recorder/src/analysis/flavor/mod.rs | 510 ++++++++++++++++++ .../src/analysis/flavor/windows.rs | 351 ++++++++++++ komorebi-recorder/src/analysis/ids.rs | 264 +++++++++ komorebi-recorder/src/analysis/mod.rs | 12 + komorebi-recorder/src/lib.rs | 6 +- komorebi-recorder/src/platform/mod.rs | 6 +- 11 files changed, 2488 insertions(+), 5 deletions(-) create mode 100644 komorebi-recorder/src/analysis/classify.rs create mode 100644 komorebi-recorder/src/analysis/envelope.rs create mode 100644 komorebi-recorder/src/analysis/events.rs create mode 100644 komorebi-recorder/src/analysis/flavor/mac.rs create mode 100644 komorebi-recorder/src/analysis/flavor/mod.rs create mode 100644 komorebi-recorder/src/analysis/flavor/windows.rs create mode 100644 komorebi-recorder/src/analysis/ids.rs create mode 100644 komorebi-recorder/src/analysis/mod.rs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3261fc18..32234603 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -10,6 +10,11 @@ Two things about it vary independently, and everything below is arranged so that | axis | what varies | where the variation lives | what a session records | |---|---|---|---| | host | the OS the recorder runs on: macOS or Windows (a third `unsupported` host builds anywhere) | [`platform`](../komorebi-recorder/src/platform/mod.rs), selected by `cfg` | `host` in the manifest | +| flavor | the komorebi being recorded: komorebi for Mac or komorebi for Windows | `Rules` in [`analysis::flavor`](../komorebi-recorder/src/analysis/flavor/mod.rs), selected by data | `komorebi.flavor` in the manifest | + +They are independent because a session recorded on one host is investigated on whichever machine the investigator has. +A session recorded on Windows is read on a Mac, and the other way round, so reading never asks which host it is +running on: it asks the session. ## The master clock @@ -43,9 +48,27 @@ only on a third OS. Where one host has no analogue of something, the facade function exists on both and one answers "nothing": `trace::start` on the `unsupported` host returns no taps and a line saying so, and `power::start` returns no watcher. +## Flavors and rules + +Which komorebi produced a session decides what its events mean (a process id and an accessibility notification on a Mac, +a window handle and a WinEvent on Windows), how it hides a window (by moving it to a corner on a Mac, by cloaking it in +place on Windows) and how its log marks where a handler starts and ends. `Flavor` names the two and is recorded in the +manifest. `Rules` is the trait that holds what each knows, and `Flavor::rules` is where a name becomes rules. Code that +reads komorebi's output asks `Rules` and does not match on `Flavor`; only convention holds that, and it has exceptions: +the index of komorebi's source that log lines are mapped to, and the places the log and a checkout of the source are +looked for on disk, are keyed by `Flavor` directly. + +The contract is a counting rule: a flavor implements every method of `Rules` that has no default, and the compiler +refuses an implementor that misses one. A method with a default is a question most flavors answer the same way, and the +doc of each says what the default is. `Rules::verified` is how a flavor says that its rules were written from komorebi's +source and have not been checked against a recording of it: an analysis that reads such a session says so. + ## Rules and the layer that enforces them | Rule | Enforced by | |---|---| | Every host provides the same functions with the same signatures | the compiler, for the host being built; `just check-windows` and CI build the Windows host from a Mac; nothing builds `unsupported` | | A timestamp in a session is on the master clock | convention, and the tests that place records at known times: the type is a plain `u64` | +| An implementor of `Rules` answers every question that has no default | the type system: a missing method is E0046, proved by a `compile_fail` example on `Rules` | +| Code that reads komorebi's output asks `Rules` and does not match on `Flavor` | convention only | +| Rules that were not checked against a recording of komorebi say so | the framework path: an analysis that reads such a session adds a warning | diff --git a/komorebi-recorder/src/analysis/classify.rs b/komorebi-recorder/src/analysis/classify.rs new file mode 100644 index 00000000..a99ed81a --- /dev/null +++ b/komorebi-recorder/src/analysis/classify.rs @@ -0,0 +1,406 @@ +//! What kind of thing each event was, and which ones are noise. +//! +//! A recording of komorebi at work is mostly events nobody asked for: when komorebi moves a window +//! the OS reports the move back, so a single command is followed by a burst of `MoveEnd` +//! notifications for the windows it just placed. Reading those as if the user had dragged windows +//! around sends an investigation the wrong way, so events are classified, with the reason. +//! +//! The classification is a judgement made from the event, its neighbours and whether the state +//! changed, and the `reason` explains it. It never hides an event; it labels it. +//! +//! Two parties make it. Which class a single event has depends on komorebi's vocabulary, so the +//! [`Rules`] of the flavor that recorded the session answer that: +//! [`Rules::classify_window_manager`] for what the OS reported and [`Rules::classify_monitor`] for +//! a display or machine notification. What only the neighbours can tell, an echo, and whether a +//! button release was a real drag, is the same for both flavors and is decided here, by +//! [`classify`]. + +use super::events::EventRecord; +use super::events::Family; +use super::flavor::Rules; +use schemars::JsonSchema; +use serde::Serialize; + +/// The kind of thing an event was. +/// +/// Serialized in kebab case (`command`, `drag`, ..., `other`). A class tells a reader what to make +/// of an event in a recording; the [`Classification`] that carries it gives the reason. +/// +/// Most are answers of the flavor's [`Rules`]. [`classify`] itself gives [`Class::Command`] to every +/// command that is not a query, and [`Class::Other`] to a query or an unreadable notification. It +/// derives [`Class::Echo`] from an event and its neighbours, and a [`Rules`] implementor never +/// answers that one. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum Class { + /// Sent to komorebi by `komorebic` or a hotkey daemon. + Command, + /// The OS reported a window being moved or resized, not caused by komorebi. + Drag, + /// Which application or window has focus changed. + Focus, + /// A window or application appeared, went away, was minimized or restored. On Windows, also a + /// window hidden or shown, which is often komorebi cloaking the windows of a workspace it left. + Lifecycle, + /// The OS reporting back a move or resize komorebi itself had just made. + Echo, + /// komorebi's own synthetic events: a show it made up, a button release its mouse listener + /// reported as the end of a move or resize that moved nothing, or (on Windows) a window it + /// raised. + Manual, + /// A display was connected, disconnected or resized. + Monitor, + /// Screen lock, unlock or a space change. On Windows, also a sleep or wake and a virtual + /// desktop left or returned to. + Lock, + /// None of the above: a query or a subscription (usually this recorder talking to komorebi), an + /// event no rule recognizes, or a notification that could not be read. + Other, +} + +/// A [`Class`] and the reason for it. +/// +/// The reason is a sentence for a reader, written by whoever gave the class: a [`Rules`] method, +/// or [`classify`] for an echo, a promoted drag, a command and a query. It names the evidence +/// where there is some (an echo names the event it followed and how long after). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct Classification { + /// The kind of event it was. + pub class: Class, + /// Why it was given that class. + pub reason: String, +} + +/// How long after komorebi acts the OS may still be reporting the windows it moved. +const ECHO_WINDOW_NS: u64 = 1_500_000_000; + +/// Commands that ask komorebi something or register a listener rather than change anything. +fn is_bookkeeping(name: &str) -> bool { + matches!( + name, + "State" + | "GlobalState" + | "DebugWindow" + | "AddSubscriberSocket" + | "AddSubscriberSocketWithOptions" + | "RemoveSubscriberSocket" + ) || name.starts_with("Query") +} + +fn class_of(event: &EventRecord, rules: &dyn Rules) -> Classification { + let (class, reason) = match event.info.family { + Family::Command if is_bookkeeping(&event.info.name) => ( + Class::Other, + "a query or subscription, not a change: usually this recorder talking to komorebi", + ), + Family::Command => (Class::Command, "a command sent to komorebi"), + Family::Monitor => rules.classify_monitor(event), + Family::Unknown => (Class::Other, "the notification could not be read"), + Family::WindowManager => rules.classify_window_manager(event), + }; + + Classification { + class, + reason: reason.to_string(), + } +} + +/// Returns the [`Classification`] of every event: one per event, in the same order. +/// +/// `events` must be in receipt order, which is how `events::load` returns +/// them. Each event is first classified alone: a command is [`Class::Command`], except a query or +/// subscription (`State`, `GlobalState`, `DebugWindow`, `AddSubscriberSocket`, +/// `AddSubscriberSocketWithOptions`, `RemoveSubscriberSocket`, or a name that starts with +/// `Query`), which is [`Class::Other`]; an event that could not be read is [`Class::Other`]; a +/// window-manager event or a monitor notification is whatever +/// [`Rules::classify_window_manager`] or [`Rules::classify_monitor`] returns. Then the neighbours +/// are looked at, and two labels change: +/// +/// - A [`Class::Manual`] event that [`Rules::is_geometry_event`] names, after which the state +/// changed (it has a different state id from the event before, and both have one), is a real +/// drag: [`Class::Drag`]. +/// - A [`Class::Drag`] after which the state did not change (the same state id as the event +/// before) is an echo, [`Class::Echo`], if komorebi acted shortly before: looking back from it +/// for the nearest earlier event that is a command, focus, lifecycle, monitor or lock event, +/// that event was received at most 1.5 s earlier. An event with no state id is never called an +/// echo. +/// +/// When the pattern does not hold (the move changed the state, nothing happened in the second and +/// a half before it, or the state is not known) the event stays a drag. It is a judgement, not a +/// proof, and the reason gives what it was based on. +/// +/// # Example +/// +/// A move that changes nothing right after a command is the OS reporting the command back; the same +/// move later, with the layout changed, is a real one: +/// +/// ```rust +/// use komorebi_recorder::analysis::classify::{classify, Class}; +/// use komorebi_recorder::analysis::events::EventRecord; +/// use komorebi_recorder::analysis::flavor::Flavor; +/// use serde_json::json; +/// +/// let rules = Flavor::Macos.rules(); +/// let event = |seq: u64, at_ms: u64, state_id: u64, value: serde_json::Value| EventRecord { +/// seq, +/// recv_mach_ns: at_ms * 1_000_000, +/// recv_wall_us: 0, +/// state_id: Some(state_id), +/// info: rules.describe_event(&value), +/// parse_error: None, +/// }; +/// +/// let moved = json!({ +/// "type": "MoveEnd", +/// "content": [{"type": "Accessibility", "content": "AXWindowMoved"}, 10, 7] +/// }); +/// let events = vec![ +/// event(1, 0, 1, json!({"type": "FocusWorkspaceNumber", "content": 1})), +/// event(2, 80, 1, moved.clone()), // state unchanged, 80 ms after the command +/// event(3, 10_000, 2, moved), // much later, and the state changed +/// ]; +/// +/// let found = classify(&events, rules); +/// let classes: Vec = found.iter().map(|found| found.class).collect(); +/// assert_eq!(classes, [Class::Command, Class::Echo, Class::Drag]); +/// assert!(found[1].reason.contains("FocusWorkspaceNumber")); +/// ``` +#[must_use] +pub fn classify(events: &[EventRecord], rules: &dyn Rules) -> Vec { + let mut classes: Vec = + events.iter().map(|event| class_of(event, rules)).collect(); + + for index in 0..events.len() { + let event = &events[index]; + + // a release that did change the layout was a real drag + if classes[index].class == Class::Manual + && rules.is_geometry_event(&event.info.name) + && index > 0 + && event.state_id.is_some() + && events[index - 1].state_id.is_some() + && event.state_id != events[index - 1].state_id + { + classes[index] = Classification { + class: Class::Drag, + reason: "the end of a mouse drag or resize, and the layout changed because of it" + .to_string(), + }; + continue; + } + + if classes[index].class != Class::Drag { + continue; + } + + // a move or resize that changed nothing, soon after komorebi acted, is komorebi's own + let unchanged = + index > 0 && event.state_id.is_some() && event.state_id == events[index - 1].state_id; + if !unchanged { + continue; + } + + let acted = (0..index).rev().find_map(|earlier| { + let gap = event + .recv_mach_ns + .saturating_sub(events[earlier].recv_mach_ns); + if gap > ECHO_WINDOW_NS { + return Some(None); + } + + matches!( + classes[earlier].class, + Class::Command | Class::Focus | Class::Lifecycle | Class::Monitor | Class::Lock + ) + .then(|| Some((earlier, gap))) + }); + + if let Some(Some((earlier, gap))) = acted { + classes[index] = Classification { + class: Class::Echo, + reason: format!( + "state unchanged, {:.0} ms after komorebi handled {} (#{}): the OS reporting back windows komorebi moved", + gap as f64 / 1e6, + events[earlier].info.summary(), + events[earlier].seq + ), + }; + } + } + + classes +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::analysis::flavor::Flavor; + use serde_json::json; + + fn event(seq: u64, at_ms: u64, state_id: Option, value: serde_json::Value) -> EventRecord { + EventRecord { + seq, + recv_mach_ns: at_ms * 1_000_000, + recv_wall_us: 0, + state_id, + info: Flavor::Macos.rules().describe_event(&value), + parse_error: None, + } + } + + fn command(seq: u64, at_ms: u64, state: u64) -> EventRecord { + event( + seq, + at_ms, + Some(state), + json!({"type": "FocusWorkspaceNumber", "content": 1}), + ) + } + + fn move_end(seq: u64, at_ms: u64, state: u64) -> EventRecord { + event( + seq, + at_ms, + Some(state), + json!({"type": "MoveEnd", "content": [{"type": "Accessibility", "content": "AXWindowMoved"}, 10, 7]}), + ) + } + + fn classes(events: &[EventRecord]) -> Vec { + classify(events, Flavor::Macos.rules()) + .iter() + .map(|c| c.class) + .collect() + } + + #[test] + fn each_family_and_name_has_a_class() { + let events = vec![ + command(1, 0, 1), + event(2, 10, Some(2), json!({"DisplayConnectionChange": 1})), + event( + 3, + 20, + Some(3), + json!({"type": "FocusChange", "content": [{"type": "Accessibility", "content": "AXApplicationActivated"}, 1, null]}), + ), + event( + 4, + 30, + Some(4), + json!({"type": "Show", "content": [{"type": "Accessibility", "content": "AXWindowCreated"}, 1]}), + ), + event( + 5, + 40, + Some(5), + json!({"type": "Show", "content": [{"type": "Manual", "content": "ShowOnInputEvent"}, 1]}), + ), + event( + 6, + 50, + Some(6), + json!({"type": "ScreenLock", "content": [{"type": "Accessibility", "content": "x"}, 1]}), + ), + ]; + + assert_eq!( + classes(&events), + [ + Class::Command, + Class::Monitor, + Class::Focus, + Class::Lifecycle, + Class::Manual, + Class::Lock + ] + ); + } + + fn synthesized_move_end(seq: u64, at_ms: u64, state: u64) -> EventRecord { + event( + seq, + at_ms, + Some(state), + json!({"type": "MoveEnd", "content": [{"type": "Manual", "content": "MoveEnd"}, 10, 7]}), + ) + } + + #[test] + fn a_button_release_komorebi_made_up_is_not_an_echo_of_a_move() { + // seen on a real recording: a click, then komorebi's mouse listener reports MoveEnd and + // ResizeEnd with the notification "MoveEnd" rather than one of macOS's + let events = vec![command(1, 0, 1), synthesized_move_end(2, 100, 1)]; + let found = classify(&events, Flavor::Macos.rules()); + assert_eq!(found[1].class, Class::Manual); + assert!( + found[1].reason.contains("mouse listener"), + "{}", + found[1].reason + ); + + // but one after which the layout really changed is a drag that ended + let dragged = vec![command(1, 0, 1), synthesized_move_end(2, 100, 2)]; + assert_eq!( + classify(&dragged, Flavor::Macos.rules())[1].class, + Class::Drag + ); + } + + #[test] + fn queries_and_subscriptions_are_not_commands() { + let events = vec![ + event( + 1, + 0, + Some(1), + json!({"type": "AddSubscriberSocketWithOptions", "content": ["x", {}]}), + ), + event(2, 10, Some(1), json!({"type": "State"})), + event(3, 20, Some(1), json!({"type": "QueryFocusedWorkspaceName"})), + ]; + assert_eq!(classes(&events), [Class::Other, Class::Other, Class::Other]); + } + + #[test] + fn a_move_that_changed_the_state_is_a_real_move() { + let events = vec![command(1, 0, 1), move_end(2, 200, 2)]; + assert_eq!(classes(&events), [Class::Command, Class::Drag]); + } + + #[test] + fn moves_that_change_nothing_right_after_a_command_are_echoes_of_it() { + // the burst seen after FocusWorkspaceNumber in a real log: one MoveEnd per window + let events = vec![ + command(1, 0, 1), + move_end(2, 80, 1), + move_end(3, 120, 1), + move_end(4, 160, 1), + ]; + + let found = classify(&events, Flavor::Macos.rules()); + assert_eq!(found[1].class, Class::Echo); + assert_eq!(found[3].class, Class::Echo); + assert!( + found[1].reason.contains("FocusWorkspaceNumber"), + "{}", + found[1].reason + ); + assert!(found[1].reason.contains("#1")); + } + + #[test] + fn an_unchanged_move_long_after_anything_is_not_called_an_echo() { + let events = vec![command(1, 0, 1), move_end(2, 10_000, 1)]; + assert_eq!(classes(&events), [Class::Command, Class::Drag]); + } + + #[test] + fn an_unchanged_move_with_no_state_is_not_called_an_echo() { + let events = vec![command(1, 0, 1), move_end(2, 100, 1)]; + let mut without = events.clone(); + without[1].state_id = None; + assert_eq!(classes(&without)[1], Class::Drag); + assert_eq!(classes(&events)[1], Class::Echo); + } +} diff --git a/komorebi-recorder/src/analysis/envelope.rs b/komorebi-recorder/src/analysis/envelope.rs new file mode 100644 index 00000000..aff362ab --- /dev/null +++ b/komorebi-recorder/src/analysis/envelope.rs @@ -0,0 +1,468 @@ +//! The shape every investigation command prints with `--json`, and how a failure maps to an exit +//! code. +//! +//! An agent driving the CLI should never have to guess whether a command worked, whether the output +//! was cut short, or why it failed, so every command answers with the same envelope and exits with +//! a code that names the kind of failure it was. +//! +//! There are two halves. An [`Envelope`] is what a command prints: `ok`, the `schema` that names +//! the shape of its `data`, the `data`, any `warnings`, whether the output was `truncated` (and the +//! `next_cursor` to ask for the rest) and, on failure, an `error`. An [`ExitKind`] is the kind of a +//! failure, and decides the process's exit code. Code that fails returns an [`eyre::Report`] built +//! by [`usage`], [`not_found`], [`unusable`] or [`over_budget`]; [`exit_kind`] reads the kind back +//! out of a report, however much context was added to it on the way up, and +//! `crate::cli::execute` turns it into the exit code and, with `--json`, an envelope. +//! +//! | Exit code | [`ExitKind`] | Meaning | +//! |---|---|---| +//! | 0 | [`Ok`](ExitKind::Ok) | the command worked | +//! | 1 | [`Error`](ExitKind::Error) | something went wrong that is none of the kinds below | +//! | 2 | [`Usage`](ExitKind::Usage) | the command line was wrong | +//! | 3 | [`NotFound`](ExitKind::NotFound) | the session, or something asked for in it, does not exist | +//! | 4 | [`Unusable`](ExitKind::Unusable) | the session exists but cannot answer: still recording, or it recorded nothing | +//! | 5 | [`Budget`](ExitKind::Budget) | the answer would have exceeded the time or size budget | +//! +//! The codes are stable. [`ENVELOPE_VERSION`] is bumped when the envelope's own fields change; +//! the shape of each command's `data` is versioned by its `schema` (`brief/1`), and the +//! `schemas` module has them. +//! +//! # Example +//! +//! A failure, with a hint for what to do next, and what a command makes of it: +//! +//! ```rust +//! use komorebi_recorder::analysis::envelope::{self, Envelope, ExitKind}; +//! +//! let failure = envelope::with_hint( +//! envelope::unusable("/tmp/s is still being recorded"), +//! "stop the recording first", +//! ); +//! assert_eq!(envelope::exit_kind(&failure), ExitKind::Unusable); +//! assert_eq!(envelope::exit_kind(&failure).code(), 4); +//! +//! // with --json the same failure is printed as an envelope with `ok: false` +//! let json = serde_json::to_value(Envelope::failed(&failure))?; +//! assert_eq!(json["ok"], false); +//! assert_eq!(json["schema"], "error/1"); +//! assert_eq!(json["error"]["kind"], "unusable"); +//! assert_eq!(json["error"]["code"], 4); +//! assert_eq!(json["error"]["hint"], "stop the recording first"); +//! +//! // and a success has the same fields, with `data` in place of `error` +//! let json = serde_json::to_value(Envelope::ok("demo/1", vec![1, 2, 3]))?; +//! assert_eq!(json["ok"], true); +//! assert_eq!(json["data"], serde_json::json!([1, 2, 3])); +//! assert!(json["error"].is_null()); +//! # Ok::<(), Box>(()) +//! ``` + +use color_eyre::eyre; +use schemars::JsonSchema; +use serde::Serialize; +use std::fmt; + +/// Bumped when the envelope's own fields change (each command's `data` is versioned by `schema`). +pub const ENVELOPE_VERSION: u32 = 1; + +/// How the process exits: the kind of a failure, and the exit code that goes with it. +/// +/// Serialized in kebab case (`ok`, `error`, `usage`, `not-found`, `unusable`, `budget`) in an +/// envelope's `error.kind`. [`ExitKind::code`] gives the exit code. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum ExitKind { + /// The command worked: exit code 0. + Ok, + /// Something went wrong that is not one of the cases below: exit code 1. This is also the kind + /// of any error that does not carry one. + Error, + /// The command line was wrong: exit code 2. For example an argument that does not parse (a + /// time like `soon`) or a path that points outside the session. + Usage, + /// The session, or something asked for in it, does not exist: exit code 3. + NotFound, + /// The session exists but cannot answer: still recording, or it recorded nothing. Exit code 4. + Unusable, + /// The answer would have exceeded the time or size budget: exit code 5. Narrowing the request + /// is the way forward. + Budget, +} + +impl ExitKind { + /// Returns the process exit code of this kind: 0 for [`ExitKind::Ok`], then 1 to 5 in the order + /// the variants are declared. + /// + /// The mapping is stable, so a script may rely on the numbers (`exit_codes_are_stable` pins + /// them). + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::envelope::ExitKind; + /// + /// assert_eq!(ExitKind::Ok.code(), 0); + /// assert_eq!(ExitKind::Usage.code(), 2); + /// assert_eq!(ExitKind::NotFound.code(), 3); + /// assert_eq!(ExitKind::Budget.code(), 5); + /// ``` + #[must_use] + pub fn code(self) -> u8 { + match self { + Self::Ok => 0, + Self::Error => 1, + Self::Usage => 2, + Self::NotFound => 3, + Self::Unusable => 4, + Self::Budget => 5, + } + } +} + +/// An error that carries how the process should exit and, optionally, what to do about it. +/// +/// It is not built directly: [`usage`], [`not_found`], [`unusable`] and [`over_budget`] make one and +/// return it as an [`eyre::Report`], and [`with_hint`] adds the hint. Its [`Display`](fmt::Display) +/// is the message, followed by the hint in parentheses when there is one. +#[derive(Debug)] +pub struct CliError { + /// How the process should exit. + pub kind: ExitKind, + /// A description of what went wrong, for a reader. + pub message: String, + /// A suggestion for what the caller can do next, if there is one. + pub hint: Option, +} + +impl fmt::Display for CliError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message)?; + if let Some(hint) = &self.hint { + write!(f, " ({hint})")?; + } + Ok(()) + } +} + +impl std::error::Error for CliError {} + +fn failure(kind: ExitKind, message: impl Into) -> eyre::Report { + eyre::Report::new(CliError { + kind, + message: message.into(), + hint: None, + }) +} + +/// Returns an error of kind [`ExitKind::Usage`] with this message: the command line was wrong. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::envelope::{self, ExitKind}; +/// +/// let error = envelope::usage("an empty time"); +/// assert_eq!(envelope::exit_kind(&error), ExitKind::Usage); +/// assert_eq!(error.to_string(), "an empty time"); +/// ``` +pub fn usage(message: impl Into) -> eyre::Report { + failure(ExitKind::Usage, message) +} + +/// Returns an error of kind [`ExitKind::NotFound`] with this message: the session, or something +/// asked for in it, does not exist. +pub fn not_found(message: impl Into) -> eyre::Report { + failure(ExitKind::NotFound, message) +} + +/// Returns an error of kind [`ExitKind::Unusable`] with this message: the session exists but +/// cannot answer. +pub fn unusable(message: impl Into) -> eyre::Report { + failure(ExitKind::Unusable, message) +} + +/// Returns an error of kind [`ExitKind::Budget`] with this message: the answer would have +/// exceeded the time or size budget. +/// +/// The message should say how to narrow the request. It is made from an `Exceeded` of the +/// `budget` module where the scan has one. +pub fn over_budget(message: impl Into) -> eyre::Report { + failure(ExitKind::Budget, message) +} + +/// Returns the same failure with a pointer to what the caller can do next. +/// +/// If `report` is a [`CliError`], its kind is kept and the hint is set on it (replacing an earlier +/// hint). That holds for a [`CliError`] that has had context added with `wrap_err` as well, but the +/// result is then the [`CliError`] alone: the context that was added is not kept. Any other error +/// becomes the context of the hint: the hint is then the outermost message, and the kind is +/// [`ExitKind::Error`]. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::envelope::{self, ExitKind}; +/// +/// let error = envelope::with_hint( +/// envelope::unusable("still recording"), +/// "run `reindex` if it died", +/// ); +/// assert_eq!(envelope::exit_kind(&error), ExitKind::Unusable); +/// assert_eq!(error.to_string(), "still recording (run `reindex` if it died)"); +/// ``` +pub fn with_hint(report: eyre::Report, hint: impl Into) -> eyre::Report { + match report.downcast::() { + Ok(mut error) => { + error.hint = Some(hint.into()); + eyre::Report::new(error) + } + Err(report) => report.wrap_err(hint.into()), + } +} + +/// Returns how `report` should make the process exit. +/// +/// The kind is that of the first [`CliError`] anywhere in the report's chain of causes, so context +/// added with `wrap_err` on the way up does not change it. A report with none is +/// [`ExitKind::Error`]. +/// +/// # Example +/// +/// ```rust +/// use color_eyre::eyre::WrapErr; +/// use komorebi_recorder::analysis::envelope::{self, ExitKind}; +/// +/// let report = Err::<(), _>(envelope::not_found("no such event")) +/// .wrap_err("while resolving the start") +/// .unwrap_err(); +/// assert_eq!(envelope::exit_kind(&report), ExitKind::NotFound); +/// +/// // an error from anywhere else is the generic kind +/// let plain = color_eyre::eyre::Report::msg("boom"); +/// assert_eq!(envelope::exit_kind(&plain), ExitKind::Error); +/// ``` +#[must_use] +pub fn exit_kind(report: &eyre::Report) -> ExitKind { + report + .chain() + .find_map(|cause| cause.downcast_ref::()) + .map_or(ExitKind::Error, |error| error.kind) +} + +/// The `error` of a failed [`Envelope`]: the kind of failure and what to do about it. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ErrorBody { + /// The kind of failure, in kebab case. + pub kind: ExitKind, + /// The process exit code of `kind`, which is also this command's exit status. + pub code: u8, + /// The message of the outermost error. When the error has a hint this includes it, in + /// parentheses, as [`CliError`]'s `Display` does. + pub message: String, + /// A suggestion for what the caller can do next, if the error gave one. + pub hint: Option, +} + +/// The JSON object every command prints with `--json`. +/// +/// Every command prints this shape, whatever it answers: `data` varies and is described by +/// `schema`, and the other fields mean the same everywhere. On success `ok` is `true`, `data` is +/// the answer and `error` is `null`. On failure `ok` is `false`, `data` is `null`, and `error` +/// describes what happened. On failure the process exit code is `error.code`; on success it is 0. +/// +/// The fields are serialized in this order: `ok`, `schema`, `envelope_version`, `data`, +/// `warnings`, `truncated`, `next_cursor`, `error`. They are always present; an absent value is +/// `null` or an empty list. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::envelope::Envelope; +/// +/// let envelope = Envelope::ok("events/1", vec!["event:1", "event:2"]) +/// .warnings(vec!["the log level was info".to_string()]) +/// .truncated(Some("2".to_string())); +/// +/// let json = serde_json::to_value(&envelope)?; +/// assert_eq!(json["ok"], true); +/// assert_eq!(json["schema"], "events/1"); +/// assert_eq!(json["warnings"][0], "the log level was info"); +/// // cut short: pass the cursor back as `--cursor` for the rest +/// assert_eq!(json["truncated"], true); +/// assert_eq!(json["next_cursor"], "2"); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug, Serialize, JsonSchema)] +pub struct Envelope { + /// Whether the command worked. + pub ok: bool, + /// Which command's `data` this is, e.g. `brief/1`; see `komorebi-recorder schema`. + pub schema: String, + /// The version of the envelope's own fields: [`ENVELOPE_VERSION`]. + pub envelope_version: u32, + /// The command's answer, shaped as `schema` says. `None` (`null`) on failure. + pub data: Option, + /// Things that went wrong reading the session that did not stop the answer, shown with it. + pub warnings: Vec, + /// The output was cut short; pass `next_cursor` back as `--cursor` for the rest. + pub truncated: bool, + /// Where to continue from when `truncated`, as the command's `--cursor` takes it. `None` + /// (`null`) when the output was not cut short, or was but the command has no cursor to give. + pub next_cursor: Option, + /// Why the command failed. `None` (`null`) on success. + pub error: Option, +} + +impl Envelope { + /// Returns the envelope of a successful command: `ok`, with `data` as the answer to the command + /// whose output is described by `schema`. + /// + /// The envelope has no warnings, is not truncated and has no error; add warnings with + /// [`Envelope::warnings`] and mark a cut-short answer with [`Envelope::truncated`]. + #[must_use] + pub fn ok(schema: &str, data: T) -> Self { + Self { + ok: true, + schema: schema.to_string(), + envelope_version: ENVELOPE_VERSION, + data: Some(data), + warnings: Vec::new(), + truncated: false, + next_cursor: None, + error: None, + } + } + + /// Returns the envelope with `warnings` as its warnings. They replace any that were there. + #[must_use] + pub fn warnings(mut self, warnings: Vec) -> Self { + self.warnings = warnings; + self + } + + /// Returns the envelope marked as cut short, with `next_cursor` as how to ask for the rest. + /// + /// A `next_cursor` of `None` still marks the output truncated. + #[must_use] + pub fn truncated(mut self, next_cursor: Option) -> Self { + self.truncated = true; + self.next_cursor = next_cursor; + self + } +} + +impl Envelope<()> { + /// Returns the envelope of a failed command: `ok` is `false`, the `schema` is `error/1`, and + /// the `error` has the kind and exit code of `report` ([`exit_kind`]). + /// + /// The `message` is the outermost error of the report, not the whole chain of causes. A + /// [`CliError`] with a hint has the hint in its message as well as in `hint`. The `hint` is the + /// one of the first [`CliError`] in the chain, if it has one. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::envelope::{self, Envelope}; + /// + /// let report = envelope::not_found("there is no event #99"); + /// let envelope = Envelope::failed(&report); + /// + /// assert!(!envelope.ok); + /// assert!(envelope.data.is_none()); + /// let error = envelope.error.expect("a failed envelope has an error"); + /// assert_eq!(error.code, 3); + /// assert_eq!(error.message, "there is no event #99"); + /// assert_eq!(error.hint, None); + /// ``` + #[must_use] + pub fn failed(report: &eyre::Report) -> Self { + let kind = exit_kind(report); + let hint = report + .chain() + .find_map(|cause| cause.downcast_ref::()) + .and_then(|error| error.hint.clone()); + + Self { + ok: false, + schema: "error/1".to_string(), + envelope_version: ENVELOPE_VERSION, + data: None, + warnings: Vec::new(), + truncated: false, + next_cursor: None, + error: Some(ErrorBody { + kind, + code: kind.code(), + message: report + .chain() + .next() + .map_or_else(String::new, ToString::to_string), + hint, + }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exit_codes_are_stable() { + let codes: Vec = [ + ExitKind::Ok, + ExitKind::Error, + ExitKind::Usage, + ExitKind::NotFound, + ExitKind::Unusable, + ExitKind::Budget, + ] + .iter() + .map(|kind| kind.code()) + .collect(); + assert_eq!(codes, [0, 1, 2, 3, 4, 5]); + } + + #[test] + fn a_plain_error_exits_with_the_generic_code() { + assert_eq!(exit_kind(&eyre::Report::msg("boom")), ExitKind::Error); + } + + #[test] + fn the_kind_survives_added_context() { + use color_eyre::eyre::WrapErr; + + let report = Err::<(), _>(not_found("no such event")) + .wrap_err("while resolving the start") + .unwrap_err(); + assert_eq!(exit_kind(&report), ExitKind::NotFound); + } + + #[test] + fn a_hint_travels_with_the_error() { + let report = with_hint(unusable("still recording"), "run `reindex` if it died"); + assert_eq!(exit_kind(&report), ExitKind::Unusable); + + let envelope = Envelope::failed(&report); + let body = envelope.error.expect("error body"); + assert_eq!(body.code, 4); + assert_eq!(body.hint.as_deref(), Some("run `reindex` if it died")); + assert!(!envelope.ok); + } + + #[test] + fn the_envelope_has_a_fixed_shape() { + let envelope = Envelope::ok("demo/1", vec![1, 2, 3]) + .warnings(vec!["careful".to_string()]) + .truncated(Some("c2".to_string())); + let value = serde_json::to_value(&envelope).expect("serialize"); + + assert_eq!(value["ok"], true); + assert_eq!(value["schema"], "demo/1"); + assert_eq!(value["envelope_version"], ENVELOPE_VERSION); + assert_eq!(value["data"], serde_json::json!([1, 2, 3])); + assert_eq!(value["warnings"], serde_json::json!(["careful"])); + assert_eq!(value["truncated"], true); + assert_eq!(value["next_cursor"], "c2"); + assert!(value["error"].is_null()); + } +} diff --git a/komorebi-recorder/src/analysis/events.rs b/komorebi-recorder/src/analysis/events.rs new file mode 100644 index 00000000..ed9d3f9c --- /dev/null +++ b/komorebi-recorder/src/analysis/events.rs @@ -0,0 +1,175 @@ +//! komorebi's subscriber events, understood. +//! +//! `events.jsonl` keeps each notification's JSON as komorebi serialized it. Three kinds reach a +//! subscriber and they look different on the wire: +//! +//! - window-manager events, from the OS: `{"type":"MoveEnd","content":[{"type":"Accessibility", +//! "content":"AXWindowMoved"},,]}` +//! - commands, from `komorebic` or a hotkey daemon: `{"type":"FocusWorkspaceNumber","content":0}` +//! - monitor changes: `{"DisplayConnectionChange":}` +//! +//! The shapes above are komorebi for Mac's. komorebi for Windows serializes the same three kinds +//! differently (a window handle and a `WinEvent` in place of a process id and an accessibility +//! notification), so reading one is up to the `Rules` of the flavor that recorded the session +//! ([`super::flavor`]). This module defines what a read event looks like, an [`EventRecord`] with +//! the name, process and window pulled out, and `load`, which reads a session's whole +//! `events.jsonl` through those rules. +//! +//! What an event *was* (a command, a drag, an echo of komorebi's own move) is not decided here; +//! [`super::classify`] labels each [`EventRecord`]. Tying an event to the log lines of the handler +//! that produced it is done by `blocks::pair`. Both read the events this module returns. + +use schemars::JsonSchema; +use serde::Serialize; +use serde_json::Value; + +/// Which of the kinds of notification a subscriber receives an event is, or that it could not be +/// read. +/// +/// Serialized in kebab case (`window-manager`, `command`, `monitor`, `unknown`). +/// `Rules::describe_event` decides the family of an event, so the same JSON can be in a different +/// family for the two flavors (a bare string is a command for komorebi for Mac and, if it is +/// not a virtual desktop notification, [`Family::Unknown`] for komorebi for Windows). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)] +#[serde(rename_all = "kebab-case")] +pub enum Family { + /// Something the operating system reported about a window or application. + WindowManager, + /// A command sent to komorebi. + Command, + /// A display was connected, disconnected or resized. On Windows, also a notification about the + /// machine (a lock, a sleep, a wake) or a virtual desktop. + Monitor, + /// The notification could not be read. + Unknown, +} + +/// One notification from komorebi, read by the `Rules` of the flavor that sent it. +/// +/// The fields are what the analysis asks of an event whatever the flavor: what kind it is, what it +/// is called, which process or window it is about, and what the OS said. A field is `None` when the +/// event does not say, which is not the same as the event being about nothing. The `exe` is left +/// out of the serialized form when it is `None`. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::events::Family; +/// use komorebi_recorder::analysis::flavor::Flavor; +/// use serde_json::json; +/// +/// let info = Flavor::Macos.rules().describe_event(&json!({ +/// "type": "FocusWorkspaceNumber", +/// "content": 2, +/// })); +/// assert_eq!(info.family, Family::Command); +/// assert_eq!(info.name, "FocusWorkspaceNumber"); +/// assert_eq!(info.argument.as_deref(), Some("2")); +/// assert_eq!(info.summary(), "FocusWorkspaceNumber 2"); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct EventInfo { + /// Which kind of notification this is. + pub family: Family, + /// `MoveEnd`, `FocusWorkspaceNumber`, `DisplayConnectionChange`, ... For an event that could + /// not be read, `unreadable`. + pub name: String, + /// The notification the OS reported, e.g. `AXWindowMoved`; window-manager events only. + pub notification: Option, + /// The process the event is about. Window-manager events of komorebi for Mac have one; + /// komorebi for Windows events never do (they have a window handle instead). + pub pid: Option, + /// The window the event is about: a window id on a Mac (a focus change may name none) or a + /// handle on Windows. + pub window_id: Option, + /// The program of the window the event is about, where the event names it (komorebi for Windows + /// does; a process id is all the Mac gives). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exe: Option, + /// A command's argument or a monitor event's display id, as compact JSON. Longer than 80 + /// characters, it is cut to 79 and ends in `…`. + pub argument: Option, +} + +impl EventInfo { + /// Returns one line saying what this is: `MoveEnd pid 20934 AXWindowMoved`. + /// + /// The line is the name, then the program, the argument, `pid `, `window ` and the + /// notification, each only if there is one, separated by spaces. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::flavor::Flavor; + /// use serde_json::json; + /// + /// let moved = Flavor::Macos.rules().describe_event(&json!({ + /// "type": "MoveEnd", + /// "content": [{"type": "Accessibility", "content": "AXWindowMoved"}, 20934, 4711] + /// })); + /// assert_eq!(moved.summary(), "MoveEnd pid 20934 window 4711 AXWindowMoved"); + /// + /// let display = Flavor::Macos.rules().describe_event(&json!({"DisplayConnectionChange": 1})); + /// assert_eq!(display.summary(), "DisplayConnectionChange 1"); + /// ``` + #[must_use] + pub fn summary(&self) -> String { + let mut text = self.name.clone(); + if let Some(exe) = &self.exe { + text.push(' '); + text.push_str(exe); + } + if let Some(argument) = &self.argument { + text.push(' '); + text.push_str(argument); + } + if let Some(pid) = self.pid { + text.push_str(&format!(" pid {pid}")); + } + if let Some(window_id) = self.window_id { + text.push_str(&format!(" window {window_id}")); + } + if let Some(notification) = &self.notification { + text.push(' '); + text.push_str(notification); + } + text + } +} + +pub(crate) fn compact(value: &Value) -> String { + let text = value.to_string(); + if text.chars().count() > 80 { + let cut: String = text.chars().take(79).collect(); + format!("{cut}…") + } else { + text + } +} + +/// One recorded notification: a line of `events.jsonl` with its JSON read into an [`EventInfo`]. +/// +/// [`EventRecord::info`] is flattened when a record is serialized, so a record's JSON has the +/// `family`, `name` and the other fields of [`EventInfo`] beside the record's fields. +#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)] +pub struct EventRecord { + /// The notification's sequence number in the session: 1 for the first the recorder accepted, + /// counting up. It is what `event:` names. + pub seq: u64, + /// When the recorder received the notification, in nanoseconds on the host's master monotonic + /// clock (`mach_` is a historical spelling; the manifest's `host.clock` says `mach`, `qpc` or + /// `std`). For a window-manager event this is when its handler finished, because komorebi + /// notifies subscribers after the handler body. + pub recv_mach_ns: u64, + /// The same moment on the wall clock, in microseconds since the Unix epoch. + pub recv_wall_us: i64, + /// The state snapshot after this event (`states/.json`); the same id as the previous event + /// means the state did not change. + pub state_id: Option, + /// The notification, as the flavor's rules read it. + #[serde(flatten)] + pub info: EventInfo, + /// Why the notification's JSON could not be parsed, if it could not. Such a record has + /// [`Family::Unknown`] and the name `unreadable`. + pub parse_error: Option, +} diff --git a/komorebi-recorder/src/analysis/flavor/mac.rs b/komorebi-recorder/src/analysis/flavor/mac.rs new file mode 100644 index 00000000..85e0dfd4 --- /dev/null +++ b/komorebi-recorder/src/analysis/flavor/mac.rs @@ -0,0 +1,272 @@ +//! komorebi for Mac, as it describes itself. +//! +//! [`MacRules`] is the [`Rules`] of [`Flavor::Macos`]. It keeps the defaults of +//! [`Rules::verified`] (`true`), [`Rules::classify_monitor`] and [`Rules::window_is_unreadable`]. +//! Its tests read events shaped as komorebi for Mac sends them, and a `State` and a log that were +//! recorded from it. What the rules rely on: +//! +//! - A window event serializes as `{"type": "MoveEnd", "content": [, , +//! ]}`, where the notification is `{"type": "Accessibility", "content": +//! "AXWindowMoved"}` for what the accessibility API reported, `{"type": "AppKitWorkspace", +//! "content": "NS..."}` for what the workspace notification center did, or `{"type": "Manual", +//! ...}` for komorebi making one up (its mouse listener reports a button release as a move or +//! resize end this way). The process id is the only identification of the application. +//! - A monitor notification is a one-entry object, `{"DisplayConnectionChange": }`. +//! A command with no argument may be a bare string or `{"type": "Retile"}`. +//! - A window in the `State` is `{"id": ..., "details": {"title": ..., "exe": ...}, "rect": +//! ...}`, and its `rect` is read live from the accessibility API. +//! - The log has a header line for each handler, `processing event: for process with +//! notification ` or `processing command: `, and a command ends with +//! `processed command: `. No line ends an event's handler: komorebi sends the notification +//! after the handler body, so an event's receive time marks the end of its handler. +//! - komorebi hides a window by moving it to a corner of its monitor, leaving a one-point sliver +//! inside the display. +//! +//! [`verified`]: Rules::verified + +use super::Flavor; +use super::Rules; +use crate::analysis::classify::Class; +use crate::analysis::events::EventInfo; +use crate::analysis::events::EventRecord; +use crate::analysis::events::Family; +use serde_json::Value; + +/// The [`Rules`] of komorebi for Mac: what its events, `State`, log and modules say. +/// +/// A unit struct with no state. [`Flavor::rules`] returns a reference to one for +/// [`Flavor::Macos`]. It can also be used directly, as the example on [`Rules`] does. +pub struct MacRules; + +/// The names komorebi gives the events the OS reports. +const WINDOW_MANAGER_EVENTS: [&str; 14] = [ + "FocusChange", + "Show", + "Destroy", + "Minimize", + "Restore", + "Manage", + "Unmanage", + "MoveStart", + "MoveEnd", + "ResizeStart", + "ResizeEnd", + "SpaceChange", + "ScreenLock", + "ScreenUnlock", +]; + +const GEOMETRY_EVENTS: [&str; 4] = ["MoveStart", "MoveEnd", "ResizeStart", "ResizeEnd"]; + +/// Whether a window-manager event was made up by komorebi itself rather than reported by macOS. +fn is_synthesized(event: &EventRecord) -> bool { + event + .info + .notification + .as_deref() + .is_some_and(|notification| { + !notification.starts_with("AX") && !notification.starts_with("NS") + }) +} + +impl Rules for MacRules { + fn flavor(&self) -> Flavor { + Flavor::Macos + } + + fn window_id(&self, window: &Value) -> Option { + window.get("id")?.as_u64() + } + + fn hides_windows_by_position(&self) -> bool { + true + } + + fn describe_event(&self, event: &Value) -> EventInfo { + let unknown = |name: &str| EventInfo { + family: Family::Unknown, + name: name.to_string(), + notification: None, + pid: None, + window_id: None, + exe: None, + argument: None, + }; + + // a monitor notification is a one-entry object: {"Resize": 69733248} + if event.get("type").is_none() + && let Some(object) = event.as_object() + && object.len() == 1 + && let Some((name, value)) = object.iter().next() + { + return EventInfo { + family: Family::Monitor, + name: name.clone(), + notification: None, + pid: None, + window_id: None, + exe: None, + argument: Some(crate::analysis::events::compact(value)), + }; + } + + // a unit-variant command is a bare string + if let Some(name) = event.as_str() { + return EventInfo { + family: Family::Command, + name: name.to_string(), + ..unknown(name) + }; + } + + let Some(name) = event.get("type").and_then(Value::as_str) else { + return unknown("unreadable"); + }; + let content = event.get("content"); + + if WINDOW_MANAGER_EVENTS.contains(&name) { + let parts = content.and_then(Value::as_array); + let at = |index: usize| parts.and_then(|parts| parts.get(index)); + return EventInfo { + family: Family::WindowManager, + name: name.to_string(), + notification: at(0) + .and_then(|notification| notification.get("content")) + .and_then(Value::as_str) + .map(str::to_string), + pid: at(1) + .and_then(Value::as_i64) + .and_then(|pid| i32::try_from(pid).ok()), + window_id: at(2) + .and_then(Value::as_u64) + .and_then(|id| u32::try_from(id).ok()), + exe: None, + argument: None, + }; + } + + EventInfo { + family: Family::Command, + name: name.to_string(), + notification: None, + pid: None, + window_id: None, + exe: None, + argument: content + .filter(|value| !value.is_null()) + .map(crate::analysis::events::compact), + } + } + + fn is_geometry_event(&self, name: &str) -> bool { + GEOMETRY_EVENTS.contains(&name) + } + + fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) { + if event + .info + .notification + .as_deref() + .is_some_and(|notification| notification.starts_with("ShowOn")) + { + return (Class::Manual, "komorebi's own synthetic show event"); + } + + match event.info.name.as_str() { + "FocusChange" => (Class::Focus, "focus moved"), + "Show" | "Destroy" | "Minimize" | "Restore" | "Manage" | "Unmanage" => { + (Class::Lifecycle, "a window or application changed") + } + // komorebi's own mouse listener reports a button release as a move or resize end + // whose notification is not one of macOS's (AX..., NS...) + name if GEOMETRY_EVENTS.contains(&name) && is_synthesized(event) => ( + Class::Manual, + "komorebi's mouse listener saw a button release after a click or drag; nothing was reported moved", + ), + name if GEOMETRY_EVENTS.contains(&name) => ( + Class::Drag, + "a window was moved or resized by something other than komorebi", + ), + "ScreenLock" | "ScreenUnlock" | "SpaceChange" => { + (Class::Lock, "the screen locked or the space changed") + } + _ => (Class::Other, "not a known kind of event"), + } + } + + fn slow_handler_cause(&self) -> &'static str { + "slow accessibility calls into other applications, or waiting for the lock another handler held" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn describe(event: &Value) -> EventInfo { + MacRules.describe_event(event) + } + + #[test] + fn a_window_manager_event_has_its_process_window_and_notification() { + let info = describe(&json!({ + "type": "MoveEnd", + "content": [{"type": "Accessibility", "content": "AXWindowMoved"}, 20934, 4711] + })); + + assert_eq!(info.family, Family::WindowManager); + assert_eq!(info.name, "MoveEnd"); + assert_eq!(info.notification.as_deref(), Some("AXWindowMoved")); + assert_eq!(info.pid, Some(20934)); + assert_eq!(info.window_id, Some(4711)); + assert_eq!( + info.summary(), + "MoveEnd pid 20934 window 4711 AXWindowMoved" + ); + } + + #[test] + fn a_focus_change_may_have_no_window() { + let info = describe(&json!({ + "type": "FocusChange", + "content": [{"type": "AppKitWorkspace", "content": "NSWorkspaceDidActivateApplicationNotification"}, 79469, null] + })); + + assert_eq!(info.pid, Some(79469)); + assert_eq!(info.window_id, None); + assert_eq!( + info.notification.as_deref(), + Some("NSWorkspaceDidActivateApplicationNotification") + ); + } + + #[test] + fn commands_carry_their_argument() { + let info = describe(&json!({"type": "FocusWorkspaceNumber", "content": 2})); + assert_eq!(info.family, Family::Command); + assert_eq!(info.name, "FocusWorkspaceNumber"); + assert_eq!(info.argument.as_deref(), Some("2")); + + let bare = describe(&json!({"type": "Retile"})); + assert_eq!(bare.family, Family::Command); + assert_eq!(bare.argument, None); + + assert_eq!(describe(&json!("Retile")).family, Family::Command); + } + + #[test] + fn monitor_notifications_are_one_entry_objects() { + let info = describe(&json!({"DisplayConnectionChange": 1})); + assert_eq!(info.family, Family::Monitor); + assert_eq!(info.name, "DisplayConnectionChange"); + assert_eq!(info.argument.as_deref(), Some("1")); + } + + #[test] + fn nonsense_is_unknown_not_a_panic() { + assert_eq!(describe(&json!(12)).family, Family::Unknown); + assert_eq!(describe(&json!({"a": 1, "b": 2})).family, Family::Unknown); + assert_eq!(describe(&json!({"type": 3})).family, Family::Unknown); + } +} diff --git a/komorebi-recorder/src/analysis/flavor/mod.rs b/komorebi-recorder/src/analysis/flavor/mod.rs new file mode 100644 index 00000000..a4ea7a19 --- /dev/null +++ b/komorebi-recorder/src/analysis/flavor/mod.rs @@ -0,0 +1,510 @@ +//! The flavors of komorebi (for Mac and for Windows), and what the output of each one means. +//! +//! The host a session was *recorded on* (see [`crate::platform`]) and the *komorebi* it was +//! recording are separate things: a session recorded on Windows is investigated on a Mac, and the +//! other way round. Everything that reads komorebi's output (its events, its `State`, its log +//! and its source) is written in komorebi's vocabulary, and that differs between the two: +//! +//! - what an event looks like on the wire and what its fields mean (a process id and an +//! accessibility notification on macOS, a window handle and a `WinEvent` on Windows); +//! - which events move or resize a window, and which are komorebi making things up; +//! - how komorebi hides a window, and so whether a window's position shows that it is hidden; +//! - how its log marks where a handler starts and ends; +//! - which of its threads and modules do what. +//! +//! The module defines a pair of roles: +//! +//! - **A [`Flavor`] is a name for a komorebi.** It is a two-valued enum, recorded in the session's +//! manifest, that identifies which komorebi wrote the files being read. +//! - **A type that implements [`Rules`] is the vocabulary of that komorebi.** It answers the +//! questions the analysis has about komorebi's events, `State`, log and source. [`MacRules`] +//! (in [`mac`]) and [`WindowsRules`] (in [`windows`]) are the two implementors, and +//! [`Flavor::rules`] is the one place that turns a name into rules. +//! +//! The analysis is written once, against `&dyn Rules`: the functions that read an event, classify +//! it, group log lines into handlers and parse a `State` take the rules as an argument or reach +//! them through the `Snapshot` they read. The host does not take part: [`Flavor::of_host`] is only +//! the flavor a recorder writes into the manifest of a session it records. +//! +//! # The questions, and who answers them +//! +//! Each method of [`Rules`] is one question. Every row of this table is a place where the two +//! flavors differ; the third column names the code that asks. +//! +//! | Method | Answers | Asked by | komorebi for Mac | komorebi for Windows | +//! |---|---|---|---|---| +//! | [`describe_event`](Rules::describe_event) | what a notification's JSON means | `EventRecord::from_row` | `[{"type": "Accessibility", ...}, pid, window]` | `["", window]` | +//! | [`is_geometry_event`](Rules::is_geometry_event) | which events start or end a move or resize | [`classify`] | `MoveStart`, `MoveEnd`, `ResizeStart`, `ResizeEnd` | `MoveResizeStart`, `MoveResizeEnd` | +//! | [`classify_window_manager`](Rules::classify_window_manager) | what an OS-reported event was, and why | [`classify`] | a button release komorebi made up is [`Class::Manual`] | `Cloak` and `Uncloak` are [`Class::Lifecycle`] | +//! | [`classify_monitor`](Rules::classify_monitor) | what a display or machine notification was | [`classify`] | the default: [`Class::Monitor`] | lock, suspend and virtual desktop notifications are [`Class::Lock`] | +//! | [`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 | +//! | [`slow_handler_cause`](Rules::slow_handler_cause) | what a slow handler was probably doing | the `overview` and `trace` answers | accessibility calls | Win32 calls | +//! | [`verified`](Rules::verified) | whether the rules were checked against a recording | `Analysis::warnings` | the default: yes | no | +//! | [`flavor`](Rules::flavor) | which flavor the rules are for | tests | [`Flavor::Macos`] | [`Flavor::Windows`] | +//! +//! # What is guaranteed, and by what +//! +//! | Rule | Enforced by | Proof | Escape hatch | +//! |---|---|---|---| +//! | An implementor of [`Rules`] answers every question that has no default | type system: the methods have no default | `compile_fail,E0046` on [`Rules`] | none | +//! | An implementor can be shared between threads | type system: `Sync` is a supertrait of [`Rules`] | the trait's definition | none | +//! | [`Flavor::rules`] has rules for every flavor | type system: an exhaustive `match` | a new [`Flavor`] variant without an arm fails to compile in this module | none | +//! | `flavor.rules().flavor()` is `flavor` | test | `each_flavor_has_rules_of_its_own_and_only_the_checked_ones_say_so` | none | +//! | A manifest with no flavor is read as komorebi for Mac | runtime: a serde default | `a_session_with_no_flavor_recorded_is_komorebi_for_mac` | none | +//! | Rules that were not checked against a recording of komorebi say so | framework path: `Analysis::warnings` adds a warning when [`verified`](Rules::verified) is `false`. The method defaults to `true`, so an implementor has to override it | `the_analysis_says_the_windows_rules_are_not_yet_checked_against_a_recording` and `a_mac_session_does_not_get_that_warning` in `tests/windows_flavor.rs` | none | +//! | A flavor for which `hides_windows_by_position` is `false` answers `false` to `is_hidden_position` | convention only | [`WindowsRules`] follows it | none | +//! | A notification that cannot be read is [`Family::Unknown`], not a panic | test, for each implementor: `nonsense_is_unknown_not_a_panic` in [`mac`] and in [`windows`]. For a new implementor, convention only | those tests | none | +//! | Code that reads komorebi's output asks [`Rules`] and does not match on [`Flavor`] | convention only | none | the two cases below | +//! +//! Two things that depend on the flavor are keyed by [`Flavor`] and not asked of [`Rules`]: the +//! index of komorebi's source that log lines are mapped to (`catalog::of`), and the places the +//! log and a checkout of the source are looked for on disk (`komorebi_log::log_dir_candidates` +//! and `annotations::default_code_root`). +//! +//! # One session, end to end +//! +//! 1. `Analysis::open` reads the manifest. Its `komorebi.flavor` is what `Analysis::flavor` +//! returns; a manifest that has none gives [`Flavor::Macos`]. +//! 1. `Analysis::events` calls `events::load` with `flavor.rules()`, which turns each line of +//! `events.jsonl` into an [`EventRecord`] with [`describe_event`](Rules::describe_event). +//! 1. [`classify`] labels each record. It asks +//! [`classify_window_manager`](Rules::classify_window_manager) or +//! [`classify_monitor`](Rules::classify_monitor), by the record's [`Family`], and +//! [`is_geometry_event`](Rules::is_geometry_event) when it decides whether a button release +//! that komorebi made up ended a real drag. +//! +//! [`MacRules`]: mac::MacRules +//! [`WindowsRules`]: windows::WindowsRules +//! [`classify`]: super::classify::classify +//! [`Family`]: super::events::Family +//! [`Family::Unknown`]: super::events::Family::Unknown + +pub mod mac; +pub mod windows; + +use super::classify::Class; +use super::events::EventInfo; +use super::events::EventRecord; +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; + +/// A name for a komorebi: komorebi for Mac or komorebi for Windows. +/// +/// A session records which of the two it was watching, in its manifest, because what komorebi's +/// events, `State` and log say differs between them. The flavor is the one place the analysis +/// learns which komorebi it is reading: [`Flavor::rules`] returns the [`Rules`] that know that +/// komorebi's vocabulary. +/// +/// A flavor names a komorebi, not an operating system. A recorder watches the komorebi of the host +/// it runs on ([`Flavor::of_host`]) and writes that flavor into the manifest, and whoever investigates +/// the session later uses the flavor from the manifest, whatever machine they are on: a session +/// recorded on Windows is read on a Mac with the Windows rules. +/// +/// The default is [`Flavor::Macos`], which is also what a manifest that has no flavor means. +/// +/// # Serialization +/// +/// A flavor is spelled in lowercase (`"macos"`, `"windows"`) wherever it is serialized, and the +/// type has a JSON Schema. [`Flavor::label`] and the [`Display`](std::fmt::Display) +/// implementation spell it for prose (`macOS`, `Windows`). +/// +/// # Example +/// +/// Each flavor's rules read the wire format of its komorebi. The same call, on the same +/// type, gives a process id and an accessibility notification for one, and a window handle, a +/// program and a `WinEvent` for the other: +/// +/// ```rust +/// use komorebi_recorder::analysis::flavor::Flavor; +/// use serde_json::json; +/// +/// let on_mac = json!({ +/// "type": "MoveEnd", +/// "content": [{"type": "Accessibility", "content": "AXWindowMoved"}, 20934, 4711] +/// }); +/// let info = Flavor::Macos.rules().describe_event(&on_mac); +/// assert_eq!(info.pid, Some(20934)); +/// assert_eq!(info.summary(), "MoveEnd pid 20934 window 4711 AXWindowMoved"); +/// +/// let on_windows = json!({ +/// "type": "FocusChange", +/// "content": ["SystemForeground", {"hwnd": 131072, "title": "a title", "exe": "chrome.exe"}] +/// }); +/// let info = Flavor::Windows.rules().describe_event(&on_windows); +/// assert_eq!(info.pid, None); +/// assert_eq!(info.exe.as_deref(), Some("chrome.exe")); +/// assert_eq!(info.summary(), "FocusChange chrome.exe window 131072 SystemForeground"); +/// +/// // a manifest spells a flavor in lowercase, and has the Mac's when it says nothing +/// assert_eq!(serde_json::to_string(&Flavor::Windows)?, r#""windows""#); +/// assert_eq!(serde_json::from_str::(r#""macos""#)?, Flavor::Macos); +/// assert_eq!(Flavor::default(), Flavor::Macos); +/// +/// // and prose says it the way people do +/// assert_eq!(Flavor::Macos.label(), "macOS"); +/// assert_eq!(Flavor::Windows.to_string(), "Windows"); +/// # Ok::<(), Box>(()) +/// ``` +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + Hash, + Default, + Serialize, + Deserialize, + JsonSchema, + clap::ValueEnum, +)] +#[serde(rename_all = "lowercase")] +pub enum Flavor { + /// komorebi for Mac. It is also what a manifest that has no flavor means, because every session + /// recorded before manifests said which komorebi they watched was recorded on a Mac. + #[default] + Macos, + /// komorebi for Windows. + Windows, +} + +impl Flavor { + /// Returns the flavor of the komorebi that runs on this machine: there is one per OS, and a + /// recorder watches the one on its own host. + /// + /// This is [`Flavor::Windows`] when the crate is built for Windows and [`Flavor::Macos`] for + /// every other target, including the `unsupported` host. Use it to say which komorebi a + /// recording made *here* is of; to read a session, use the flavor in its manifest. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::flavor::Flavor; + /// + /// assert_eq!(Flavor::of_host() == Flavor::Windows, cfg!(windows)); + /// ``` + #[must_use] + pub fn of_host() -> Self { + if cfg!(windows) { + Flavor::Windows + } else { + Flavor::Macos + } + } + + /// Returns the [`Rules`] of this flavor: the vocabulary of this komorebi. + /// + /// This is the only place a flavor is turned into rules. The rules are a shared, stateless + /// value of [`MacRules`](mac::MacRules) or [`WindowsRules`](windows::WindowsRules), so calling + /// this is free and the result may be kept for as long as the program runs. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::flavor::Flavor; + /// + /// for flavor in [Flavor::Macos, Flavor::Windows] { + /// assert_eq!(flavor.rules().flavor(), flavor); + /// } + /// + /// // only the rules of a komorebi that was checked against a recording say so + /// assert!(Flavor::Macos.rules().verified()); + /// assert!(!Flavor::Windows.rules().verified()); + /// ``` + #[must_use] + pub fn rules(self) -> &'static dyn Rules { + match self { + Flavor::Macos => &mac::MacRules, + Flavor::Windows => &windows::WindowsRules, + } + } + + /// Returns the name to use in prose: `macOS` or `Windows`. + /// + /// This is also what the [`Display`](std::fmt::Display) implementation writes. The serialized + /// form is different: `macos` or `windows`. + #[must_use] + pub fn label(self) -> &'static str { + match self { + Flavor::Macos => "macOS", + Flavor::Windows => "Windows", + } + } +} + +impl std::fmt::Display for Flavor { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.label()) + } +} + +/// The vocabulary of one flavor of komorebi, as the questions the analysis asks of it. +/// +/// The role of this trait is to answer, for one komorebi, every question the analysis has about +/// komorebi's vocabulary: how an event is written, what a `State` calls a window, where a +/// hidden window is, what a handler's first and last log line look like, and what each of +/// komorebi's modules does. Each method is one question. The [module documentation](self) has the +/// table of them, with what each flavor answers, and the guarantee table. +/// +/// - **The analysis calls it.** It is given a `&dyn Rules` (from [`Flavor::rules`]) and asks it, +/// and has no way to tell which flavor it was given. +/// - **A flavor implements it.** [`MacRules`](mac::MacRules) is komorebi for Mac and +/// [`WindowsRules`](windows::WindowsRules) is komorebi for Windows. A third implementor is +/// written only for a third komorebi. To be chosen by name it also needs a [`Flavor`] variant, +/// because [`Flavor::rules`] is an exhaustive `match`. The functions that take a `&dyn Rules` +/// (`events::load`, `EventRecord::from_row` and +/// [`classify`](super::classify::classify), and `blocks::build`) accept any implementor, +/// whether or not `Flavor::rules` can return it. +/// +/// # The contract +/// +/// - **Most methods have no default, and a few do.** An implementor must write +/// [`flavor`](Rules::flavor), [`window_id`](Rules::window_id), +/// [`hides_windows_by_position`](Rules::hides_windows_by_position), +/// [`describe_event`](Rules::describe_event), [`is_geometry_event`](Rules::is_geometry_event), +/// [`classify_window_manager`](Rules::classify_window_manager), +/// `is_hidden_position`, `block_header`, +/// `is_block_end`, `role` and +/// [`slow_handler_cause`](Rules::slow_handler_cause); a missing one is a compile error (see +/// below). [`verified`](Rules::verified), [`classify_monitor`](Rules::classify_monitor) and +/// [`window_is_unreadable`](Rules::window_is_unreadable) have a default that suits a flavor +/// with nothing to say about them. A default is not a guarantee: an implementor may override it. +/// - **Answers come from the arguments.** Every method takes `&self`, and the trait requires +/// `Sync`, so rules are shared between threads and carry no state. The one piece of context a +/// method may need is passed in: `block_header` is given the block that +/// is open. +/// - **Unreadable input is an answer, not a panic.** komorebi's output is read after the fact, from +/// a session that may be from a newer komorebi than this recorder. [`describe_event`] answers +/// [`Family::Unknown`] for JSON it does not understand, and [`window_id`] answers `None` for +/// JSON that is not a window. Both implementors have a test for `describe_event`; nothing +/// enforces the rule for a new implementor. +/// - **Hiding has two questions, and they must agree.** A flavor for which +/// [`hides_windows_by_position`](Rules::hides_windows_by_position) is `false` should answer `false` to every call of +/// `is_hidden_position`. Some checks ask only the second, and would otherwise report a +/// window as parked. Only convention enforces this; [`WindowsRules`](windows::WindowsRules) +/// follows it. +/// - **A block stops collecting lines in one of two ways.** `block_header` is asked of every +/// timestamped line of the log and starts a block when it returns `Some`. A block that is still +/// open stops collecting lines when the next header starts a new block, or when +/// `is_block_end` returns `true`. `is_block_end` is asked only of the lines that were added to +/// the open block, never of the line that started it. A flavor whose log has no end line answers +/// `false`, and its blocks stop at the next header. +/// +/// [`describe_event`]: Rules::describe_event +/// [`window_id`]: Rules::window_id +/// [`hides_windows_by_position`]: Rules::hides_windows_by_position +/// [`Family::Unknown`]: super::events::Family::Unknown +/// +/// # Example implementation +/// +/// An implementor that reads komorebi for Mac, by delegating to [`MacRules`](mac::MacRules), but +/// that reports it was never checked against a recording. [`verified`](Rules::verified) is the one +/// method written beyond the ones that have no default, and the others keep theirs: +/// +/// ```rust +/// # use komorebi_recorder::analysis::classify::Class; +/// # use komorebi_recorder::analysis::events::{EventInfo, EventRecord}; +/// # use komorebi_recorder::analysis::flavor::mac::MacRules; +/// # use komorebi_recorder::analysis::flavor::{Flavor, Rules}; +/// # use serde_json::Value; +/// struct Unchecked; +/// +/// impl Rules for Unchecked { +/// fn flavor(&self) -> Flavor { Flavor::Macos } +/// fn verified(&self) -> bool { false } +/// fn window_id(&self, window: &Value) -> Option { MacRules.window_id(window) } +/// fn hides_windows_by_position(&self) -> bool { MacRules.hides_windows_by_position() } +/// fn describe_event(&self, event: &Value) -> EventInfo { MacRules.describe_event(event) } +/// fn is_geometry_event(&self, name: &str) -> bool { MacRules.is_geometry_event(name) } +/// fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) { +/// MacRules.classify_window_manager(event) +/// } +/// fn slow_handler_cause(&self) -> &'static str { MacRules.slow_handler_cause() } +/// } +/// +/// let rules: &dyn Rules = &Unchecked; +/// let event = serde_json::json!({"type": "FocusWorkspaceNumber", "content": 2}); +/// assert_eq!(rules.describe_event(&event).argument.as_deref(), Some("2")); +/// assert!(!rules.verified()); +/// // a method that was not written has its default +/// assert!(!rules.window_is_unreadable(&serde_json::json!({"id": 1}))); +/// ``` +/// +/// # Example: a missing method is refused +/// +/// An implementor that leaves out a method that has no default does not compile. This is the +/// implementor above without `slow_handler_cause`: +/// +/// ```rust,compile_fail,E0046 +/// # use komorebi_recorder::analysis::classify::Class; +/// # use komorebi_recorder::analysis::events::{EventInfo, EventRecord}; +/// # use komorebi_recorder::analysis::flavor::mac::MacRules; +/// # use komorebi_recorder::analysis::flavor::{Flavor, Rules}; +/// # use serde_json::Value; +/// struct Unchecked; +/// +/// impl Rules for Unchecked { +/// fn flavor(&self) -> Flavor { Flavor::Macos } +/// fn verified(&self) -> bool { false } +/// fn window_id(&self, window: &Value) -> Option { MacRules.window_id(window) } +/// fn hides_windows_by_position(&self) -> bool { MacRules.hides_windows_by_position() } +/// fn describe_event(&self, event: &Value) -> EventInfo { MacRules.describe_event(event) } +/// fn is_geometry_event(&self, name: &str) -> bool { MacRules.is_geometry_event(name) } +/// fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) { +/// MacRules.classify_window_manager(event) +/// } +/// // no `slow_handler_cause` +/// } +/// ``` +/// +/// The error is E0046, `not all trait items implemented, missing: slow_handler_cause`. The same +/// refusal applies to each method without a default, so a new flavor cannot leave +/// one of komorebi's questions unanswered. +pub trait Rules: Sync { + /// Returns the flavor these rules are for. + /// + /// `flavor.rules().flavor()` is `flavor` for both flavors. + fn flavor(&self) -> Flavor; + + /// Returns whether these rules have been checked against a real recording of the komorebi + /// they describe, rather than only written from its source. + /// + /// The default is `true`. `Analysis::warnings` adds a + /// warning to the answers about a session whose flavor has unverified rules, saying that this + /// build reads komorebi for that flavor from its source and has not yet checked it against a + /// recording. A flavor whose rules were not checked must override this to say so. + /// + /// komorebi for Mac keeps the default. komorebi for Windows answers `false`. + fn verified(&self) -> bool { + true + } + + /// Returns what a display or machine notification ([`Family::Monitor`], not a window event or + /// a command) was, as a [`Class`] and a sentence giving the reason. The sentence is what a reader + /// sees as the event's reason. + /// + /// The default is `(Class::Monitor, "a display changed")`. komorebi for Mac keeps it. komorebi + /// for Windows overrides it, because its monitor notifications also carry the machine's + /// state: a session locked or unlocked, a sleep or a wake, and a virtual desktop left or + /// returned to are [`Class::Lock`]. + /// + /// [`Family::Monitor`]: super::events::Family::Monitor + fn classify_monitor(&self, _event: &EventRecord) -> (Class, &'static str) { + (Class::Monitor, "a display changed") + } + + /// Returns the id a window is known by in `State`, or `None` if `window` is not a window. + /// + /// On a Mac that is the window's `id`, and on Windows it is the handle, `hwnd`; a handle that + /// is negative is not an id. The value is the key under which a `Snapshot` lists the window, + /// and what an event's window is looked up by. + fn window_id(&self, window: &Value) -> Option; + + /// Returns whether `window` is one komorebi could not read when it wrote the state (it had + /// been destroyed), so that its title, program and rect say nothing. + /// + /// A window that is unreadable is kept, with its id, but has no rect: a zero rect would read as + /// a window parked at the corner of the screen. + /// + /// The default is `false`. komorebi for Mac keeps it. komorebi for Windows reads a window's + /// title, program and rect when it serializes the state, and writes `could not get window + /// title` (and likewise for the program and class) in place of one it could not read, so its + /// rules look for that. + fn window_is_unreadable(&self, _window: &Value) -> bool { + false + } + + /// Returns whether komorebi hides a window by moving it to a corner, so that whether a window + /// is hidden can be read from its position. + /// + /// komorebi for Mac does. komorebi for Windows hides a window by cloaking it where it is by + /// default, so there a hidden window is not told from a visible one by where it is, and the + /// checks that rely on position are skipped rather than guessed. If this is `false`, + /// `is_hidden_position` should be `false` as well. + fn hides_windows_by_position(&self) -> bool; + + /// Reads the JSON komorebi sent a subscriber as an event, and returns an [`EventInfo`] that + /// describes it. + /// + /// This never fails. JSON with no readable `type` that is not one of the shapes below is + /// [`Family::Unknown`] and is named `unreadable`; a name that is not a window event or a + /// monitor notification is read as a command, because a flavor has no list of commands. + /// + /// Three kinds reach a subscriber and look different on the wire. What differs by flavor: + /// + /// - komorebi for Mac: a window-manager event is `{"type": "MoveEnd", "content": + /// [{"type": "Accessibility", "content": "AXWindowMoved"}, , ]}`, with a + /// process id and no program. A command is `{"type": "", "content": }`, with + /// no `content` when it has no argument, or a bare string. A monitor notification is a + /// one-entry object such as `{"DisplayConnectionChange": }`. + /// - komorebi for Windows: a window event is `{"type": "FocusChange", "content": ["", + /// ]}`, or `{"type": "Manage", "content": }` for the events that have no + /// `WinEvent`. A window is `{"hwnd": ..., "title": ..., "exe": ..., "class": ..., "rect": + /// ...}`, so the event has a window handle and a program and no process id. A notification + /// about the machine is `{"type": "SessionLocked"}`; a virtual desktop notification is a bare + /// string, and any other bare string is [`Family::Unknown`], named after the string. A + /// command is `{"type": "", "content": }`, told apart from a window event + /// by its name. + /// + /// [`Family::Unknown`]: super::events::Family::Unknown + fn describe_event(&self, event: &Value) -> EventInfo; + + /// Returns whether an event with this name starts or ends moving or resizing a window. + /// + /// komorebi for Mac names four: `MoveStart`, `MoveEnd`, `ResizeStart` and `ResizeEnd`. + /// komorebi for Windows names two: `MoveResizeStart` and `MoveResizeEnd`. + /// [`classify`](super::classify::classify) uses this to tell a button release that komorebi + /// made up from the end of a real drag: one after which the layout changed. + fn is_geometry_event(&self, name: &str) -> bool; + + /// Returns what a window-manager event (one the OS reported, as opposed to a command or a + /// monitor change) was, as a [`Class`] and a sentence giving the reason. + /// + /// An event that starts or ends a move or resize (see + /// [`is_geometry_event`](Rules::is_geometry_event)) is [`Class::Drag`] when the OS reported it, + /// and [`Class::Manual`] when komorebi made it up. [`Class::Echo`] is not an answer to give: + /// [`classify`](super::classify::classify) turns a drag that changed nothing, soon after + /// komorebi acted, into an echo itself. + fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str); + + /// Returns what a handler that took long was most likely doing, as a phrase that completes a + /// sentence such as "took at least 250 ms to handle: ...". + /// + /// It names the calls the handler makes into other programs' windows, which differ by OS: + /// accessibility calls on a Mac and Win32 calls on Windows. The phrase also names waiting for + /// the lock another handler held. + fn slow_handler_cause(&self) -> &'static str; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn flavors_are_spelled_in_lowercase_and_the_host_has_one() { + assert_eq!( + serde_json::to_string(&Flavor::Windows).expect("json"), + r#""windows""# + ); + assert_eq!( + serde_json::from_str::(r#""macos""#).expect("parse"), + Flavor::Macos + ); + assert_eq!(Flavor::of_host() == Flavor::Windows, cfg!(windows)); + } + + #[test] + fn each_flavor_has_rules_of_its_own_and_only_the_checked_ones_say_so() { + assert_eq!(Flavor::Macos.rules().flavor(), Flavor::Macos); + assert_eq!(Flavor::Windows.rules().flavor(), Flavor::Windows); + assert!(Flavor::Macos.rules().verified()); + assert!( + !Flavor::Windows.rules().verified(), + "the Windows rules are from komorebi's source until a recording of it has been read" + ); + } +} diff --git a/komorebi-recorder/src/analysis/flavor/windows.rs b/komorebi-recorder/src/analysis/flavor/windows.rs new file mode 100644 index 00000000..1f8cf05e --- /dev/null +++ b/komorebi-recorder/src/analysis/flavor/windows.rs @@ -0,0 +1,351 @@ +//! komorebi for Windows, as it describes itself. +//! +//! [`WindowsRules`] is the [`Rules`] of [`Flavor::Windows`]. It overrides all three methods that +//! have a default: [`Rules::verified`], [`Rules::classify_monitor`] and +//! [`Rules::window_is_unreadable`]. +//! +//! The rules are written from komorebi for Windows' source and not yet checked against a recording +//! of it. That is what [`Rules::verified`] reports, and what the analysis tells whoever reads a +//! Windows session. What the rules rely on: +//! +//! - A window event serializes as `{"type": "FocusChange", "content": ["", ]}`, +//! or `{"type": "Manage", "content": }` for the three that have no `WinEvent` (`Manage`, +//! `Unmanage`, `Raise`). A window is `{hwnd, title, exe, class, rect}`, every field read live at +//! the moment of serializing, so a window that was destroyed reads `could not get window title` +//! and a rect of zeros. +//! - Monitor notifications are unit variants tagged the same way, `{"type": "SessionLocked"}`, +//! and virtual desktop notifications are bare strings. +//! - A command is `{"type": "", "content": }` like a window event, told apart by its +//! name. +//! - The log has no `processing event:` line. A handler's lines carry the span +//! `process_event{event="FocusChange" winevent="SystemForeground" hwnd=131072}` (or +//! `process_command{message=...}`), and an INFO `processed: ` (`processed` for a command) +//! after the subscribers were notified marks its end. +//! - komorebi hides a window by cloaking it where it is, by default, so nothing in the `State` +//! shows a window as hidden: [`Rules::hides_windows_by_position`] is `false` and +//! `Rules::is_hidden_position` never matches. + +use super::Flavor; +use super::Rules; +use crate::analysis::classify::Class; +use crate::analysis::events::EventInfo; +use crate::analysis::events::EventRecord; +use crate::analysis::events::Family; +use serde_json::Value; + +/// The [`Rules`] of komorebi for Windows: what its events, `State`, log and modules say. +/// +/// A unit struct with no state. [`Flavor::rules`] returns a reference to one for +/// [`Flavor::Windows`]. Its [`verified`](Rules::verified) is `false`. +pub struct WindowsRules; + +/// The events the OS reports about a window, and komorebi's own `Manage`, `Unmanage` and `Raise`. +const WINDOW_MANAGER_EVENTS: [&str; 14] = [ + "Destroy", + "FocusChange", + "Hide", + "Cloak", + "Minimize", + "Show", + "Uncloak", + "MoveResizeStart", + "MoveResizeEnd", + "MouseCapture", + "Manage", + "Unmanage", + "Raise", + "TitleUpdate", +]; + +/// komorebi's notifications about the machine and its displays. +const MONITOR_NOTIFICATIONS: [&str; 7] = [ + "ResolutionScalingChanged", + "WorkAreaChanged", + "DisplayConnectionChange", + "EnteringSuspendedState", + "ResumingFromSuspendedState", + "SessionLocked", + "SessionUnlocked", +]; + +/// Sent as bare strings. +const VIRTUAL_DESKTOP_NOTIFICATIONS: [&str; 2] = [ + "EnteredAssociatedVirtualDesktop", + "LeftAssociatedVirtualDesktop", +]; + +const GEOMETRY_EVENTS: [&str; 2] = ["MoveResizeStart", "MoveResizeEnd"]; + +/// What komorebi puts in place of a field it could not read. +const COULD_NOT_GET: &str = "could not get window"; + +/// A field of a window, unless komorebi could not read it. +fn field(window: &Value, key: &str) -> Option { + window + .get(key)? + .as_str() + .filter(|text| !text.starts_with(COULD_NOT_GET)) + .map(str::to_string) +} + +fn handle(window: &Value) -> Option { + window + .get("hwnd")? + .as_i64() + .and_then(|hwnd| u32::try_from(hwnd).ok()) +} + +impl Rules for WindowsRules { + fn flavor(&self) -> Flavor { + Flavor::Windows + } + + fn verified(&self) -> bool { + false + } + + fn describe_event(&self, event: &Value) -> EventInfo { + let unknown = |name: &str| EventInfo { + family: Family::Unknown, + name: name.to_string(), + notification: None, + pid: None, + window_id: None, + exe: None, + argument: None, + }; + + // virtual desktop notifications are bare strings + if let Some(name) = event.as_str() { + return EventInfo { + family: if VIRTUAL_DESKTOP_NOTIFICATIONS.contains(&name) { + Family::Monitor + } else { + Family::Unknown + }, + ..unknown(name) + }; + } + + let Some(name) = event.get("type").and_then(Value::as_str) else { + return unknown("unreadable"); + }; + let content = event.get("content"); + + if MONITOR_NOTIFICATIONS.contains(&name) { + return EventInfo { + family: Family::Monitor, + ..unknown(name) + }; + } + + if WINDOW_MANAGER_EVENTS.contains(&name) { + // `[, ]`, or just `` for the events with no WinEvent + let (notification, window) = match content { + Some(Value::Array(parts)) => ( + parts.first().and_then(Value::as_str).map(str::to_string), + parts.get(1), + ), + other => (None, other), + }; + + return EventInfo { + family: Family::WindowManager, + name: name.to_string(), + notification, + pid: None, + window_id: window.and_then(handle), + exe: window.and_then(|window| field(window, "exe")), + argument: None, + }; + } + + EventInfo { + family: Family::Command, + name: name.to_string(), + argument: content + .filter(|value| !value.is_null()) + .map(crate::analysis::events::compact), + ..unknown(name) + } + } + + fn is_geometry_event(&self, name: &str) -> bool { + GEOMETRY_EVENTS.contains(&name) + } + + fn classify_window_manager(&self, event: &EventRecord) -> (Class, &'static str) { + match event.info.name.as_str() { + "FocusChange" => (Class::Focus, "focus moved"), + "Show" | "Destroy" | "Minimize" | "Manage" | "Unmanage" => ( + Class::Lifecycle, + "a window appeared, went away, was minimized or restored, or komorebi began or stopped managing it", + ), + // switching workspace hides the windows of the one left by cloaking them, and the OS + // reports that back + "Hide" | "Cloak" | "Uncloak" => ( + Class::Lifecycle, + "a window was hidden or shown: komorebi cloaks the windows of a workspace it leaves, so this is often its own doing reported back", + ), + name if GEOMETRY_EVENTS.contains(&name) => ( + Class::Drag, + "a window was moved or resized with the mouse (or by something other than komorebi)", + ), + "MouseCapture" => ( + Class::Other, + "a window captured or released the mouse: part of a drag, or a menu", + ), + "Raise" => (Class::Manual, "komorebi raised a window itself"), + "TitleUpdate" => (Class::Other, "a window changed its title"), + _ => (Class::Other, "not a known kind of event"), + } + } + + fn classify_monitor(&self, event: &EventRecord) -> (Class, &'static str) { + match event.info.name.as_str() { + "SessionLocked" | "SessionUnlocked" => { + (Class::Lock, "the session was locked or unlocked") + } + "EnteringSuspendedState" | "ResumingFromSuspendedState" => { + (Class::Lock, "the machine went to sleep or woke") + } + "EnteredAssociatedVirtualDesktop" | "LeftAssociatedVirtualDesktop" => ( + Class::Lock, + "the virtual desktop komorebi is managing was left or returned to", + ), + _ => (Class::Monitor, "a display changed"), + } + } + + fn window_id(&self, window: &Value) -> Option { + window + .get("hwnd")? + .as_i64() + .and_then(|hwnd| u64::try_from(hwnd).ok()) + } + + fn window_is_unreadable(&self, window: &Value) -> bool { + window + .get("title") + .and_then(Value::as_str) + .is_some_and(|title| title.starts_with(COULD_NOT_GET)) + } + + fn hides_windows_by_position(&self) -> bool { + false + } + + fn slow_handler_cause(&self) -> &'static str { + "slow Win32 calls into other programs' windows (positioning one that is busy or hung, or an animation), or waiting for the lock another handler held" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn describe(event: &Value) -> EventInfo { + WindowsRules.describe_event(event) + } + + fn window(hwnd: i64, exe: &str) -> Value { + json!({ + "hwnd": hwnd, "title": "a title", "exe": exe, "class": "Chrome_WidgetWin_1", + "rect": {"left": 0, "top": 0, "right": 100, "bottom": 100} + }) + } + + #[test] + fn a_window_event_names_its_win_event_handle_and_program() { + let info = describe(&json!({ + "type": "FocusChange", + "content": ["SystemForeground", window(131_072, "chrome.exe")] + })); + + assert_eq!(info.family, Family::WindowManager); + assert_eq!(info.name, "FocusChange"); + assert_eq!(info.notification.as_deref(), Some("SystemForeground")); + assert_eq!(info.window_id, Some(131_072)); + assert_eq!(info.exe.as_deref(), Some("chrome.exe")); + assert_eq!(info.pid, None); + assert_eq!( + info.summary(), + "FocusChange chrome.exe window 131072 SystemForeground" + ); + } + + #[test] + fn manage_unmanage_and_raise_carry_a_window_and_no_win_event() { + for name in ["Manage", "Unmanage", "Raise"] { + let info = describe(&json!({"type": name, "content": window(7, "code.exe")})); + assert_eq!(info.family, Family::WindowManager, "{name}"); + assert_eq!(info.notification, None); + assert_eq!(info.window_id, Some(7)); + assert_eq!(info.exe.as_deref(), Some("code.exe")); + } + } + + #[test] + fn a_window_komorebi_could_not_read_has_a_handle_and_no_program() { + let info = describe(&json!({ + "type": "Destroy", + "content": ["ObjectDestroy", { + "hwnd": 9, "title": "could not get window title", + "exe": "could not get window exe", "class": "could not get window class", + "rect": {"left": 0, "top": 0, "right": 0, "bottom": 0} + }] + })); + + assert_eq!(info.window_id, Some(9)); + assert_eq!(info.exe, None, "an error message is not a program"); + } + + #[test] + fn notifications_about_the_machine_are_monitor_events_and_not_commands() { + for name in MONITOR_NOTIFICATIONS { + let info = describe(&json!({"type": name})); + assert_eq!(info.family, Family::Monitor, "{name}"); + assert_eq!(info.name, name); + } + + for name in VIRTUAL_DESKTOP_NOTIFICATIONS { + let info = describe(&json!(name)); + assert_eq!(info.family, Family::Monitor, "{name}"); + } + + // a bare string that is not one of those is not something to guess at + assert_eq!(describe(&json!("Retile")).family, Family::Unknown); + } + + #[test] + fn commands_carry_their_argument() { + let info = describe(&json!({"type": "FocusWorkspaceNumber", "content": 2})); + assert_eq!(info.family, Family::Command); + assert_eq!(info.argument.as_deref(), Some("2")); + assert_eq!(describe(&json!({"type": "Retile"})).family, Family::Command); + } + + #[test] + fn nonsense_is_unknown_not_a_panic() { + assert_eq!(describe(&json!(12)).family, Family::Unknown); + assert_eq!(describe(&json!({"type": 3})).family, Family::Unknown); + assert_eq!(describe(&json!({"a": 1})).family, Family::Unknown); + } + + #[test] + fn handles_are_window_ids_and_unreadable_windows_are_noticed() { + assert_eq!( + WindowsRules.window_id(&window(131_072, "a.exe")), + Some(131_072) + ); + assert_eq!( + WindowsRules.window_id(&json!({"id": 5})), + None, + "a Mac window" + ); + assert!(WindowsRules.window_is_unreadable(&json!({"title": "could not get window title"}))); + assert!(!WindowsRules.window_is_unreadable(&window(1, "a.exe"))); + assert!(!WindowsRules.hides_windows_by_position()); + } +} diff --git a/komorebi-recorder/src/analysis/ids.rs b/komorebi-recorder/src/analysis/ids.rs new file mode 100644 index 00000000..1142cae3 --- /dev/null +++ b/komorebi-recorder/src/analysis/ids.rs @@ -0,0 +1,264 @@ +//! Stable names for things in a session, so a command's output can be fed straight back in. +//! +//! An event is `event:`, a line of the recorded komorebi log is `log:`, a recorder +//! incident is `incident:` (1-based line of `recorder.jsonl`) and a user or agent annotation is +//! `bug:`, `note:` or `finding:`. All of them are accepted wherever a time is, see +//! `crate::analysis::timespec`. +//! +//! [`ItemRef`] parses and prints these names. An annotation id is `a-` and eight lowercase +//! hexadecimal digits (`a-3f9c1e02`), made by [`new_annotation_id`] and recognized by +//! [`is_annotation_id`]. This module only names things: whether `event:12` exists in a session is +//! asked of the session when the name is resolved to a time. + +use color_eyre::eyre; +use std::collections::hash_map::RandomState; +use std::fmt; +use std::hash::BuildHasher; +use std::hash::Hasher; +use std::str::FromStr; + +/// A reference to one thing in a session: an event, a line of komorebi's log, a recorder incident +/// or an annotation. +/// +/// A reference is parsed from its text with [`str::parse`] ([`FromStr`]) and printed with +/// [`Display`](fmt::Display), and the two agree: the printed form of a reference (with a valid +/// annotation id, if it is an annotation) parses back to it. Parsing accepts more than printing +/// writes, so the text of a reference is not always what the reference prints as. +/// +/// | Text | Reference | +/// |---|---| +/// | `event:12` | [`ItemRef::Event`]`(12)` | +/// | `log:345` | [`ItemRef::Log`]`(345)` | +/// | `incident:2` | [`ItemRef::Incident`]`(2)` | +/// | `ann:a-3f9c1e02`, `bug:a-3f9c1e02`, `note:a-3f9c1e02`, `finding:a-3f9c1e02`, `a-3f9c1e02` | [`ItemRef::Annotation`]`("a-3f9c1e02")` | +/// +/// The kind of an annotation (a bug region, a note or a finding) is not part of the reference: +/// all four prefixes, and the bare id, are the same reference, and it prints as `ann:`. +/// +/// # Errors +/// +/// Parsing fails with a usage error (the exit kind `Usage` of the `envelope` module) when: +/// +/// - the text, trimmed of surrounding whitespace, is neither an annotation id nor has a `:`: +/// `'' is not an item reference`; +/// - the prefix is not `event`, `log`, `incident`, `ann`, `bug`, `note` or `finding`: +/// `unknown reference ''`; +/// - the part after `event:`, `log:` or `incident:` is not a whole number (so it is not empty, +/// negative or fractional), or does not fit in a `u64`; +/// - the part after `ann:`, `bug:`, `note:` or `finding:` is not an annotation id: +/// `'' is not an annotation id like a-3f9c1e02`. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::ids::ItemRef; +/// +/// let event: ItemRef = "event:12".parse()?; +/// assert_eq!(event, ItemRef::Event(12)); +/// assert_eq!(event.to_string(), "event:12"); +/// +/// // the kind of annotation does not matter, and a bare id is one +/// let note: ItemRef = "note:a-3f9c1e02".parse()?; +/// assert_eq!(note, "bug:a-3f9c1e02".parse()?); +/// assert_eq!(note, "a-3f9c1e02".parse()?); +/// assert_eq!(note.to_string(), "ann:a-3f9c1e02"); +/// +/// // mistakes are errors that say what was wrong +/// let error = "event:twelve".parse::().unwrap_err(); +/// assert_eq!( +/// error.to_string(), +/// "'event:twelve': an event sequence number must be a whole number" +/// ); +/// let error = "frame:3".parse::().unwrap_err(); +/// assert!(error.to_string().starts_with("unknown reference 'frame:3'")); +/// # Ok::<(), Box>(()) +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ItemRef { + /// A komorebi notification, by its [`seq`](super::events::EventRecord::seq). + Event(u64), + /// A line of the session's recorded `komorebi.log`, 1-based. + Log(u64), + /// A line of the recorder's incident log, 1-based. + Incident(u64), + /// An annotation (a bug region, a note or a finding), by its id: `a-` and eight lowercase hex + /// digits. + Annotation(String), +} + +impl fmt::Display for ItemRef { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Event(seq) => write!(f, "event:{seq}"), + Self::Log(line) => write!(f, "log:{line}"), + Self::Incident(number) => write!(f, "incident:{number}"), + Self::Annotation(id) => write!(f, "ann:{id}"), + } + } +} + +impl ItemRef { + /// Returns whether `input` starts with one of the prefixes [`ItemRef`] understands: `event`, + /// `log`, `incident`, `ann`, `bug`, `note` or `finding`, followed by a `:`. + /// + /// The part after the colon is not looked at, so a true answer does not mean that `input` + /// parses. A bare annotation id has no prefix; use [`is_annotation_id`] for that. + /// + /// # Example + /// + /// ```rust + /// use komorebi_recorder::analysis::ids::ItemRef; + /// + /// assert!(ItemRef::has_prefix("event:12")); + /// assert!(ItemRef::has_prefix("event:twelve")); // has the prefix, but would not parse + /// assert!(!ItemRef::has_prefix("a-3f9c1e02")); + /// assert!(!ItemRef::has_prefix("12.5")); + /// ``` + #[must_use] + pub fn has_prefix(input: &str) -> bool { + input + .split_once(':') + .is_some_and(|(prefix, _)| PREFIXES.contains(&prefix)) + } +} + +const PREFIXES: [&str; 7] = ["event", "log", "incident", "ann", "bug", "note", "finding"]; + +impl FromStr for ItemRef { + type Err = eyre::Report; + + fn from_str(input: &str) -> Result { + let input = input.trim(); + // a bare annotation id is fine + if is_annotation_id(input) { + return Ok(Self::Annotation(input.to_string())); + } + + let (prefix, rest) = input + .split_once(':') + .ok_or_else(|| super::envelope::usage(format!("'{input}' is not an item reference")))?; + let number = |what: &str| -> eyre::Result { + rest.parse().map_err(|_| { + super::envelope::usage(format!("'{input}': {what} must be a whole number")) + }) + }; + + match prefix { + "event" => Ok(Self::Event(number("an event sequence number")?)), + "log" => Ok(Self::Log(number("a log line")?)), + "incident" => Ok(Self::Incident(number("an incident number")?)), + "ann" | "bug" | "note" | "finding" if is_annotation_id(rest) => { + Ok(Self::Annotation(rest.to_string())) + } + "ann" | "bug" | "note" | "finding" => Err(super::envelope::usage(format!( + "'{rest}' is not an annotation id like a-3f9c1e02" + ))), + _ => Err(super::envelope::usage(format!( + "unknown reference '{input}': expected event:, log:, incident: or bug:" + ))), + } + } +} + +/// Returns whether `text` is an annotation id: `a-` and exactly eight lowercase hexadecimal digits. +/// +/// Uppercase digits are not accepted, and nothing around the id is trimmed. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::ids::is_annotation_id; +/// +/// assert!(is_annotation_id("a-3f9c1e02")); +/// assert!(!is_annotation_id("a-3F9C1E02")); // lowercase only +/// assert!(!is_annotation_id("a-3f9c1e0")); // eight digits, not seven +/// assert!(!is_annotation_id("bug:a-3f9c1e02")); +/// ``` +#[must_use] +pub fn is_annotation_id(text: &str) -> bool { + text.strip_prefix("a-").is_some_and(|hex| { + hex.len() == 8 + && hex + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + }) +} + +/// Returns a fresh annotation id, one that [`is_annotation_id`] accepts. +/// +/// The id is random per process (the standard library seeds its hasher from the OS) and mixed with +/// the clock and the process id, so two recorders marking at once do not collide in practice. +/// That is not guaranteed: an id has 32 bits, and nothing here checks that an id is unused. +/// +/// # Example +/// +/// ```rust +/// use komorebi_recorder::analysis::ids::{is_annotation_id, new_annotation_id}; +/// +/// let id = new_annotation_id(); +/// assert!(is_annotation_id(&id)); +/// assert_eq!(id.len(), 10); // `a-` and eight digits +/// ``` +#[must_use] +pub fn new_annotation_id() -> String { + let mut hasher = RandomState::new().build_hasher(); + hasher.write_u64(crate::clock::mono_now_ns()); + hasher.write_u32(std::process::id()); + format!("a-{:08x}", hasher.finish() as u32) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn references_round_trip() { + for text in ["event:12", "log:345", "incident:2", "ann:a-3f9c1e02"] { + let item: ItemRef = text.parse().expect(text); + assert_eq!(item.to_string(), text); + } + } + + #[test] + fn annotation_kinds_and_bare_ids_are_aliases() { + let expected = ItemRef::Annotation("a-3f9c1e02".to_string()); + for text in [ + "bug:a-3f9c1e02", + "note:a-3f9c1e02", + "finding:a-3f9c1e02", + "a-3f9c1e02", + ] { + assert_eq!(text.parse::().expect(text), expected); + } + } + + #[test] + fn bad_references_are_usage_errors() { + for text in [ + "event:x", + "log:", + "bug:123", + "frame:3", + "nonsense", + "bug:a-XYZ", + ] { + let error = text.parse::().expect_err(text); + assert_eq!( + super::super::envelope::exit_kind(&error), + super::super::envelope::ExitKind::Usage, + "{text}" + ); + } + } + + #[test] + fn new_ids_look_right_and_do_not_collide() { + let mut seen = std::collections::HashSet::new(); + for _ in 0..1000 { + let id = new_annotation_id(); + assert!(is_annotation_id(&id), "{id}"); + seen.insert(id); + } + assert!(seen.len() > 990, "only {} distinct ids", seen.len()); + } +} diff --git a/komorebi-recorder/src/analysis/mod.rs b/komorebi-recorder/src/analysis/mod.rs new file mode 100644 index 00000000..54b95dd5 --- /dev/null +++ b/komorebi-recorder/src/analysis/mod.rs @@ -0,0 +1,12 @@ +//! Understanding a recorded session without a window. +//! +//! Everything here reads a session directory and produces plain serializable values, so the same +//! answers serve the command line and anything else that wants them. +//! This module holds the parts every command shares: the JSON envelope and exit codes +//! ([`envelope`]) and how an event or a log line is named ([`ids`]). + +pub mod classify; +pub mod envelope; +pub mod events; +pub mod flavor; +pub mod ids; diff --git a/komorebi-recorder/src/lib.rs b/komorebi-recorder/src/lib.rs index a095a17d..9cd6824a 100644 --- a/komorebi-recorder/src/lib.rs +++ b/komorebi-recorder/src/lib.rs @@ -13,8 +13,8 @@ //! //! Two things vary independently. The _host_ is the OS the recorder runs on, and everything that differs by it is behind //! [`platform`]. The _flavor_ is the komorebi being recorded, komorebi for Mac or komorebi for Windows, and everything -//! that differs by it is behind a trait in the analysis. A session records both, so a session recorded on one host can -//! be read on the other. +//! that differs by it is behind a trait in [`analysis::flavor`]. A session records both, so a session recorded on one +//! host can be read on the other. //! //! Every record in a session is stamped on one monotonic clock, the _master clock_ ([`clock`]). Video frames and the OS //! trace are already on it; komorebi's log lines carry wall-clock time and are mapped onto it with paired readings of @@ -42,6 +42,7 @@ //! | [`timecode`] | parsing and printing video timecodes | //! | [`clock`] | the master clock, anchors and the map between the wall clock and the master clock | //! | [`platform`] | everything that differs by host, behind one facade | +//! | [`analysis`] | understanding a session without a window, starting with the komorebi flavors | //! //! # What is not supported //! @@ -54,6 +55,7 @@ //! The Windows host is type-checked and cross-built from a Mac and built on Windows in CI, and has never been run. See //! [`platform`] for what each host provides. +pub mod analysis; pub mod clock; pub mod platform; pub mod timecode; diff --git a/komorebi-recorder/src/platform/mod.rs b/komorebi-recorder/src/platform/mod.rs index bb531186..0f1ebf38 100644 --- a/komorebi-recorder/src/platform/mod.rs +++ b/komorebi-recorder/src/platform/mod.rs @@ -14,9 +14,9 @@ //! # The host axis //! //! This is the *host* axis: what the recorder is running on. -//! Which komorebi produced a session is a separate axis, the *flavor*: a session recorded on -//! Windows can be investigated on a Mac, and the [`Host`] a session was recorded on is part of its -//! manifest. +//! Which komorebi produced a session is a separate axis (see [`crate::analysis::flavor`]): a +//! session recorded on Windows can be investigated on a Mac, and the [`Host`] a session was +//! recorded on is part of its manifest. //! //! # Adding a function //!