mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-20 07:31:39 +01:00
feat(analysis): explain one event, follow one window
One event end to end: what its handler logged, what other threads logged meanwhile, and every change with who made it and how sure that is. The state, the diff and the events are answered as plain values, an overview ranks what stands out in a recording, and invariants flag states that are wrong: a window in two containers, a window parked off screen on the workspace that is showing (a rule that holds only where komorebi hides windows by moving them, so it is skipped on Windows).
This commit is contained in:
1 parent
3a325470eb
commit
079f1ac6d0
7 files changed
+3446
No files matched your search
@@ -219,6 +219,7 @@ anchors sampled every 5 seconds during the recording and at every sleep, so cloc
|
||||
- subscriber events are stamped when the recorder receives them. komorebi sends the notification _after_ it has handled
|
||||
the event, so the stamp is when the handler **finished**; the `processing event` line in `komorebi.log` is when it
|
||||
began.
|
||||
`komorebi-recorder trace` ties the two together.
|
||||
|
||||
`komorebi-recorder selftest` checks this on your machine: it records a rendered on-screen clock and compares the clock
|
||||
visible in the video with the time the session predicts. The result is stored in `session.json` under `calibration`.
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
//! The answers to "what was the state", "what changed" and "what happened", as data.
|
||||
//!
|
||||
//! Built here, from an [`Analysis`], so that the commands print them and the viewer draws the
|
||||
//! same thing. The data types are plain values that serialize: `komorebi-recorder` prints one as
|
||||
//! text ([`crate::report`]) or, with `--json`, inside an envelope whose `schema` names the type.
|
||||
//!
|
||||
//! | Question | Asked with | Answered by | Data | Schema | Command |
|
||||
//! |---|---|---|---|---|---|
|
||||
//! | What was the state at a moment? | [`StateQuery`] | [`Analysis::state_answer`] | [`StateData`] | [`SCHEMA_STATE`] | `state` |
|
||||
//! | What changed between two moments? | two times | [`Analysis::diff_answer`] | [`DiffData`] | [`SCHEMA_DIFF`] | `diff` |
|
||||
//! | What happened? | [`EventQuery`] | [`Analysis::events_answer`] | [`EventsAnswer`], with [`EventsData`] | [`SCHEMA_EVENTS`] | `events` |
|
||||
//!
|
||||
//! The types at the end ([`AnnotationData`], [`AnnotationsData`], [`DeletedData`]) are what the
|
||||
//! `annotate` and `annotations` commands print with `--json`.
|
||||
//!
|
||||
//! Times are nanoseconds on the host's master monotonic clock (`*_mach_ns`), which
|
||||
//! [`Analysis::resolve`] gives for any time the user can type.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust
|
||||
//! use komorebi_recorder::analysis::Analysis;
|
||||
//! use komorebi_recorder::analysis::answers::{EventQuery, StateQuery};
|
||||
//! use komorebi_recorder::testkit::{SessionBuilder, mach_ns, state_with_windows};
|
||||
//! use serde_json::json;
|
||||
//!
|
||||
//! let (session, _) = SessionBuilder::new("doc-answers")
|
||||
//! .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
//! .event(4.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal"), (8, "Browser")])))
|
||||
//! .build();
|
||||
//! let analysis = Analysis::open(&session.dir)?;
|
||||
//!
|
||||
//! // what was the state at 3 s: one window
|
||||
//! let before = analysis.state_answer(mach_ns(3.0), &StateQuery::default())?;
|
||||
//! assert_eq!(before.workspaces[0].windows, 1);
|
||||
//! assert_eq!(before.origin.seq, Some(1));
|
||||
//!
|
||||
//! // what changed by 5 s: the browser appeared and the terminal made room
|
||||
//! let diff = analysis.diff_answer(mach_ns(3.0), mach_ns(5.0))?;
|
||||
//! assert!(diff.changes.iter().any(|change| change.text.contains("Browser") && change.text.contains("appeared")));
|
||||
//!
|
||||
//! // what happened: both events, or one at a time
|
||||
//! let all = analysis.events_answer(&EventQuery::default());
|
||||
//! assert_eq!((all.data.matching, all.data.total), (2, 2));
|
||||
//! let first = analysis.events_answer(&EventQuery { limit: Some(1), ..EventQuery::default() });
|
||||
//! assert_eq!(first.next_cursor.as_deref(), Some("1"));
|
||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
//! ```
|
||||
|
||||
use super::Analysis;
|
||||
use super::classify::Class;
|
||||
use super::diff;
|
||||
use super::diff::Change;
|
||||
use super::envelope;
|
||||
use super::facade::StateAt;
|
||||
use super::facade::StateSource;
|
||||
use super::invariants;
|
||||
use super::invariants::Violation;
|
||||
use super::state::Focus;
|
||||
use super::state::Location;
|
||||
use super::state::Monitor;
|
||||
use super::state::Place;
|
||||
use super::state::Rect;
|
||||
use super::state::Snapshot;
|
||||
use super::state::Window;
|
||||
use super::views::EventView;
|
||||
use super::views::Moment;
|
||||
use super::views::StateOrigin;
|
||||
use crate::annotations::AnnotationView;
|
||||
use color_eyre::eyre;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The `schema` of the `state` command's output: the name that [`StateData`] has in an envelope.
|
||||
pub const SCHEMA_STATE: &str = "state/1";
|
||||
/// The `schema` of the `diff` command's output: the name that [`DiffData`] has in an envelope.
|
||||
pub const SCHEMA_DIFF: &str = "diff/1";
|
||||
/// The `schema` of the `events` command's output: the name that [`EventsData`] has in an envelope.
|
||||
pub const SCHEMA_EVENTS: &str = "events/1";
|
||||
|
||||
/// A window asked about and everything known about where it is.
|
||||
#[derive(Debug, Clone, Serialize, JsonSchema)]
|
||||
pub struct WindowMatch {
|
||||
/// The window, as the state records it. Its `rect` is where it really was when the state was
|
||||
/// written, not where komorebi's layout put it.
|
||||
pub window: Window,
|
||||
/// Which monitor, workspace and place in the workspace it is in.
|
||||
pub location: Location,
|
||||
/// Where the layout says this container should be, when it is a tiled window.
|
||||
///
|
||||
/// `None` for a window that is not in a container of the workspace's layout (monocle, maximized
|
||||
/// or floating, or a workspace with a monocle container) or whose container has no recorded
|
||||
/// layout rect.
|
||||
pub layout_rect: Option<Rect>,
|
||||
/// Parked off screen the way komorebi hides windows.
|
||||
///
|
||||
/// This is whether the window's real rect is where komorebi parks a window it has hidden on that
|
||||
/// monitor, which depends on the komorebi that recorded the state: komorebi for Windows hides a
|
||||
/// window by cloaking it in place, so its position never says.
|
||||
pub hidden_position: bool,
|
||||
}
|
||||
|
||||
/// One workspace of one monitor, in a state answer.
|
||||
#[derive(Debug, Clone, Serialize, JsonSchema)]
|
||||
pub struct WorkspaceSummary {
|
||||
/// The monitor (display id) the workspace is on.
|
||||
pub monitor_id: u64,
|
||||
/// The workspace's name.
|
||||
pub name: String,
|
||||
/// Whether it is the workspace showing on its monitor.
|
||||
pub showing: bool,
|
||||
/// How many windows it holds, of every kind: tiled, monocle, maximized and floating.
|
||||
pub windows: usize,
|
||||
}
|
||||
|
||||
/// The answer to "what was komorebi's state at this moment", made by [`Analysis::state_answer`].
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct StateData {
|
||||
/// The moment asked about, on every clock.
|
||||
pub at: Moment,
|
||||
/// Which notification the state is from, and how old it is at `at`.
|
||||
pub origin: StateOrigin,
|
||||
/// What has the keyboard focus.
|
||||
pub focus: Option<Focus>,
|
||||
/// Whether komorebi was paused.
|
||||
pub paused: bool,
|
||||
/// The monitors, with only the workspaces asked for (the showing ones by default).
|
||||
pub monitors: Vec<Monitor>,
|
||||
/// Every workspace of every monitor, however the monitors and workspaces were filtered.
|
||||
pub workspaces: Vec<WorkspaceSummary>,
|
||||
/// The windows that matched the window asked about (`--window`); empty if none was asked about.
|
||||
pub matches: Vec<WindowMatch>,
|
||||
/// What looks wrong in the state, narrowed to the monitor and windows asked about.
|
||||
pub violations: Vec<Violation>,
|
||||
}
|
||||
|
||||
/// One difference between two states: the sentence a person would say, and the change it says it
|
||||
/// of.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct ChangeView {
|
||||
/// The change in words.
|
||||
pub text: String,
|
||||
/// The change itself. Its fields are flattened into the same JSON object as `text`.
|
||||
#[serde(flatten)]
|
||||
pub change: Change,
|
||||
}
|
||||
|
||||
/// The answer to "what changed between these two moments", made by [`Analysis::diff_answer`].
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct DiffData {
|
||||
/// The earlier moment, as given.
|
||||
pub from: Moment,
|
||||
/// Which notification the state at `from` is from.
|
||||
pub from_origin: StateOrigin,
|
||||
/// The later moment, as given.
|
||||
pub to: Moment,
|
||||
/// Which notification the state at `to` is from.
|
||||
pub to_origin: StateOrigin,
|
||||
/// What differs between the two states. Empty if nothing a person would notice does, which is
|
||||
/// also the case when both moments fall in the same state.
|
||||
pub changes: Vec<ChangeView>,
|
||||
/// Violations present at `to` and not at `from`.
|
||||
pub violations_appeared: Vec<Violation>,
|
||||
/// Violations present at `from` and not at `to`.
|
||||
pub violations_resolved: Vec<Violation>,
|
||||
}
|
||||
|
||||
/// The answer to "what happened", made by [`Analysis::events_answer`]: the events that matched, in
|
||||
/// order, with the counts to tell whether the list is whole.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct EventsData {
|
||||
/// The events returned, in the order they were received.
|
||||
pub events: Vec<EventView>,
|
||||
/// How many events matched the filters, including any not returned because of the limit
|
||||
/// (`--limit`) or because they come before the cursor (`--cursor`).
|
||||
pub matching: usize,
|
||||
/// How many events the session has.
|
||||
pub total: usize,
|
||||
/// The name komorebi knew this recorder by. When komorebi logs at DEBUG it names it for each
|
||||
/// notification pushed, which makes pairing events with handlers exact.
|
||||
pub subscriber: Option<String>,
|
||||
}
|
||||
|
||||
/// Which windows, monitors and workspaces a state answer is about.
|
||||
///
|
||||
/// The default asks about nothing in particular: every monitor, the workspaces that are showing,
|
||||
/// and no window.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct StateQuery {
|
||||
/// A window id, or text found in a window's application or title (compared without regard to
|
||||
/// case). The workspaces holding a match are included in the answer even if they are not
|
||||
/// showing. If nothing matches, [`Analysis::state_answer`] fails.
|
||||
pub window: Option<String>,
|
||||
/// Only this monitor (display id) in [`StateData::monitors`] and [`StateData::violations`].
|
||||
pub monitor: Option<u64>,
|
||||
/// Include workspaces that are not showing.
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// Which events an events answer includes.
|
||||
///
|
||||
/// The default includes every event. A filter is only applied if it is set, and an event must pass
|
||||
/// all of the filters that are.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EventQuery {
|
||||
/// Only events received at or after this time (nanoseconds on the master clock).
|
||||
pub from_mach_ns: Option<u64>,
|
||||
/// Only events received at or before this time.
|
||||
pub to_mach_ns: Option<u64>,
|
||||
/// Only events of these classes; empty means any class.
|
||||
pub classes: Vec<Class>,
|
||||
/// Leave out echoes of komorebi's own moves ([`Class::Echo`]).
|
||||
pub hide_echo: bool,
|
||||
/// Only events whose name contains this text, compared without regard to case.
|
||||
pub name: Option<String>,
|
||||
/// Only events about this process id.
|
||||
pub pid: Option<i32>,
|
||||
/// Only events about this window id.
|
||||
pub window: Option<u32>,
|
||||
/// Most events to return; `None` for all.
|
||||
pub limit: Option<usize>,
|
||||
/// Only events after this sequence number.
|
||||
pub after_seq: Option<u64>,
|
||||
}
|
||||
|
||||
/// An events answer and where to continue if it was cut short.
|
||||
pub struct EventsAnswer {
|
||||
/// The events and their counts.
|
||||
pub data: EventsData,
|
||||
/// Set if [`EventQuery::limit`] cut the answer short: the sequence number of the last event
|
||||
/// returned, to pass back as [`EventQuery::after_seq`] (the `--cursor` of the `events` command)
|
||||
/// for the rest. `None` if the answer is whole.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
fn matches_window(text: &str, window: &Window) -> bool {
|
||||
if let Ok(id) = text.parse::<u64>()
|
||||
&& window.id == id
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let needle = text.to_lowercase();
|
||||
window.exe.to_lowercase().contains(&needle) || window.title.to_lowercase().contains(&needle)
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
fn origin(&self, at: &StateAt, asked_mach_ns: u64) -> StateOrigin {
|
||||
match at.source {
|
||||
StateSource::Event { seq, recv_mach_ns } => StateOrigin {
|
||||
source: "event".to_string(),
|
||||
seq: Some(seq),
|
||||
state_id: at.state_id,
|
||||
age_ms: Some(asked_mach_ns.saturating_sub(recv_mach_ns) as f64 / 1e6),
|
||||
},
|
||||
StateSource::Start => StateOrigin {
|
||||
source: "start".to_string(),
|
||||
seq: None,
|
||||
state_id: None,
|
||||
age_ms: Some(
|
||||
asked_mach_ns.saturating_sub(self.manifest.start.mach_ns) as f64 / 1e6,
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the state at `mach_ns`, filtered to what `query` asks about, with what looks wrong
|
||||
/// in it.
|
||||
///
|
||||
/// The state is the one [`Analysis::state_at`] finds, so it is as of the latest notification
|
||||
/// before `mach_ns`; [`StateData::origin`] names which one and how old it is.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the errors of [`Analysis::state_at`] (no state was recorded before `mach_ns`), and a
|
||||
/// not-found error if [`StateQuery::window`] is set and no window in the state matches it.
|
||||
pub fn state_answer(&self, mach_ns: u64, query: &StateQuery) -> eyre::Result<StateData> {
|
||||
let found = self.state_at(mach_ns)?;
|
||||
let snapshot: &Snapshot = &found.snapshot;
|
||||
|
||||
let matches: Vec<WindowMatch> = match &query.window {
|
||||
Some(text) => snapshot
|
||||
.windows()
|
||||
.into_iter()
|
||||
.filter(|(_, window)| matches_window(text, window))
|
||||
.map(|(location, window)| {
|
||||
let monitor = snapshot
|
||||
.monitors
|
||||
.iter()
|
||||
.find(|monitor| monitor.id == location.monitor_id);
|
||||
let layout_rect = monitor
|
||||
.and_then(|monitor| {
|
||||
monitor
|
||||
.workspaces
|
||||
.iter()
|
||||
.find(|workspace| workspace.name == location.workspace)
|
||||
})
|
||||
.and_then(|workspace| match location.place {
|
||||
Place::Container { index, .. } if workspace.monocle.is_none() => {
|
||||
workspace.layout_rects.get(index).copied()
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let hidden_position = window
|
||||
.rect
|
||||
.as_ref()
|
||||
.zip(monitor)
|
||||
.is_some_and(|(rect, monitor)| snapshot.is_hidden_position(rect, monitor));
|
||||
WindowMatch {
|
||||
window: window.clone(),
|
||||
location,
|
||||
layout_rect,
|
||||
hidden_position,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
if query.window.is_some() && matches.is_empty() {
|
||||
return Err(envelope::not_found(format!(
|
||||
"no window matches '{}' in the state at {}",
|
||||
query.window.as_deref().unwrap_or_default(),
|
||||
self.moment(mach_ns).timecode
|
||||
)));
|
||||
}
|
||||
|
||||
let all_windows = snapshot.windows();
|
||||
let workspaces: Vec<WorkspaceSummary> = snapshot
|
||||
.monitors
|
||||
.iter()
|
||||
.flat_map(|monitor| {
|
||||
let all_windows = &all_windows;
|
||||
monitor
|
||||
.workspaces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(move |(index, workspace)| WorkspaceSummary {
|
||||
monitor_id: monitor.id,
|
||||
name: workspace.name.clone(),
|
||||
showing: index == monitor.focused,
|
||||
windows: all_windows
|
||||
.iter()
|
||||
.filter(|(location, _)| {
|
||||
location.monitor_id == monitor.id
|
||||
&& location.workspace == workspace.name
|
||||
})
|
||||
.count(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let wanted = |monitor: &Monitor, index: usize, name: &str| {
|
||||
query.all
|
||||
|| index == monitor.focused
|
||||
|| matches.iter().any(|found| {
|
||||
found.location.monitor_id == monitor.id && found.location.workspace == name
|
||||
})
|
||||
};
|
||||
let monitors: Vec<Monitor> = snapshot
|
||||
.monitors
|
||||
.iter()
|
||||
.filter(|monitor| query.monitor.is_none_or(|id| id == monitor.id))
|
||||
.map(|monitor| {
|
||||
let mut kept = monitor.clone();
|
||||
kept.workspaces = monitor
|
||||
.workspaces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, workspace)| wanted(monitor, *index, &workspace.name))
|
||||
.map(|(_, workspace)| workspace.clone())
|
||||
.collect();
|
||||
kept
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut violations = invariants::check(snapshot);
|
||||
if let Some(id) = query.monitor {
|
||||
violations.retain(|violation| violation.monitor_id.is_none_or(|monitor| monitor == id));
|
||||
}
|
||||
if !matches.is_empty() {
|
||||
violations.retain(|violation| {
|
||||
violation.window_ids.is_empty()
|
||||
|| violation
|
||||
.window_ids
|
||||
.iter()
|
||||
.any(|id| matches.iter().any(|found| found.window.id == *id))
|
||||
});
|
||||
}
|
||||
|
||||
Ok(StateData {
|
||||
at: self.moment(mach_ns),
|
||||
origin: self.origin(&found, mach_ns),
|
||||
focus: snapshot.focus(),
|
||||
paused: snapshot.paused,
|
||||
monitors,
|
||||
workspaces,
|
||||
matches,
|
||||
violations,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns what changed between the state at `from_mach_ns` and the state at `to_mach_ns`, in
|
||||
/// terms a person would use, and which violations appeared or went away.
|
||||
///
|
||||
/// Both states are found as [`Analysis::state_at`] does. The order of the two times is not
|
||||
/// checked: with `to_mach_ns` before `from_mach_ns` the answer describes the change backwards.
|
||||
/// The `diff` command refuses that.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the errors of [`Analysis::state_at`] for either moment.
|
||||
pub fn diff_answer(&self, from_mach_ns: u64, to_mach_ns: u64) -> eyre::Result<DiffData> {
|
||||
let before = self.state_at(from_mach_ns)?;
|
||||
let after = self.state_at(to_mach_ns)?;
|
||||
let changes = diff::diff(&before.snapshot, &after.snapshot);
|
||||
|
||||
let (was, now) = (
|
||||
invariants::check(&before.snapshot),
|
||||
invariants::check(&after.snapshot),
|
||||
);
|
||||
Ok(DiffData {
|
||||
from: self.moment(from_mach_ns),
|
||||
from_origin: self.origin(&before, from_mach_ns),
|
||||
to: self.moment(to_mach_ns),
|
||||
to_origin: self.origin(&after, to_mach_ns),
|
||||
changes: changes
|
||||
.into_iter()
|
||||
.map(|change| ChangeView {
|
||||
text: change.describe(),
|
||||
change,
|
||||
})
|
||||
.collect(),
|
||||
violations_appeared: now.iter().filter(|v| !was.contains(v)).cloned().collect(),
|
||||
violations_resolved: was.iter().filter(|v| !now.contains(v)).cloned().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the events matching `query`, in the order they were received.
|
||||
///
|
||||
/// This does not fail: an empty answer means nothing matched. At most [`EventQuery::limit`]
|
||||
/// events are returned, starting after [`EventQuery::after_seq`]; [`EventsData::matching`]
|
||||
/// counts the matches before that, and [`EventsAnswer::next_cursor`] gives where to continue.
|
||||
#[must_use]
|
||||
pub fn events_answer(&self, query: &EventQuery) -> EventsAnswer {
|
||||
let all = self.events();
|
||||
let needle = query.name.as_deref().map(str::to_lowercase);
|
||||
let wanted: Vec<usize> = (0..all.len())
|
||||
.filter(|index| {
|
||||
let event = &all[*index];
|
||||
let class = self.pairing().classes[*index].class;
|
||||
query
|
||||
.from_mach_ns
|
||||
.is_none_or(|from| event.recv_mach_ns >= from)
|
||||
&& query.to_mach_ns.is_none_or(|to| event.recv_mach_ns <= to)
|
||||
&& (query.classes.is_empty() || query.classes.contains(&class))
|
||||
&& !(query.hide_echo && class == Class::Echo)
|
||||
&& needle
|
||||
.as_ref()
|
||||
.is_none_or(|needle| event.info.name.to_lowercase().contains(needle))
|
||||
&& query.pid.is_none_or(|pid| event.info.pid == Some(pid))
|
||||
&& query
|
||||
.window
|
||||
.is_none_or(|window| event.info.window_id == Some(window))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let remaining: Vec<usize> = wanted
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|index| query.after_seq.is_none_or(|after| all[*index].seq > after))
|
||||
.collect();
|
||||
let count = query
|
||||
.limit
|
||||
.map_or(remaining.len(), |limit| limit.min(remaining.len()));
|
||||
let events: Vec<EventView> = remaining[..count]
|
||||
.iter()
|
||||
.filter_map(|index| self.event_view(*index))
|
||||
.collect();
|
||||
let next_cursor = (count < remaining.len())
|
||||
.then(|| events.last().map(|view| view.seq.to_string()))
|
||||
.flatten();
|
||||
|
||||
EventsAnswer {
|
||||
data: EventsData {
|
||||
events,
|
||||
matching: wanted.len(),
|
||||
total: all.len(),
|
||||
subscriber: self.pairing().subscriber.clone(),
|
||||
},
|
||||
next_cursor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `annotate add` / `edit` answer with the annotation as it now reads.
|
||||
#[derive(Serialize, JsonSchema)]
|
||||
pub struct AnnotationData {
|
||||
/// The annotation, read back from the file after the write.
|
||||
pub annotation: AnnotationView,
|
||||
}
|
||||
|
||||
/// The answer of `annotate delete`.
|
||||
#[derive(Serialize, JsonSchema)]
|
||||
pub struct DeletedData {
|
||||
/// The id of the annotation that was removed.
|
||||
pub deleted: String,
|
||||
}
|
||||
|
||||
/// The answer of `annotations`: the session's annotations, optionally of one kind.
|
||||
#[derive(Serialize, JsonSchema)]
|
||||
pub struct AnnotationsData {
|
||||
/// The annotations, ordered by start and then by id.
|
||||
pub annotations: Vec<AnnotationView>,
|
||||
}
|
||||
@@ -0,0 +1,715 @@
|
||||
//! Things that should never be true of komorebi's state, and what true state looks like.
|
||||
//!
|
||||
//! These are checks on one state taken on its own, so they can be run at any moment of a
|
||||
//! recording. A violation is evidence, not a verdict: komorebi may be mid-way through a
|
||||
//! transition, or an application may refuse a size komorebi asked for. Each says what it saw and
|
||||
//! how sure it is by severity.
|
||||
//!
|
||||
//! There are two entry points, which look at different things:
|
||||
//!
|
||||
//! - [`check`] reads a [`Snapshot`] alone: the state komorebi reported, including where each
|
||||
//! window really was when it was serialized.
|
||||
//! - `check_probed` compares a snapshot with what Windows reported about one window just after
|
||||
//! an event about it (`record --probe-windows`).
|
||||
//!
|
||||
//! `state`, `diff`, `trace` and `brief` call [`check`] on the states they show, and `overview`
|
||||
//! calls both to find the states that were wrong and for how long.
|
||||
//!
|
||||
//! # The checks
|
||||
//!
|
||||
//! A violation's [`kind`](Violation::kind) is a stable name. Which flavor of komorebi a check
|
||||
//! applies to is decided by how that komorebi hides a window: komorebi for Mac parks it in a corner
|
||||
//! of its monitor, so a window's position shows whether it is hidden; komorebi for Windows cloaks
|
||||
//! it where it is, so no position does (see [`Snapshot::hides_windows_by_position`]).
|
||||
//!
|
||||
//! | kind | severity | what it reports | komorebi for Mac | komorebi for Windows |
|
||||
//! |---|---|---|---|---|
|
||||
//! | `window-in-two-places` | error | one window id is in more than one place | [`check`] | [`check`] |
|
||||
//! | `duplicate-monitor-id` | error | two monitors have the same id | [`check`] | [`check`] |
|
||||
//! | `focus-out-of-range` | error | a monitor focuses a workspace, or a workspace a container, past the end of its list | [`check`] | [`check`] |
|
||||
//! | `visible-window-hidden` | error | a window that should be on screen is hidden | [`check`]: parked in the hiding position | `check_probed`: Windows has it cloaked, minimized or not visible |
|
||||
//! | `monitor-overlap` | warn | two monitors' areas overlap | [`check`] | [`check`] |
|
||||
//! | `empty-container` | warn | a container holds no windows | [`check`] | [`check`] |
|
||||
//! | `off-screen` | warn | a window on a showing workspace is where no monitor is | [`check`] | [`check`] |
|
||||
//! | `layout-mismatch` | warn | a tiled window is not where the last layout put it | [`check`] | [`check`] |
|
||||
//! | `hidden-window-visible` | warn | a window that should be hidden is on screen | [`check`]: not parked, on a workspace that is not showing | `check_probed`: Windows has it on screen |
|
||||
//! | `unmanaged-window` | info | a window is on screen and komorebi does not have it | never | `check_probed` |
|
||||
//!
|
||||
//! So on a komorebi for Windows state [`check`] never reports `visible-window-hidden` or
|
||||
//! `hidden-window-visible`, and on a komorebi for Mac state `check_probed` reports nothing: the
|
||||
//! probe exists only on Windows. Without a probe, nothing can say whether a Windows window is
|
||||
//! really hidden.
|
||||
|
||||
use super::state::Location;
|
||||
use super::state::Monitor;
|
||||
use super::state::Place;
|
||||
use super::state::Rect;
|
||||
use super::state::Snapshot;
|
||||
use super::state::Window;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// How far a window's real rect may be from where the layout put it before it is reported. An
|
||||
/// application with a minimum size (a terminal snapping to whole rows) is a few points off.
|
||||
const LAYOUT_TOLERANCE: i64 = 4;
|
||||
|
||||
/// A window on a workspace that is not showing, with more than this share of itself on a display,
|
||||
/// is leaking through.
|
||||
const LEAK_SHARE_PERCENT: i64 = 25;
|
||||
|
||||
/// How serious a [`Violation`] is, and how sure it is that something is wrong.
|
||||
///
|
||||
/// The variants are ordered from most to least serious (`Error < Warn < Info`), which is the order
|
||||
/// [`check`] sorts its result in.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::invariants::Severity;
|
||||
///
|
||||
/// assert!(Severity::Error < Severity::Warn);
|
||||
/// assert!(Severity::Warn < Severity::Info);
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Severity {
|
||||
/// The state is wrong in a way that a person would see or that komorebi's bookkeeping should
|
||||
/// not allow: a window in two places, a window that should be showing and is not.
|
||||
Error,
|
||||
/// The state is probably wrong, or is wrong in a way that may be an application's doing: a
|
||||
/// tiled window off from its layout, a window where no monitor is.
|
||||
Warn,
|
||||
/// Worth knowing and not a fault in itself: a window komorebi does not manage.
|
||||
Info,
|
||||
}
|
||||
|
||||
/// One thing wrong with a state, with the windows and place it is about.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
pub struct Violation {
|
||||
/// Stable name of the check, e.g. `visible-window-hidden`. The kinds are listed in the
|
||||
/// [module](self) documentation.
|
||||
pub kind: String,
|
||||
/// How serious it is.
|
||||
pub severity: Severity,
|
||||
/// A sentence saying what was seen, naming the windows and where they are. Two violations are
|
||||
/// equal only if their messages are, so a problem whose numbers change reads as a different
|
||||
/// violation.
|
||||
pub message: String,
|
||||
/// The ids of the windows it is about; empty for a problem with monitors or workspaces.
|
||||
pub window_ids: Vec<u64>,
|
||||
/// The display id of the monitor it is about, if it is about one.
|
||||
pub monitor_id: Option<u64>,
|
||||
/// The name of the workspace it is about, if it is about one.
|
||||
pub workspace: Option<String>,
|
||||
}
|
||||
|
||||
fn violation(
|
||||
kind: &str,
|
||||
severity: Severity,
|
||||
message: String,
|
||||
window_ids: Vec<u64>,
|
||||
location: Option<&Location>,
|
||||
) -> Violation {
|
||||
Violation {
|
||||
kind: kind.to_string(),
|
||||
severity,
|
||||
message,
|
||||
window_ids,
|
||||
monitor_id: location.map(|location| location.monitor_id),
|
||||
workspace: location.map(|location| location.workspace.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `found` with the monitor and workspace it is about filled in.
|
||||
fn about(mut found: Violation, monitor_id: u64, workspace: Option<&str>) -> Violation {
|
||||
found.monitor_id = Some(monitor_id);
|
||||
found.workspace = workspace.map(str::to_string);
|
||||
found
|
||||
}
|
||||
|
||||
fn name(window: &Window) -> String {
|
||||
format!("{} \"{}\" (window {})", window.exe, window.title, window.id)
|
||||
}
|
||||
|
||||
/// Checks one state and returns every violation found, most serious first.
|
||||
///
|
||||
/// The result is sorted by severity and then by kind, so errors come before warnings, and is empty
|
||||
/// for a state with nothing wrong. Which checks apply to which flavor is in the [module](self)
|
||||
/// documentation: on a komorebi for Windows state the position-based checks of hidden windows do
|
||||
/// not run, because that state cannot show whether a window is hidden (use `check_probed`
|
||||
/// for that).
|
||||
///
|
||||
/// What is checked:
|
||||
///
|
||||
/// - the same window in more than one place;
|
||||
/// - two monitors with one id, or whose areas overlap;
|
||||
/// - a focus index past the end of what it indexes, for monitors and for workspaces;
|
||||
/// - a container with no windows;
|
||||
/// - for every window that has a rect, on a workspace that is showing: parked in komorebi's hiding
|
||||
/// position (`visible-window-hidden`, in any kind of place), else on no monitor
|
||||
/// (`off-screen`);
|
||||
/// - for every window on a workspace that is not showing, where windows are hidden by position:
|
||||
/// not parked, and with at least 25% of its area on its monitor (`hidden-window-visible`);
|
||||
/// - for the focused workspace of each monitor, if it is tiling and not monocle, maximized or on
|
||||
/// the floating layer: a focused window more than 4 points from where the last layout put its
|
||||
/// container, in any of left, top, width and height (`layout-mismatch`). The few points of slack
|
||||
/// are for an application with a minimum size, such as a terminal snapping to whole rows.
|
||||
///
|
||||
/// A window with no rect, or whose monitor is not in the state, is skipped by the position checks.
|
||||
/// The function does not fail or panic.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::flavor::Flavor;
|
||||
/// use komorebi_recorder::analysis::invariants::Severity;
|
||||
/// use komorebi_recorder::analysis::invariants::check;
|
||||
/// use komorebi_recorder::analysis::state::Snapshot;
|
||||
/// use komorebi_recorder::testkit::container;
|
||||
/// use komorebi_recorder::testkit::monitor;
|
||||
/// use komorebi_recorder::testkit::state;
|
||||
/// use komorebi_recorder::testkit::window;
|
||||
/// use komorebi_recorder::testkit::workspace;
|
||||
///
|
||||
/// // One window fills the only workspace of a 1000x800 monitor, but it is parked in the sliver at
|
||||
/// // the bottom left, where komorebi for Mac puts a window it has hidden.
|
||||
/// let layout = [[0, 0, 1000, 800]];
|
||||
/// let parked = window(1, "Ghostty", Some([-999, 790, 1000, 800]));
|
||||
/// let screen = monitor(
|
||||
/// 1,
|
||||
/// [0, 0, 1000, 800],
|
||||
/// vec![workspace("one", vec![container("a", vec![parked])], 0, &layout)],
|
||||
/// 0,
|
||||
/// );
|
||||
/// let snapshot = Snapshot::parse(Flavor::Macos, &state(vec![screen], 0));
|
||||
///
|
||||
/// let found = check(&snapshot);
|
||||
/// assert_eq!(found.len(), 1);
|
||||
/// assert_eq!(found[0].kind, "visible-window-hidden");
|
||||
/// assert_eq!(found[0].severity, Severity::Error);
|
||||
/// assert_eq!(found[0].window_ids, [1]);
|
||||
/// assert_eq!(found[0].monitor_id, Some(1));
|
||||
/// ```
|
||||
///
|
||||
/// Every kind that [`check`] reports has a unit test in this module, named after it
|
||||
/// (`a_window_on_the_showing_workspace_parked_off_screen_is_an_error`,
|
||||
/// `a_tiled_window_that_is_not_where_the_layout_put_it_is_a_mismatch`, ...).
|
||||
#[must_use]
|
||||
pub fn check(snapshot: &Snapshot) -> Vec<Violation> {
|
||||
let mut found = Vec::new();
|
||||
let windows = snapshot.windows();
|
||||
|
||||
// the same window in two places
|
||||
let mut places: BTreeMap<u64, Vec<&Location>> = BTreeMap::new();
|
||||
for (location, window) in &windows {
|
||||
places.entry(window.id).or_default().push(location);
|
||||
}
|
||||
for (id, locations) in &places {
|
||||
if locations.len() > 1 {
|
||||
let described: Vec<String> = locations
|
||||
.iter()
|
||||
.map(|location| location.describe())
|
||||
.collect();
|
||||
found.push(violation(
|
||||
"window-in-two-places",
|
||||
Severity::Error,
|
||||
format!(
|
||||
"window {id} is in {} places: {}",
|
||||
locations.len(),
|
||||
described.join("; ")
|
||||
),
|
||||
vec![*id],
|
||||
locations.first().copied(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// monitors that overlap or share an id
|
||||
for (index, monitor) in snapshot.monitors.iter().enumerate() {
|
||||
for other in &snapshot.monitors[index + 1..] {
|
||||
if monitor.id == other.id {
|
||||
found.push(violation(
|
||||
"duplicate-monitor-id",
|
||||
Severity::Error,
|
||||
format!("two monitors have the id {}", monitor.id),
|
||||
vec![],
|
||||
None,
|
||||
));
|
||||
} else if monitor.size.overlap_area(&other.size) > 0 {
|
||||
found.push(violation(
|
||||
"monitor-overlap",
|
||||
Severity::Warn,
|
||||
format!(
|
||||
"monitor {} ({}) and monitor {} ({}) overlap",
|
||||
monitor.id,
|
||||
monitor.size.describe(),
|
||||
other.id,
|
||||
other.size.describe()
|
||||
),
|
||||
vec![],
|
||||
None,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// a focus that points past the end of what it focuses
|
||||
if monitor.focused >= monitor.workspaces.len() && !monitor.workspaces.is_empty() {
|
||||
found.push(about(
|
||||
violation(
|
||||
"focus-out-of-range",
|
||||
Severity::Error,
|
||||
format!(
|
||||
"monitor {} focuses workspace {} of {}",
|
||||
monitor.id,
|
||||
monitor.focused,
|
||||
monitor.workspaces.len()
|
||||
),
|
||||
vec![],
|
||||
None,
|
||||
),
|
||||
monitor.id,
|
||||
None,
|
||||
));
|
||||
}
|
||||
for workspace in &monitor.workspaces {
|
||||
if workspace.focused >= workspace.containers.len() && !workspace.containers.is_empty() {
|
||||
found.push(about(
|
||||
violation(
|
||||
"focus-out-of-range",
|
||||
Severity::Error,
|
||||
format!(
|
||||
"monitor {} workspace {} focuses container {} of {}",
|
||||
monitor.id,
|
||||
workspace.name,
|
||||
workspace.focused,
|
||||
workspace.containers.len()
|
||||
),
|
||||
vec![],
|
||||
None,
|
||||
),
|
||||
monitor.id,
|
||||
Some(&workspace.name),
|
||||
));
|
||||
}
|
||||
for container in &workspace.containers {
|
||||
if container.windows.is_empty() {
|
||||
found.push(about(
|
||||
violation(
|
||||
"empty-container",
|
||||
Severity::Warn,
|
||||
format!(
|
||||
"monitor {} workspace {} has an empty container {}",
|
||||
monitor.id, workspace.name, container.id
|
||||
),
|
||||
vec![],
|
||||
None,
|
||||
),
|
||||
monitor.id,
|
||||
Some(&workspace.name),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let monitor_of = |id: u64| snapshot.monitors.iter().find(|monitor| monitor.id == id);
|
||||
|
||||
for (location, window) in &windows {
|
||||
let (Some(rect), Some(monitor)) = (&window.rect, monitor_of(location.monitor_id)) else {
|
||||
continue;
|
||||
};
|
||||
let hidden = snapshot.is_hidden_position(rect, monitor);
|
||||
|
||||
if location.workspace_visible {
|
||||
// on a workspace that is showing, so it should be on screen
|
||||
if hidden {
|
||||
found.push(violation(
|
||||
"visible-window-hidden",
|
||||
Severity::Error,
|
||||
format!(
|
||||
"{} is on {} which is showing, but it is parked off screen at {}",
|
||||
name(window),
|
||||
location.describe(),
|
||||
rect.describe()
|
||||
),
|
||||
vec![window.id],
|
||||
Some(location),
|
||||
));
|
||||
} else if snapshot
|
||||
.monitors
|
||||
.iter()
|
||||
.all(|monitor| monitor.size.overlap_area(rect) == 0)
|
||||
{
|
||||
found.push(violation(
|
||||
"off-screen",
|
||||
Severity::Warn,
|
||||
format!(
|
||||
"{} is on {} but at {} which is on no display",
|
||||
name(window),
|
||||
location.describe(),
|
||||
rect.describe()
|
||||
),
|
||||
vec![window.id],
|
||||
Some(location),
|
||||
));
|
||||
}
|
||||
} else if snapshot.hides_windows_by_position()
|
||||
&& !hidden
|
||||
&& rect.area() > 0
|
||||
&& leaks(rect, monitor)
|
||||
{
|
||||
found.push(violation(
|
||||
"hidden-window-visible",
|
||||
Severity::Warn,
|
||||
format!(
|
||||
"{} is on {} which is not showing, but it is on screen at {}",
|
||||
name(window),
|
||||
location.describe(),
|
||||
rect.describe()
|
||||
),
|
||||
vec![window.id],
|
||||
Some(location),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// tiled windows that are not where the layout put them
|
||||
for monitor in &snapshot.monitors {
|
||||
let Some(workspace) = monitor.focused_workspace() else {
|
||||
continue;
|
||||
};
|
||||
if !workspace.tiling
|
||||
|| workspace.layer == "Floating"
|
||||
|| workspace.monocle.is_some()
|
||||
|| workspace.maximized.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
for (index, container) in workspace.containers.iter().enumerate() {
|
||||
let (Some(expected), Some(window)) = (
|
||||
workspace.layout_rects.get(index),
|
||||
container.focused_window(),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let Some(actual) = &window.rect else {
|
||||
continue;
|
||||
};
|
||||
if snapshot.is_hidden_position(actual, monitor) {
|
||||
// reported as visible-window-hidden
|
||||
continue;
|
||||
}
|
||||
|
||||
let delta = expected.max_delta(actual);
|
||||
if delta > LAYOUT_TOLERANCE {
|
||||
let location = Location {
|
||||
monitor_id: monitor.id,
|
||||
workspace: workspace.name.clone(),
|
||||
place: Place::Container {
|
||||
index,
|
||||
tab: container.focused,
|
||||
},
|
||||
workspace_visible: true,
|
||||
};
|
||||
found.push(violation(
|
||||
"layout-mismatch",
|
||||
Severity::Warn,
|
||||
format!(
|
||||
"{} is at {} but the layout put container {index} at {} ({delta} points off)",
|
||||
name(window),
|
||||
actual.describe(),
|
||||
expected.describe()
|
||||
),
|
||||
vec![window.id],
|
||||
Some(&location),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
found.sort_by(|a, b| (a.severity, &a.kind).cmp(&(b.severity, &b.kind)));
|
||||
found
|
||||
}
|
||||
|
||||
/// Whether enough of `rect` is on `monitor` for the window to be seen.
|
||||
fn leaks(rect: &Rect, monitor: &Monitor) -> bool {
|
||||
let overlap = monitor.size.overlap_area(rect);
|
||||
rect.area() > 0 && overlap * 100 / rect.area() >= LEAK_SHARE_PERCENT
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testkit::container;
|
||||
use crate::testkit::monitor;
|
||||
use crate::testkit::state;
|
||||
use crate::testkit::window;
|
||||
use crate::testkit::workspace;
|
||||
|
||||
fn snapshot(monitors: Vec<serde_json::Value>) -> Snapshot {
|
||||
Snapshot::from_value(&state(monitors, 0))
|
||||
}
|
||||
|
||||
fn kinds(violations: &[Violation]) -> Vec<&str> {
|
||||
violations
|
||||
.iter()
|
||||
.map(|violation| violation.kind.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
const SCREEN: [i64; 4] = [0, 0, 1000, 800];
|
||||
|
||||
#[test]
|
||||
fn a_tidy_state_has_no_violations() {
|
||||
let layout = [[0, 0, 500, 800], [500, 0, 500, 800]];
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![
|
||||
container("a", vec![window(1, "x", Some(layout[0]))]),
|
||||
container("b", vec![window(2, "y", Some(layout[1]))]),
|
||||
],
|
||||
0,
|
||||
&layout,
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
|
||||
assert_eq!(check(&state), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_on_the_showing_workspace_parked_off_screen_is_an_error() {
|
||||
let layout = [[0, 0, 1000, 800]];
|
||||
// right edge one point inside the monitor: the bottom-left hiding sliver
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![container(
|
||||
"a",
|
||||
vec![window(1, "x", Some([-999, 790, 1000, 800]))],
|
||||
)],
|
||||
0,
|
||||
&layout,
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
|
||||
let found = check(&state);
|
||||
assert_eq!(kinds(&found), ["visible-window-hidden"]);
|
||||
assert_eq!(found[0].severity, Severity::Error);
|
||||
assert_eq!(found[0].window_ids, [1]);
|
||||
assert_eq!(found[0].monitor_id, Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_on_a_workspace_that_is_not_showing_but_on_screen_is_leaking() {
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![
|
||||
workspace("one", vec![], 0, &[]),
|
||||
workspace(
|
||||
"two",
|
||||
vec![container(
|
||||
"a",
|
||||
vec![window(1, "x", Some([100, 100, 500, 500]))],
|
||||
)],
|
||||
0,
|
||||
&[],
|
||||
),
|
||||
],
|
||||
0,
|
||||
)]);
|
||||
|
||||
let found = check(&state);
|
||||
assert_eq!(kinds(&found), ["hidden-window-visible"]);
|
||||
assert_eq!(found[0].workspace.as_deref(), Some("two"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_window_on_a_hidden_workspace_is_fine() {
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![
|
||||
workspace("one", vec![], 0, &[]),
|
||||
workspace(
|
||||
"two",
|
||||
vec![container(
|
||||
"a",
|
||||
vec![window(1, "x", Some([-499, 790, 500, 800]))],
|
||||
)],
|
||||
0,
|
||||
&[],
|
||||
),
|
||||
],
|
||||
0,
|
||||
)]);
|
||||
|
||||
assert_eq!(check(&state), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiled_window_that_is_not_where_the_layout_put_it_is_a_mismatch() {
|
||||
let layout = [[0, 0, 500, 800], [500, 0, 500, 800]];
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![
|
||||
container("a", vec![window(1, "x", Some(layout[0]))]),
|
||||
// 120 points narrower than asked
|
||||
container("b", vec![window(2, "y", Some([500, 0, 380, 800]))]),
|
||||
],
|
||||
0,
|
||||
&layout,
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
|
||||
let found = check(&state);
|
||||
assert_eq!(kinds(&found), ["layout-mismatch"]);
|
||||
assert_eq!(found[0].window_ids, [2]);
|
||||
assert!(
|
||||
found[0].message.contains("120 points off"),
|
||||
"{}",
|
||||
found[0].message
|
||||
);
|
||||
|
||||
// a few points of slack is not a mismatch
|
||||
let close = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![container(
|
||||
"b",
|
||||
vec![window(2, "y", Some([502, 0, 497, 800]))],
|
||||
)],
|
||||
0,
|
||||
&[[500, 0, 500, 800]],
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
assert_eq!(check(&close), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visible_window_on_no_display_is_off_screen() {
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![container(
|
||||
"a",
|
||||
vec![window(1, "x", Some([5000, 5000, 500, 500]))],
|
||||
)],
|
||||
0,
|
||||
&[],
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
|
||||
assert_eq!(kinds(&check(&state)), ["off-screen"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_window_in_two_containers_is_an_error() {
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![
|
||||
container("a", vec![window(1, "x", None)]),
|
||||
container("b", vec![window(1, "x", None)]),
|
||||
],
|
||||
0,
|
||||
&[],
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
|
||||
let found = check(&state);
|
||||
assert_eq!(kinds(&found), ["window-in-two-places"]);
|
||||
assert!(found[0].message.contains("2 places"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_monitors_and_broken_focus_are_reported() {
|
||||
let overlapping = snapshot(vec![
|
||||
monitor(1, [0, 0, 1000, 800], vec![], 0),
|
||||
monitor(2, [500, 0, 1000, 800], vec![], 0),
|
||||
]);
|
||||
assert_eq!(kinds(&check(&overlapping)), ["monitor-overlap"]);
|
||||
|
||||
let duplicate = snapshot(vec![
|
||||
monitor(1, [0, 0, 100, 100], vec![], 0),
|
||||
monitor(1, [100, 0, 100, 100], vec![], 0),
|
||||
]);
|
||||
assert_eq!(kinds(&check(&duplicate)), ["duplicate-monitor-id"]);
|
||||
|
||||
let broken = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![container("a", vec![window(1, "x", None)])],
|
||||
5,
|
||||
&[],
|
||||
)],
|
||||
3,
|
||||
)]);
|
||||
assert_eq!(
|
||||
kinds(&check(&broken)),
|
||||
["focus-out-of-range", "focus-out-of-range"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_sort_before_warnings() {
|
||||
let state = snapshot(vec![monitor(
|
||||
1,
|
||||
SCREEN,
|
||||
vec![workspace(
|
||||
"one",
|
||||
vec![
|
||||
container("a", vec![]),
|
||||
container("b", vec![window(1, "x", Some([-999, 790, 1000, 800]))]),
|
||||
],
|
||||
0,
|
||||
&[],
|
||||
)],
|
||||
0,
|
||||
)]);
|
||||
|
||||
let found = check(&state);
|
||||
assert_eq!(kinds(&found), ["visible-window-hidden", "empty-container"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_state_is_checked_without_inventing_problems() {
|
||||
let value: serde_json::Value =
|
||||
serde_json::from_str(include_str!("../../tests/fixtures/state.json")).expect("fixture");
|
||||
let found = check(&Snapshot::from_value(&value));
|
||||
eprintln!("{found:#?}");
|
||||
|
||||
// every window on a workspace that is not showing is parked, and the showing ones sit
|
||||
// where the layout put them
|
||||
assert!(
|
||||
found
|
||||
.iter()
|
||||
.all(|violation| violation.severity != Severity::Error),
|
||||
"{found:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! ([`envelope`]), how a point in time is named ([`timespec`], [`ids`]) and the guard that keeps
|
||||
//! file access inside the session ([`guard`]).
|
||||
|
||||
pub mod answers;
|
||||
pub mod blocks;
|
||||
pub mod catalog;
|
||||
pub mod classify;
|
||||
@@ -18,10 +19,13 @@ pub mod flavor;
|
||||
pub mod guard;
|
||||
pub mod history;
|
||||
pub mod ids;
|
||||
pub mod invariants;
|
||||
pub mod logparse;
|
||||
pub mod lookup;
|
||||
pub mod overview;
|
||||
pub mod state;
|
||||
pub mod timespec;
|
||||
pub mod trace;
|
||||
pub mod views;
|
||||
|
||||
pub use facade::Analysis;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,540 @@
|
||||
//! One event, end to end: what ran, what it logged, what it changed and who changed it.
|
||||
//!
|
||||
//! komorebi sends the state *after* each notification, so what an event changed is the difference
|
||||
//! between its state and the previous event's. That difference is not all the handler's doing:
|
||||
//! background threads (the reaper, the workspace reconciliator) change state with no notification
|
||||
//! of their own, and their changes show up in whichever event comes next. So every change is given
|
||||
//! an **attribution** with the evidence for it and how sure it is, and a change nothing explains is
|
||||
//! said to be unexplained rather than blamed on the handler.
|
||||
//!
|
||||
//! [`Analysis::trace`] builds a [`TraceData`] for one event: what its handler logged (each line
|
||||
//! tied to the statement of komorebi's source that wrote it), what other threads logged in the
|
||||
//! interval, what changed with each change attributed, and which of the state's violations
|
||||
//! (see [`super::invariants`]) the event introduced or cleared. It is what the `trace` command
|
||||
//! prints, and what the viewer's inspector shows for an event.
|
||||
//!
|
||||
//! # How a change is attributed
|
||||
//!
|
||||
//! The rules are tried in this order for each change, and the first that applies decides:
|
||||
//!
|
||||
//! | the change | the evidence | `actor` | `confidence` |
|
||||
//! |---|---|---|---|
|
||||
//! | a window went away | `komorebi::reaper` logged `reaping window: <that window's id>` in the interval | `reaper` | `high` |
|
||||
//! | a window moved, a workspace came into focus, containers were reordered, or a rect really changed | `komorebi::workspace_reconciliator` logged a line containing `reconciliat` in the interval | `workspace-reconciliator` | `low` if the handler could also have made the change (below), else `medium` |
|
||||
//! | one the event's handler is expected to make | none needed | `handler` | `high` if the handler's lines were found in the log, else `medium` |
|
||||
//! | anything else | none: no log line accounts for it | `unexplained` | `low` |
|
||||
//!
|
||||
//! A handler is expected to make any change if the event is a command, a monitor change or could
|
||||
//! not be read, and for a window-manager event it depends on the kind: a `FocusChange` is expected
|
||||
//! to change focus, a workspace's focus, move a window, change a rect or reorder containers; a
|
||||
//! `MoveStart`, `MoveEnd`, `ResizeStart` or `ResizeEnd` to change a rect, move a window, reorder
|
||||
//! containers or change focus; every other window-manager event (windows shown, hidden or
|
||||
//! closed reshuffle everything around them) to make any change.
|
||||
//!
|
||||
//! The attribution is a judgement from the log, and gives what it rests on in `evidence` and
|
||||
//! `reason`. `unexplained` is a finding in itself: komorebi changed state with no notification
|
||||
//! and nothing in the log accounts for it, or its log level does not show the cause.
|
||||
//!
|
||||
//! # Flavor
|
||||
//!
|
||||
//! The first two rules look for log lines of komorebi for Mac: its reaper logs `reaping window:
|
||||
//! <id>` and it has a workspace reconciliator. komorebi for Windows does neither (its source has no
|
||||
//! workspace reconciliator and no such reaper line), so for a Windows session a change is
|
||||
//! attributed to the `handler` or is `unexplained`. Everything else here is the same for both:
|
||||
//! the roles of the log lines ([`Rules::role`](super::flavor::Rules::role)), the explanation of a
|
||||
//! slow handler ([`Rules::slow_handler_cause`](super::flavor::Rules::slow_handler_cause)) and
|
||||
//! where a window is hidden are the rules of the flavor that recorded the session.
|
||||
|
||||
use super::Analysis;
|
||||
use super::answers::ChangeView;
|
||||
use super::catalog;
|
||||
use super::catalog::Confidence;
|
||||
use super::diff;
|
||||
use super::diff::Change;
|
||||
use super::envelope;
|
||||
use super::invariants;
|
||||
use super::invariants::Violation;
|
||||
use super::logparse::Line;
|
||||
use super::timespec::Edge;
|
||||
use super::timespec::Lookup;
|
||||
use super::views::EventView;
|
||||
use color_eyre::eyre;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The schema name that identifies a [`TraceData`] in an envelope (`trace/1`); listed by the
|
||||
/// `schema` command.
|
||||
pub const SCHEMA_TRACE: &str = "trace/1";
|
||||
|
||||
/// Where in komorebi's source a log line came from: the statement that wrote it, reduced to what a
|
||||
/// reader of a trace needs (see `Source` in [`super::catalog`] for the whole match).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct SourceRef {
|
||||
/// `file:line` of the statement in komorebi's source, as an editor opens it.
|
||||
pub location: String,
|
||||
/// The function the statement is in, with its type if it is in an `impl`:
|
||||
/// `WindowManager::process_event`.
|
||||
pub function: String,
|
||||
/// How much the text of the line pins the statement down. An `ambiguous` or `generic` match
|
||||
/// is not a place to pin a cause on.
|
||||
pub confidence: Confidence,
|
||||
/// The file differs between the recorded komorebi and the indexed source, so the statement
|
||||
/// may not be the one that ran.
|
||||
pub file_changed: bool,
|
||||
}
|
||||
|
||||
/// A line of komorebi's log, with where it came from in the source.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct TraceLine {
|
||||
/// The line of the session's `komorebi.log`, counting from 1.
|
||||
pub line: u64,
|
||||
/// When the line was logged, in seconds of video time; `None` if it has no time or it cannot
|
||||
/// be placed on the session's clock.
|
||||
pub video_s: Option<f64>,
|
||||
/// The level in capitals (`INFO`); `None` for a line that is not a log record.
|
||||
pub level: Option<String>,
|
||||
/// The span chain, e.g. `process_event:focus_window`. Empty for a line from a thread that
|
||||
/// is not in a handler.
|
||||
pub spans: String,
|
||||
/// The module the line was logged from, such as `komorebi::reaper`.
|
||||
pub target: Option<String>,
|
||||
/// The message, without ANSI escapes.
|
||||
pub message: String,
|
||||
/// The statement that wrote it, if one matched.
|
||||
pub source: Option<SourceRef>,
|
||||
/// The part of komorebi that logged it changes state without sending a notification, so its
|
||||
/// lines are candidates for a change with no event before it.
|
||||
pub changes_state_silently: bool,
|
||||
}
|
||||
|
||||
/// Who made a change, and what that is based on.
|
||||
///
|
||||
/// This is a judgement from the log, not a fact: see the [module](self) documentation for the
|
||||
/// rules.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
pub struct Attribution {
|
||||
/// `handler`, `reaper`, `workspace-reconciliator` or `unexplained`.
|
||||
pub actor: String,
|
||||
/// `high`, `medium` or `low`.
|
||||
pub confidence: String,
|
||||
/// The line numbers of `komorebi.log` that support it: the log lines of the reaper or the
|
||||
/// reconciliator, or the handler's header. Empty for `unexplained`, and for a handler whose
|
||||
/// lines were not found.
|
||||
pub evidence: Vec<u64>,
|
||||
/// The attribution in a sentence.
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// A change an event made, with who made it.
|
||||
///
|
||||
/// In JSON it is the fields of the change (a `ChangeView`: `text` and the change's fields,
|
||||
/// including its `kind`) with an `attribution` beside them.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct TracedChange {
|
||||
/// The change, with a line of text that describes it.
|
||||
#[serde(flatten)]
|
||||
pub change: ChangeView,
|
||||
/// Who made it.
|
||||
pub attribution: Attribution,
|
||||
}
|
||||
|
||||
/// One event end to end: the `data` of the `trace` command.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct TraceData {
|
||||
/// The event, with its class and the handler that was paired with it.
|
||||
pub event: EventView,
|
||||
/// The lines the handler logged, in order; empty if the log has no block for this event.
|
||||
pub handler: Vec<TraceLine>,
|
||||
/// Lines from other threads logged between the previous notification and this one: what else
|
||||
/// was going on. For the first event that is everything logged before it. Lines that belong to
|
||||
/// any handler, and continuation lines such as panic backtraces, are not included.
|
||||
pub ambient: Vec<TraceLine>,
|
||||
/// The changes the event made, each with its attribution: the difference between the state when
|
||||
/// its handler began (the state the previous event left) and the state it carried. Empty, with
|
||||
/// a note, if the state before or after is unknown.
|
||||
pub changes: Vec<TracedChange>,
|
||||
/// Violations (see [`super::invariants`]) that are in the state after the event and were not in
|
||||
/// the state before it. A violation is the same one only if its message is the same.
|
||||
pub violations_appeared: Vec<Violation>,
|
||||
/// Violations that were in the state before the event and are not in the state after it.
|
||||
pub violations_resolved: Vec<Violation>,
|
||||
/// Things worth knowing that are not data: a slow handler, errors, a missing log.
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
fn spans_of(line: &Line) -> String {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(":")
|
||||
}
|
||||
|
||||
/// Whether a change is the kind of thing this event's handler is expected to do.
|
||||
fn expected_of_handler(event: &EventView, change: &Change) -> bool {
|
||||
use crate::analysis::events::Family;
|
||||
match event.info.family {
|
||||
// commands, monitor changes and anything unreadable can do anything
|
||||
Family::Command | Family::Monitor | Family::Unknown => true,
|
||||
Family::WindowManager => match event.info.name.as_str() {
|
||||
"FocusChange" => matches!(
|
||||
change,
|
||||
Change::Focus { .. }
|
||||
| Change::WorkspaceFocus { .. }
|
||||
| Change::WindowMoved { .. }
|
||||
| Change::WindowRect { .. }
|
||||
| Change::ContainerOrder { .. }
|
||||
),
|
||||
"MoveStart" | "MoveEnd" | "ResizeStart" | "ResizeEnd" => matches!(
|
||||
change,
|
||||
Change::WindowRect { .. }
|
||||
| Change::WindowMoved { .. }
|
||||
| Change::ContainerOrder { .. }
|
||||
| Change::Focus { .. }
|
||||
),
|
||||
// showing, hiding and closing windows reshuffles everything around them
|
||||
_ => true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
fn trace_line(&self, line: &Line, skew: &catalog::Skew) -> TraceLine {
|
||||
let source = match (&line.target, line.level) {
|
||||
(Some(target), Some(level)) => self.catalog().find(target, level, &line.message),
|
||||
_ => None,
|
||||
};
|
||||
let role = line
|
||||
.target
|
||||
.as_deref()
|
||||
.map(|target| self.flavor().rules().role(target));
|
||||
TraceLine {
|
||||
line: line.number,
|
||||
video_s: line
|
||||
.wall_us
|
||||
.and_then(|wall_us| self.clock().wall_to_mach(wall_us))
|
||||
.map(|mach_ns| self.video_s(mach_ns)),
|
||||
level: line.level.map(|level| format!("{level:?}").to_uppercase()),
|
||||
spans: spans_of(line),
|
||||
target: line.target.clone(),
|
||||
message: line.message.clone(),
|
||||
source: source.map(|source| SourceRef {
|
||||
location: source.statement.location(),
|
||||
function: source.statement.qualified_function(),
|
||||
confidence: source.confidence,
|
||||
file_changed: skew.file_changed(&source.statement.file),
|
||||
}),
|
||||
changes_state_silently: role.is_some_and(|role| role.changes_state_silently),
|
||||
}
|
||||
}
|
||||
|
||||
/// Traces event `seq`: what its handler logged, what else was logged, what it changed and who
|
||||
/// made each change.
|
||||
///
|
||||
/// The changes are the difference between the state at the moment the handler began and the
|
||||
/// state the event carried, so anything background threads did since the previous
|
||||
/// notification is in them too, attributed by [the rules](self#how-a-change-is-attributed).
|
||||
/// The handler's lines are those komorebi's log has for the event, if any. The notes say
|
||||
/// what is missing or worth knowing: no handler lines in the log, a handler that took 100 ms or
|
||||
/// more from its header to the notification (with the flavor's likely cause), errors and
|
||||
/// warnings the handler logged, and, for an event the analysis classified as an echo of
|
||||
/// komorebi's own move, why.
|
||||
///
|
||||
/// `TraceData::os_trace` is `None` in the result: ask `Analysis::os_trace` for it and set
|
||||
/// it, as `trace --os` does.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if:
|
||||
///
|
||||
/// - there is no event numbered `seq` (the not-found exit kind);
|
||||
/// - the event carried a state, it is not the first event, and no state was recorded before it
|
||||
/// (not found);
|
||||
/// - a state file is missing (not found) or is not valid JSON.
|
||||
///
|
||||
/// An event that carried no state, and the first event of a session that has no starting
|
||||
/// state, are not errors: they have no `changes` and a note saying why.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
/// use komorebi_recorder::testkit::state_with_windows;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let notification = |name: &str, what: &str| {
|
||||
/// json!({"type": name, "content": [{"type": "Accessibility", "content": what}, 7, 1]})
|
||||
/// };
|
||||
///
|
||||
/// // Two windows; then Brave is closed (the reaper notices, and sends no notification of its
|
||||
/// // own) and the next focus change reports the result.
|
||||
/// let (session, _) = SessionBuilder::new("doc-trace")
|
||||
/// .event(
|
||||
/// 1.0,
|
||||
/// notification("Show", "AXWindowCreated"),
|
||||
/// Some(state_with_windows(&[(1, "Ghostty"), (2, "Brave")])),
|
||||
/// )
|
||||
/// .event(
|
||||
/// 4.0,
|
||||
/// notification("FocusChange", "AXApplicationActivated"),
|
||||
/// Some(state_with_windows(&[(1, "Ghostty")])),
|
||||
/// )
|
||||
/// .log(3.5, "INFO", "komorebi::reaper: reaping window: 2")
|
||||
/// .log(
|
||||
/// 3.9,
|
||||
/// "INFO",
|
||||
/// "process_event: komorebi::process_event: processing event: FocusChange for process 7 with notification AXApplicationActivated",
|
||||
/// )
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// let trace = analysis.trace(2)?;
|
||||
/// assert_eq!(trace.handler.len(), 1);
|
||||
/// // the reaper's line is from another thread, so it is ambient
|
||||
/// assert_eq!(trace.ambient[0].message, "reaping window: 2");
|
||||
///
|
||||
/// // window 2 vanished with no notification of its own, and the reaper's line says why
|
||||
/// let removed = trace
|
||||
/// .changes
|
||||
/// .iter()
|
||||
/// .find(|traced| traced.change.change.kind() == "window-removed")
|
||||
/// .expect("a window was removed");
|
||||
/// assert_eq!(removed.attribution.actor, "reaper");
|
||||
/// assert_eq!(removed.attribution.confidence, "high");
|
||||
/// assert_eq!(removed.attribution.evidence, [1]);
|
||||
///
|
||||
/// // an event that does not exist is an error
|
||||
/// assert!(analysis.trace(99).is_err());
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
///
|
||||
/// Also covered by
|
||||
/// `tests/trace.rs::a_change_with_no_event_of_its_own_is_blamed_on_the_reaper_by_its_log_line`
|
||||
/// and `tests/trace.rs::an_event_with_no_log_says_so_instead_of_inventing_a_handler`, and, for
|
||||
/// a Windows session, by
|
||||
/// `tests/windows_flavor.rs::the_state_is_read_by_window_handle_and_a_trace_says_what_moved`.
|
||||
pub fn trace(&self, seq: u64) -> eyre::Result<TraceData> {
|
||||
let index = self
|
||||
.event_index(seq)
|
||||
.ok_or_else(|| envelope::not_found(format!("there is no event #{seq}")))?;
|
||||
let view = self
|
||||
.event_view(index)
|
||||
.ok_or_else(|| envelope::not_found(format!("there is no event #{seq}")))?;
|
||||
let event = &self.events()[index];
|
||||
let log = self.log();
|
||||
let pair = &self.pairing().pairs[index];
|
||||
let block = pair.block.and_then(|id| log.blocks.get(id));
|
||||
|
||||
let skew = self.skew();
|
||||
let handler: Vec<TraceLine> = block
|
||||
.map(|block| {
|
||||
block
|
||||
.lines
|
||||
.iter()
|
||||
.filter_map(|number| log.lines.get(usize::try_from(number - 1).ok()?))
|
||||
.map(|line| self.trace_line(line, &skew))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// lines from other threads between the previous notification and this one
|
||||
let previous_recv = index
|
||||
.checked_sub(1)
|
||||
.map_or(0, |before| self.events()[before].recv_mach_ns);
|
||||
let handler_lines: std::collections::HashSet<u64> = log
|
||||
.blocks
|
||||
.iter()
|
||||
.flat_map(|block| block.lines.iter().copied())
|
||||
.collect();
|
||||
let ambient_lines: Vec<&Line> = log
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|line| !line.continuation && !handler_lines.contains(&line.number))
|
||||
.filter(|line| {
|
||||
line.wall_us
|
||||
.and_then(|wall_us| self.clock().wall_to_mach(wall_us))
|
||||
.is_some_and(|mach_ns| mach_ns > previous_recv && mach_ns <= event.recv_mach_ns)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// what changed, and who did it
|
||||
let start = self.event_mach_ns(seq, Edge::Start)?;
|
||||
let (changes, appeared, resolved, mut notes) =
|
||||
if index == 0 && self.state_at(start).is_err() {
|
||||
(
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
"no state was recorded before this event, so what it changed is unknown"
|
||||
.to_string(),
|
||||
],
|
||||
)
|
||||
} else if event.state_id.is_none() {
|
||||
(
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
vec!["this notification carried no state".to_string()],
|
||||
)
|
||||
} else {
|
||||
let before = self.state_at(start)?;
|
||||
let after = self.state_at(event.recv_mach_ns)?;
|
||||
let raw = diff::diff(&before.snapshot, &after.snapshot);
|
||||
let (was, now) = (
|
||||
invariants::check(&before.snapshot),
|
||||
invariants::check(&after.snapshot),
|
||||
);
|
||||
let traced = raw
|
||||
.into_iter()
|
||||
.map(|change| {
|
||||
let attribution = self.attribute(&view, &change, &ambient_lines);
|
||||
TracedChange {
|
||||
change: ChangeView {
|
||||
text: change.describe(),
|
||||
change,
|
||||
},
|
||||
attribution,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(
|
||||
traced,
|
||||
now.iter().filter(|v| !was.contains(v)).cloned().collect(),
|
||||
was.iter().filter(|v| !now.contains(v)).cloned().collect(),
|
||||
Vec::new(),
|
||||
)
|
||||
};
|
||||
|
||||
if let Some(block) = block {
|
||||
if let Some(ms) = pair.handler_ms
|
||||
&& ms >= 100.0
|
||||
{
|
||||
notes.push(format!(
|
||||
"the handler took at least {ms:.0} ms from its header to the notification: {}",
|
||||
self.flavor().rules().slow_handler_cause()
|
||||
));
|
||||
}
|
||||
if block.errors + block.warnings > 0 {
|
||||
notes.push(format!(
|
||||
"the handler logged {} error(s) and {} warning(s)",
|
||||
block.errors, block.warnings
|
||||
));
|
||||
}
|
||||
} else {
|
||||
notes.push(
|
||||
"no handler lines for this event were found in komorebi's log: it may not have \
|
||||
been recorded, or komorebi may log this kind of event only at a more verbose level"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if view.class == super::classify::Class::Echo {
|
||||
notes.push(view.reason.clone());
|
||||
}
|
||||
|
||||
Ok(TraceData {
|
||||
event: view,
|
||||
handler,
|
||||
ambient: ambient_lines
|
||||
.iter()
|
||||
.map(|line| self.trace_line(line, &skew))
|
||||
.collect(),
|
||||
changes,
|
||||
violations_appeared: appeared,
|
||||
violations_resolved: resolved,
|
||||
notes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Say who made `change`, from what the log shows happened around it.
|
||||
fn attribute(&self, event: &EventView, change: &Change, ambient: &[&Line]) -> Attribution {
|
||||
let lines_of = |target: &str, needle: &str| -> Vec<u64> {
|
||||
ambient
|
||||
.iter()
|
||||
.filter(|line| {
|
||||
line.target.as_deref() == Some(target) && line.message.contains(needle)
|
||||
})
|
||||
.map(|line| line.number)
|
||||
.collect()
|
||||
};
|
||||
|
||||
// a window removed that the reaper logged reaping, by id
|
||||
if let Change::WindowRemoved { window, .. } = change {
|
||||
let evidence = lines_of(
|
||||
"komorebi::reaper",
|
||||
&format!("reaping window: {}", window.id),
|
||||
);
|
||||
if !evidence.is_empty() {
|
||||
return Attribution {
|
||||
actor: "reaper".to_string(),
|
||||
confidence: "high".to_string(),
|
||||
evidence,
|
||||
reason: format!(
|
||||
"the reaper logged reaping window {}: it removes windows that no longer \
|
||||
exist, without sending a notification",
|
||||
window.id
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let reconciling = lines_of("komorebi::workspace_reconciliator", "reconciliat");
|
||||
let moves = matches!(
|
||||
change,
|
||||
Change::WindowMoved { .. }
|
||||
| Change::WorkspaceFocus { .. }
|
||||
| Change::ContainerOrder { .. }
|
||||
| Change::WindowRect { .. }
|
||||
);
|
||||
let by_handler = expected_of_handler(event, change);
|
||||
|
||||
if moves && !reconciling.is_empty() {
|
||||
return Attribution {
|
||||
actor: "workspace-reconciliator".to_string(),
|
||||
confidence: if by_handler { "low" } else { "medium" }.to_string(),
|
||||
evidence: reconciling,
|
||||
reason: if by_handler {
|
||||
"the workspace reconciliator ran in this interval and could have done this, \
|
||||
but so could the handler"
|
||||
.to_string()
|
||||
} else {
|
||||
"the workspace reconciliator ran in this interval, and this is not what this \
|
||||
event's handler does"
|
||||
.to_string()
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if by_handler {
|
||||
let quality = event.handler.as_ref().map(|handler| handler.quality);
|
||||
return Attribution {
|
||||
actor: "handler".to_string(),
|
||||
confidence: if quality.is_some() { "high" } else { "medium" }.to_string(),
|
||||
evidence: event
|
||||
.handler
|
||||
.as_ref()
|
||||
.map(|handler| vec![handler.header_line])
|
||||
.unwrap_or_default(),
|
||||
reason: format!(
|
||||
"{} is the kind of change {} makes",
|
||||
change.kind(),
|
||||
event.info.name
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
Attribution {
|
||||
actor: "unexplained".to_string(),
|
||||
confidence: "low".to_string(),
|
||||
evidence: Vec::new(),
|
||||
reason: format!(
|
||||
"{} is not something {} does, and no background activity in the log accounts for \
|
||||
it: komorebi changed state with no notification, or the log is at a level that \
|
||||
does not show it",
|
||||
change.kind(),
|
||||
event.info.name
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,19 @@
|
||||
//!
|
||||
//! Times are written as timecodes (`00:12.500`, see [`crate::timecode::format`]) in video time.
|
||||
|
||||
use crate::analysis::answers::DiffData;
|
||||
use crate::analysis::answers::EventsData;
|
||||
use crate::analysis::answers::StateData;
|
||||
use crate::analysis::code::CodeData;
|
||||
use crate::analysis::history::HistoryData;
|
||||
use crate::analysis::invariants::Severity;
|
||||
use crate::analysis::invariants::Violation;
|
||||
use crate::analysis::overview::Finding;
|
||||
use crate::analysis::overview::OverviewData;
|
||||
use crate::analysis::state::Container;
|
||||
use crate::analysis::state::Window;
|
||||
use crate::analysis::trace::TraceData;
|
||||
use crate::analysis::trace::TraceLine;
|
||||
use crate::annotations::AnnotationView;
|
||||
use crate::annotations::Kind;
|
||||
use crate::timecode;
|
||||
@@ -460,6 +471,337 @@ fn rect_text(rect: &Option<crate::analysis::state::Rect>) -> String {
|
||||
.map_or_else(|| "rect unknown".to_string(), |rect| rect.describe())
|
||||
}
|
||||
|
||||
fn window_line(window: &Window, marker: &str) -> String {
|
||||
format!(
|
||||
"{marker} window {} {} \"{}\" {}",
|
||||
window.id,
|
||||
window.exe,
|
||||
window.title,
|
||||
rect_text(&window.rect)
|
||||
)
|
||||
}
|
||||
|
||||
fn container_lines(out: &mut String, index: usize, container: &Container, focused: bool) {
|
||||
for (tab, window) in container.windows.iter().enumerate() {
|
||||
let marker = if tab == 0 {
|
||||
format!("{index:>3}{}", if focused { "*" } else { " " })
|
||||
} else {
|
||||
" ".to_string()
|
||||
};
|
||||
let front = if container.windows.len() > 1 && tab == container.focused {
|
||||
" (front tab)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let _ = writeln!(out, " {}{front}", window_line(window, &marker));
|
||||
}
|
||||
}
|
||||
|
||||
fn violation_lines(out: &mut String, violations: &[Violation]) {
|
||||
for violation in violations {
|
||||
let severity = match violation.severity {
|
||||
Severity::Error => "error",
|
||||
Severity::Warn => "warn ",
|
||||
Severity::Info => "info ",
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {severity} {}: {}",
|
||||
violation.kind, violation.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the answer to `state`: the moment and which notification the state is from, the focus,
|
||||
/// each monitor with its workspaces and the windows in them, the windows asked about, and what looks
|
||||
/// wrong.
|
||||
///
|
||||
/// The heading says how old the state is. If it is more than five seconds old a note says that
|
||||
/// komorebi can change state without a notification, so it may be out of date. A workspace that is
|
||||
/// showing is marked, and workspaces that are not showing and were left out of the answer are listed
|
||||
/// with their window counts. A window that matched what was asked about says where it is, where it
|
||||
/// really is and, for a tiled window, where the layout says it should be.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::analysis::answers::StateQuery;
|
||||
/// use komorebi_recorder::report::state_text;
|
||||
/// use komorebi_recorder::testkit::{SessionBuilder, mach_ns, state_with_windows};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-state-text")
|
||||
/// .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
/// let data = analysis.state_answer(mach_ns(2.5), &StateQuery::default())?;
|
||||
///
|
||||
/// let text = state_text(&data);
|
||||
/// assert!(text.starts_with("state at 00:02.500 (as of event #1, 500 ms before)\n"));
|
||||
/// assert!(text.contains("workspace one [showing]"));
|
||||
/// assert!(text.contains("window 7 Terminal"));
|
||||
/// assert!(text.contains("nothing looks wrong in this state"));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn state_text(data: &StateData) -> String {
|
||||
let mut out = String::new();
|
||||
let age = data.origin.age_ms.map_or_else(String::new, |age| {
|
||||
if age < 1000.0 {
|
||||
format!(", {age:.0} ms before")
|
||||
} else {
|
||||
format!(", {:.1} s before", age / 1000.0)
|
||||
}
|
||||
});
|
||||
let source = match (data.origin.source.as_str(), data.origin.seq) {
|
||||
("event", Some(seq)) => format!("as of event #{seq}{age}"),
|
||||
_ => format!("the state when recording began{age}"),
|
||||
};
|
||||
let _ = writeln!(out, "state at {} ({source})", data.at.timecode);
|
||||
if data.origin.age_ms.is_some_and(|age| age > 5000.0) {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"note: nothing was reported for a while, and komorebi can change state without a \
|
||||
notification, so this may be out of date"
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(focus) = &data.focus {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"focus: window {} on monitor {} workspace {}",
|
||||
focus
|
||||
.window_id
|
||||
.map_or_else(|| "(none)".to_string(), |id| id.to_string()),
|
||||
focus.monitor_id,
|
||||
focus.workspace
|
||||
);
|
||||
}
|
||||
if data.paused {
|
||||
let _ = writeln!(out, "komorebi is PAUSED");
|
||||
}
|
||||
|
||||
for monitor in &data.monitors {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nmonitor {} \"{}\" {}",
|
||||
monitor.id,
|
||||
monitor.device,
|
||||
monitor.size.describe()
|
||||
);
|
||||
|
||||
for (index, workspace) in monitor.workspaces.iter().enumerate() {
|
||||
let showing = data.workspaces.iter().any(|summary| {
|
||||
summary.monitor_id == monitor.id
|
||||
&& summary.name == workspace.name
|
||||
&& summary.showing
|
||||
});
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" workspace {}{} {}{}",
|
||||
workspace.name,
|
||||
if showing { " [showing]" } else { "" },
|
||||
workspace.layout,
|
||||
if workspace.layer == "Floating" {
|
||||
" [floating layer]"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
);
|
||||
let _ = index;
|
||||
|
||||
for (container_index, container) in workspace.containers.iter().enumerate() {
|
||||
container_lines(
|
||||
&mut out,
|
||||
container_index,
|
||||
container,
|
||||
showing && container_index == workspace.focused,
|
||||
);
|
||||
}
|
||||
if let Some(monocle) = &workspace.monocle {
|
||||
let _ = writeln!(out, " monocle:");
|
||||
container_lines(&mut out, 0, monocle, true);
|
||||
}
|
||||
if let Some(window) = &workspace.maximized {
|
||||
let _ = writeln!(out, "{}", window_line(window, " maximized"));
|
||||
}
|
||||
for window in &workspace.floating {
|
||||
let _ = writeln!(out, "{}", window_line(window, " floating"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let hidden: Vec<String> = data
|
||||
.workspaces
|
||||
.iter()
|
||||
.filter(|summary| {
|
||||
!summary.showing
|
||||
&& !data.monitors.iter().any(|monitor| {
|
||||
monitor.id == summary.monitor_id
|
||||
&& monitor
|
||||
.workspaces
|
||||
.iter()
|
||||
.any(|workspace| workspace.name == summary.name)
|
||||
})
|
||||
})
|
||||
.map(|summary| format!("{} ({})", summary.name, summary.windows))
|
||||
.collect();
|
||||
if !hidden.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nnot showing (windows): {} (--all to list them)",
|
||||
hidden.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
for found in &data.matches {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nwindow {} {} \"{}\"\n where: {}\n really at: {}{}",
|
||||
found.window.id,
|
||||
found.window.exe,
|
||||
found.window.title,
|
||||
found.location.describe(),
|
||||
rect_text(&found.window.rect),
|
||||
if found.hidden_position {
|
||||
" (parked off screen)"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
);
|
||||
if let Some(layout) = &found.layout_rect {
|
||||
let _ = writeln!(out, " layout says: {}", layout.describe());
|
||||
}
|
||||
}
|
||||
|
||||
if data.violations.is_empty() {
|
||||
let _ = writeln!(out, "\nnothing looks wrong in this state");
|
||||
} else {
|
||||
let _ = writeln!(out, "\nwrong in this state:");
|
||||
violation_lines(&mut out, &data.violations);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders the answer to `diff`: the two moments, a line for each change, and the violations that
|
||||
/// appeared or were resolved between them.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::report::diff_text;
|
||||
/// use komorebi_recorder::testkit::{SessionBuilder, mach_ns, state_with_windows};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-diff-text")
|
||||
/// .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
/// .event(4.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal"), (8, "Browser")])))
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// let text = diff_text(&analysis.diff_answer(mach_ns(3.0), mach_ns(5.0))?);
|
||||
/// assert!(text.starts_with("from 00:03.000 to 00:05.000\n"));
|
||||
/// assert!(text.contains("Browser \"window 8\" (window 8) appeared on monitor 1 workspace one"));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn diff_text(data: &DiffData) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(out, "from {} to {}", data.from.timecode, data.to.timecode);
|
||||
if data.changes.is_empty() {
|
||||
let _ = writeln!(out, "no difference between the two states");
|
||||
}
|
||||
for change in &data.changes {
|
||||
let _ = writeln!(out, " {}", change.text);
|
||||
}
|
||||
if !data.violations_appeared.is_empty() {
|
||||
let _ = writeln!(out, "\nwrong now, and not before:");
|
||||
violation_lines(&mut out, &data.violations_appeared);
|
||||
}
|
||||
if !data.violations_resolved.is_empty() {
|
||||
let _ = writeln!(out, "\nwrong before, and not now:");
|
||||
violation_lines(&mut out, &data.violations_resolved);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders the answer to `events`: how many of the session's events matched and a line for each one
|
||||
/// returned.
|
||||
///
|
||||
/// A line has the sequence number, the time, the class, what the event was, where the log has its
|
||||
/// handler at least how long the handler ran and how many errors (`E`) and warnings (`W`) it logged,
|
||||
/// and whether the state changed. With `verbose` a line follows each event saying why it was classified
|
||||
/// as it was.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::analysis::answers::EventQuery;
|
||||
/// use komorebi_recorder::report::events_text;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-events-text")
|
||||
/// .event(2.0, json!({"type": "Retile"}), None)
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// let text = events_text(&analysis.events_answer(&EventQuery::default()).data, false);
|
||||
/// assert!(text.starts_with("1 of 1 events\n#1 00:02.000 command"));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn events_text(data: &EventsData, verbose: bool) -> String {
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{} of {} events{}",
|
||||
data.matching,
|
||||
data.total,
|
||||
data.subscriber
|
||||
.as_ref()
|
||||
.map_or_else(String::new, |name| format!(
|
||||
" (recorded as subscriber {name})"
|
||||
))
|
||||
);
|
||||
|
||||
for event in &data.events {
|
||||
let handler = event.handler.as_ref().map_or_else(String::new, |handler| {
|
||||
let ms = handler
|
||||
.handler_ms
|
||||
.map_or_else(String::new, |ms| format!(" {ms:.0} ms"));
|
||||
let problems = if handler.errors + handler.warnings > 0 {
|
||||
format!(" {}E/{}W", handler.errors, handler.warnings)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
format!(" handler{ms}{problems}")
|
||||
});
|
||||
let state = match event.state_changed {
|
||||
Some(true) => " state changed",
|
||||
Some(false) => " state unchanged",
|
||||
None => "",
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"#{:<5} {} {:<9} {}{handler}{state}",
|
||||
event.seq,
|
||||
timecode::format(event.video_s),
|
||||
format!("{:?}", event.class).to_lowercase(),
|
||||
event.summary,
|
||||
);
|
||||
if verbose {
|
||||
let _ = writeln!(out, " {}", event.reason);
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders the answer to `code`: for each log line asked about, the statement in komorebi's source
|
||||
/// that wrote it, and for a search, the statements that matched.
|
||||
///
|
||||
@@ -580,6 +922,153 @@ pub fn code_text(data: &CodeData) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn trace_line_text(out: &mut String, line: &TraceLine) {
|
||||
let time = line.video_s.map_or_else(String::new, |seconds| {
|
||||
format!(" {}", timecode::format(seconds))
|
||||
});
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" log:{:<6}{time} {:<5} {}{}",
|
||||
line.line,
|
||||
line.level.as_deref().unwrap_or(""),
|
||||
if line.spans.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("[{}] ", line.spans)
|
||||
},
|
||||
line.message
|
||||
);
|
||||
if let Some(source) = &line.source {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" from {} in {}{}{}",
|
||||
source.location,
|
||||
source.function,
|
||||
if source.file_changed {
|
||||
" [file differs from the recorded komorebi]"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
if line.changes_state_silently {
|
||||
" [changes state without a notification]"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the answer to `trace`: the event, what its handler logged, and each change to the state
|
||||
/// with who is held to have made it.
|
||||
///
|
||||
/// The text also has what other threads logged meanwhile, the evidence for each attribution, and
|
||||
/// what looks wrong after the event that did not before. When the data has them, it adds what
|
||||
/// Windows said about the event's window (a recording made with `--probe-windows`), the OS trace
|
||||
/// around the event (`trace --os`) grouped by where it came from, and notes such as a slow handler.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::report::trace_text;
|
||||
/// use komorebi_recorder::testkit::{SessionBuilder, state_with_windows};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-trace-text")
|
||||
/// .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// let text = trace_text(&analysis.trace(1)?);
|
||||
/// assert!(text.starts_with("event #1 received 00:02.000 Retile\n command ("));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn trace_text(data: &TraceData) -> String {
|
||||
let mut out = String::new();
|
||||
let event = &data.event;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"event #{} received {} {}\n {} ({})",
|
||||
event.seq,
|
||||
timecode::format(event.video_s),
|
||||
event.summary,
|
||||
format!("{:?}", event.class).to_lowercase(),
|
||||
event.reason
|
||||
);
|
||||
if let Some(handler) = &event.handler {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" handler logged {} line(s) from {}, began {}{}",
|
||||
handler.lines,
|
||||
timecode::format(handler.started_video_s),
|
||||
handler.handler_ms.map_or_else(String::new, |ms| format!(
|
||||
"{ms:.0} ms before it was received"
|
||||
)),
|
||||
if handler.errors + handler.warnings > 0 {
|
||||
format!(
|
||||
", {} error(s), {} warning(s)",
|
||||
handler.errors, handler.warnings
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if !data.handler.is_empty() {
|
||||
let _ = writeln!(out, "\nwhat the handler logged:");
|
||||
for line in &data.handler {
|
||||
trace_line_text(&mut out, line);
|
||||
}
|
||||
}
|
||||
if !data.ambient.is_empty() {
|
||||
let _ = writeln!(out, "\nlogged by other threads meanwhile:");
|
||||
for line in &data.ambient {
|
||||
trace_line_text(&mut out, line);
|
||||
}
|
||||
}
|
||||
|
||||
if data.changes.is_empty() {
|
||||
let _ = writeln!(out, "\nthe state did not change");
|
||||
} else {
|
||||
let _ = writeln!(out, "\nwhat changed, and who did it:");
|
||||
for traced in &data.changes {
|
||||
let attribution = &traced.attribution;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {}\n -> {} ({}): {}",
|
||||
traced.change.text, attribution.actor, attribution.confidence, attribution.reason
|
||||
);
|
||||
if !attribution.evidence.is_empty() {
|
||||
let lines: Vec<String> = attribution
|
||||
.evidence
|
||||
.iter()
|
||||
.map(|line| format!("log:{line}"))
|
||||
.collect();
|
||||
let _ = writeln!(out, " evidence: {}", lines.join(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !data.violations_appeared.is_empty() {
|
||||
let _ = writeln!(out, "\nwrong after this event, and not before:");
|
||||
violation_lines(&mut out, &data.violations_appeared);
|
||||
}
|
||||
if !data.violations_resolved.is_empty() {
|
||||
let _ = writeln!(out, "\nwrong before this event, and not after:");
|
||||
violation_lines(&mut out, &data.violations_resolved);
|
||||
}
|
||||
if !data.notes.is_empty() {
|
||||
let _ = writeln!(out, "\nnotes:");
|
||||
for note in &data.notes {
|
||||
let _ = writeln!(out, " - {note}");
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Renders the answer to `window`: the windows the query matched, then an entry for each event that
|
||||
/// came with a change to one of them.
|
||||
///
|
||||
@@ -652,6 +1141,106 @@ pub fn history_text(data: &HistoryData) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn finding_line(finding: &Finding) -> String {
|
||||
let severity = match finding.severity {
|
||||
Severity::Error => "error",
|
||||
Severity::Warn => "warn ",
|
||||
Severity::Info => "info ",
|
||||
};
|
||||
let bugs = if finding.bugs.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
" [in or just before a bug region]".to_string()
|
||||
};
|
||||
format!(
|
||||
"{severity} {} {} {}{bugs}",
|
||||
timecode::format(finding.start_video_s),
|
||||
finding.kind,
|
||||
finding.summary
|
||||
)
|
||||
}
|
||||
|
||||
/// Renders the answer to `overview`: the session's size, the bug regions the user marked, the
|
||||
/// findings most worth looking at first, and a histogram of when things happened.
|
||||
///
|
||||
/// Each finding has the command to dig into it. The histogram has a row for each bucket of time with something in it: a bar scaled to the
|
||||
/// busiest bucket's number of events, then the counts of events, log errors and incidents.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::report::overview_text;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-overview-text")
|
||||
/// .event(2.0, json!({"type": "Retile"}), None)
|
||||
/// .build();
|
||||
/// let text = overview_text(&Analysis::open(&session.dir)?.overview(None)?);
|
||||
/// assert!(text.contains(": 10 s of video, 1 events, 0 log lines, 0 incidents"));
|
||||
/// assert!(text.contains("when things happened (events | errors | incidents):"));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn overview_text(data: &OverviewData) -> String {
|
||||
let mut out = String::new();
|
||||
let session = &data.session;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"session {}: {} s of video, {} events, {} log lines, {} incidents",
|
||||
session.dir,
|
||||
session.duration_s as i64,
|
||||
session.events,
|
||||
session.log_lines,
|
||||
session.incidents
|
||||
);
|
||||
|
||||
for bug in &data.bugs {
|
||||
let _ = writeln!(out, "\nbug region:");
|
||||
out.push_str(&annotation_text(bug));
|
||||
}
|
||||
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nfindings, most worth looking at first ({} of {}):",
|
||||
data.findings.len(),
|
||||
data.findings_total
|
||||
);
|
||||
for finding in &data.findings {
|
||||
let _ = writeln!(out, " {}", finding_line(finding));
|
||||
if let Some(next) = &finding.next {
|
||||
let _ = writeln!(out, " {next}");
|
||||
}
|
||||
}
|
||||
|
||||
let peak = data
|
||||
.histogram
|
||||
.iter()
|
||||
.map(|bucket| bucket.events)
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.max(1);
|
||||
let _ = writeln!(out, "\nwhen things happened (events | errors | incidents):");
|
||||
for bucket in &data.histogram {
|
||||
if bucket.events + bucket.log_errors + bucket.incidents == 0 {
|
||||
continue;
|
||||
}
|
||||
let bar = "#".repeat((bucket.events * 30).div_ceil(peak));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {} {:<30} {:>4} {:>3} {:>2}",
|
||||
timecode::format(bucket.start_s),
|
||||
bar,
|
||||
bucket.events,
|
||||
bucket.log_errors,
|
||||
bucket.incidents
|
||||
);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in new issue
Block a user