mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-19 15:18:40 +01:00
feat(analysis): trace a log line to its source
Every `tracing` statement in komorebi's source is indexed at build time, for each flavor, so a line of its log can be traced to the statement that wrote it with the code around it. A recording from a different komorebi than the one indexed is said to be skewed, decided by the files that differ between the two commits rather than by commit equality. The `Analysis` facade that every question is asked of arrives with it, and one window's history through a recording.
This commit is contained in:
1 parent
72419d89a2
commit
3a325470eb
15 files changed
+3775
-2
No files matched your search
Generated
+2
@@ -1919,9 +1919,11 @@ dependencies = [
|
||||
"objc2-screen-capture-kit",
|
||||
"parking_lot",
|
||||
"png",
|
||||
"proc-macro2",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json_lenient",
|
||||
"syn",
|
||||
"sysinfo",
|
||||
"uds_windows",
|
||||
"windows 0.62.2",
|
||||
|
||||
@@ -139,3 +139,7 @@ windows = { version = "0.62", features = [
|
||||
"Win32_UI_Shell_Common",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
[build-dependencies]
|
||||
proc-macro2 = { version = "1", features = ["span-locations"] }
|
||||
syn = { version = "2", features = ["full", "visit"] }
|
||||
@@ -0,0 +1,493 @@
|
||||
//! Index every log statement in komorebi's source, for each flavor of komorebi.
|
||||
//!
|
||||
//! komorebi's log says what happened but not where in its code, and a recording is only useful for
|
||||
//! finding a fix if a line of the log can be traced to the statement that wrote it. This scans the
|
||||
//! `tracing` macros (`info!`, `warn!`, ...) and `#[instrument]` functions of komorebi's crates and
|
||||
//! writes a catalog (`log_catalog.rs` in `OUT_DIR`) of each statement's level, module, message
|
||||
//! template, file, line and enclosing function, together with the commit the source is at, so that
|
||||
//! `komorebi-recorder code` can answer "which line wrote this?" and say when the answer may be
|
||||
//! about a different version of komorebi than the one that was recorded.
|
||||
//!
|
||||
//! There is one catalog per flavor, because komorebi for Mac and komorebi for Windows are different
|
||||
//! programs with different logs. Each is built from a checkout named by an environment variable:
|
||||
//!
|
||||
//! | flavor | variable | when it is not set |
|
||||
//! |---|---|---|
|
||||
//! | macOS | `KOMOREBI_MAC_SRC` | an empty catalog, which says so |
|
||||
//! | Windows | `KOMOREBI_WINDOWS_SRC` | an empty catalog, which says so |
|
||||
//!
|
||||
//! The commit of each comes from git, or else from `KOMOREBI_MAC_COMMIT` /
|
||||
//! `KOMOREBI_WINDOWS_COMMIT` for a build outside a checkout (nix).
|
||||
//!
|
||||
//! If a source is not there the catalog is empty and says so.
|
||||
|
||||
use proc_macro2::TokenStream;
|
||||
use proc_macro2::TokenTree;
|
||||
use std::env;
|
||||
use std::fmt::Write as _;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use syn::visit::Visit;
|
||||
|
||||
/// A flavor of komorebi to index.
|
||||
struct Flavor {
|
||||
/// The name of its catalog in the generated code.
|
||||
name: &'static str,
|
||||
/// The variable naming a checkout of it.
|
||||
source_env: &'static str,
|
||||
/// The variable giving the commit when the checkout is not a git repository.
|
||||
commit_env: &'static [&'static str],
|
||||
/// The source trees to index: their directory under the checkout, and their Rust crate name.
|
||||
crates: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
const FLAVORS: &[Flavor] = &[
|
||||
Flavor {
|
||||
name: "MAC",
|
||||
source_env: "KOMOREBI_MAC_SRC",
|
||||
commit_env: &["KOMOREBI_MAC_COMMIT"],
|
||||
crates: &[
|
||||
("komorebi/src", "komorebi"),
|
||||
("komorebi-client/src", "komorebi_client"),
|
||||
],
|
||||
},
|
||||
Flavor {
|
||||
name: "WINDOWS",
|
||||
source_env: "KOMOREBI_WINDOWS_SRC",
|
||||
commit_env: &["KOMOREBI_WINDOWS_COMMIT"],
|
||||
crates: &[
|
||||
("komorebi/src", "komorebi"),
|
||||
("komorebi-layouts/src", "komorebi_layouts"),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
struct Entry {
|
||||
level: String,
|
||||
target: String,
|
||||
template: String,
|
||||
file: String,
|
||||
line: usize,
|
||||
function: String,
|
||||
owner: String,
|
||||
}
|
||||
|
||||
struct SpanEntry {
|
||||
name: String,
|
||||
file: String,
|
||||
line: usize,
|
||||
function: String,
|
||||
owner: String,
|
||||
}
|
||||
|
||||
struct Finder<'a> {
|
||||
file: String,
|
||||
modules: Vec<String>,
|
||||
functions: Vec<String>,
|
||||
owners: Vec<String>,
|
||||
logs: &'a mut Vec<Entry>,
|
||||
spans: &'a mut Vec<SpanEntry>,
|
||||
}
|
||||
|
||||
fn level_of(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"error" => Some("ERROR"),
|
||||
"warn" => Some("WARN"),
|
||||
"info" => Some("INFO"),
|
||||
"debug" => Some("DEBUG"),
|
||||
"trace" => Some("TRACE"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The comma-separated top-level arguments of a macro call.
|
||||
fn arguments(tokens: TokenStream) -> Vec<Vec<TokenTree>> {
|
||||
let mut all = vec![Vec::new()];
|
||||
for token in tokens {
|
||||
match &token {
|
||||
TokenTree::Punct(punct) if punct.as_char() == ',' => all.push(Vec::new()),
|
||||
_ => all.last_mut().expect("never empty").push(token),
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn string_literal(tokens: &[TokenTree]) -> Option<String> {
|
||||
let [TokenTree::Literal(literal)] = tokens else {
|
||||
return None;
|
||||
};
|
||||
let stream: TokenStream = TokenTree::Literal(literal.clone()).into();
|
||||
syn::parse2::<syn::LitStr>(stream)
|
||||
.ok()
|
||||
.map(|literal| literal.value())
|
||||
}
|
||||
|
||||
impl Finder<'_> {
|
||||
fn target(&self) -> String {
|
||||
self.modules.join("::")
|
||||
}
|
||||
|
||||
fn function(&self) -> String {
|
||||
self.functions.last().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn owner(&self) -> String {
|
||||
self.owners.last().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn instrumented(&mut self, attributes: &[syn::Attribute], function: &str) {
|
||||
for attribute in attributes {
|
||||
let path = attribute.path();
|
||||
let last = path
|
||||
.segments
|
||||
.last()
|
||||
.map(|segment| segment.ident.to_string());
|
||||
if last.as_deref() != Some("instrument") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// #[instrument(name = "...")] renames the span
|
||||
let mut name = function.to_string();
|
||||
let _ = attribute.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("name") {
|
||||
if let Ok(value) = meta.value().and_then(|value| value.parse::<syn::LitStr>()) {
|
||||
name = value.value();
|
||||
}
|
||||
} else if meta.input.peek(syn::Token![=]) {
|
||||
let _ = meta.value().and_then(|value| value.parse::<syn::Expr>());
|
||||
} else if meta.input.peek(syn::token::Paren) {
|
||||
let _ = meta.input.parse::<TokenTree>();
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
self.spans.push(SpanEntry {
|
||||
name,
|
||||
file: self.file.clone(),
|
||||
line: path
|
||||
.segments
|
||||
.first()
|
||||
.map_or(0, |segment| segment.ident.span().start().line),
|
||||
function: function.to_string(),
|
||||
owner: self.owner(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'ast> Visit<'ast> for Finder<'_> {
|
||||
fn visit_item_mod(&mut self, module: &'ast syn::ItemMod) {
|
||||
self.modules.push(module.ident.to_string());
|
||||
syn::visit::visit_item_mod(self, module);
|
||||
self.modules.pop();
|
||||
}
|
||||
|
||||
fn visit_item_impl(&mut self, item: &'ast syn::ItemImpl) {
|
||||
let owner = match &*item.self_ty {
|
||||
syn::Type::Path(path) => path
|
||||
.path
|
||||
.segments
|
||||
.last()
|
||||
.map(|segment| segment.ident.to_string())
|
||||
.unwrap_or_default(),
|
||||
_ => String::new(),
|
||||
};
|
||||
self.owners.push(owner);
|
||||
syn::visit::visit_item_impl(self, item);
|
||||
self.owners.pop();
|
||||
}
|
||||
|
||||
fn visit_item_fn(&mut self, function: &'ast syn::ItemFn) {
|
||||
let name = function.sig.ident.to_string();
|
||||
self.instrumented(&function.attrs, &name);
|
||||
self.functions.push(name);
|
||||
syn::visit::visit_item_fn(self, function);
|
||||
self.functions.pop();
|
||||
}
|
||||
|
||||
fn visit_impl_item_fn(&mut self, function: &'ast syn::ImplItemFn) {
|
||||
let name = function.sig.ident.to_string();
|
||||
self.instrumented(&function.attrs, &name);
|
||||
self.functions.push(name);
|
||||
syn::visit::visit_impl_item_fn(self, function);
|
||||
self.functions.pop();
|
||||
}
|
||||
|
||||
fn visit_macro(&mut self, mac: &'ast syn::Macro) {
|
||||
let last = mac
|
||||
.path
|
||||
.segments
|
||||
.last()
|
||||
.map(|segment| segment.ident.to_string());
|
||||
let Some(level) = last.as_deref().and_then(level_of) else {
|
||||
// another macro may wrap code that logs (objc2's `define_class!` holds whole impls):
|
||||
// read what it wraps as items, then as statements, and look inside
|
||||
if let Ok(file) = syn::parse2::<syn::File>(mac.tokens.clone()) {
|
||||
self.visit_file(&file);
|
||||
} else if let Ok(statements) =
|
||||
syn::parse::Parser::parse2(syn::Block::parse_within, mac.tokens.clone())
|
||||
{
|
||||
for statement in &statements {
|
||||
self.visit_stmt(statement);
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
// only tracing's: `tracing::info!` or a bare `info!`
|
||||
let qualified = mac.path.segments.len() == 1
|
||||
|| mac
|
||||
.path
|
||||
.segments
|
||||
.first()
|
||||
.is_some_and(|segment| segment.ident == "tracing");
|
||||
if !qualified {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut target = self.target();
|
||||
let mut template = None;
|
||||
for argument in arguments(mac.tokens.clone()) {
|
||||
// `target: "x"` overrides the module as the log target
|
||||
if let [TokenTree::Ident(name), TokenTree::Punct(colon), rest @ ..] =
|
||||
argument.as_slice()
|
||||
&& name == "target"
|
||||
&& colon.as_char() == ':'
|
||||
{
|
||||
if let Some(text) = string_literal(rest) {
|
||||
target = text;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if template.is_none() {
|
||||
template = string_literal(&argument);
|
||||
}
|
||||
}
|
||||
|
||||
self.logs.push(Entry {
|
||||
level: level.to_string(),
|
||||
target,
|
||||
template: template.unwrap_or_default(),
|
||||
file: self.file.clone(),
|
||||
line: mac
|
||||
.path
|
||||
.segments
|
||||
.first()
|
||||
.map_or(0, |segment| segment.ident.span().start().line),
|
||||
function: self.function(),
|
||||
owner: self.owner(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn source_files(directory: &Path, found: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = fs::read_dir(directory) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut paths: Vec<PathBuf> = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
if path.is_dir() {
|
||||
source_files(&path, found);
|
||||
} else if path.extension().is_some_and(|extension| extension == "rs") {
|
||||
found.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `komorebi/src/a/b.rs` under crate `komorebi` is module `komorebi::a::b`.
|
||||
fn module_of(crate_name: &str, root: &Path, file: &Path) -> Vec<String> {
|
||||
let relative = file.strip_prefix(root).unwrap_or(file);
|
||||
let mut modules = vec![crate_name.to_string()];
|
||||
let parts: Vec<String> = relative
|
||||
.with_extension("")
|
||||
.components()
|
||||
.map(|component| component.as_os_str().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
for (index, part) in parts.iter().enumerate() {
|
||||
let last = index + 1 == parts.len();
|
||||
if last && (part == "mod" || part == "lib" || part == "main") {
|
||||
continue;
|
||||
}
|
||||
modules.push(part.clone());
|
||||
}
|
||||
modules
|
||||
}
|
||||
|
||||
fn git(repo: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.arg("-C")
|
||||
.arg(repo)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
output
|
||||
.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
/// A path as the catalog stores it: relative to the checkout and always `/`-separated, so the same
|
||||
/// source gives the same keys whichever OS the recorder is built on.
|
||||
fn key(path: &Path, repo: &Path) -> String {
|
||||
path.strip_prefix(repo)
|
||||
.unwrap_or(path)
|
||||
.components()
|
||||
.map(|component| component.as_os_str().to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
}
|
||||
|
||||
/// The generated code for one flavor's catalog.
|
||||
fn index(flavor: &Flavor) -> String {
|
||||
println!("cargo:rerun-if-env-changed={}", flavor.source_env);
|
||||
for variable in flavor.commit_env {
|
||||
println!("cargo:rerun-if-env-changed={variable}");
|
||||
}
|
||||
|
||||
let repo = env::var_os(flavor.source_env)
|
||||
.map(PathBuf::from)
|
||||
.filter(|path| !path.as_os_str().is_empty());
|
||||
|
||||
let mut logs = Vec::new();
|
||||
let mut spans = Vec::new();
|
||||
let mut files_scanned = 0_usize;
|
||||
let mut parse_failures = Vec::new();
|
||||
|
||||
if let Some(repo) = &repo {
|
||||
for (directory, crate_name) in flavor.crates {
|
||||
let root = repo.join(directory);
|
||||
println!("cargo:rerun-if-changed={}", root.display());
|
||||
|
||||
let mut files = Vec::new();
|
||||
source_files(&root, &mut files);
|
||||
for path in files {
|
||||
let Ok(text) = fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let relative = key(&path, repo);
|
||||
match syn::parse_file(&text) {
|
||||
Ok(file) => {
|
||||
files_scanned += 1;
|
||||
let mut finder = Finder {
|
||||
file: relative,
|
||||
modules: module_of(crate_name, &root, &path),
|
||||
functions: Vec::new(),
|
||||
owners: Vec::new(),
|
||||
logs: &mut logs,
|
||||
spans: &mut spans,
|
||||
};
|
||||
finder.visit_file(&file);
|
||||
}
|
||||
Err(error) => parse_failures.push(format!("{relative}: {error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for failure in &parse_failures {
|
||||
println!(
|
||||
"cargo:warning=komorebi-recorder could not index {} source: {failure}",
|
||||
flavor.name
|
||||
);
|
||||
}
|
||||
if files_scanned == 0 && repo.is_some() {
|
||||
println!(
|
||||
"cargo:warning=komorebi's {} source was not found at {}: `code` will not be able to map \
|
||||
its log lines to source",
|
||||
flavor.name,
|
||||
repo.as_ref()
|
||||
.map_or_else(String::new, |repo| repo.display().to_string())
|
||||
);
|
||||
}
|
||||
|
||||
// the commit the indexed source is at, and whether it has uncommitted changes
|
||||
let git_dir = repo.as_ref().map(|repo| repo.join(".git"));
|
||||
if let Some(git_dir) = git_dir.filter(|git_dir| git_dir.exists()) {
|
||||
println!("cargo:rerun-if-changed={}", git_dir.join("HEAD").display());
|
||||
}
|
||||
// a build outside a git checkout (nix) is told the commit instead
|
||||
let from_git = repo
|
||||
.as_ref()
|
||||
.and_then(|repo| git(repo, &["rev-parse", "HEAD"]));
|
||||
let commit = from_git
|
||||
.or_else(|| {
|
||||
flavor
|
||||
.commit_env
|
||||
.iter()
|
||||
.find_map(|variable| env::var(variable).ok().filter(|hash| !hash.is_empty()))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(repo) = &repo {
|
||||
// so `code` can find the checkout again at run time, if it is still there
|
||||
println!(
|
||||
"cargo:rustc-env=KOMOREBI_{}_ROOT={}",
|
||||
flavor.name,
|
||||
repo.display()
|
||||
);
|
||||
}
|
||||
let source_paths: Vec<&str> = flavor.crates.iter().map(|(path, _)| *path).collect();
|
||||
let dirty = !commit.is_empty()
|
||||
&& repo.as_ref().is_some_and(|repo| {
|
||||
let mut args = vec!["status", "--porcelain", "--"];
|
||||
args.extend(&source_paths);
|
||||
git(repo, &args).is_some_and(|status| !status.is_empty())
|
||||
});
|
||||
|
||||
let mut out = String::new();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"/// The log statements indexed from the {} flavor's komorebi source when the crate was built; empty if no\n\
|
||||
/// source was named then.",
|
||||
flavor.name.to_lowercase()
|
||||
);
|
||||
let _ = writeln!(out, "pub static {}: Catalog = Catalog {{", flavor.name);
|
||||
let _ = writeln!(out, " commit: {commit:?},");
|
||||
let _ = writeln!(out, " dirty: {dirty},");
|
||||
let _ = writeln!(out, " files_scanned: {files_scanned},");
|
||||
let _ = writeln!(out, " source_paths: &{source_paths:?},");
|
||||
let _ = writeln!(out, " entries: &[");
|
||||
for entry in &logs {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" RawEntry {{ level: {:?}, target: {:?}, template: {:?}, file: {:?}, line: {}, function: {:?}, owner: {:?} }},",
|
||||
entry.level,
|
||||
entry.target,
|
||||
entry.template,
|
||||
entry.file,
|
||||
entry.line,
|
||||
entry.function,
|
||||
entry.owner
|
||||
);
|
||||
}
|
||||
let _ = writeln!(out, " ],");
|
||||
let _ = writeln!(out, " spans: &[");
|
||||
for span in &spans {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" RawSpan {{ name: {:?}, file: {:?}, line: {}, function: {:?}, owner: {:?} }},",
|
||||
span.name, span.file, span.line, span.function, span.owner
|
||||
);
|
||||
}
|
||||
let _ = writeln!(out, " ],");
|
||||
let _ = writeln!(out, "}};");
|
||||
out
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
|
||||
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
|
||||
let out: String = FLAVORS.iter().map(index).collect();
|
||||
|
||||
fs::write(out_dir.join("log_catalog.rs"), out).expect("write log_catalog.rs");
|
||||
}
|
||||
@@ -803,10 +803,21 @@ mod tests {
|
||||
.iter()
|
||||
.filter(|line| matches!(line.root_span(), Some("process_event" | "process_command")))
|
||||
.count();
|
||||
let found = lines
|
||||
.iter()
|
||||
.filter(|line| !line.continuation)
|
||||
.filter(|line| {
|
||||
matches!((&line.target, line.level), (Some(target), Some(level))
|
||||
if crate::analysis::catalog::of(Flavor::Macos).find(target, level, &line.message).is_some())
|
||||
})
|
||||
.count();
|
||||
let structured = lines.iter().filter(|line| !line.continuation).count();
|
||||
|
||||
eprintln!(
|
||||
"{} lines: {events} event blocks, {commands} command blocks holding {in_blocks} of {handler_lines} handler lines",
|
||||
lines.len()
|
||||
"{} lines: {events} event blocks, {commands} command blocks holding {in_blocks} of {handler_lines} handler lines; \
|
||||
{found} of {structured} lines found in the source ({}%)",
|
||||
lines.len(),
|
||||
found * 100 / structured.max(1)
|
||||
);
|
||||
assert!(events > 0);
|
||||
assert!(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,316 @@
|
||||
//! From a recorded log line to the source that wrote it.
|
||||
//!
|
||||
//! This is what turns "komorebi did something odd at 00:12" into "this statement, in this function,
|
||||
//! ran": each line of a handler's output is matched to the `tracing` statement in komorebi's source
|
||||
//! that produced it (see [`super::catalog`]), shown with the code around it, and described by the
|
||||
//! role of the part of komorebi it came from. Every answer carries whether the source is the
|
||||
//! version that was recorded.
|
||||
//!
|
||||
//! The `code` command is a thin layer over three functions on [`Analysis`], each returning
|
||||
//! [`CodeData`]:
|
||||
//!
|
||||
//! | asked | function |
|
||||
//! |---|---|
|
||||
//! | what wrote these log lines | [`Analysis::code_for_lines`] |
|
||||
//! | what wrote everything one event's handler logged | [`Analysis::code_for_event`] |
|
||||
//! | which statements say this (no log line needed) | [`Analysis::code_search`] |
|
||||
//!
|
||||
//! # Flavor
|
||||
//!
|
||||
//! The statements come from the catalog of the flavor the session recorded
|
||||
//! ([`Analysis::catalog`]) and the role of each line from that flavor's rules
|
||||
//! ([`Rules::role`](super::flavor::Rules::role)), so a session recorded from komorebi for Windows
|
||||
//! is explained by komorebi for Windows' source, on either host.
|
||||
//! If the recorder was built without that flavor's source the catalog is empty: no line is
|
||||
//! matched, and [`CodeData::skew`] carries the warning on how to build one.
|
||||
//!
|
||||
//! # What a match does and does not say
|
||||
//!
|
||||
//! A [`Source`] names the statement whose text a line fits
|
||||
//! ([`Confidence`](super::catalog::Confidence) reports how well), not that the statement ran in the
|
||||
//! version that was recorded: that is [`LineSource::file_changed`] and [`CodeData::skew`]. A line
|
||||
//! with no [`Source`] is one no statement in the indexed source could have written, which for a
|
||||
//! line from a komorebi that is not the indexed one is a finding in itself.
|
||||
|
||||
use super::Analysis;
|
||||
use super::catalog::Skew;
|
||||
use super::catalog::Source;
|
||||
use super::catalog::Statement;
|
||||
use super::envelope;
|
||||
use color_eyre::eyre;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Serialize;
|
||||
use std::path::Path;
|
||||
|
||||
/// The schema name that identifies a [`CodeData`] in an envelope (`code/1`); listed by the
|
||||
/// `schema` command.
|
||||
pub const SCHEMA_CODE: &str = "code/1";
|
||||
|
||||
/// A few lines of komorebi's source around a statement.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
pub struct Snippet {
|
||||
/// The file, relative to the checkout of komorebi and `/`-separated.
|
||||
pub file: String,
|
||||
/// The statement's line.
|
||||
pub line: usize,
|
||||
/// `(line number, text)` of each line shown, in order and without line endings.
|
||||
pub lines: Vec<(usize, String)>,
|
||||
}
|
||||
|
||||
/// One line of komorebi's log, with the statement of komorebi's source that wrote it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct LineSource {
|
||||
/// 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 the line has no time or it
|
||||
/// cannot be placed on the session's clock.
|
||||
pub video_s: Option<f64>,
|
||||
/// The line's level in capitals (`INFO`); `None` for a line that is not a log record, such as
|
||||
/// a panic message.
|
||||
pub level: Option<String>,
|
||||
/// The module the line was logged from (its target), such as `komorebi::reaper`; `None` where
|
||||
/// the line has none.
|
||||
pub target: Option<String>,
|
||||
/// The line's message, without ANSI escapes.
|
||||
pub message: String,
|
||||
/// The part of komorebi that logged it, in a sentence. `None` if the line has no target.
|
||||
pub role: Option<String>,
|
||||
/// That part changes state without sending a notification.
|
||||
pub changes_state_silently: bool,
|
||||
/// The statement that wrote it, if one matched. `None` for a line without a target and level,
|
||||
/// and for one that no statement in the indexed source could have written.
|
||||
pub source: Option<Source>,
|
||||
/// The file the statement is in differs between the recorded komorebi and the indexed source,
|
||||
/// so it may not be the statement that ran. Also `true` when it cannot be told which files
|
||||
/// differ ([`Skew::file_changed`]). `false` when there is no `source`.
|
||||
pub file_changed: bool,
|
||||
/// The statement and the lines around it. `None` if there is no `source`, or the checkout of
|
||||
/// komorebi was not given or does not have the file.
|
||||
pub snippet: Option<Snippet>,
|
||||
}
|
||||
|
||||
/// The source of some of komorebi's log, or the statements that match a search: the `data` of the
|
||||
/// `code` command.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct CodeData {
|
||||
/// How the indexed source compares with the komorebi that was recorded. It applies to
|
||||
/// everything below.
|
||||
pub skew: Skew,
|
||||
/// The thing asked about, e.g. `event:12` or `log:345`, or `grep <text>`.
|
||||
pub about: String,
|
||||
/// One per log line asked about, in the order asked. Empty for a search.
|
||||
pub lines: Vec<LineSource>,
|
||||
/// Statements whose text contains what was searched for (`--grep`), in source order. Empty
|
||||
/// unless the answer is to a search.
|
||||
pub statements: Vec<Statement>,
|
||||
}
|
||||
|
||||
/// A few lines of source around `statement`, `context` lines on each side, read from the checkout
|
||||
/// at `root`. `None` without a checkout, or if its file for the statement cannot be read.
|
||||
fn snippet(root: Option<&Path>, statement: &Statement, context: usize) -> Option<Snippet> {
|
||||
let text = std::fs::read_to_string(root?.join(&statement.file)).ok()?;
|
||||
let all: Vec<&str> = text.lines().collect();
|
||||
let first = statement.line.saturating_sub(context).max(1);
|
||||
let last = (statement.line + context).min(all.len());
|
||||
(first <= last).then(|| Snippet {
|
||||
file: statement.file.clone(),
|
||||
line: statement.line,
|
||||
lines: (first..=last)
|
||||
.map(|number| (number, all[number - 1].to_string()))
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Returns the statement of komorebi's source that wrote each of the lines `numbers` of the
|
||||
/// session's komorebi log.
|
||||
///
|
||||
/// `about` is only a label, kept in [`CodeData::about`]. `numbers` are line numbers of
|
||||
/// `komorebi.log`, counting from 1. `context` is how many lines of source to show on each side
|
||||
/// of a statement.
|
||||
///
|
||||
/// `root` is a checkout of komorebi, from which the snippets are read and against which the
|
||||
/// skew is computed. With `None` no snippets are returned, and the skew is worked out with the
|
||||
/// checkout that [`default_code_root`](crate::annotations::default_code_root) finds for the
|
||||
/// session's flavor, if any. The `code` command passes the checkout it resolved, so it gets
|
||||
/// snippets whenever one exists.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if a number in `numbers` is `0` or past the last line of the log (the
|
||||
/// not-found exit kind). The first bad number fails the whole call: no partial answer is
|
||||
/// returned.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-code-lines")
|
||||
/// .log(2.0, "INFO", "komorebi::reaper: reaping window: 4711")
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// // the first line of komorebi.log, with no checkout to show source from
|
||||
/// let data = analysis.code_for_lines("log:1", &[1], 3, None)?;
|
||||
/// assert_eq!(data.about, "log:1");
|
||||
/// assert_eq!(data.lines[0].target.as_deref(), Some("komorebi::reaper"));
|
||||
/// assert_eq!(data.lines[0].message, "reaping window: 4711");
|
||||
/// assert!(data.lines[0].snippet.is_none());
|
||||
///
|
||||
/// // a line that is not in the log is an error, not an empty answer
|
||||
/// assert!(analysis.code_for_lines("log:9", &[9], 3, None).is_err());
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
///
|
||||
/// Which statement a line is matched to depends on the source the recorder was built with, so
|
||||
/// it is covered by `tests/code.rs::a_log_line_is_traced_to_the_statement_that_wrote_it`, which
|
||||
/// also covers the role, and
|
||||
/// `tests/code.rs::only_the_files_that_changed_since_the_recorded_commit_are_doubted`, which
|
||||
/// covers [`LineSource::file_changed`].
|
||||
pub fn code_for_lines(
|
||||
&self,
|
||||
about: &str,
|
||||
numbers: &[u64],
|
||||
context: usize,
|
||||
root: Option<&Path>,
|
||||
) -> eyre::Result<CodeData> {
|
||||
let log = self.log();
|
||||
let skew = match root {
|
||||
Some(root) => self.skew_in(Some(root)),
|
||||
None => self.skew(),
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
for number in numbers {
|
||||
let line = usize::try_from(number.saturating_sub(1))
|
||||
.ok()
|
||||
.filter(|_| *number >= 1)
|
||||
.and_then(|index| log.lines.get(index))
|
||||
.ok_or_else(|| {
|
||||
envelope::not_found(format!(
|
||||
"komorebi.log has {} lines; there is no line {number}",
|
||||
log.lines.len()
|
||||
))
|
||||
})?;
|
||||
|
||||
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));
|
||||
|
||||
let file_changed = source
|
||||
.as_ref()
|
||||
.is_some_and(|source| skew.file_changed(&source.statement.file));
|
||||
lines.push(LineSource {
|
||||
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()),
|
||||
target: line.target.clone(),
|
||||
message: line.message.clone(),
|
||||
role: role.map(|role| role.summary.to_string()),
|
||||
changes_state_silently: role.is_some_and(|role| role.changes_state_silently),
|
||||
file_changed,
|
||||
snippet: source
|
||||
.as_ref()
|
||||
.and_then(|source| snippet(root, &source.statement, context)),
|
||||
source,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(CodeData {
|
||||
skew,
|
||||
about: about.to_string(),
|
||||
lines,
|
||||
statements: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the source of everything the handler of event `seq` logged, header line first.
|
||||
///
|
||||
/// The lines are those of the handler's block in komorebi's log (see [`Analysis::pairing`]),
|
||||
/// answered like [`Analysis::code_for_lines`], with `event:<seq>` as [`CodeData::about`].
|
||||
/// `context` and `root` are as for [`Analysis::code_for_lines`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error (the not-found exit kind) if:
|
||||
///
|
||||
/// - there is no event numbered `seq`;
|
||||
/// - no handler lines were found in komorebi's log for the event: the log may not have been
|
||||
/// recorded, or komorebi's log level may not show its handler.
|
||||
///
|
||||
/// The lines of a handler are covered by
|
||||
/// `tests/code.rs::an_event_is_explained_by_everything_its_handler_logged`, and the missing
|
||||
/// event by
|
||||
/// `tests/code.rs::a_line_no_statement_writes_is_said_so_and_a_bad_reference_is_not_found`.
|
||||
pub fn code_for_event(
|
||||
&self,
|
||||
seq: u64,
|
||||
context: usize,
|
||||
root: Option<&Path>,
|
||||
) -> eyre::Result<CodeData> {
|
||||
let index = self
|
||||
.event_index(seq)
|
||||
.ok_or_else(|| envelope::not_found(format!("there is no event #{seq}")))?;
|
||||
let block = self
|
||||
.pairing()
|
||||
.pairs
|
||||
.get(index)
|
||||
.and_then(|pair| pair.block)
|
||||
.and_then(|id| self.log().blocks.get(id))
|
||||
.ok_or_else(|| {
|
||||
envelope::not_found(format!(
|
||||
"no handler lines were found in komorebi's log for event #{seq}: the log may \
|
||||
not have been recorded, or komorebi's log level may not show its handler"
|
||||
))
|
||||
})?;
|
||||
|
||||
self.code_for_lines(&format!("event:{seq}"), &block.lines.clone(), context, root)
|
||||
}
|
||||
|
||||
/// Returns the statements of komorebi's source whose message contains `text`, without needing
|
||||
/// a log line.
|
||||
///
|
||||
/// The comparison ignores case and looks only at the statements' message templates, so
|
||||
/// `reaping` finds `reaping window: {window_id}`. The statements are those of the catalog of
|
||||
/// the session's flavor, in source order, in [`CodeData::statements`]; [`CodeData::lines`] is
|
||||
/// empty and [`CodeData::about`] is `grep <text>`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-code-search").build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
/// # if analysis.catalog().is_empty() { return Ok(()); } // built without KOMOREBI_MAC_SRC
|
||||
///
|
||||
/// let found = analysis.code_search("Reaping WINDOW");
|
||||
/// assert_eq!(found.about, "grep Reaping WINDOW");
|
||||
/// assert!(found.lines.is_empty());
|
||||
/// assert!(!found.statements.is_empty());
|
||||
/// assert!(found.statements.iter().any(|statement| statement.file == "komorebi/src/reaper.rs"));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
///
|
||||
/// Also covered by `tests/code.rs::statements_can_be_searched_by_their_text`.
|
||||
#[must_use]
|
||||
pub fn code_search(&self, text: &str) -> CodeData {
|
||||
let needle = text.to_lowercase();
|
||||
CodeData {
|
||||
skew: self.skew(),
|
||||
about: format!("grep {text}"),
|
||||
lines: Vec::new(),
|
||||
statements: self.catalog().statements_matching(&needle),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
//! A session opened for investigation: everything the commands and the viewer ask, computed once.
|
||||
//!
|
||||
//! [`Analysis`] is the object every command asks questions of, and the one the viewer holds while a
|
||||
//! session is open in its window. [`Analysis::open`] takes the directory of a finished session. Opening is
|
||||
//! cheap; each part (events, the parsed log, the pairing of the two, states) is read the first
|
||||
//! time it is needed and kept.
|
||||
//!
|
||||
//! # Flavor, not host
|
||||
//!
|
||||
//! An `Analysis` is shaped by the komorebi that was recorded, not by the host it is run on. The
|
||||
//! manifest says which ([`Analysis::flavor`]), and everything that reads komorebi's own output
|
||||
//! (events, `State`, log) goes through the [`Rules`](super::flavor::Rules) of that [`Flavor`], so a
|
||||
//! session recorded on Windows opens on a Mac and the other way round.
|
||||
//!
|
||||
//! # Where the questions are
|
||||
//!
|
||||
//! This file holds the parts every question shares: the session, its clock, its events, its log,
|
||||
//! the pairing of the two, and the state at a moment. The questions are further methods of
|
||||
//! [`Analysis`], each defined next to the data it returns:
|
||||
//!
|
||||
//! | Question | Methods | Module |
|
||||
//! |---|---|---|
|
||||
//! | An event or a moment as a reader sees it | [`Analysis::event_view`], [`Analysis::moment`] | [`super::views`] |
|
||||
//! | The state at a moment, what changed, which events | `state_answer`, `diff_answer`, `events_answer` | `analysis::answers` |
|
||||
//! | What the user says is wrong, and what is around it | `brief` | `analysis::brief` |
|
||||
//! | What stands out in the whole recording | `overview`, `findings`, `incidents`, `session_info`, `histogram` | `analysis::overview` |
|
||||
//! | One event end to end, and the OS trace around it | `trace`, `os_trace` | `analysis::trace`, `analysis::os_trace` |
|
||||
//! | One window's life | `window_history` | `analysis::history` |
|
||||
//! | Where a word appears | `search` | `analysis::search` |
|
||||
//! | Which line of komorebi's source wrote a log line | `code_for_lines`, `code_for_event`, `code_search` | `analysis::code` |
|
||||
//! | When the picture changed, and a contact sheet | `changes`, `sheet` | `analysis::changes`, `analysis::sheet` |
|
||||
//!
|
||||
//! # What is kept, and what is read every time
|
||||
//!
|
||||
//! The events, the parsed log, the pairing and the state at the start of the recording are read
|
||||
//! once, the first time something asks, and kept for the life of the `Analysis`; each state a
|
||||
//! notification carries is parsed once and shared. So an `Analysis` describes the session as it was
|
||||
//! when each part was first read, and does not notice a file changing afterwards. That is
|
||||
//! harmless for a finished session. The annotations are the exception: they are written to while
|
||||
//! people and agents work, so they are not kept, and each question that needs them reads
|
||||
//! `annotations.jsonl` again.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```rust
|
||||
//! use komorebi_recorder::analysis::Analysis;
|
||||
//! use komorebi_recorder::testkit::{SessionBuilder, mach_ns, state_with_windows};
|
||||
//! use serde_json::json;
|
||||
//!
|
||||
//! // a recording in which komorebi received one command, two seconds in, and had one window
|
||||
//! let (session, _manifest) = SessionBuilder::new("doc-analysis")
|
||||
//! .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
//! .log(2.0, "INFO", "komorebi::process_command: retile")
|
||||
//! .build();
|
||||
//!
|
||||
//! let analysis = Analysis::open(&session.dir)?;
|
||||
//! assert_eq!(analysis.events().len(), 1);
|
||||
//! assert_eq!(analysis.log().lines.len(), 1);
|
||||
//!
|
||||
//! // any time argument a command takes
|
||||
//! assert_eq!(analysis.resolve("event:1.end")?.mach_ns, mach_ns(2.0));
|
||||
//!
|
||||
//! // the state at a moment is the one the latest notification before it carried
|
||||
//! let state = analysis.state_at(mach_ns(3.0))?;
|
||||
//! assert_eq!(state.snapshot.windows().len(), 1);
|
||||
//! # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
//! ```
|
||||
|
||||
use super::blocks;
|
||||
use super::blocks::Block;
|
||||
use super::blocks::Pair;
|
||||
use super::classify;
|
||||
use super::classify::Classification;
|
||||
use super::envelope;
|
||||
use super::events;
|
||||
use super::events::EventRecord;
|
||||
use super::flavor::Flavor;
|
||||
use super::guard::SessionPath;
|
||||
use super::logparse;
|
||||
use super::logparse::Line;
|
||||
use super::state::Snapshot;
|
||||
use super::timespec::Edge;
|
||||
use super::timespec::Lookup;
|
||||
use super::timespec::Resolved;
|
||||
use super::timespec::TimeSpec;
|
||||
use crate::annotations;
|
||||
use crate::clock::ClockMap;
|
||||
use crate::incidents::INCIDENTS_FILE;
|
||||
use crate::incidents::Incident;
|
||||
use crate::session::Manifest;
|
||||
use crate::session::STATUS_RECORDING;
|
||||
use crate::session::Session;
|
||||
use crate::sources::komorebi_events::state_file_name;
|
||||
use crate::timeline;
|
||||
use color_eyre::eyre;
|
||||
use color_eyre::eyre::WrapErr;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// The parsed komorebi log of a session.
|
||||
///
|
||||
/// Read from `komorebi.log` by [`Analysis::log`]. A session with no log, or one that cannot be
|
||||
/// read, has an empty `LogData`.
|
||||
pub struct LogData {
|
||||
/// Every line of the file, in file order. A `Line` has the 1-based number of its line in the
|
||||
/// file.
|
||||
pub lines: Vec<Line>,
|
||||
/// The handler blocks the lines form (`analysis::blocks::build`), in the order their headers
|
||||
/// were logged.
|
||||
pub blocks: Vec<Block>,
|
||||
}
|
||||
|
||||
/// Which handler produced which event, and what kind of event it was.
|
||||
///
|
||||
/// Made once by [`Analysis::pairing`].
|
||||
pub struct Pairing {
|
||||
/// The name the recorder subscribed as to komorebi.
|
||||
///
|
||||
/// It is the one the manifest recorded. A session that did not record it has it worked out from
|
||||
/// which of komorebi's `pushed notification` log lines line up with the events, and `None` if
|
||||
/// that finds nothing.
|
||||
pub subscriber: Option<String>,
|
||||
/// One per event, in event order.
|
||||
pub pairs: Vec<Pair>,
|
||||
/// One per event, in event order: what kind of event it was and why.
|
||||
pub classes: Vec<Classification>,
|
||||
}
|
||||
|
||||
/// Where the state at a moment came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StateSource {
|
||||
/// The notification of this event.
|
||||
Event {
|
||||
/// The event's sequence number.
|
||||
seq: u64,
|
||||
/// When the notification was received, in nanoseconds on the host's master monotonic
|
||||
/// clock.
|
||||
recv_mach_ns: u64,
|
||||
},
|
||||
/// The state recorded when the recording started, before any event.
|
||||
Start,
|
||||
}
|
||||
|
||||
/// The state komorebi was in at a moment, and where that knowledge came from.
|
||||
///
|
||||
/// Returned by [`Analysis::state_at`].
|
||||
pub struct StateAt {
|
||||
/// The state, parsed. Shared with the cache of the [`Analysis`] that returned it.
|
||||
pub snapshot: Arc<Snapshot>,
|
||||
/// The id of the recorded state (`states/<id>.json`); `None` for [`StateSource::Start`].
|
||||
pub state_id: Option<u64>,
|
||||
/// Which notification, or the start of the recording, this state is as of.
|
||||
pub source: StateSource,
|
||||
}
|
||||
|
||||
/// A finished session, opened to be asked questions.
|
||||
///
|
||||
/// It holds the [`Session`] and its [`Manifest`], and reads the rest of the session lazily and at
|
||||
/// most once (see the [module docs](self) for what is kept). The questions themselves are methods
|
||||
/// defined next to the data they answer; this type has the parts they share. The komorebi that
|
||||
/// was recorded decides how its output is read: see [`Analysis::flavor`].
|
||||
///
|
||||
/// A file name that comes from the session's own data, such as a video segment's file in the
|
||||
/// manifest, is resolved through [`Analysis::guard`], so that it cannot lead outside the session.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::analysis::envelope::{ExitKind, exit_kind};
|
||||
/// use komorebi_recorder::session::STATUS_RECORDING;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
///
|
||||
/// let (session, mut manifest) = SessionBuilder::new("doc-analysis-open").build();
|
||||
/// assert!(Analysis::open(&session.dir).is_ok());
|
||||
///
|
||||
/// // a session whose manifest still says `recording` cannot be analyzed yet
|
||||
/// manifest.status = STATUS_RECORDING.to_string();
|
||||
/// session.write_manifest(&manifest)?;
|
||||
/// let error = Analysis::open(&session.dir).err().expect("not finished");
|
||||
/// assert_eq!(exit_kind(&error), ExitKind::Unusable);
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
pub struct Analysis {
|
||||
/// The session directory.
|
||||
pub session: Session,
|
||||
/// The manifest, read when the session was opened.
|
||||
pub manifest: Manifest,
|
||||
guard: SessionPath,
|
||||
clock: ClockMap,
|
||||
events: OnceLock<(Vec<EventRecord>, Vec<String>)>,
|
||||
log: OnceLock<LogData>,
|
||||
pairing: OnceLock<Pairing>,
|
||||
start_state: OnceLock<Option<Arc<Snapshot>>>,
|
||||
states: Mutex<HashMap<u64, Arc<Snapshot>>>,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Opens a finished session. One that is still being recorded, or whose recorder died, cannot
|
||||
/// be analyzed yet and says how to proceed.
|
||||
///
|
||||
/// Only the manifest (`session.json`) is read here; everything else is read when a question
|
||||
/// first needs it. A session whose status is `complete` or `recovered` can be opened.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - a not-found error if `dir` does not exist, or is not a session (it has no `session.json`);
|
||||
/// - an error if the manifest cannot be read, is not valid, or was written by a newer
|
||||
/// `komorebi-recorder` than this one;
|
||||
/// - an unusable error if the manifest says the session is still `recording`. If a recorder
|
||||
/// holds the session's lock the message says to stop the recording first. Otherwise (the lock
|
||||
/// is not held, or the session has none) the recorder was killed or crashed, and the error
|
||||
/// carries the hint to recover the session with `komorebi-recorder reindex`.
|
||||
///
|
||||
/// Not-found and unusable errors are what `komorebi-recorder` exits with code 3 and 4 on (see
|
||||
/// `analysis::envelope::ExitKind`).
|
||||
pub fn open(dir: &Path) -> eyre::Result<Self> {
|
||||
let guard = SessionPath::new(dir)?;
|
||||
let session = Session::open(guard.root())?;
|
||||
let manifest = session.manifest()?;
|
||||
|
||||
if manifest.status == STATUS_RECORDING {
|
||||
let shown = session.dir.display();
|
||||
return Err(match crate::lock::recorder(&session.dir) {
|
||||
crate::lock::Recorder::Running(_) => envelope::unusable(format!(
|
||||
"{shown} is still being recorded; stop the recording first"
|
||||
)),
|
||||
_ => envelope::with_hint(
|
||||
envelope::unusable(format!(
|
||||
"{shown} was left unfinished: its recorder was killed or crashed"
|
||||
)),
|
||||
format!("recover it with `komorebi-recorder reindex {shown}`"),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let clock = ClockMap::new(manifest.anchors.clone());
|
||||
Ok(Self {
|
||||
session,
|
||||
manifest,
|
||||
guard,
|
||||
clock,
|
||||
events: OnceLock::new(),
|
||||
log: OnceLock::new(),
|
||||
pairing: OnceLock::new(),
|
||||
start_state: OnceLock::new(),
|
||||
states: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the log statements of the komorebi that recorded the session, as indexed from its
|
||||
/// source when this program was built.
|
||||
///
|
||||
/// The catalog is the one for the session's [flavor](Analysis::flavor), and is empty if this
|
||||
/// build was made without that komorebi's source. It is the checkout the build saw, which may
|
||||
/// not be the commit that was recorded: see [`Analysis::skew`].
|
||||
#[must_use]
|
||||
pub fn catalog(&self) -> &'static super::catalog::Catalog {
|
||||
super::catalog::of(self.flavor())
|
||||
}
|
||||
|
||||
/// Returns how the indexed source ([`Analysis::catalog`]) compares with the komorebi that
|
||||
/// ran.
|
||||
///
|
||||
/// The repository is found by `annotations::default_code_root`; the commands that take a
|
||||
/// `--komorebi-src` use [`Analysis::skew_in`].
|
||||
#[must_use]
|
||||
pub fn skew(&self) -> super::catalog::Skew {
|
||||
self.skew_in(crate::annotations::default_code_root(self.flavor()).as_deref())
|
||||
}
|
||||
|
||||
/// Returns [`Analysis::skew`] with the checkout of komorebi's repository given.
|
||||
///
|
||||
/// The checkout is what the comparison asks which files differ between the recorded commit and
|
||||
/// the indexed one. With `None` there is no repository to ask.
|
||||
#[must_use]
|
||||
pub fn skew_in(&self, root: Option<&std::path::Path>) -> super::catalog::Skew {
|
||||
super::catalog::skew(self.flavor(), &self.manifest.komorebi.versions, root)
|
||||
}
|
||||
|
||||
/// Returns the komorebi that recorded the session, which decides how its output is read.
|
||||
///
|
||||
/// It is the flavor in the manifest ([`Flavor::Macos`] for a session that does not say), and
|
||||
/// not the one of the host this program runs on.
|
||||
#[must_use]
|
||||
pub fn flavor(&self) -> Flavor {
|
||||
self.manifest.komorebi.flavor
|
||||
}
|
||||
|
||||
/// Returns the guard that resolves file names inside the session directory, refusing absolute
|
||||
/// paths, `..` and symlinks that lead out.
|
||||
#[must_use]
|
||||
pub fn guard(&self) -> &SessionPath {
|
||||
&self.guard
|
||||
}
|
||||
|
||||
/// Returns the clock map of the session: conversions between the host's master monotonic clock
|
||||
/// and the wall clock, from the anchors in the manifest.
|
||||
#[must_use]
|
||||
pub fn clock(&self) -> &ClockMap {
|
||||
&self.clock
|
||||
}
|
||||
|
||||
fn loaded_events(&self) -> &(Vec<EventRecord>, Vec<String>) {
|
||||
self.events.get_or_init(|| {
|
||||
events::load(&self.session, self.flavor().rules()).unwrap_or_else(|error| {
|
||||
(
|
||||
Vec::new(),
|
||||
vec![format!("could not read the events: {error:#}")],
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns every komorebi notification, in the order received: by receive time, and by sequence
|
||||
/// number among events received at the same time.
|
||||
///
|
||||
/// The events are read from `events.jsonl` the first time. A session with no events file has
|
||||
/// none, without a warning. A line that cannot be read is skipped and counted in
|
||||
/// [`Analysis::warnings`]; if the file itself cannot be read the result is empty and
|
||||
/// [`Analysis::warnings`] reports it.
|
||||
#[must_use]
|
||||
pub fn events(&self) -> &[EventRecord] {
|
||||
&self.loaded_events().0
|
||||
}
|
||||
|
||||
/// Returns things that went wrong reading the session's files, to be shown with any answer.
|
||||
///
|
||||
/// These are, in this order: a warning if the rules for the session's [flavor](Analysis::flavor)
|
||||
/// have not been checked against a recording of that komorebi
|
||||
/// ([`Rules::verified`](super::flavor::Rules::verified)); and what went wrong reading the
|
||||
/// events (see [`Analysis::events`]). Problems with the log are not reported: a log that is
|
||||
/// missing or unreadable is read as empty ([`Analysis::log`]).
|
||||
///
|
||||
/// The list is empty when nothing went wrong, which is the usual case.
|
||||
#[must_use]
|
||||
pub fn warnings(&self) -> Vec<String> {
|
||||
let mut warnings = Vec::new();
|
||||
let flavor = self.flavor();
|
||||
if !flavor.rules().verified() {
|
||||
warnings.push(format!(
|
||||
"this session recorded komorebi for {flavor}, which this build reads from \
|
||||
komorebi's source and has not yet checked against a recording of it: event \
|
||||
names, window handles and the grouping of log lines are probably right, but if \
|
||||
something looks wrong, that is the first suspect"
|
||||
));
|
||||
}
|
||||
|
||||
warnings.extend(self.loaded_events().1.iter().cloned());
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Returns the position in [`Analysis::events`] of the event with this sequence number, or
|
||||
/// `None` if the session has no such event.
|
||||
///
|
||||
/// This is a linear search. The position is not the sequence number: events are ordered by
|
||||
/// receive time, and a session may be missing events.
|
||||
#[must_use]
|
||||
pub fn event_index(&self, seq: u64) -> Option<usize> {
|
||||
self.events().iter().position(|event| event.seq == seq)
|
||||
}
|
||||
|
||||
/// Returns komorebi's log, parsed, with its handler blocks.
|
||||
///
|
||||
/// It is read from `komorebi.log` the first time. A session with no log, or one that cannot be
|
||||
/// read, has an empty one, and nothing reports it: check [`LogData::lines`].
|
||||
#[must_use]
|
||||
pub fn log(&self) -> &LogData {
|
||||
self.log.get_or_init(|| {
|
||||
let bytes = std::fs::read(self.session.path("komorebi.log")).unwrap_or_default();
|
||||
let lines = logparse::parse(&bytes);
|
||||
let blocks = blocks::build(&lines, &self.clock, self.flavor().rules());
|
||||
LogData { lines, blocks }
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns which handler block produced each event and what kind of event each was.
|
||||
///
|
||||
/// This reads the events and the log if they have not been read. The result is made once.
|
||||
#[must_use]
|
||||
pub fn pairing(&self) -> &Pairing {
|
||||
self.pairing.get_or_init(|| {
|
||||
let log = self.log();
|
||||
let events = self.events();
|
||||
// the recorder wrote its own name into the manifest; older sessions are worked out from
|
||||
// which of komorebi's "pushed notification" lines line up with the events
|
||||
let subscriber = self
|
||||
.manifest
|
||||
.komorebi
|
||||
.subscriber
|
||||
.clone()
|
||||
.or_else(|| blocks::infer_subscriber(&log.blocks, events));
|
||||
Pairing {
|
||||
pairs: blocks::pair(events, &log.blocks, subscriber.as_deref()),
|
||||
classes: classify::classify(events, self.flavor().rules()),
|
||||
subscriber,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns whether the state changed at the event at `index` of [`Analysis::events`]: whether
|
||||
/// its state id differs from the previous event's.
|
||||
///
|
||||
/// The answer is `None` when it is not known: `index` is out of range, is `0` (there is no
|
||||
/// previous event to compare with), or either event has no state id.
|
||||
#[must_use]
|
||||
pub fn state_changed(&self, index: usize) -> Option<bool> {
|
||||
let events = self.events();
|
||||
let (this, before) = (
|
||||
events.get(index)?.state_id?,
|
||||
events.get(index.checked_sub(1)?)?.state_id?,
|
||||
);
|
||||
Some(this != before)
|
||||
}
|
||||
|
||||
/// Returns the recorded state with this id (the file `states/000001.json` for id 1), parsed.
|
||||
///
|
||||
/// A state is parsed once; later calls with the same id return the same shared value. The ids
|
||||
/// are the `state_id` of the events and of [`StateAt`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns a not-found error if there is no such state, or its file cannot be read, and an
|
||||
/// error if the file is not valid JSON. A state that is JSON but not shaped as expected does not
|
||||
/// fail: it is read tolerantly, with what is missing left empty.
|
||||
pub fn snapshot(&self, state_id: u64) -> eyre::Result<Arc<Snapshot>> {
|
||||
if let Some(found) = self
|
||||
.states
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(&state_id)
|
||||
{
|
||||
return Ok(found.clone());
|
||||
}
|
||||
|
||||
let path = self.guard.resolve(&state_file_name(state_id))?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|_| envelope::not_found(format!("there is no recorded state {state_id}")))?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text)
|
||||
.wrap_err_with(|| format!("{} is not valid JSON", path.display()))?;
|
||||
let snapshot = Arc::new(Snapshot::parse(self.flavor(), &value));
|
||||
self.states
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(state_id, snapshot.clone());
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
fn start_snapshot(&self) -> Option<Arc<Snapshot>> {
|
||||
self.start_state
|
||||
.get_or_init(|| {
|
||||
let text = std::fs::read_to_string(self.session.path("state-start.json")).ok()?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
Some(Arc::new(Snapshot::parse(self.flavor(), &value)))
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Returns the state komorebi was in at `mach_ns`, in nanoseconds on the host's master
|
||||
/// monotonic clock: the one in the latest notification before it, or the starting state if
|
||||
/// there has been none. It is the state as of that notification, so it can be out of date if
|
||||
/// komorebi changed state without sending one since.
|
||||
///
|
||||
/// A notification received at exactly `mach_ns` counts as before it. Only a notification that
|
||||
/// carries a state counts. [`StateAt::source`] names the one that was used, and how old it was is
|
||||
/// the difference between `mach_ns` and its `recv_mach_ns`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns a not-found error if no state was recorded before this moment (komorebi was not
|
||||
/// running, or had sent no notification yet and the recording has no starting state), and the
|
||||
/// errors of [`Analysis::snapshot`] if the state's file is missing or invalid.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::analysis::facade::StateSource;
|
||||
/// use komorebi_recorder::testkit::{SessionBuilder, mach_ns, state_with_windows};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-state-at")
|
||||
/// .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// // before the first notification there is nothing to say
|
||||
/// assert!(analysis.state_at(mach_ns(1.0)).is_err());
|
||||
///
|
||||
/// // after it, the state it carried, as of that event
|
||||
/// let found = analysis.state_at(mach_ns(3.5))?;
|
||||
/// assert_eq!(found.state_id, Some(1));
|
||||
/// assert_eq!(
|
||||
/// found.source,
|
||||
/// StateSource::Event { seq: 1, recv_mach_ns: mach_ns(2.0) },
|
||||
/// );
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
pub fn state_at(&self, mach_ns: u64) -> eyre::Result<StateAt> {
|
||||
let events = self.events();
|
||||
let latest = events
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|event| event.recv_mach_ns <= mach_ns && event.state_id.is_some());
|
||||
|
||||
if let Some(event) = latest {
|
||||
let state_id = event.state_id.unwrap_or_default();
|
||||
return Ok(StateAt {
|
||||
snapshot: self.snapshot(state_id)?,
|
||||
state_id: Some(state_id),
|
||||
source: StateSource::Event {
|
||||
seq: event.seq,
|
||||
recv_mach_ns: event.recv_mach_ns,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
self.start_snapshot()
|
||||
.map(|snapshot| StateAt {
|
||||
snapshot,
|
||||
state_id: None,
|
||||
source: StateSource::Start,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
envelope::not_found(
|
||||
"no state was recorded before this moment (komorebi was not running, or \
|
||||
had sent no notification yet)",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves any time argument a command takes: `12.5`, `1:02.5`, `wall:<RFC 3339>`,
|
||||
/// `mach:<ns>`, `event:<seq>`, `log:<line>`, `incident:<n>` or `bug:<id>`, each optionally
|
||||
/// followed by `.start` or `.end` and an offset such as `+3s`. The forms are those of
|
||||
/// `analysis::timespec`.
|
||||
///
|
||||
/// Resolving never guesses: a name that is not there is an error. An annotation without an end
|
||||
/// ends when the recording did. An event's start is when its handler began, where the log
|
||||
/// says (see the `Lookup` implementation below), and its end is when its notification was
|
||||
/// received.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns a usage error if the text is empty or is not one of those forms. Returns a
|
||||
/// not-found error if it names an event, log line, incident or annotation the session does not
|
||||
/// have (a log line without a time included), and an unusable error for a `wall:` time when the
|
||||
/// session has no clock anchors.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::testkit::{SessionBuilder, mach_ns};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-resolve")
|
||||
/// .event(2.0, json!({"type": "Retile"}), None)
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// assert_eq!(analysis.resolve("2.5")?.video_s, 2.5);
|
||||
/// assert_eq!(analysis.resolve("event:1.end+1s")?.video_s, 3.0);
|
||||
/// assert_eq!(analysis.resolve("event:1.end")?.mach_ns, mach_ns(2.0));
|
||||
///
|
||||
/// let error = analysis.resolve("event:2").unwrap_err();
|
||||
/// assert_eq!(error.to_string(), "there is no event #2");
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
pub fn resolve(&self, text: &str) -> eyre::Result<Resolved> {
|
||||
text.parse::<TimeSpec>()?.resolve(&self.manifest, self)
|
||||
}
|
||||
|
||||
/// Returns `mach_ns` (nanoseconds on the host's master monotonic clock) as seconds of video
|
||||
/// time: negative before the first frame of the recording.
|
||||
#[must_use]
|
||||
pub fn video_s(&self, mach_ns: u64) -> f64 {
|
||||
self.manifest.video_seconds(mach_ns)
|
||||
}
|
||||
|
||||
/// Returns `mach_ns` as a UTC time in RFC 3339 form with microseconds, or `None` if the session
|
||||
/// has no clock anchors to convert with.
|
||||
#[must_use]
|
||||
pub fn wall_utc(&self, mach_ns: u64) -> Option<String> {
|
||||
self.clock
|
||||
.mach_to_wall(mach_ns)
|
||||
.and_then(timeline::format_wall_us)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves the names a `TimeSpec` can use against the files of the session.
|
||||
///
|
||||
/// | Name | Resolves to |
|
||||
/// |---|---|
|
||||
/// | `event:<seq>` or `.start` | when the event's handler began, from the log; the time the event was received if the log has no block for it. It is clamped to no earlier than the previous event's receipt and (where there is room) before this one's, so that the state at the start is exactly the state the previous event left |
|
||||
/// | `event:<seq>.end` | when the notification was received, which is when the handler finished |
|
||||
/// | `log:<line>` | the line's timestamp (lines are counted from 1) |
|
||||
/// | `incident:<n>` | the `n`th line of `incidents.jsonl` (counted from 1) |
|
||||
/// | `bug:<id>`, `.start`, `.end` | the annotation's start or end; an open region ends when the recording did |
|
||||
///
|
||||
/// Each of them that names something the session lacks is a not-found error. Annotations are read
|
||||
/// from the file each time.
|
||||
impl Lookup for Analysis {
|
||||
fn event_mach_ns(&self, seq: u64, edge: Edge) -> eyre::Result<u64> {
|
||||
let index = self
|
||||
.event_index(seq)
|
||||
.ok_or_else(|| envelope::not_found(format!("there is no event #{seq}")))?;
|
||||
let event = &self.events()[index];
|
||||
|
||||
if edge == Edge::End {
|
||||
return Ok(event.recv_mach_ns);
|
||||
}
|
||||
|
||||
// The start of an event is when its handler began, where the log says. It is clamped to
|
||||
// after the previous notification and before this one, so that the state at the start is
|
||||
// exactly the state the previous event left and never already includes this event.
|
||||
let began = self
|
||||
.pairing()
|
||||
.pairs
|
||||
.get(index)
|
||||
.and_then(|pair| pair.block)
|
||||
.and_then(|id| self.log().blocks.get(id))
|
||||
.map_or(event.recv_mach_ns, |block| block.header_mach_ns);
|
||||
let previous = index
|
||||
.checked_sub(1)
|
||||
.map_or(0, |before| self.events()[before].recv_mach_ns);
|
||||
Ok(began
|
||||
.min(event.recv_mach_ns.saturating_sub(1))
|
||||
.max(previous))
|
||||
}
|
||||
|
||||
fn log_mach_ns(&self, line: u64) -> eyre::Result<u64> {
|
||||
let log = self.log();
|
||||
let parsed = usize::try_from(line.saturating_sub(1))
|
||||
.ok()
|
||||
.filter(|_| line >= 1)
|
||||
.and_then(|index| log.lines.get(index))
|
||||
.ok_or_else(|| {
|
||||
envelope::not_found(format!(
|
||||
"komorebi.log has {} lines; there is no line {line}",
|
||||
log.lines.len()
|
||||
))
|
||||
})?;
|
||||
|
||||
parsed
|
||||
.wall_us
|
||||
.and_then(|wall_us| self.clock.wall_to_mach(wall_us))
|
||||
.ok_or_else(|| envelope::not_found(format!("log line {line} has no time")))
|
||||
}
|
||||
|
||||
fn incident_mach_ns(&self, number: u64) -> eyre::Result<u64> {
|
||||
let text = std::fs::read_to_string(self.session.path(INCIDENTS_FILE))
|
||||
.map_err(|_| envelope::not_found("the session recorded no incidents"))?;
|
||||
usize::try_from(number.saturating_sub(1))
|
||||
.ok()
|
||||
.filter(|_| number >= 1)
|
||||
.and_then(|index| text.lines().nth(index))
|
||||
.and_then(|line| serde_json::from_str::<Incident>(line).ok())
|
||||
.map(|incident| incident.mach_ns)
|
||||
.ok_or_else(|| envelope::not_found(format!("there is no incident {number}")))
|
||||
}
|
||||
|
||||
fn annotation_span(&self, id: &str) -> eyre::Result<(u64, Option<u64>)> {
|
||||
let loaded = annotations::load(&self.session.dir)?;
|
||||
loaded
|
||||
.get(id)
|
||||
.map(|annotation| (annotation.start_mach_ns, annotation.end_mach_ns))
|
||||
.ok_or_else(|| envelope::not_found(format!("there is no annotation {id}")))
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ use super::Flavor;
|
||||
use super::Rules;
|
||||
use crate::analysis::blocks::Block;
|
||||
use crate::analysis::blocks::BlockKind;
|
||||
use crate::analysis::catalog::Role;
|
||||
use crate::analysis::classify::Class;
|
||||
use crate::analysis::events::EventInfo;
|
||||
use crate::analysis::events::EventRecord;
|
||||
@@ -259,11 +260,125 @@ impl Rules for MacRules {
|
||||
kind == BlockKind::Command && line.message.starts_with(COMMAND_FINISHED)
|
||||
}
|
||||
|
||||
fn role(&self, target: &str) -> Role {
|
||||
crate::analysis::catalog::role_in(ROLES, target)
|
||||
}
|
||||
|
||||
fn slow_handler_cause(&self) -> &'static str {
|
||||
"slow accessibility calls into other applications, or waiting for the lock another handler held"
|
||||
}
|
||||
}
|
||||
|
||||
/// The modules of komorebi for Mac and what each does, for [`Rules::role`].
|
||||
///
|
||||
/// Each entry is `(module, summary, changes_state_silently)`: the module path that appears as a log
|
||||
/// line's target, a sentence about what the part does, and whether it changes komorebi's state
|
||||
/// without sending a subscriber notification (the reaper and the workspace reconciliator do). A
|
||||
/// target is matched to the entry with the longest module that is a prefix of it, so
|
||||
/// `komorebi::accessibility::error` finds `komorebi::accessibility`.
|
||||
pub const ROLES: &[(&str, &str, bool)] = &[
|
||||
(
|
||||
"komorebi::process_event",
|
||||
"handles events from the OS one at a time under the window-manager lock; the subscriber notification is sent after the handler body",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::process_command",
|
||||
"handles commands from komorebic or a hotkey daemon one at a time under the lock; notifies subscribers before it logs 'processed command'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::window_manager",
|
||||
"window-manager operations, called from the handlers",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::workspace",
|
||||
"operations on a workspace's containers: layout, focus, adding and removing",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::container",
|
||||
"operations on a container and its tabbed windows",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::monitor",
|
||||
"operations on a monitor and its workspaces",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::window",
|
||||
"operations on one window, through the accessibility API",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::macos_api",
|
||||
"calls into macOS; an AXError comes from the target application or the OS, not from komorebi",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::accessibility",
|
||||
"calls into the macOS accessibility API; an AXError comes from the target application or the OS",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::application",
|
||||
"per-application accessibility observers",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::border_manager",
|
||||
"draws window borders on its own thread; cosmetic, never changes the layout state",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::reaper",
|
||||
"background thread that removes windows that no longer exist; it takes the lock and changes state without sending a notification",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"komorebi::workspace_reconciliator",
|
||||
"background thread that moves windows between workspaces after a space change; it takes the lock and changes state without sending a notification",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"komorebi::monitor_reconciliator",
|
||||
"background thread that reacts to displays connecting, disconnecting and resizing; it sends a monitor notification when done",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::display_reconfiguration_listener",
|
||||
"macOS callback for display changes, feeding the monitor reconciliator",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::static_config",
|
||||
"loads and applies komorebi.json",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::theme_manager",
|
||||
"applies border and bar themes",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::input_event_listener",
|
||||
"watches the mouse and keyboard for the hacks that need them",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::window_manager_event_listener",
|
||||
"receives OS notifications and queues them for the event handler",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::notification_center_listener",
|
||||
"receives macOS workspace notifications (app activation, space change, screen lock)",
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -334,4 +449,18 @@ mod tests {
|
||||
assert_eq!(describe(&json!({"a": 1, "b": 2})).family, Family::Unknown);
|
||||
assert_eq!(describe(&json!({"type": 3})).family, Family::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_are_found_by_the_longest_module_prefix() {
|
||||
let role = |target: &str| MacRules.role(target);
|
||||
assert!(role("komorebi::reaper").changes_state_silently);
|
||||
assert!(role("komorebi::workspace_reconciliator").changes_state_silently);
|
||||
assert!(!role("komorebi::process_event").changes_state_silently);
|
||||
assert!(
|
||||
role("komorebi::accessibility::error")
|
||||
.summary
|
||||
.contains("accessibility")
|
||||
);
|
||||
assert_eq!(role("komorebi::brand_new").summary, "komorebi internals");
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,7 @@
|
||||
//! | [`is_hidden_position`](Rules::is_hidden_position) | whether a rect is where a hidden window is parked | `Snapshot::is_hidden_position` | a one-point sliver inside the display | never |
|
||||
//! | [`block_header`](Rules::block_header) | whether a log line starts a handler's block | `blocks::build` | the `processing event:` and `processing command:` lines | the first line of a `process_event{...}` or `process_command{...}` span whose fields differ from the open block's |
|
||||
//! | [`is_block_end`](Rules::is_block_end) | whether a log line ends a handler's block | `blocks::build` | `processed command: ...`, for commands only | `processed: ...` for events, `processed` for commands |
|
||||
//! | [`role`](Rules::role) | what the part of komorebi that logged a line does | the `code` and `trace` answers | `mac::ROLES` | `windows::ROLES` |
|
||||
//! | [`slow_handler_cause`](Rules::slow_handler_cause) | what a slow handler was probably doing | the `overview` and `trace` answers | accessibility calls | Win32 calls |
|
||||
//! | [`verified`](Rules::verified) | whether the rules were checked against a recording | `Analysis::warnings` | the default: yes | no |
|
||||
//! | [`flavor`](Rules::flavor) | which flavor the rules are for | tests | [`Flavor::Macos`] | [`Flavor::Windows`] |
|
||||
@@ -83,6 +84,9 @@
|
||||
//! [`window_is_unreadable`](Rules::window_is_unreadable) for every window. The snapshot keeps
|
||||
//! its flavor for [`hides_windows_by_position`](Rules::hides_windows_by_position) and
|
||||
//! `is_hidden_position`.
|
||||
//! 1. Answers that explain a log line or a slow handler ask `role` and
|
||||
//! [`slow_handler_cause`](Rules::slow_handler_cause). `Analysis::warnings` asks
|
||||
//! [`verified`](Rules::verified).
|
||||
//!
|
||||
//! [`MacRules`]: mac::MacRules
|
||||
//! [`WindowsRules`]: windows::WindowsRules
|
||||
@@ -95,6 +99,7 @@ pub mod windows;
|
||||
|
||||
use super::blocks::Block;
|
||||
use super::blocks::BlockKind;
|
||||
use super::catalog::Role;
|
||||
use super::classify::Class;
|
||||
use super::events::EventInfo;
|
||||
use super::events::EventRecord;
|
||||
@@ -342,6 +347,7 @@ pub struct BlockHeader {
|
||||
///
|
||||
/// ```rust
|
||||
/// # use komorebi_recorder::analysis::blocks::{Block, BlockKind};
|
||||
/// # use komorebi_recorder::analysis::catalog::Role;
|
||||
/// # use komorebi_recorder::analysis::classify::Class;
|
||||
/// # use komorebi_recorder::analysis::events::{EventInfo, EventRecord};
|
||||
/// # use komorebi_recorder::analysis::flavor::mac::MacRules;
|
||||
@@ -370,6 +376,7 @@ pub struct BlockHeader {
|
||||
/// fn is_block_end(&self, line: &Line, kind: BlockKind) -> bool {
|
||||
/// MacRules.is_block_end(line, kind)
|
||||
/// }
|
||||
/// fn role(&self, target: &str) -> Role { MacRules.role(target) }
|
||||
/// fn slow_handler_cause(&self) -> &'static str { MacRules.slow_handler_cause() }
|
||||
/// }
|
||||
///
|
||||
@@ -388,6 +395,7 @@ pub struct BlockHeader {
|
||||
///
|
||||
/// ```rust,compile_fail,E0046
|
||||
/// # use komorebi_recorder::analysis::blocks::{Block, BlockKind};
|
||||
/// # use komorebi_recorder::analysis::catalog::Role;
|
||||
/// # use komorebi_recorder::analysis::classify::Class;
|
||||
/// # use komorebi_recorder::analysis::events::{EventInfo, EventRecord};
|
||||
/// # use komorebi_recorder::analysis::flavor::mac::MacRules;
|
||||
@@ -416,6 +424,7 @@ pub struct BlockHeader {
|
||||
/// fn is_block_end(&self, line: &Line, kind: BlockKind) -> bool {
|
||||
/// MacRules.is_block_end(line, kind)
|
||||
/// }
|
||||
/// fn role(&self, target: &str) -> Role { MacRules.role(target) }
|
||||
/// // no `slow_handler_cause`
|
||||
/// }
|
||||
/// ```
|
||||
@@ -560,6 +569,13 @@ pub trait Rules: Sync {
|
||||
/// ones) and `processed` for a command.
|
||||
fn is_block_end(&self, line: &Line, kind: BlockKind) -> bool;
|
||||
|
||||
/// Returns what the part of komorebi that logs from `target` does.
|
||||
///
|
||||
/// `target` is the module that logged, e.g. `komorebi::container`. The answer is for the
|
||||
/// longest module prefix in the flavor's table, which is `ROLES` in [`mac`] or [`windows`],
|
||||
/// and for a target with no such prefix the answer is `komorebi internals`.
|
||||
fn role(&self, target: &str) -> Role;
|
||||
|
||||
/// Returns what a handler that took long was most likely doing, as a phrase that completes a
|
||||
/// sentence such as "took at least 250 ms to handle: ...".
|
||||
///
|
||||
|
||||
@@ -30,6 +30,7 @@ use super::Flavor;
|
||||
use super::Rules;
|
||||
use crate::analysis::blocks::Block;
|
||||
use crate::analysis::blocks::BlockKind;
|
||||
use crate::analysis::catalog::Role;
|
||||
use crate::analysis::classify::Class;
|
||||
use crate::analysis::events::EventInfo;
|
||||
use crate::analysis::events::EventRecord;
|
||||
@@ -311,11 +312,126 @@ impl Rules for WindowsRules {
|
||||
}
|
||||
}
|
||||
|
||||
fn role(&self, target: &str) -> Role {
|
||||
crate::analysis::catalog::role_in(ROLES, target)
|
||||
}
|
||||
|
||||
fn slow_handler_cause(&self) -> &'static str {
|
||||
"slow Win32 calls into other programs' windows (positioning one that is busy or hung, or an animation), or waiting for the lock another handler held"
|
||||
}
|
||||
}
|
||||
|
||||
/// The modules of komorebi for Windows and what each does, for [`Rules::role`].
|
||||
///
|
||||
/// Each entry is `(module, summary, changes_state_silently)`: the module path that appears as a log
|
||||
/// line's target, a sentence about what the part does, and whether it changes komorebi's state
|
||||
/// without sending a subscriber notification. No part of komorebi for Windows does: its reaper
|
||||
/// sends a synthetic `Destroy`. A target is matched to the entry with the longest module that is a
|
||||
/// prefix of it, so `komorebi::windows_api::error` finds `komorebi::windows_api`.
|
||||
pub const ROLES: &[(&str, &str, bool)] = &[
|
||||
(
|
||||
"komorebi::process_event",
|
||||
"handles events from the OS one at a time under the window-manager lock; the subscriber notification is sent after the handler body, just before it logs 'processed'",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::process_command",
|
||||
"handles commands from komorebic or a hotkey daemon one at a time under the lock",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::window_manager",
|
||||
"window-manager operations, called from the handlers",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::workspace",
|
||||
"operations on a workspace's containers: layout, focus, adding and removing",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::container",
|
||||
"operations on a container and its stacked windows",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::monitor",
|
||||
"operations on a monitor and its workspaces",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::window",
|
||||
"operations on one window, through the Win32 API",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::windows_api",
|
||||
"calls into Win32; an error comes from the target window or the OS, not from komorebi",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::set_window_position",
|
||||
"moving and sizing a window, possibly animated",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::process_movement",
|
||||
"reacts to a window being dragged with the mouse",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::winevent_listener",
|
||||
"a hook that receives WinEvents from the OS and queues them for the event handler",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::windows_callbacks",
|
||||
"callbacks Windows calls with window and display events",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::reaper",
|
||||
"background thread that removes windows that no longer exist; it takes the lock and sends a synthetic Destroy notification when it does",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::monitor_reconciliator",
|
||||
"a hidden window that hears of display, power and session changes (WM_DISPLAYCHANGE, suspend, lock) and reconciles komorebi's monitors with them, sending a monitor notification",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::border_manager",
|
||||
"draws window borders on its own thread; cosmetic, never changes the layout state",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::focus_manager",
|
||||
"keeps the focus where komorebi wants it on its own thread",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::transparency_manager",
|
||||
"applies transparency to unfocused windows; cosmetic",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::stackbar_manager",
|
||||
"draws the tab bars of stacked windows; cosmetic",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::static_config",
|
||||
"loads and applies komorebi.json",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"komorebi::theme_manager",
|
||||
"applies border and bar themes",
|
||||
false,
|
||||
),
|
||||
("komorebi::animation", "animates window movement", false),
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -424,4 +540,23 @@ mod tests {
|
||||
assert!(!WindowsRules.window_is_unreadable(&window(1, "a.exe")));
|
||||
assert!(!WindowsRules.hides_windows_by_position());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roles_are_found_and_the_reaper_notifies() {
|
||||
let reaper = WindowsRules.role("komorebi::reaper");
|
||||
assert!(
|
||||
!reaper.changes_state_silently,
|
||||
"the Windows reaper sends a Destroy"
|
||||
);
|
||||
assert!(
|
||||
WindowsRules
|
||||
.role("komorebi::windows_api::error")
|
||||
.summary
|
||||
.contains("Win32")
|
||||
);
|
||||
assert_eq!(
|
||||
WindowsRules.role("komorebi::brand_new").summary,
|
||||
"komorebi internals"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
//! One window's life through a recording: when it appeared, where komorebi put it, when it was
|
||||
//! parked off screen or moved, and which event did each.
|
||||
//!
|
||||
//! Most bugs are about one window ("my terminal ended up behind the dock"), and the state at any
|
||||
//! moment is dozens of windows. [`Analysis::window_history`] follows the windows that match a query
|
||||
//! through every recorded state and reports each moment something about them changed, with the
|
||||
//! event it came with. The `window` command prints it.
|
||||
//!
|
||||
//! # What is reported
|
||||
//!
|
||||
//! The recorded states are read in event order, and an event makes an entry for a window if:
|
||||
//!
|
||||
//! - the window **appeared** in the state, or **went away** from it;
|
||||
//! - it **moved**: its monitor, its workspace or its kind of place (container, monocle, maximized,
|
||||
//! floating) differs from the last state it was in. A change of container index or tab within
|
||||
//! the same kind of place is not a move;
|
||||
//! - its workspace **came into view** or **went out of view**;
|
||||
//! - it was **parked off screen** in komorebi's hiding position, or **brought back**;
|
||||
//! - its **rect** is really somewhere else: more than 2 points off in left, top, width or height,
|
||||
//! while it was not parked or brought back by the same event; or
|
||||
//! - the event is **about the window** (it names the window's id) and the window is in the
|
||||
//! state, even if nothing about the window changed.
|
||||
//!
|
||||
//! An event whose notification carried no state is skipped, since there is nothing to compare.
|
||||
//! A window is followed only through the states in which it matches the query, so a window whose
|
||||
//! title changes to something the query no longer matches is reported as having gone away.
|
||||
//!
|
||||
//! # Flavor
|
||||
//!
|
||||
//! Whether a window is parked is decided by the rules of the flavor that recorded the session
|
||||
//! ([`Snapshot::is_hidden_position`]). komorebi for Mac parks a hidden window in a corner of its
|
||||
//! monitor. komorebi for Windows cloaks it in place, so for a Windows session the history has no
|
||||
//! "parked off screen" or "brought back" entries and every [`HistoryEntry::hidden`] is `false`.
|
||||
|
||||
use super::Analysis;
|
||||
use super::classify::Class;
|
||||
use super::envelope;
|
||||
use super::state::Location;
|
||||
use super::state::Place;
|
||||
use super::state::Rect;
|
||||
use super::state::Snapshot;
|
||||
use super::state::Window;
|
||||
use color_eyre::eyre;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The schema name that identifies a [`HistoryData`] in an envelope (`window/1`); listed by the
|
||||
/// `schema` command.
|
||||
pub const SCHEMA_WINDOW: &str = "window/1";
|
||||
|
||||
/// A window rect that moved by no more than this is not reported as having moved.
|
||||
const RECT_TOLERANCE: i64 = 2;
|
||||
|
||||
/// A window that a query matched, named as it was the first time it matched.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
|
||||
pub struct TrackedWindow {
|
||||
/// The window's id in komorebi's state: a window id on a Mac, a window handle on Windows.
|
||||
pub id: u64,
|
||||
/// The program the window belongs to, as komorebi names it.
|
||||
pub exe: String,
|
||||
/// The window's title in the first state it matched in. A title can change later.
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
/// One moment in a window's life: something about it changed, or an event was about it.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct HistoryEntry {
|
||||
/// The id of the window the entry is about.
|
||||
pub window_id: u64,
|
||||
/// The event whose notification carried this state.
|
||||
pub seq: u64,
|
||||
/// When the notification was received, in seconds of video time. An event is received when its
|
||||
/// handler has finished.
|
||||
pub video_s: f64,
|
||||
/// When the notification was received, in nanoseconds on the host's master monotonic clock.
|
||||
pub mach_ns: u64,
|
||||
/// A line saying what the event was, such as `MoveEnd pid 20934 AXWindowMoved`.
|
||||
pub event: String,
|
||||
/// The kind of event, as the analysis classified it.
|
||||
pub class: Class,
|
||||
/// Where the window was after this event; `None` if it was gone.
|
||||
pub location: Option<Location>,
|
||||
/// Where it really was on screen after this event.
|
||||
pub rect: Option<Rect>,
|
||||
/// Whether the window is parked in komorebi's hiding position (see
|
||||
/// [`Snapshot::is_hidden_position`]). Always `false` for a session recorded from komorebi for
|
||||
/// Windows, which hides a window without moving it.
|
||||
pub hidden: bool,
|
||||
/// How the window changed since the last state it was in, in words. Empty when the entry is
|
||||
/// only there because the event was about the window.
|
||||
pub changes: Vec<String>,
|
||||
/// This event was *about* the window (it names its id), not just a bystander.
|
||||
pub about_window: bool,
|
||||
}
|
||||
|
||||
/// The life of the windows a query matched: the `data` of the `window` command.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct HistoryData {
|
||||
/// The query, as given.
|
||||
pub query: String,
|
||||
/// Every window the query matched in any recorded state, ordered by window id.
|
||||
pub windows: Vec<TrackedWindow>,
|
||||
/// The entries for events after the cursor, in event order and, within an event, in window id
|
||||
/// order. At most the `limit` asked for.
|
||||
pub entries: Vec<HistoryEntry>,
|
||||
/// How many entries there are after the cursor, including any not returned.
|
||||
pub matching: usize,
|
||||
}
|
||||
|
||||
/// What about a window is worth noticing when it changes.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Seen {
|
||||
monitor_id: u64,
|
||||
workspace: String,
|
||||
kind: &'static str,
|
||||
visible: bool,
|
||||
rect: Option<Rect>,
|
||||
hidden: bool,
|
||||
location: Location,
|
||||
}
|
||||
|
||||
fn kind_of(place: &Place) -> &'static str {
|
||||
match place {
|
||||
Place::Container { .. } => "container",
|
||||
Place::Monocle { .. } => "monocle",
|
||||
Place::Maximized => "maximized",
|
||||
Place::Floating { .. } => "floating",
|
||||
}
|
||||
}
|
||||
|
||||
fn seen(snapshot: &Snapshot, location: Location, window: &Window) -> Seen {
|
||||
let hidden = window.rect.as_ref().is_some_and(|rect| {
|
||||
snapshot
|
||||
.monitors
|
||||
.iter()
|
||||
.find(|monitor| monitor.id == location.monitor_id)
|
||||
.is_some_and(|monitor| snapshot.is_hidden_position(rect, monitor))
|
||||
});
|
||||
Seen {
|
||||
monitor_id: location.monitor_id,
|
||||
workspace: location.workspace.clone(),
|
||||
kind: kind_of(&location.place),
|
||||
visible: location.workspace_visible,
|
||||
rect: window.rect,
|
||||
hidden,
|
||||
location,
|
||||
}
|
||||
}
|
||||
|
||||
fn matches(query: &str, window: &Window) -> bool {
|
||||
if let Ok(id) = query.parse::<u64>()
|
||||
&& window.id == id
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let needle = query.to_lowercase();
|
||||
window.exe.to_lowercase().contains(&needle) || window.title.to_lowercase().contains(&needle)
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Returns the history of the windows matching `query`, for events after `after_seq`, at most
|
||||
/// `limit` entries.
|
||||
///
|
||||
/// `query` is a window id or text. A window matches if its id is the number `query` spells, or
|
||||
/// if `query`, compared case-insensitively, is part of the window's program or title. A number
|
||||
/// therefore matches windows whose title contains it as well as the window with that id.
|
||||
///
|
||||
/// `after_seq` is a cursor: only entries for events whose `seq` is greater are counted and
|
||||
/// returned, so a caller pages by passing the last `seq` it has. With `limit` set, entries
|
||||
/// stop being returned after that many, but [`HistoryData::matching`] still counts all of them.
|
||||
/// All the windows the query matched are in [`HistoryData::windows`] whatever the cursor.
|
||||
/// What an entry means is described in the [module](self) documentation.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if:
|
||||
///
|
||||
/// - no window matching `query` appears in any recorded state (the not-found exit kind). An
|
||||
/// empty `entries`, because the cursor is past the last change, is not an error;
|
||||
/// - a state that an event refers to cannot be read: the file is missing (not found) or is not
|
||||
/// valid JSON.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
/// use komorebi_recorder::testkit::state_with_windows;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// // Ghostty fills the screen, then Safari is opened beside it and Ghostty is squeezed.
|
||||
/// let (session, _) = SessionBuilder::new("doc-window-history")
|
||||
/// .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(1, "Ghostty")])))
|
||||
/// .event(
|
||||
/// 3.0,
|
||||
/// json!({"type": "Retile"}),
|
||||
/// Some(state_with_windows(&[(1, "Ghostty"), (2, "Safari")])),
|
||||
/// )
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// let history = analysis.window_history("ghostty", None, None)?;
|
||||
/// assert_eq!(history.windows.len(), 1);
|
||||
/// assert_eq!(history.windows[0].id, 1);
|
||||
/// assert_eq!(history.entries.len(), 2);
|
||||
/// assert_eq!(
|
||||
/// history.entries[0].changes,
|
||||
/// ["appeared on monitor 1 workspace one (container 0)"]
|
||||
/// );
|
||||
/// assert_eq!(
|
||||
/// history.entries[1].changes,
|
||||
/// ["really at 500x800 at (0, 0) instead of 1000x800 at (0, 0)"]
|
||||
/// );
|
||||
///
|
||||
/// // paging: only what came after event 1
|
||||
/// let rest = analysis.window_history("ghostty", Some(1), None)?;
|
||||
/// assert_eq!(rest.entries.len(), 1);
|
||||
/// assert_eq!(rest.matching, 1);
|
||||
///
|
||||
/// // a query nothing matches is an error, not an empty history
|
||||
/// assert!(analysis.window_history("no such window", None, None).is_err());
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
///
|
||||
/// Also covered by `tests/trace.rs::a_window_is_followed_through_every_state` and
|
||||
/// `tests/trace.rs::window_history_pages_with_a_cursor`.
|
||||
pub fn window_history(
|
||||
&self,
|
||||
query: &str,
|
||||
after_seq: Option<u64>,
|
||||
limit: Option<usize>,
|
||||
) -> eyre::Result<HistoryData> {
|
||||
let mut tracked: BTreeMap<u64, TrackedWindow> = BTreeMap::new();
|
||||
let mut last: BTreeMap<u64, Option<Seen>> = BTreeMap::new();
|
||||
let mut entries: Vec<HistoryEntry> = Vec::new();
|
||||
let mut matching = 0_usize;
|
||||
|
||||
let mut previous_state_id: Option<u64> = None;
|
||||
let mut previous_snapshot: Option<std::sync::Arc<Snapshot>> = None;
|
||||
|
||||
for (index, event) in self.events().iter().enumerate() {
|
||||
let Some(state_id) = event.state_id else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// an unchanged state cannot have changed a window, but the event may be about it
|
||||
let snapshot = if previous_state_id == Some(state_id) {
|
||||
previous_snapshot.clone().ok_or_else(|| {
|
||||
eyre::Report::msg("internal error: repeated state without a snapshot")
|
||||
})?
|
||||
} else {
|
||||
self.snapshot(state_id)?
|
||||
};
|
||||
previous_state_id = Some(state_id);
|
||||
previous_snapshot = Some(snapshot.clone());
|
||||
|
||||
let class = self.pairing().classes[index].class;
|
||||
let here: BTreeMap<u64, (Location, &Window)> = snapshot
|
||||
.windows()
|
||||
.into_iter()
|
||||
.filter(|(_, window)| matches(query, window))
|
||||
.fold(BTreeMap::new(), |mut found, (location, window)| {
|
||||
found.entry(window.id).or_insert((location, window));
|
||||
found
|
||||
});
|
||||
|
||||
for (id, (_, window)) in &here {
|
||||
tracked.entry(*id).or_insert_with(|| TrackedWindow {
|
||||
id: *id,
|
||||
exe: window.exe.clone(),
|
||||
title: window.title.clone(),
|
||||
});
|
||||
last.entry(*id).or_insert(None);
|
||||
}
|
||||
|
||||
let about = |id: u64| {
|
||||
event
|
||||
.info
|
||||
.window_id
|
||||
.is_some_and(|window| u64::from(window) == id)
|
||||
};
|
||||
let ids: Vec<u64> = last.keys().copied().collect();
|
||||
for id in ids {
|
||||
let now = here
|
||||
.get(&id)
|
||||
.map(|(location, window)| seen(&snapshot, location.clone(), window));
|
||||
let before = last.get(&id).cloned().flatten();
|
||||
|
||||
let mut changes = Vec::new();
|
||||
match (&before, &now) {
|
||||
(None, Some(now)) => {
|
||||
changes.push(format!("appeared on {}", now.location.describe()))
|
||||
}
|
||||
(Some(_), None) => changes.push("went away".to_string()),
|
||||
(Some(was), Some(now)) => {
|
||||
if (was.monitor_id, &was.workspace, was.kind)
|
||||
!= (now.monitor_id, &now.workspace, now.kind)
|
||||
{
|
||||
changes.push(format!(
|
||||
"moved from {} to {}",
|
||||
was.location.describe(),
|
||||
now.location.describe()
|
||||
));
|
||||
}
|
||||
if was.visible != now.visible {
|
||||
changes.push(
|
||||
if now.visible {
|
||||
"its workspace came into view"
|
||||
} else {
|
||||
"its workspace went out of view"
|
||||
}
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if was.hidden != now.hidden {
|
||||
changes.push(
|
||||
if now.hidden {
|
||||
"parked off screen in komorebi's hiding position"
|
||||
} else {
|
||||
"brought back on screen"
|
||||
}
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if let (Some(from), Some(to)) = (&was.rect, &now.rect)
|
||||
&& from.max_delta(to) > RECT_TOLERANCE
|
||||
&& was.hidden == now.hidden
|
||||
{
|
||||
changes.push(format!(
|
||||
"really at {} instead of {}",
|
||||
to.describe(),
|
||||
from.describe()
|
||||
));
|
||||
}
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
|
||||
let relevant = !changes.is_empty() || (about(id) && now.is_some());
|
||||
if relevant && after_seq.is_none_or(|after| event.seq > after) {
|
||||
matching += 1;
|
||||
if limit.is_none_or(|limit| entries.len() < limit) {
|
||||
entries.push(HistoryEntry {
|
||||
window_id: id,
|
||||
seq: event.seq,
|
||||
video_s: self.video_s(event.recv_mach_ns),
|
||||
mach_ns: event.recv_mach_ns,
|
||||
event: event.info.summary(),
|
||||
class,
|
||||
location: now.as_ref().map(|seen| seen.location.clone()),
|
||||
rect: now.as_ref().and_then(|seen| seen.rect),
|
||||
hidden: now.as_ref().is_some_and(|seen| seen.hidden),
|
||||
changes,
|
||||
about_window: about(id),
|
||||
});
|
||||
}
|
||||
}
|
||||
last.insert(id, now);
|
||||
}
|
||||
}
|
||||
|
||||
if tracked.is_empty() {
|
||||
return Err(envelope::not_found(format!(
|
||||
"no window matching '{query}' appears in any recorded state"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(HistoryData {
|
||||
query: query.to_string(),
|
||||
windows: tracked.into_values().collect(),
|
||||
entries,
|
||||
matching,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,21 @@
|
||||
//! file access inside the session ([`guard`]).
|
||||
|
||||
pub mod blocks;
|
||||
pub mod catalog;
|
||||
pub mod classify;
|
||||
pub mod code;
|
||||
pub mod diff;
|
||||
pub mod envelope;
|
||||
pub mod events;
|
||||
pub mod facade;
|
||||
pub mod flavor;
|
||||
pub mod guard;
|
||||
pub mod history;
|
||||
pub mod ids;
|
||||
pub mod logparse;
|
||||
pub mod lookup;
|
||||
pub mod state;
|
||||
pub mod timespec;
|
||||
pub mod views;
|
||||
|
||||
pub use facade::Analysis;
|
||||
@@ -0,0 +1,226 @@
|
||||
//! Answers shaped for a reader: what the commands print as JSON and the viewer draws.
|
||||
//!
|
||||
//! The analysis keeps what it reads in the forms that are convenient to compute with (an
|
||||
//! [`EventRecord`](super::events::EventRecord), a handler block, a state snapshot). This module has
|
||||
//! the shapes of the pieces that more than one answer shows, and the methods of [`Analysis`] that
|
||||
//! build them: an event with its class and handler ([`EventView`], [`HandlerView`]), a moment on
|
||||
//! every clock ([`Moment`]), and where a shown state came from ([`StateOrigin`]). The shapes
|
||||
//! serialize to JSON and have JSON Schemas; the `schemas` module names the answers they are part
|
||||
//! of.
|
||||
//!
|
||||
//! Times in these shapes are in the units a reader thinks in: seconds on the video timeline
|
||||
//! (`*_video_s`, `video_s`), milliseconds for durations, and UTC wall time as text. The master
|
||||
//! clock (`mach_ns`, nanoseconds on the host's master monotonic clock; `mach_` is a historical
|
||||
//! spelling) is given as well, for passing back as a time argument.
|
||||
|
||||
use super::blocks::Quality;
|
||||
use super::classify::Class;
|
||||
use super::events::EventInfo;
|
||||
use super::facade::Analysis;
|
||||
use super::state::Snapshot;
|
||||
use crate::timecode;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Serialize;
|
||||
|
||||
/// The handler that produced an event, as far as the log shows.
|
||||
///
|
||||
/// A handler is the block of komorebi's log lines that carry one event's or command's span, from its
|
||||
/// header on. All its fields come from those lines, so they are only as good as the log level
|
||||
/// komorebi ran at: at the default `info` level there is little to see.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct HandlerView {
|
||||
/// How the event was tied to this handler (a `Quality`).
|
||||
pub quality: Quality,
|
||||
/// The number of the handler's header line in the session's `komorebi.log`, counting from 1.
|
||||
pub header_line: u64,
|
||||
/// The number of the last line the handler logged.
|
||||
pub last_line: u64,
|
||||
/// When the handler's header was logged, in video time.
|
||||
pub started_video_s: f64,
|
||||
/// At least how long the handler took, in milliseconds: header to the event being received.
|
||||
pub handler_ms: Option<f64>,
|
||||
/// How many log lines the handler logged, header included.
|
||||
pub lines: usize,
|
||||
/// How many of those lines are at level ERROR.
|
||||
pub errors: u32,
|
||||
/// How many of those lines are at level WARN.
|
||||
pub warnings: u32,
|
||||
}
|
||||
|
||||
/// One komorebi event as a reader sees it: what it was, when, what kind of event, whether it
|
||||
/// changed the state, and the handler that ran.
|
||||
///
|
||||
/// This is an element of the `events` answer and the event a `trace` is about. The fields of the
|
||||
/// event's [`EventInfo`] are flattened into it, so its JSON has `family`, `name`, `notification`,
|
||||
/// `pid`, `window_id`, `argument` (and `exe`, if there is one) beside the fields below. Built by
|
||||
/// [`Analysis::event_view`].
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct EventView {
|
||||
/// The event's sequence number in the session, counting from 1: what `event:<seq>` names.
|
||||
pub seq: u64,
|
||||
/// When the recorder received the notification, which is when the handler finished, in video
|
||||
/// time (seconds since the video's `t = 0`; negative before it).
|
||||
pub video_s: f64,
|
||||
/// The same moment as `video_s`, as nanoseconds on the host's master monotonic clock.
|
||||
pub mach_ns: u64,
|
||||
/// The same moment on the wall clock, as RFC 3339 UTC with microseconds
|
||||
/// (`2026-10-26T19:43:35.062613Z`). `None` if the session's clock anchors cannot place it.
|
||||
pub wall_utc: Option<String>,
|
||||
/// The notification, as the flavor's rules read it.
|
||||
#[serde(flatten)]
|
||||
pub info: EventInfo,
|
||||
/// [`EventInfo::summary`]: one line saying what the event is.
|
||||
pub summary: String,
|
||||
/// The kind of event it was.
|
||||
pub class: Class,
|
||||
/// Why it was given that class.
|
||||
pub reason: String,
|
||||
/// Whether this event changed komorebi's state: `Some(true)` if its state differs from the
|
||||
/// previous event's. `None` when either event has no recorded state, and for the first event.
|
||||
pub state_changed: Option<bool>,
|
||||
/// The id of the state snapshot taken after this event (`states/<id>.json`), if one was
|
||||
/// recorded.
|
||||
pub state_id: Option<u64>,
|
||||
/// The handler the log shows for this event, if one could be tied to it.
|
||||
pub handler: Option<HandlerView>,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Returns event number `index` of the session as a reader sees it, or `None` if there is no
|
||||
/// such event.
|
||||
///
|
||||
/// `index` counts from 0 over [`Analysis::events`], in the order the events were received. It
|
||||
/// is a position, not a sequence number: event `seq` is at [`Analysis::event_index`]. The
|
||||
/// handler is filled in when the log could be tied to the event (see [`Analysis::pairing`]).
|
||||
///
|
||||
/// Covered by `events_are_classified_and_paired_with_the_handler_that_ran` in
|
||||
/// `tests/investigate.rs`, which reads these views as the `events` command prints them.
|
||||
#[must_use]
|
||||
pub fn event_view(&self, index: usize) -> Option<EventView> {
|
||||
let event = self.events().get(index)?;
|
||||
let pairing = self.pairing();
|
||||
let classification = pairing.classes.get(index)?;
|
||||
let pair = pairing.pairs.get(index)?;
|
||||
let log = self.log();
|
||||
|
||||
let handler = pair
|
||||
.block
|
||||
.and_then(|id| log.blocks.get(id))
|
||||
.map(|block| HandlerView {
|
||||
quality: pair.quality,
|
||||
header_line: block.header_line,
|
||||
last_line: block.last_line,
|
||||
started_video_s: self.video_s(block.header_mach_ns),
|
||||
handler_ms: pair.handler_ms,
|
||||
lines: block.lines.len(),
|
||||
errors: block.errors,
|
||||
warnings: block.warnings,
|
||||
});
|
||||
|
||||
Some(EventView {
|
||||
seq: event.seq,
|
||||
video_s: self.video_s(event.recv_mach_ns),
|
||||
mach_ns: event.recv_mach_ns,
|
||||
wall_utc: self.wall_utc(event.recv_mach_ns),
|
||||
summary: event.info.summary(),
|
||||
info: event.info.clone(),
|
||||
class: classification.class,
|
||||
reason: classification.reason.clone(),
|
||||
state_changed: self.state_changed(index),
|
||||
state_id: event.state_id,
|
||||
handler,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A moment on every clock a reader might think in.
|
||||
///
|
||||
/// Every field names the same instant, and each can be given back to a command as a time:
|
||||
/// `video_s` or `timecode` as they are, `mach:<mach_ns>`, or `wall:<wall_utc>`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct Moment {
|
||||
/// Seconds since the video's `t = 0`; negative before it.
|
||||
pub video_s: f64,
|
||||
/// `video_s` as a timecode: `00:12.500`, or `1:02:03.250` from an hour on, with a leading `-`
|
||||
/// when negative (see [`crate::timecode::format`]).
|
||||
pub timecode: String,
|
||||
/// Nanoseconds on the host's master monotonic clock (`mach_` is a historical spelling).
|
||||
pub mach_ns: u64,
|
||||
/// The wall clock, as RFC 3339 UTC with microseconds. `None` if the session's clock anchors
|
||||
/// cannot place the moment.
|
||||
pub wall_utc: Option<String>,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Returns the moment `mach_ns` (nanoseconds on the master clock) on every clock a reader might
|
||||
/// think in.
|
||||
#[must_use]
|
||||
pub fn moment(&self, mach_ns: u64) -> Moment {
|
||||
let video_s = self.video_s(mach_ns);
|
||||
Moment {
|
||||
video_s,
|
||||
timecode: timecode::format(video_s),
|
||||
mach_ns,
|
||||
wall_utc: self.wall_utc(mach_ns),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a state shown to a reader came from.
|
||||
///
|
||||
/// A state is known only from the notifications komorebi sent, and the state recorded when the
|
||||
/// recording began, so a state "at" a moment is the latest one before it. This records which one,
|
||||
/// and how stale it may be.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
|
||||
pub struct StateOrigin {
|
||||
/// `event` (the notification of that event) or `start` (the state when recording began).
|
||||
pub source: String,
|
||||
/// The sequence number of the event whose notification carried the state; `None` for `start`.
|
||||
pub seq: Option<u64>,
|
||||
/// The id of the stored state (`states/<id>.json`); `None` for `start`.
|
||||
pub state_id: Option<u64>,
|
||||
/// How long before the asked-for moment the state was taken. komorebi can change state without
|
||||
/// sending a notification, so a large number means the state may be out of date.
|
||||
pub age_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// Returns a one-line description of a snapshot for headings: how many monitors and windows it has,
|
||||
/// such as `2 monitors, 17 windows`.
|
||||
///
|
||||
/// The words are singular for exactly one (`1 monitor, 1 window`), and plural otherwise, 0 included.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::flavor::Flavor;
|
||||
/// use komorebi_recorder::analysis::state::Snapshot;
|
||||
/// use komorebi_recorder::analysis::views::headline;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let state = json!({"monitors": {"elements": [{
|
||||
/// "id": 1,
|
||||
/// "workspaces": {"elements": [{
|
||||
/// "name": "one",
|
||||
/// "containers": {"elements": [
|
||||
/// {"id": "a", "windows": {"elements": [{"id": 1}], "focused": 0}},
|
||||
/// {"id": "b", "windows": {"elements": [{"id": 2}], "focused": 0}}
|
||||
/// ], "focused": 0}
|
||||
/// }], "focused": 0}
|
||||
/// }], "focused": 0}});
|
||||
///
|
||||
/// let snapshot = Snapshot::parse(Flavor::Macos, &state);
|
||||
/// assert_eq!(headline(&snapshot), "1 monitor, 2 windows");
|
||||
///
|
||||
/// let empty = Snapshot::parse(Flavor::Macos, &json!({}));
|
||||
/// assert_eq!(headline(&empty), "0 monitors, 0 windows");
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn headline(snapshot: &Snapshot) -> String {
|
||||
let windows = snapshot.windows().len();
|
||||
let monitors = snapshot.monitors.len();
|
||||
format!(
|
||||
"{monitors} monitor{}, {windows} window{}",
|
||||
if monitors == 1 { "" } else { "s" },
|
||||
if windows == 1 { "" } else { "s" }
|
||||
)
|
||||
}
|
||||
@@ -26,6 +26,8 @@
|
||||
//!
|
||||
//! Times are written as timecodes (`00:12.500`, see [`crate::timecode::format`]) in video time.
|
||||
|
||||
use crate::analysis::code::CodeData;
|
||||
use crate::analysis::history::HistoryData;
|
||||
use crate::annotations::AnnotationView;
|
||||
use crate::annotations::Kind;
|
||||
use crate::timecode;
|
||||
@@ -453,6 +455,203 @@ pub fn annotation_text(view: &AnnotationView) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
fn rect_text(rect: &Option<crate::analysis::state::Rect>) -> String {
|
||||
rect.as_ref()
|
||||
.map_or_else(|| "rect unknown".to_string(), |rect| rect.describe())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// The text opens with a warning if the source is not the version that was recorded. For each log
|
||||
/// line it gives how sure the match is, the code around it and what the part of komorebi it came
|
||||
/// from does. A line that no statement in the indexed source explains says so. A match is `exact`, `likely`,
|
||||
/// `ambiguous` (with how many other statements read the same) or `generic` (the statement only
|
||||
/// prints a value, so the match says little).
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::report::code_text;
|
||||
/// use komorebi_recorder::testkit::SessionBuilder;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-code-text")
|
||||
/// .log(2.0, "INFO", "process_command: komorebi::process_command: processing command: Retile")
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// // the log line is named whether or not this build has komorebi's source to match it against
|
||||
/// let data = analysis.code_for_lines("log:1", &[1], 3, None)?;
|
||||
/// assert!(code_text(&data).contains("log:1 "));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn code_text(data: &CodeData) -> String {
|
||||
let mut out = String::new();
|
||||
if let Some(warning) = &data.skew.warning {
|
||||
let _ = writeln!(out, "WARNING: {warning}\n");
|
||||
}
|
||||
|
||||
for line in &data.lines {
|
||||
let time = line.video_s.map_or_else(String::new, |seconds| {
|
||||
format!(" {}", timecode::format(seconds))
|
||||
});
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"log:{}{time} {} {}\n {}",
|
||||
line.line,
|
||||
line.level.as_deref().unwrap_or(""),
|
||||
line.target.as_deref().unwrap_or(""),
|
||||
line.message,
|
||||
);
|
||||
|
||||
match &line.source {
|
||||
Some(source) => {
|
||||
let note = match source.confidence {
|
||||
crate::analysis::catalog::Confidence::Exact => "exact".to_string(),
|
||||
crate::analysis::catalog::Confidence::Likely => "likely".to_string(),
|
||||
crate::analysis::catalog::Confidence::Ambiguous => format!(
|
||||
"ambiguous: {} other statement(s) read the same",
|
||||
source.alternatives.len()
|
||||
),
|
||||
crate::analysis::catalog::Confidence::Generic => {
|
||||
"generic: the statement only prints a value, so this says little"
|
||||
.to_string()
|
||||
}
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" -> {} in {} ({note}){}",
|
||||
source.statement.location(),
|
||||
source.statement.qualified_function(),
|
||||
if line.file_changed {
|
||||
" [this file differs from the recorded komorebi]"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
for other in &source.alternatives {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" or {} in {}",
|
||||
other.location(),
|
||||
other.qualified_function()
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = writeln!(out, " -> no statement in the indexed source writes this");
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(snippet) = &line.snippet {
|
||||
for (number, text) in &snippet.lines {
|
||||
let marker = if *number == snippet.line { ">" } else { " " };
|
||||
let _ = writeln!(out, " {number:>5} {marker} {text}");
|
||||
}
|
||||
}
|
||||
if let Some(role) = &line.role {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" role: {role}{}",
|
||||
if line.changes_state_silently {
|
||||
" [CHANGES STATE WITHOUT A NOTIFICATION]"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
);
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
for statement in &data.statements {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{} {} in {}\n {} {}",
|
||||
statement.location(),
|
||||
statement.level,
|
||||
statement.qualified_function(),
|
||||
statement.target,
|
||||
statement.template
|
||||
);
|
||||
}
|
||||
|
||||
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.
|
||||
///
|
||||
/// An entry says where the window was afterwards, where it really was and what changed. An entry for
|
||||
/// an event that was about the window but changed nothing about it says so. If more
|
||||
/// entries matched than the data holds, the last line says how many more.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use komorebi_recorder::analysis::Analysis;
|
||||
/// use komorebi_recorder::report::history_text;
|
||||
/// use komorebi_recorder::testkit::{SessionBuilder, state_with_windows};
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let (session, _) = SessionBuilder::new("doc-history-text")
|
||||
/// .event(2.0, json!({"type": "Retile"}), Some(state_with_windows(&[(7, "Terminal")])))
|
||||
/// .build();
|
||||
/// let analysis = Analysis::open(&session.dir)?;
|
||||
///
|
||||
/// let text = history_text(&analysis.window_history("Terminal", None, None)?);
|
||||
/// assert!(text.starts_with("'Terminal' matched: Terminal"));
|
||||
/// # Ok::<(), Box<dyn std::error::Error>>(())
|
||||
/// ```
|
||||
#[must_use]
|
||||
pub fn history_text(data: &HistoryData) -> String {
|
||||
let mut out = String::new();
|
||||
let names: Vec<String> = data
|
||||
.windows
|
||||
.iter()
|
||||
.map(|window| format!("{} \"{}\" (window {})", window.exe, window.title, window.id))
|
||||
.collect();
|
||||
let _ = writeln!(out, "'{}' matched: {}", data.query, names.join("; "));
|
||||
|
||||
for entry in &data.entries {
|
||||
let place = entry
|
||||
.location
|
||||
.as_ref()
|
||||
.map_or_else(|| "gone".to_string(), |location| location.describe());
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"#{:<5} {} window {} {}\n after: {} {}{}",
|
||||
entry.seq,
|
||||
timecode::format(entry.video_s),
|
||||
entry.window_id,
|
||||
entry.event,
|
||||
place,
|
||||
rect_text(&entry.rect),
|
||||
if entry.hidden {
|
||||
" (parked off screen)"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
);
|
||||
for change in &entry.changes {
|
||||
let _ = writeln!(out, " - {change}");
|
||||
}
|
||||
if entry.changes.is_empty() && entry.about_window {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" - the event was about this window; nothing about it changed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if data.matching > data.entries.len() {
|
||||
let _ = writeln!(out, "... {} more", data.matching - data.entries.len());
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -640,6 +640,28 @@ pub fn numbered_frame_index(bgra: &[u8], width: u32, height: u32) -> u32 {
|
||||
index
|
||||
}
|
||||
|
||||
/// The checkout of komorebi for Mac that the tests which read komorebi's source read it from.
|
||||
///
|
||||
/// That is the catalog and `code`. It is the checkout `KOMOREBI_MAC_SRC` names, which `nix develop`
|
||||
/// sets to the revision pinned in `flake.lock`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics, naming the variable, when it is not set: those tests have nothing to check without a
|
||||
/// tree.
|
||||
#[must_use]
|
||||
pub fn komorebi_mac_src() -> PathBuf {
|
||||
std::env::var_os("KOMOREBI_MAC_SRC")
|
||||
.map(PathBuf::from)
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"KOMOREBI_MAC_SRC is not set: it names the checkout of komorebi for Mac that these \
|
||||
tests read (`nix develop` sets it)"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `ffmpeg` is there to make test videos with.
|
||||
#[must_use]
|
||||
pub fn ffmpeg_available() -> bool {
|
||||
|
||||
Reference in new issue
Block a user