mod draw;
mod marks;
#[cfg(test)]
mod range_tests;
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 marks::Marks;
use rows::{Kind, Row, Sized};
use source::{Done, Job, Listing, PAGE, Source, Work};
const RELOADING: &str = "reloading\u{2026}";
const REACH_PAGES: usize = 10;
#[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<Scope>,
opened: Option<(Repo, Capture)>,
keep: Option<Scope>,
marks: Marks,
aimed: Option<Scope>,
counting: Option<Scope>,
counts: Vec<(Scope, Result<usize, String>)>,
reached: usize,
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: None,
over: over.clone(),
help: false,
generation: 0,
opening: None,
opened: None,
marks: Marks::default(),
aimed: None,
counting: None,
counts: Vec::new(),
reached: 0,
keys,
geometry: Geometry::default(),
};
if let Some(over) = over {
picker.aim(over);
}
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.ask_count();
self.settle_cursor();
changed
}
pub(crate) fn take_opened(&mut self) -> Option<(Repo, Capture)> {
self.opened.take()
}
fn ask(&mut self, job: Job) -> bool {
let asked = self.work.ask(self.generation, job);
if !asked {
self.status = Some("could not start a thread to ask git".into());
}
asked
}
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, scope, captured } if generation == self.generation => {
if self.opening.as_ref() != Some(&scope) {
return;
}
self.opening = None;
let name = scope.title();
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 = matches!(
scope,
Scope::Commit { .. } | Scope::Range { .. } | Scope::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::Count { generation, scope, count } if generation == self.generation => {
self.take_count(scope, count);
}
Done::List { .. } | Done::Size { .. } | Done::Capture { .. } | Done::Count { .. } => {}
}
}
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.reach_marks();
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.aim(scope);
if self.listed {
self.reach_marks();
}
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.more != More::Loading {
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.confirm(),
Some(Action::MarkCommit) => {
self.mark();
self.ask_count();
}
Some(Action::Reload) => self.reload(),
Some(Action::Help) => self.help = true,
Some(Action::Back) if !self.marks.is_empty() && self.aimed.is_none() => {
self.marks.clear();
self.forget_failed_counts();
self.status = None;
}
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 mark(&mut self) {
let Some(row) = self.rows.get(self.cursor) else { return };
if row.scope().is_some_and(|scope| matches!(scope, Scope::Commit { .. })) {
self.aimed = None;
}
self.counts.retain(|(_, count)| count.is_ok());
if self.marks.toggle(row) {
self.status = None;
} else {
self.status = Some(format!("only commits can be marked; {} is not one", row.name()));
}
}
fn confirm(&mut self) -> Outcome {
if self.rows.get(self.cursor).is_some_and(|row| row.kind == Kind::More) {
return self.choose(self.cursor);
}
if let Some(aimed @ Scope::Range { to, .. }) = &self.aimed {
let on_newest =
self.rows.get(self.cursor).and_then(Row::scope) == Some(Scope::Commit { sha: to.clone() });
if on_newest {
let aimed = aimed.clone();
return self.capture(aimed);
}
return self.choose(self.cursor);
}
if let Some(scope) = self.marks.range(&self.rows) {
return self.capture(scope);
}
match self.marks.span(&self.rows) {
Some((marked, _)) => self.choose(marked),
None => self.choose(self.cursor),
}
}
fn choose(&mut self, index: usize) -> Outcome {
let Some(row) = self.rows.get(index) else { return Outcome::Stay };
if row.kind == Kind::More {
self.list_more();
return Outcome::Stay;
}
if row.is_empty() && row.scope() != self.over {
self.status = Some(format!("{} has no changes", row.name()));
return Outcome::Stay;
}
let Some(scope) = row.scope() else { return Outcome::Stay };
self.capture(scope)
}
fn list_more(&mut self) {
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 });
}
}
fn capture(&mut self, scope: Scope) -> Outcome {
if self.over.as_ref() == Some(&scope) {
return Outcome::Close;
}
if self.opening.as_ref() == Some(&scope) {
return Outcome::Stay;
}
self.work.stop_captures();
self.work.stop_sizes();
self.counting = None;
for row in &mut self.rows {
if row.size == Sized::Asking {
row.size = Sized::Waiting;
}
}
self.status = Some(format!("opening {}\u{2026}", scope.title()));
self.opening = Some(scope.clone());
self.ask(Job::Capture { scope });
Outcome::Stay
}
fn reload(&mut self) {
self.generation += 1;
self.work.stop_all();
self.opening = None;
self.counting = None;
self.reached = 0;
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();
}
}