use std::io::{Seek as _, Write as _};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::mpsc::SyncSender;
use anyhow::{Context as _, Result};
use diffs_rs::engine::{self, Command, Engine, Input, InputEffect, Marker, Options, SidebarPreference};
use diffs_rs::reading::SourceRange;
use diffs_rs::theme::Appearance;
use plannotator_tui_review::{Capture, Side};
use ratatui::Frame;
use ratatui::crossterm::event::{Event, MouseEventKind};
use ratatui::layout::Rect;
use ratatui::style::Style;
mod place;
mod sections;
use sections::Sections;
fn next_generation() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Lines {
pub(super) path: String,
pub(super) side: Side,
pub(super) first: u32,
pub(super) last: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Progress {
Loading,
Coloring,
SourceFailed,
Failed(String),
Ready,
}
pub(super) struct Diff {
engine: Engine,
sections: Option<(String, Sections)>,
paths: Vec<String>,
fixed: Option<String>,
area: Rect,
generation: u64,
notice: Option<&'static str>,
drawn: bool,
}
impl std::fmt::Debug for Diff {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Diff").field("paths", &self.paths).finish_non_exhaustive()
}
}
impl Diff {
pub(super) fn open(
capture: &Capture,
paths: &[String],
light: bool,
wake: SyncSender<()>,
) -> Result<Self> {
let options = Options {
appearance: if light { Appearance::Light } else { Appearance::Dark },
chrome: false,
sidebar: SidebarPreference::Hide,
..Options::default()
};
let sections = Sections::of(&capture.patch);
let patch = sections.select(&capture.patch, paths);
let input = input_bytes(&patch, capture.scope.title())?;
let mut engine = Engine::open(input, options, wake).context("opening the diff viewer")?;
engine.set_terminal_background(true)?;
Ok(Self::with(engine, Some((capture.patch_key.clone(), sections)), None))
}
fn with(engine: Engine, sections: Option<(String, Sections)>, fixed: Option<String>) -> Self {
Self {
engine,
sections,
paths: Vec::new(),
fixed,
area: Rect::default(),
generation: next_generation(),
notice: None,
drawn: false,
}
}
pub(super) fn open_whole(bytes: &[u8], name: &str, light: bool, wake: SyncSender<()>) -> Result<Self> {
let options = Options {
appearance: if light { Appearance::Light } else { Appearance::Dark },
layout: engine::Layout::Unified,
chrome: false,
..Options::default()
};
let input = input_bytes(bytes, name.to_owned())?;
let mut engine = Engine::open(input, options, wake).context("opening the whole-file view")?;
engine.set_terminal_background(true)?;
Ok(Self::with(engine, None, Some(name.to_owned())))
}
pub(super) fn replace(&mut self, capture: &Capture, paths: &[String]) -> Result<()> {
let fresh = self.sections.as_ref().is_none_or(|(key, _)| *key != capture.patch_key);
if fresh {
self.sections = Some((capture.patch_key.clone(), Sections::of(&capture.patch)));
}
let patch = self.sections.as_ref().map(|(_, s)| s.select(&capture.patch, paths)).unwrap_or_default();
let input = input_bytes(&patch, capture.scope.title())?;
self.engine.replace(input).context("reloading the diff viewer")?;
self.paths.clear();
self.generation = next_generation();
self.drawn = false;
Ok(())
}
pub(super) fn generation(&self) -> u64 {
self.generation
}
pub(super) fn poll(&mut self, capture: &Capture) -> Result<bool> {
self.engine.poll()?;
let files = self.engine.status().files;
if files == self.paths.len() {
return Ok(false);
}
if let Some(path) = &self.fixed {
self.paths = vec![path.clone(); files.min(1)];
return Ok(true);
}
self.paths = (0..files).map(|index| self.capture_path(capture, index)).collect();
self.drawn = false;
Ok(true)
}
fn capture_path(&self, capture: &Capture, index: usize) -> String {
let Some(meta) = self.engine.file(index) else { return String::new() };
let by_path = capture.files.iter().find(|f| *f.path == *meta.path);
by_path
.or_else(|| capture.files.iter().find(|f| *f.path == *meta.old_path))
.map_or_else(|| meta.path.to_string(), |f| f.path.clone())
}
pub(super) fn files_shown(&self) -> usize {
self.paths.len()
}
pub(super) fn paths(&self) -> &[String] {
&self.paths
}
fn index(&self, path: &str) -> Option<usize> {
self.paths.iter().position(|p| p == path)
}
pub(super) fn needs_draw(&self) -> bool {
self.engine.needs_draw()
}
pub(super) fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
self.engine.draw(frame, area)?;
self.area = area.intersection(frame.area());
Ok(())
}
pub(super) fn after_draw(&mut self) {
self.engine.after_draw();
self.drawn = !self.paths.is_empty();
}
pub(super) fn drawn(&self) -> bool {
self.drawn
}
pub(super) fn close(&mut self) -> Result<()> {
self.engine.close()
}
pub(super) fn progress(&self) -> Progress {
let status = self.engine.status();
if let Some(error) = status.error {
Progress::Failed(error.to_owned())
} else if status.loading {
Progress::Loading
} else if status.coloring || status.preparing_source {
Progress::Coloring
} else if status.source_failed {
Progress::SourceFailed
} else {
Progress::Ready
}
}
pub(super) fn run(&mut self, command: Command) -> Result<()> {
let growing = self.growing();
let effect = self.engine.execute(command)?;
let step = match command {
_ if effect == InputEffect::Ignored => return Ok(()),
Command::Down | Command::PageDown => Some(true),
Command::Up | Command::PageUp => Some(false),
_ => None,
};
self.keep_in_hunk(growing, step)
}
pub(super) fn handle_event(&mut self, event: Event) -> Result<bool> {
let step = match &event {
Event::Mouse(mouse) => match mouse.kind {
MouseEventKind::ScrollDown => Some(true),
MouseEventKind::ScrollUp => Some(false),
_ => None,
},
_ => None,
};
let growing = self.growing();
let acted = self.engine.handle_event(event, true)? != InputEffect::Ignored;
if acted {
self.keep_in_hunk(growing, step)?;
}
Ok(acted)
}
pub(super) fn take_notice(&mut self) -> Option<&'static str> {
self.notice.take()
}
pub(super) fn hunk_span(&self, path: &str, side: Side, line: u32) -> Option<(u32, u32)> {
let file = self.index(path)?;
self.hunk_of(file, side == Side::Old, line).map(|(_, span)| span)
}
pub(super) fn selection(&self) -> Option<Lines> {
let range = self.engine.selection()?;
Some(Lines {
path: self.paths.get(range.file)?.clone(),
side: side_of(range.side),
first: range.first,
last: range.last,
})
}
pub(super) fn selecting(&self) -> bool {
self.engine.selection_extending()
}
pub(super) fn cursor(&self) -> Result<Option<Lines>> {
let Some(at) = self.engine.selected_source()? else { return Ok(None) };
let line = match at.side {
engine::Side::Old => at.old_line,
engine::Side::New => at.new_line,
};
let path = self.paths.get(at.file).cloned();
Ok(path.zip(line).map(|(path, line)| Lines { path, side: side_of(at.side), first: line, last: line }))
}
pub(super) fn cursor_side(&self) -> Result<Option<Side>> {
Ok(self.engine.selected_source()?.map(|at| side_of(at.side)))
}
pub(super) fn line_on(&self, side: Side) -> Result<Option<(&str, u32)>> {
let Some(at) = self.engine.selected_source()? else { return Ok(None) };
let line = match side {
Side::Old => at.old_line,
Side::New => at.new_line,
};
Ok(self.paths.get(at.file).map(String::as_str).zip(line))
}
pub(super) fn selectable(&mut self) -> Result<bool> {
if self.engine.execute(Command::SelectLines)? == InputEffect::Ignored {
return Ok(false);
}
self.run(Command::ClearSelection)?;
Ok(true)
}
pub(super) fn select(&mut self, lines: &Lines) -> Result<()> {
let file = self.index(&lines.path).with_context(|| format!("{} is not in the diff", lines.path))?;
let range = SourceRange {
review: self.engine.review_id(),
file,
side: engine_side(lines.side),
first: lines.first,
last: lines.last,
};
self.engine.select_range(range)?;
Ok(())
}
pub(super) fn begin_or_end_selection(&mut self) -> Result<()> {
self.run(Command::SelectLines)
}
pub(super) fn clear_selection(&mut self) -> Result<()> {
self.run(Command::ClearSelection)
}
pub(super) fn reveal(&mut self, path: &str, side: Side, line: u32) -> Result<()> {
let file = self.index(path).with_context(|| format!("{path} is not in the diff"))?;
self.engine.reveal(file, engine_side(side), line)?;
Ok(())
}
pub(super) fn set_markers(&mut self, marks: &[(Lines, Style)]) -> Result<()> {
let review = self.engine.review_id();
let markers: Vec<Marker> = marks
.iter()
.filter(|(lines, _)| lines.first >= 1 && lines.first <= lines.last)
.filter_map(|(lines, style)| {
let file = self.index(&lines.path)?;
let range = SourceRange {
review,
file,
side: engine_side(lines.side),
first: lines.first,
last: lines.last,
};
Some(Marker { range, style: *style })
})
.collect();
self.engine.set_markers(&markers)
}
}
fn input_bytes(bytes: &[u8], label: String) -> Result<Input> {
static NEXT: AtomicU32 = AtomicU32::new(0);
let path = std::env::temp_dir().join(format!(
"plannotator-tui-patch-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let mut file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(&path)
.with_context(|| format!("creating {}", path.display()))?;
let _ = std::fs::remove_file(&path);
file.write_all(bytes).context("writing the patch for the viewer")?;
file.rewind().context("rewinding the patch for the viewer")?;
Ok(Input::Stream { file, label })
}
fn side_of(side: engine::Side) -> Side {
match side {
engine::Side::Old => Side::Old,
engine::Side::New => Side::New,
}
}
fn engine_side(side: Side) -> engine::Side {
match side {
Side::Old => engine::Side::Old,
Side::New => engine::Side::New,
}
}