mod draw;
mod rows;
pub(crate) mod shown;
pub(crate) mod source;
#[cfg(test)]
mod tests;
use std::sync::Arc;
use std::sync::mpsc::SyncSender;
use plannotator_tui_review::{Capture, Repo, Scope};
use ratatui::crossterm::event::{KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use crate::keys::{self, Action, Keymap};
use rows::{Kind, Row, Sized};
use source::{Done, Job, Listing, PAGE, Source, Work};
const RELOADING: &str = "reloading\u{2026}";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
Stay,
Close,
Quit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum More {
None,
Ready,
Loading,
}
#[derive(Debug, Default, Clone)]
struct Geometry {
rows: Vec<(Rect, usize)>,
area: Rect,
visible: usize,
}
pub(crate) struct Picker {
work: Work,
name: String,
rows: Vec<Row>,
listed: bool,
more: More,
cursor: usize,
pinned: bool,
scroll: usize,
status: Option<String>,
over: Option<Scope>,
help: bool,
generation: u64,
opening: Option<usize>,
opened: Option<(Repo, Capture)>,
keep: Option<Scope>,
keys: Keymap,
geometry: Geometry,
}
impl std::fmt::Debug for Picker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Picker")
.field("name", &self.name)
.field("rows", &self.rows.len())
.finish_non_exhaustive()
}
}
impl Picker {
pub(crate) fn open(
source: Arc<dyn Source>,
listing: Option<Listing>,
over: Option<Scope>,
keys: Keymap,
wake: SyncSender<()>,
) -> Self {
let name = rows::clean(&source.name());
let mut picker = Self {
work: Work::new(source, wake),
name,
rows: [Kind::Uncommitted, Kind::Unstaged, Kind::Staged].map(Row::new).into(),
listed: false,
more: More::None,
cursor: 0,
pinned: false,
scroll: 0,
status: None,
keep: over.clone(),
over,
help: false,
generation: 0,
opening: None,
opened: None,
keys,
geometry: Geometry::default(),
};
if let Some(listing) = listing {
picker.take_listing(0, Ok(listing));
} else {
picker.keep_cursor(false);
picker.ask(Job::List { skip: 0, count: PAGE });
}
picker.ask_sizes();
picker
}
pub(crate) fn say(&mut self, status: String) {
self.status = Some(status);
}
pub(crate) fn tick(&mut self) -> bool {
let answers = self.work.take();
let changed = !answers.is_empty();
for done in answers {
self.take(done);
}
if !self.work.pump() {
self.status = Some("could not start a thread to ask git".into());
}
self.ask_sizes();
self.settle_cursor();
changed
}
pub(crate) fn take_opened(&mut self) -> Option<(Repo, Capture)> {
self.opened.take()
}
fn ask(&mut self, job: Job) {
if !self.work.ask(self.generation, job) {
self.status = Some("could not start a thread to ask git".into());
}
}
fn take(&mut self, done: Done) {
match done {
Done::List { generation, skip, listing } if generation == self.generation => {
self.take_listing(skip, listing);
}
Done::Size { generation, row, size } if generation == self.generation => {
if let Some(row) = self.rows.get_mut(row) {
row.size = match size {
Ok(size) => Sized::Known(size),
Err(error) => Sized::Failed(error),
};
}
}
Done::Capture { generation, row, captured } if generation == self.generation => {
if self.opening != Some(row) {
return;
}
self.opening = None;
let name = self.rows.get(row).map(Row::name).unwrap_or_default();
match *captured {
Ok((_, capture)) if capture.is_empty() => {
self.status = Some(format!("{name} has no changes"));
}
Ok(opened) => {
self.status = None;
self.opened = Some(opened);
}
Err(error) => {
let stale = self
.rows
.get(row)
.is_some_and(|row| matches!(row.kind, Kind::Commit(_) | Kind::Branch(_)))
&& !error.contains("too large");
let key = self.keys.hint(Action::Reload);
self.status = Some(if stale && !key.is_empty() {
format!("{name}: {error} \u{b7} press {key} to reload")
} else {
format!("{name}: {error}")
});
}
}
}
Done::List { .. } | Done::Size { .. } | Done::Capture { .. } => {}
}
}
fn take_listing(&mut self, skip: usize, listing: Result<Listing, String>) {
let listing = match listing {
Ok(listing) => listing,
Err(error) => {
self.status = Some(format!("could not list the commits: {error}"));
if skip > 0 {
self.more = More::Ready;
}
self.listed = true;
return;
}
};
if skip == 0 {
if self.status.as_deref() == Some(RELOADING) {
self.status = None;
}
self.rows.truncate(3);
self.rows.extend(listing.branch.map(|scope| Row::new(Kind::Branch(scope))));
} else if self.rows.last().is_some_and(|row| row.kind == Kind::More) {
self.rows.pop();
}
self.rows.extend(listing.commits.into_iter().map(|commit| Row::new(Kind::Commit(commit))));
self.more = if listing.more { More::Ready } else { More::None };
if listing.more {
self.rows.push(Row::new(Kind::More));
}
self.listed = true;
self.keep_cursor(true);
self.cursor = self.cursor.min(self.rows.len().saturating_sub(1));
}
pub(crate) fn keep_at(&mut self, scope: Scope) {
self.keep = Some(scope);
self.keep_cursor(self.listed);
}
fn keep_cursor(&mut self, listed: bool) {
let Some(keep) = &self.keep else { return };
if let Some(at) = self.rows.iter().position(|row| row.scope().as_ref() == Some(keep)) {
self.cursor = at;
self.pinned = true;
self.keep = None;
} else if listed {
self.keep = None;
}
}
fn ask_sizes(&mut self) {
let shown = self.scroll..self.scroll + self.geometry.visible.max(1);
while self.work.has_room() && self.opening.is_none() && self.opened.is_none() {
let waiting = |row: &Row| row.size == Sized::Waiting && row.kind != Kind::More;
let next = shown
.clone()
.find(|&i| self.rows.get(i).is_some_and(waiting))
.or_else(|| self.rows.iter().position(waiting));
let Some(index) = next else { return };
let Some(row) = self.rows.get_mut(index) else { return };
let Some(scope) = row.scope() else { return };
row.size = Sized::Asking;
self.ask(Job::Size { row: index, scope });
}
}
fn settle_cursor(&mut self) {
if self.pinned {
return;
}
let first = self.rows.iter().position(|row| row.kind != Kind::More && !row.is_empty());
self.cursor = first.unwrap_or(0);
}
fn nothing_to_review(&self) -> bool {
self.listed
&& self
.rows
.iter()
.filter(|row| !matches!(row.kind, Kind::Commit(_) | Kind::More))
.all(Row::is_empty)
}
fn has_commits(&self) -> bool {
self.rows.iter().any(|row| matches!(row.kind, Kind::Commit(_)))
}
fn move_to(&mut self, index: usize) {
self.pinned = true;
self.cursor = index.min(self.rows.len().saturating_sub(1));
}
pub(crate) fn key(&mut self, key: &KeyEvent) -> Outcome {
let action = self.keys.action(key, keys::PICK_CHANGES);
if self.help {
match action {
Some(Action::Quit | Action::Interrupt) => return Outcome::Quit,
Some(_) => self.help = false,
None => {}
}
return Outcome::Stay;
}
let page = self.geometry.visible.saturating_sub(1).max(1);
let last = self.rows.len().saturating_sub(1);
match action {
Some(Action::Down) => self.move_to(self.cursor + 1),
Some(Action::Up) => self.move_to(self.cursor.saturating_sub(1)),
Some(Action::PageDown) => self.move_to(self.cursor + page),
Some(Action::PageUp) => self.move_to(self.cursor.saturating_sub(page)),
Some(Action::Top) => self.move_to(0),
Some(Action::Bottom) => self.move_to(last),
Some(Action::Confirm) => return self.choose(self.cursor),
Some(Action::Reload) => self.reload(),
Some(Action::Help) => self.help = true,
Some(Action::Back | Action::PickChanges) => {
if self.over.is_some() {
return Outcome::Close;
}
self.status = self.keys.labelled(Action::Quit, "quits");
}
Some(Action::Quit | Action::Interrupt) => return Outcome::Quit,
_ => {}
}
Outcome::Stay
}
pub(crate) fn mouse(&mut self, mouse: MouseEvent) -> Outcome {
if self.help {
if matches!(mouse.kind, MouseEventKind::Down(_)) {
self.help = false;
}
return Outcome::Stay;
}
match mouse.kind {
MouseEventKind::Down(MouseButton::Left) => {
let hit = self.geometry.rows.iter().find(|(rect, _)| {
mouse.row == rect.y && mouse.column >= rect.x && mouse.column < rect.right()
});
if let Some(&(_, index)) = hit {
self.move_to(index);
return self.choose(index);
}
}
MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
let visible = self.geometry.visible.max(1);
let most = self.rows.len().saturating_sub(visible);
self.scroll = if mouse.kind == MouseEventKind::ScrollDown {
(self.scroll + 3).min(most)
} else {
self.scroll.saturating_sub(3)
};
self.pinned = true;
self.cursor = self
.cursor
.clamp(self.scroll, (self.scroll + visible).saturating_sub(1))
.min(self.rows.len().saturating_sub(1));
}
_ => {}
}
Outcome::Stay
}
fn choose(&mut self, index: usize) -> Outcome {
let Some(row) = self.rows.get(index) else { return Outcome::Stay };
if row.kind == Kind::More {
if self.more == More::Ready {
self.more = More::Loading;
let skip = self.rows.iter().filter(|row| matches!(row.kind, Kind::Commit(_))).count();
self.ask(Job::List { skip, count: PAGE });
}
return Outcome::Stay;
}
if self.over.is_some() && row.scope() == self.over {
return Outcome::Close;
}
let name = row.name();
if row.is_empty() {
self.status = Some(format!("{name} has no changes"));
return Outcome::Stay;
}
let Some(scope) = row.scope() else { return Outcome::Stay };
if self.opening == Some(index) {
return Outcome::Stay;
}
self.work.stop_captures();
self.work.stop_sizes();
for row in &mut self.rows {
if row.size == Sized::Asking {
row.size = Sized::Waiting;
}
}
self.opening = Some(index);
self.status = Some(format!("opening {name}\u{2026}"));
self.ask(Job::Capture { row: index, scope });
Outcome::Stay
}
fn reload(&mut self) {
self.generation += 1;
self.work.stop_all();
self.opening = None;
self.keep = self.rows.get(self.cursor).and_then(Row::scope).filter(|_| self.pinned);
let count = self.rows.iter().filter(|row| matches!(row.kind, Kind::Commit(_))).count().max(PAGE);
self.rows = [Kind::Uncommitted, Kind::Unstaged, Kind::Staged].map(Row::new).into();
self.listed = false;
self.more = More::None;
self.ask(Job::List { skip: 0, count });
self.status = Some(RELOADING.into());
self.ask_sizes();
}
}