#![allow(clippy::print_stdout, reason = "the CLI's job is to print")]
use std::io::{IsTerminal as _, Write as _, stdout};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use plannotator_tui_schema::{DocumentSource, Kind};
use ratatui::crossterm::event::{
self, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
EnableFocusChange, EnableMouseCapture, KeyboardEnhancementFlags, PopKeyboardEnhancementFlags,
PushKeyboardEnhancementFlags,
};
use ratatui::crossterm::execute;
use crate::app::App;
use crate::config::Config;
use crate::delivery::command::DeliverCommand;
use crate::delivery::{Caller, Clipboard, Delivery, Discard, HerdrAgent};
use crate::doc::Document;
use crate::gate::{self, Decision, GateError, ReviewArgs};
use crate::hc::agent::HcAgent;
use crate::herdr::context::HerdrEnv;
use crate::layout::DocLayout;
use crate::rex::agent::RexAgent;
pub(crate) const USAGE: &str = "usage:
plannotator-tui <file.md | folder> [--gate] [--json] [--require-approval] [--result-file <path>]
plannotator-tui --export <file.md>
plannotator-tui --bench <file.md>
plannotator-tui --blocks <file.md>
plannotator-tui --annotate <file.md> <quote> <text> [comment|looks_good|delete] [--occurrence N]
plannotator-tui --annotate-block <file.md> <block> <text> [comment|looks_good|delete]
plannotator-tui --snapshot <file.md> [cols rows scroll] [select-quote] [menu]
plannotator-tui review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [DIR]
plannotator-tui config
plannotator-tui --version
plannotator-tui herdr open [file.md | folder] [--placement overlay|split|popup] [--deliver-to <pane>]
[--gate] [--result-file <path>]
plannotator-tui herdr last [--placement P] [--deliver-to <pane>] [--newest]
plannotator-tui herdr terminal [--lines N] [--placement P] [--deliver-to <pane>] [--print]
plannotator-tui herdr review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [--placement P]
[--deliver-to <pane>]
plannotator-tui herdr pane
plannotator-tui rex open [file.md | folder] [--block <id>] [--session <id>] [--paste]
[--placement split|popup|tab] [--gate] [--result-file <path>]
plannotator-tui rex last [--block <id>] [--session <id>] [--newest] [--paste] [--placement P]
plannotator-tui rex terminal [--block <id>] [--session <id>] [--lines N] [--paste] [--placement P] [--print]
plannotator-tui rex find [--block <id>] [--session <id>] [--lines N] [--paste] [--placement P]
plannotator-tui rex review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [--block <id>]
[--session <id>] [--paste] [--placement P]
plannotator-tui rex install [--dry-run | --print]
plannotator-tui rex pane (open <path> [--gate [--result-file <path>]] | last <last args>
| terminal --block <id> [--lines N] | review <scope> <repo>)
plannotator-tui pi list [--json]
plannotator-tui pi send --session <id or name> < feedback.md
plannotator-tui pi install [--dry-run | --print]
plannotator-tui hc open [file.md | folder] [--terminal <t>] [--placement overlay|split|popup]
[--gate] [--result-file <path>]
plannotator-tui hc last [--terminal <t>] [--placement P] [--newest] [--session <transcript>]
plannotator-tui hc review [--staged | --unstaged | --base REF | --commit SHA | PR | --pick] [--terminal <t>]
[--placement P]
plannotator-tui hc pane (open <path> [--gate [--result-file <path>]] | last <last args> | review <scope> <repo>)
plannotator-tui last [--host claude|codex|pi|omp|copilot|droid|hermes|opencode|cmd|agy] [--pid N] [--session <transcript>]
[--session-id <id>] [--stdin] [--print] [--pick N] [--newest]";
fn doc_width(cols: u16, ui: &crate::config::UiConfig) -> usize {
let rail = if ui.notes_rail == crate::notes_rail::RailStart::Shown { 1 + 36 } else { 0 };
let room = cols.saturating_sub(2 + rail).max(20);
let cap = ui.doc_width;
usize::from(if cap > 0 { room.min(cap.max(20)) } else { room })
}
fn open_file(path: &PathBuf) -> Result<DocumentSource> {
let content = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
Ok(DocumentSource::file(path.clone(), content))
}
pub(crate) fn delivery(interactive: bool) -> Box<dyn Delivery> {
review_delivery(interactive, None)
}
fn review_delivery(interactive: bool, path: Option<&Path>) -> Box<dyn Delivery> {
if !interactive {
return Box::new(Discard);
}
agent_pane(true).or_else(|| deliver_command(path)).unwrap_or_else(|| Box::new(Clipboard))
}
fn deliver_command(path: Option<&Path>) -> Option<Box<dyn Delivery>> {
let configured = Config::load().unwrap_or_default().deliver.command;
let command = DeliverCommand::from_lookup(|k| std::env::var(k).ok(), configured.as_deref(), path)?;
Some(Box::new(command))
}
fn gate_delivery() -> Box<dyn Delivery> {
agent_pane(false).unwrap_or_else(|| Box::new(Caller))
}
fn agent_pane(refuse_unreachable: bool) -> Option<Box<dyn Delivery>> {
match crate::pi::target::PiSession::from_lookup(|k| std::env::var(k).ok(), &crate::pi::root()) {
Some(Ok(pi)) => return Some(Box::new(pi)),
Some(Err(gone)) => return Some(Box::new(gone)),
None => {}
}
match RexAgent::from_lookup(|k| std::env::var(k).ok()) {
Some(Ok(agent)) => return Some(Box::new(agent)),
Some(Err(unreachable)) if refuse_unreachable => return Some(Box::new(unreachable)),
_ => {}
}
if let Some(agent) = HcAgent::from_lookup(|k| std::env::var(k).ok()) {
return Some(Box::new(agent));
}
let env = HerdrEnv::from_env();
match env.delivery_target() {
Some(target) if env.in_herdr => {
let agent = target.agent.or_else(|| env.agent_in_pane(&target.pane));
Some(Box::new(HerdrAgent::new(env.bin, target.pane, agent)))
}
_ => None,
}
}
fn open_app(path: &PathBuf, width: usize, interactive: bool) -> Result<App> {
open_review(path, width, review_delivery(interactive, Some(path)))
}
fn open_review(path: &PathBuf, width: usize, delivery: Box<dyn Delivery>) -> Result<App> {
if path.is_dir() {
App::open_folder(path, width, delivery)
} else {
App::open(open_file(path)?, width, delivery)
}
}
fn parse_kind(word: &str) -> Result<Kind> {
match word {
"comment" => Ok(Kind::Comment),
"looks_good" | "approve" => Ok(Kind::LooksGood),
"delete" => Ok(Kind::Delete),
other => anyhow::bail!("unknown type {other:?}: use comment, looks_good or delete\n{USAGE}"),
}
}
fn annotate_options(rest: &[String], occurrences: bool) -> Result<(Kind, usize)> {
let mut kind = None;
let mut occurrence = 1;
let mut items = rest.iter().map(String::as_str);
while let Some(item) = items.next() {
match item {
"--occurrence" if occurrences => {
occurrence = items
.next()
.and_then(|n| n.parse::<usize>().ok())
.filter(|n| *n >= 1)
.context("--occurrence takes a number from 1")?;
}
flag if flag.starts_with("--") => anyhow::bail!("unknown flag {flag}\n{USAGE}"),
other if kind.is_none() => kind = Some(parse_kind(other)?),
other => anyhow::bail!("unexpected argument {other:?}\n{USAGE}"),
}
}
Ok((kind.unwrap_or(Kind::Comment), occurrence))
}
pub(crate) fn run(args: &[String]) -> Result<ExitCode> {
if wants_decision(args) {
return review_command(args);
}
tool(args).map(|()| ExitCode::SUCCESS)
}
fn wants_decision(args: &[String]) -> bool {
let decision_flag = |arg: &String| gate::FLAGS.contains(&arg.as_str());
match args.first() {
Some(first) if decision_flag(first) => true,
Some(first)
if first.starts_with('-')
|| matches!(first.as_str(), "config" | "herdr" | "rex" | "hc" | "pi" | "last" | "review") =>
{
false
}
Some(_) => args.iter().skip(1).any(decision_flag),
None => false,
}
}
fn tool(args: &[String]) -> Result<()> {
let arg = |i: usize| args.get(i).map(String::as_str);
let path = |i: usize| arg(i).map(|p| crate::workspace_paths::absolute(Path::new(p))).context(USAGE);
match arg(0) {
Some("--bench") => bench(&path(1)?),
Some("--export") => {
let target = path(1)?;
let app = open_app(&target, 100, false)?;
print!("{}", if target.is_dir() { app.folder_feedback()? } else { app.feedback() });
Ok(())
}
Some("--blocks") => {
let mut app = open_app(&path(1)?, 100, false)?;
for line in app.describe_blocks() {
println!("{line}");
}
Ok(())
}
Some("--annotate") => {
let mut app = open_app(&path(1)?, 100, false)?;
let quote = arg(2).context(USAGE)?;
let body = arg(3).context(USAGE)?.to_owned();
let (kind, occurrence) = annotate_options(args.get(4..).unwrap_or_default(), true)?;
app.add_quote_annotation_at(quote, occurrence, kind, body)
}
Some("--annotate-block") => {
let mut app = open_app(&path(1)?, 100, false)?;
let block: usize = arg(2).and_then(|s| s.parse().ok()).context(USAGE)?;
let body = arg(3).context(USAGE)?.to_owned();
let (kind, _) = annotate_options(args.get(4..).unwrap_or_default(), false)?;
app.add_block_annotation(block, kind, body)
}
Some("--snapshot") => {
let cols: u16 = arg(2).and_then(|s| s.parse().ok()).unwrap_or(140);
let rows: u16 = arg(3).and_then(|s| s.parse().ok()).unwrap_or(40);
let scroll: i64 = arg(4).and_then(|s| s.parse().ok()).unwrap_or(0);
let menu = args.get(5..).is_some_and(|rest| rest.last().is_some_and(|last| last == "menu"));
let select = arg(5).filter(|quote| *quote != "menu");
snapshot(&path(1)?, cols, rows, scroll, select, menu)
}
Some("--version" | "-V") => {
println!("plannotator-tui {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("config") => show_config(),
Some("herdr") => herdr_command(args.get(1..).unwrap_or_default()),
Some("rex") => crate::rex::cli::run(args.get(1..).unwrap_or_default()),
Some("hc") => crate::hc::cli::run(args.get(1..).unwrap_or_default()),
Some("pi") => crate::pi::cli::run(args.get(1..).unwrap_or_default()),
Some("last") => last_command(args.get(1..).unwrap_or_default()),
Some("review") => code_review(args.get(1..).unwrap_or_default()),
Some(flag) if flag.starts_with("--") => anyhow::bail!("unknown flag {flag}\n{USAGE}"),
Some(_) => interactive(&path(0)?),
None => anyhow::bail!(USAGE),
}
}
fn code_review(args: &[String]) -> Result<()> {
#[cfg(unix)]
{
crate::review::cli::run(args)
}
#[cfg(not(unix))]
{
let _ = args;
anyhow::bail!("code review is not available on Windows yet")
}
}
fn show_config() -> Result<()> {
let home = std::env::home_dir().unwrap_or_else(|| PathBuf::from("/"));
let path = crate::config::config_path(|k| std::env::var(k).ok(), &home);
let mut config = Config::load_from(&path)?;
config.ui.theme = crate::theme::effective_setting(|key| std::env::var(key).ok(), config.ui.theme)?;
let env = |k: &str| std::env::var(k).ok();
if let Some(command) = DeliverCommand::from_lookup(env, config.deliver.command.as_deref(), None) {
config.deliver.command = Some(command.line().to_owned());
}
let state = if path.is_file() { "" } else { " (not present; defaults)" };
println!("# {}{state}", path.display());
print!("{}", config.to_toml()?);
Ok(())
}
fn review_command(args: &[String]) -> Result<ExitCode> {
let strict = gate::is_strict(args);
gated_review(args).map_err(|err| if strict { GateError(err).into() } else { err })
}
fn gated_review(args: &[String]) -> Result<ExitCode> {
let options = ReviewArgs::parse(args).map_err(|err| anyhow::anyhow!("{err:#}\n{USAGE}"))?;
let path = crate::workspace_paths::absolute(&options.path);
anyhow::ensure!(path.exists(), "{}: no such file or folder", path.display());
let result_file = options.result_file.as_deref().map(crate::workspace_paths::absolute);
if let Some(file) = &result_file {
gate::check_result_file(file)?;
}
anyhow::ensure!(
stdout().is_terminal(),
"stdout is not a terminal: the review is drawn there; read the decision from --result-file instead"
);
let mode = options.mode();
let decision = run_review(|width| {
let mut app = open_review(&path, width, gate_delivery())?;
app.gate = mode;
Ok(app)
})?
.unwrap_or(Decision::Dismissed);
let mut out = stdout().lock();
if options.json {
let line = if options.strict() { decision.strict_json() } else { decision.json(&path) };
writeln!(out, "{line}")?;
} else if let Some(text) = decision.plain(&gate::context_line(&path, path.is_dir())) {
writeln!(out, "{text}")?;
}
out.flush()?;
if let Some(file) = &result_file {
gate::publish(file, &decision.strict_json())?;
}
Ok(ExitCode::from(decision.exit_code(options.require_approval)))
}
fn herdr_command(args: &[String]) -> Result<()> {
let strict = args.first().is_some_and(|sub| sub == "open") && gate::is_strict(args);
herdr_launch(args).map_err(|err| if strict { GateError(err).into() } else { err })
}
fn herdr_launch(args: &[String]) -> Result<()> {
use crate::herdr::launch::{OpenArgs, agent_get, agent_identity, plan, plan_last, process_info, run};
let sub = args.first().map(String::as_str);
if sub == Some("pane") {
return herdr_pane();
}
if sub == Some("terminal") {
return herdr_terminal(args.get(1..).unwrap_or_default());
}
if sub == Some("review") {
return herdr_review(args.get(1..).unwrap_or_default());
}
if !matches!(sub, Some("open" | "last")) {
anyhow::bail!(USAGE);
}
let mut open = OpenArgs::default();
let mut rest = args.get(1..).unwrap_or_default().iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--placement" => {
let value = rest.next().context("--placement needs a value")?;
open.placement = Some(value.parse()?);
}
"--deliver-to" => {
open.deliver_to = Some(rest.next().context("--deliver-to needs a value")?.clone());
}
"--newest" if sub == Some("last") => open.newest = true,
"--newest" => {
anyhow::bail!("--newest is only for `herdr last`; `herdr open` has no picker to skip")
}
"--gate" if sub == Some("open") => open.gate = true,
"--result-file" if sub == Some("open") => {
let value = rest.next().filter(|v| !v.starts_with("--"));
let value = value.context("missing value for --result-file")?;
open.result_file = Some(crate::workspace_paths::absolute(Path::new(value)));
}
"--gate" | "--result-file" => anyhow::bail!("{arg} is only for `herdr open`"),
flag if flag.starts_with("--") => anyhow::bail!("unknown flag {flag}\n{USAGE}"),
path if open.path.is_none() => open.path = Some(PathBuf::from(path)),
extra => anyhow::bail!("unexpected argument {extra:?}\n{USAGE}"),
}
}
if let Some(file) = &open.result_file {
anyhow::ensure!(open.gate, "--result-file requires --gate");
gate::check_result_file(file)?;
}
let env = HerdrEnv::from_env();
let config = Config::load()?;
let cwd = std::env::current_dir().context("current directory")?;
let launch = if sub == Some("last") {
let probe = plan(&env, &config, OpenArgs { path: None, ..open.clone() }, &cwd)?;
let pane = probe.deliver.as_ref().map(|t| t.pane.clone()).or(probe.target_pane);
let pane = pane.context("no agent pane to read: not focused on one and no --deliver-to")?;
let agent = agent_get(&env, &pane);
let process = match agent.as_deref().and_then(agent_identity) {
Some(_) => None,
None => Some(process_info(&env, &pane)?),
};
plan_last(&env, &config, open, &cwd, process.as_deref(), agent.as_deref())?
} else {
plan(&env, &config, open, &cwd)?
};
run(&env, &launch)
}
fn herdr_terminal(args: &[String]) -> Result<()> {
use crate::herdr::launch::{OpenArgs, TerminalRead, plan_terminal, run};
use crate::herdr::terminal;
let mut open = OpenArgs::default();
let mut lines = crate::terminal::DEFAULT_LINES;
let mut print = false;
let mut rest = args.iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--lines" => lines = lines_value(rest.next())?,
"--placement" => {
let value = rest.next().context("--placement needs a value")?;
open.placement = Some(value.parse()?);
}
"--deliver-to" => {
open.deliver_to = Some(rest.next().context("--deliver-to needs a value")?.clone());
}
"--print" => print = true,
other => anyhow::bail!("unexpected argument {other:?}\n{USAGE}"),
}
}
let env = HerdrEnv::from_env();
let pane = env.reviewed_pane().context("no focused pane to read")?;
let text = terminal::read(&env, &pane, lines)?;
if print {
print!("{}", crate::terminal::document(&text));
return Ok(());
}
let config = Config::load()?;
let cwd = std::env::current_dir().context("current directory")?;
let launch = plan_terminal(&env, &config, open, &cwd, TerminalRead { pane, lines })?;
run(&env, &launch)
}
fn herdr_review(args: &[String]) -> Result<()> {
#[cfg(unix)]
{
crate::review::herdr::launch(args)
}
#[cfg(not(unix))]
{
let _ = args;
anyhow::bail!("code review is not available on Windows yet")
}
}
pub(crate) fn review_pane(scope: &str, repo: Option<&Path>) -> Result<()> {
#[cfg(unix)]
{
crate::review::scope::pane(scope, repo)
}
#[cfg(not(unix))]
{
let _ = (scope, repo);
anyhow::bail!("code review is not available on Windows yet")
}
}
fn herdr_pane() -> Result<()> {
let env = HerdrEnv::from_env();
let result = if let Some(pane) = env.terminal_pane.clone() {
crate::herdr::terminal::run(&env, &pane)
} else if env.has_message_source() {
crate::last::run(&crate::last::LastOptions {
host: env.host.clone(),
pid: env.message_pid,
session: env.session.clone(),
session_id: env.session_id.clone(),
pick: picker_count(),
newest: env.newest,
..crate::last::LastOptions::default()
})
} else if let Some(scope) = &env.review {
review_pane(scope, env.repo.as_deref())
} else {
let path = env.file.clone().unwrap_or(std::env::current_dir().context("current directory")?);
if env.gate { gated_pane(&path, env.result_file.as_deref()) } else { interactive(&path) }
};
if let Err(err) = &result {
wait_on_error(err);
}
result
}
pub(crate) fn lines_value(value: Option<&String>) -> Result<u32> {
value.and_then(|n| n.parse::<u32>().ok()).filter(|n| *n >= 1).context("--lines takes a number from 1")
}
pub(crate) fn wait_on_error(err: &anyhow::Error) {
#[allow(clippy::print_stderr, reason = "the pane is the only place this can be read")]
{
eprintln!("plannotator-tui: {err:#}\n\npress enter to close");
}
let mut line = String::new();
let _ = std::io::stdin().read_line(&mut line);
}
fn picker_count() -> usize {
Config::load().unwrap_or_default().last.pick
}
pub(crate) fn last_command(args: &[String]) -> Result<()> {
crate::last::run(&last_options(args, picker_count())?)
}
fn last_options(args: &[String], pick: usize) -> Result<crate::last::LastOptions> {
let mut options = crate::last::LastOptions { pick, ..crate::last::LastOptions::default() };
let mut rest = args.iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--host" => options.host = Some(rest.next().context("--host needs a value")?.clone()),
"--pid" => options.pid = Some(rest.next().context("--pid needs a value")?.parse()?),
"--session" => {
options.session = Some(PathBuf::from(rest.next().context("--session needs a value")?));
}
"--session-id" => {
options.session_id = Some(rest.next().context("--session-id needs a value")?.clone());
}
"--stdin" => options.stdin = true,
"--print" => options.print = true,
"--pick" => options.pick = rest.next().context("--pick needs a value")?.parse()?,
"--newest" => options.newest = true,
other => anyhow::bail!("unknown argument {other}\n{USAGE}"),
}
}
Ok(options)
}
pub(crate) fn gated_pane(path: &PathBuf, result_file: Option<&Path>) -> Result<()> {
if let Some(file) = result_file {
gate::check_result_file(file)?;
}
let decision = run_review(|width| {
let mut app = open_review(path, width, gate_delivery())?;
app.gate = gate::Gate::Approve;
Ok(app)
})?
.unwrap_or(Decision::Dismissed);
match result_file {
Some(file) => gate::publish(file, &decision.strict_json()),
None => Ok(()),
}
}
pub(crate) fn interactive(path: &PathBuf) -> Result<()> {
run_ui(|width| open_app(path, width, true))
}
pub(crate) fn run_ui(build: impl FnOnce(usize) -> Result<App>) -> Result<()> {
run_review(build).map(drop)
}
fn run_review(build: impl FnOnce(usize) -> Result<App>) -> Result<Option<Decision>> {
with_terminal(|terminal, session| {
let width = doc_width(terminal.size().map_or(120, |s| s.width), &session.config.ui);
let mut app = build(width)?;
app.shift_enter = session.shift_enter;
app.keys = session.config.keys;
app.ui = session.config.ui;
app.start_notes_rail();
app.editor = crate::editor::from_env(|key| std::env::var(key).ok());
if let Some(notice) = session.config_notice {
app.add_notice(notice);
}
event_loop(terminal, app)
})
}
pub(crate) struct Session {
pub(crate) config: Config,
pub(crate) config_notice: Option<String>,
pub(crate) shift_enter: bool,
}
pub(crate) fn with_terminal<T>(
run: impl FnOnce(&mut ratatui::DefaultTerminal, Session) -> Result<T>,
) -> Result<T> {
let (config, config_notice) = Config::load_for_screen(&Config::path());
crate::theme::install(
crate::theme::resolve(|key| std::env::var(key).ok(), config.ui.theme, crate::theme::detect)?,
&config.colors,
);
let mut terminal = ratatui::init();
plannotator_tui_review::children::screen_taken(true);
#[cfg(unix)]
crate::hangup::watch();
let pushed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let flags = std::sync::Arc::clone(&pushed);
std::panic::set_hook(release_first(
move || release_input(flags.load(std::sync::atomic::Ordering::Acquire)),
std::panic::take_hook(),
));
crate::layout::keep_hook_off_layout_threads();
execute!(stdout(), EnableMouseCapture)?;
let shift_enter = ratatui::crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false);
pushed.store(shift_enter, std::sync::atomic::Ordering::Release);
claim_input(shift_enter);
let result = run(&mut terminal, Session { config, config_notice, shift_enter });
release_input(shift_enter);
ratatui::restore();
plannotator_tui_review::children::screen_taken(false);
result
}
fn claim_input(shift_enter: bool) {
let _ = execute!(stdout(), EnableBracketedPaste, EnableFocusChange);
if shift_enter {
let _ = execute!(
stdout(),
PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
);
}
}
pub(crate) fn release_input(shift_enter: bool) {
if shift_enter {
let _ = execute!(stdout(), PopKeyboardEnhancementFlags);
}
let _ = execute!(stdout(), DisableFocusChange, DisableBracketedPaste);
let _ = execute!(stdout(), DisableMouseCapture);
}
type PanicHook = Box<dyn Fn(&std::panic::PanicHookInfo<'_>) + Send + Sync + 'static>;
fn release_first(release: impl Fn() + Send + Sync + 'static, previous: PanicHook) -> PanicHook {
Box::new(move |info| {
release();
previous(info);
})
}
fn run_editor(
terminal: &mut ratatui::DefaultTerminal,
shift_enter: bool,
request: &crate::editor::EditorRequest,
) -> Result<std::io::Result<std::process::ExitStatus>> {
use ratatui::crossterm::{cursor, terminal as term};
release_input(shift_enter);
ratatui::restore();
let _ = execute!(stdout(), cursor::Show);
let outcome = match crate::editor::command(request) {
Some(mut command) => command.status(),
None => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "the editor command is empty")),
};
term::enable_raw_mode().context("taking the terminal back from the editor")?;
execute!(stdout(), term::EnterAlternateScreen, EnableMouseCapture)
.context("taking the terminal back from the editor")?;
claim_input(shift_enter);
terminal.clear()?;
Ok(outcome)
}
fn event_loop(terminal: &mut ratatui::DefaultTerminal, mut app: App) -> Result<Option<Decision>> {
app.clipboard = true;
app.start_pi_link();
let mut dirty = true;
while !app.quit {
if let Some(request) = app.take_editor_request() {
let outcome = run_editor(terminal, app.shift_enter, &request)?;
app.editor_returned(&request, outcome);
dirty = true;
}
dirty |= app.poll_background();
if dirty {
let started = Instant::now();
terminal.draw(|frame| app.draw(frame))?;
app.record_frame(started.elapsed().as_secs_f64() * 1000.0);
dirty = false;
}
let wait = if app.background_pending() {
Duration::from_millis(25)
} else if app.held_at_edge() {
crate::ui::drag::STEP
} else {
Duration::from_millis(250)
};
if event::poll(wait)? {
app.handle_event(&event::read()?)?;
dirty = true;
while !app.wants_editor() && event::poll(Duration::ZERO)? {
app.handle_event(&event::read()?)?;
}
}
}
Ok(app.take_decision())
}
fn bench(path: &PathBuf) -> Result<()> {
let source = open_file(path)?;
let bytes = source.content.len();
let t = Instant::now();
let doc = Document::parse(source.content);
let parse_ms = t.elapsed().as_secs_f64() * 1000.0;
let t = Instant::now();
let mut lazy = DocLayout::start(&doc, 100);
let start_ms = t.elapsed().as_secs_f64() * 1000.0;
let (first_blocks, first_rows) = (lazy.blocks.len(), lazy.total_rows);
lazy.finish();
let finish_ms = t.elapsed().as_secs_f64() * 1000.0;
let t = Instant::now();
let mut layout = DocLayout::build(&doc, 100);
let build_ms = t.elapsed().as_secs_f64() * 1000.0;
let reflow: Vec<String> = [60usize, 140, 80, 120]
.into_iter()
.map(|width| {
let t = Instant::now();
layout.reflow(width);
format!("{width}→{:.1}ms", t.elapsed().as_secs_f64() * 1000.0)
})
.collect();
let t = Instant::now();
let hits = (0..layout.total_rows).step_by(7).filter(|&row| layout.block_at_row(row).is_some()).count();
let lookup_us = t.elapsed().as_secs_f64() * 1e6 / (layout.total_rows / 7).max(1) as f64;
let t = Instant::now();
let index = crate::doc_search::Index::of(&layout);
let index_ms = t.elapsed().as_secs_f64() * 1000.0;
let searches: Vec<String> = ["e", "th", "the", "plugin", "Plugin", "no such text anywhere"]
.into_iter()
.map(|query| {
let t = Instant::now();
let found = index.find(query).len();
format!("{query:?} {found}→{:.1}ms", t.elapsed().as_secs_f64() * 1000.0)
})
.collect();
let cells: usize = layout.blocks.iter().flat_map(|b| b.rows.iter()).map(|r| r.cells.len()).sum();
let mapped: usize =
layout.blocks.iter().flat_map(|b| b.rows.iter()).flat_map(|r| r.cells.iter()).flatten().count();
println!("{}: {bytes} bytes, {} blocks", path.display(), doc.blocks.len());
println!("parse+split {parse_ms:8.1} ms");
println!("first screens {start_ms:8.1} ms ({first_blocks} blocks, {first_rows} rows)");
println!(" rest in background {finish_ms:8.1} ms (until every block is laid out)");
println!("render+align+wrap {build_ms:8.1} ms ({} rows)", layout.total_rows);
println!("reflow {}", reflow.join(" "));
println!("row lookup {lookup_us:8.3} µs avg ({hits} hits)");
println!("search index {index_ms:8.1} ms");
println!("search {}", searches.join(" "));
println!("cells mapped {mapped}/{cells} ({:.1}%)", mapped as f64 * 100.0 / cells.max(1) as f64);
Ok(())
}
fn snapshot(
path: &PathBuf,
cols: u16,
rows: u16,
scroll: i64,
select: Option<&str>,
menu: bool,
) -> Result<()> {
use ratatui::backend::TestBackend;
use ratatui::style::Modifier;
let mut terminal = ratatui::Terminal::new(TestBackend::new(cols, rows))?;
let mut app = open_app(path, doc_width(cols, &crate::config::UiConfig::default()), false)?;
terminal.draw(|frame| app.draw(frame))?;
app.scroll_for_snapshot(scroll);
if let Some(quote) = select {
app.select_quote_for_snapshot(quote)?;
}
if menu {
app.open_review_menu();
}
terminal.draw(|frame| app.draw(frame))?;
let buffer = terminal.backend().buffer();
let mut marks = Vec::new();
for y in 0..buffer.area.height {
let mut line = String::new();
let mut mark = String::new();
for x in 0..buffer.area.width {
let Some(cell) = buffer.cell((x, y)) else { continue };
line.push_str(cell.symbol());
let style = cell.style();
mark.push(if style.add_modifier.contains(Modifier::REVERSED) {
'%'
} else if style.add_modifier.contains(Modifier::CROSSED_OUT) {
'-'
} else if style.bg == Some(crate::theme::palette().approve_bg) {
'+'
} else if style.bg == Some(crate::theme::palette().comment_bg) {
'#'
} else {
' '
});
}
println!("{}", line.trim_end());
marks.push(mark);
}
if marks.iter().any(|m| !m.trim().is_empty()) {
println!("--- marks ---");
for m in marks {
println!("{}", m.trim_end());
}
}
Ok(())
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::{doc_width, last_options};
use crate::config::UiConfig;
use crate::notes_rail::RailStart;
fn args(list: &[&str]) -> Vec<String> {
list.iter().map(|&arg| arg.to_owned()).collect()
}
#[test]
fn last_offers_the_configured_count_and_pick_overrides_it() {
assert_eq!(last_options(&args(&["--newest"]), 60).expect("parses").pick, 60);
assert_eq!(last_options(&args(&["--pick", "5"]), 60).expect("parses").pick, 5);
}
#[test]
fn a_panic_turns_the_input_modes_off_before_the_hook_that_gives_the_screen_back() {
use std::sync::{Arc, Mutex};
use std::thread;
let here = thread::current().id();
let order = Arc::new(Mutex::new(Vec::new()));
let original: Arc<super::PanicHook> = Arc::new(std::panic::take_hook());
let (released, given_back, others) = (Arc::clone(&order), Arc::clone(&order), Arc::clone(&original));
let previous: super::PanicHook = Box::new(move |info| {
if thread::current().id() == here {
given_back.lock().expect("order").push("screen");
} else {
others(info);
}
});
let release = move || {
if thread::current().id() == here {
released.lock().expect("order").push("input modes");
}
};
std::panic::set_hook(super::release_first(release, previous));
#[allow(clippy::panic, reason = "the hook runs on a panic")]
let outcome = std::panic::catch_unwind(|| std::panic::panic_any("on purpose"));
drop(std::panic::take_hook());
std::panic::set_hook(Box::new(move |info| original(info)));
assert!(outcome.is_err());
assert_eq!(*order.lock().expect("order"), ["input modes", "screen"]);
}
#[test]
fn the_first_frames_width_leaves_out_a_rail_unless_it_always_shows() {
let fill = UiConfig { doc_width: 0, ..UiConfig::default() };
assert_eq!(doc_width(120, &UiConfig { notes_rail: RailStart::Shown, ..fill }), 120 - 2 - 1 - 36);
assert_eq!(doc_width(120, &UiConfig { notes_rail: RailStart::Hidden, ..fill }), 118);
assert_eq!(doc_width(120, &fill), 118, "when-notes: the rail comes with the first note");
assert_eq!(doc_width(120, &UiConfig::default()), 80);
}
}