//! Terminal session loop for the `brain` review TUI. use std::collections::BTreeSet; use std::io; use std::mem; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; use std::time::Duration; use rustik_diff::{ ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffState, DiffViewer, FileDiff, FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, HunkFocus, ReviewProgress, ViewChange, spawn_highlighter, }; use rustik_repo::{DiffStat, git}; use rustik_tui::{ Backend as TuiBackend, Column, Constraint, Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, ScrollView, Style, Table, TableOptions, Terminal, }; use rustik_tui_termion as tui_termion; use crate::backend::{ Accepted, Backend, Brain, Commit, CommitHunks, CommitReviewState, FilePatches, HistoryStatus, }; use crate::comments::{Comments, ReviewComments}; use crate::error::Error; use crate::review::{FileVisibility, HunkVisibility, Visibility}; mod commit; mod event; mod hunk; mod status; mod worker; use commit::{CommitReview, CommitSlot}; use event::{ContextFetch, Resize, TerminalEvent, Update, context_change}; use hunk::{CommentEdit, HunkView}; pub(crate) use status::BRAIN_BADGE_BG; use status::{ ActionContext, Chrome, HISTORY_DIFFSTAT_MAX_WIDTH, SELECTED_COMMIT_BG, Status, StatusContext, commit_row, commit_row_suffix, current_timestamp, viewer_area, }; use worker::{ Command as WorkerCommand, LoadCommit, Output as WorkerOutput, ReviewMutation, Worker, }; /// Terminal backend used by the interactive viewer. type BrainTerminal = Terminal>; /// Minimum width of a history diffstat graph. const HISTORY_DIFFSTAT_MIN_WIDTH: usize = 8; /// Spinner repaint interval while repository work is pending. const SPINNER_INTERVAL: Duration = Duration::from_millis(80); /// Fraction of the history panel available to the diffstat graph. const HISTORY_DIFFSTAT_WIDTH_DIVISOR: usize = 6; /// Active view in the session. enum Mode { /// The commit list. Commits, /// The diff of the current commit. Diff, /// A single hunk with an inline comment box. /// /// Boxed because the hunk view owns its own diff viewer, which would /// otherwise dominate the size of every mode value. Hunk(Box), } impl Mode { /// Returns the footer label for this active view. fn label(&self) -> &'static str { match self { Self::Commits => "history", Self::Diff => "commit", Self::Hunk(_) => "hunk", } } /// Returns the active file's visibility for this view. fn file_visibility(&self, loaded: Option<&CommitReview>) -> FileVisibility { if matches!(self, Self::Diff) && loaded.is_some_and(CommitReview::is_full_file) { FileVisibility::Full } else { FileVisibility::Context } } /// Returns the focus-independent mutation represented by `event`. fn deferred_mutation(&self, event: &Event<()>) -> Option { match (self, event) { (Self::Commits | Self::Diff, Event::Key(Key::Char('a'))) => { Some(DeferredMutation::ToggleAcceptance) } (Self::Diff, Event::Key(Key::Char('A'))) => { Some(DeferredMutation::ToggleFileAcceptance) } (Self::Diff, Event::Key(Key::Char('u'))) => Some(DeferredMutation::UndoAcceptance), (Self::Commits, Event::Key(Key::Char('r'))) => Some(DeferredMutation::ToggleRejection), (Self::Commits, Event::Key(Key::Char('d'))) => Some(DeferredMutation::ToggleDrop), _ => None, } } /// Returns whether `event` is read-only navigation in this view. fn allows_navigation_during_persistence(&self, event: &Event<()>) -> bool { match self { Self::Commits => matches!( event, Event::Key(Key::Char('j' | 'k') | Key::Down | Key::Up) | Event::Mouse(Mouse::Press { button: MouseButton::WheelDown | MouseButton::WheelUp, .. }) ), Self::Diff => matches!( event, Event::Key( Key::Char('j' | 'k' | 'n' | 'p' | 'g' | 'G' | ' ') | Key::Down | Key::Up | Key::PageDown | Key::PageUp | Key::Ctrl('d' | 'u') | Key::Home | Key::End ) | Event::Mouse(Mouse::Press { button: MouseButton::WheelDown | MouseButton::WheelUp, .. }) ), Self::Hunk(_) => false, } } } /// Terminal event channel shared by pre-session prompts and the session loop. /// /// Reading terminal input consumes it, so one input worker must feed every /// consumer; creating a second stream would steal keystrokes from the first. pub struct Events { /// Sender cloned by background workers. tx: Sender, /// Receiver drained by the session loop. rx: Receiver, } impl Events { /// Creates the channel and spawns the blocking terminal input worker. pub fn spawn() -> Self { let (tx, rx) = mpsc::channel(); TerminalEvent::spawn_input_worker(tx.clone()); Self { tx, rx } } /// Blocks until the next terminal input event, skipping other events. /// /// Returns `None` once the input worker has disconnected. pub fn next_input(&self) -> Option>> { loop { match self.rx.recv() { Ok(TerminalEvent::Input(event)) => return Some(event), Ok(_) => {} Err(_) => return None, } } } /// Discards input received while no interactive screen was visible. pub fn discard_pending(&self) { while self.rx.try_recv().is_ok() {} } } /// Runs the terminal event loop until the reviewer quits. pub fn run( terminal: &mut BrainTerminal, events: Events, commits: Vec, backend: Box, brain: Brain, comments: ReviewComments, options: DiffOptions, ) -> Result<(), Error> { let Events { tx: events_tx, rx: events_rx, } = events; let range = backend.range_label(); let history_commits = (commits.len() > 1).then(|| commits.clone()); let mut repositories = commits .iter() .map(|commit| backend.repo(commit)) .collect::>(); let mut slots = commits .into_iter() .map(|commit| CommitSlot { remaining_stats: commit.stats, commit, progress: ReviewProgress::default(), accepted_hunks: 0, total_hunks: 0, comment_count: 0, state: CommitReviewState::Pending, document: None, identities: None, loaded: None, }) .collect::>(); slots.reverse(); repositories.reverse(); let mode = if slots.len() > 1 { Mode::Commits } else { Mode::Diff }; let repository_worker = Worker::spawn(backend, brain.clone(), events_tx.clone()); let mut session = Session { terminal, commits: slots, range, history_status: None, accepted: Vec::new(), pending: None, deferred_mutation: None, current: 0, hunk_visibility: HunkVisibility::default(), mode, parked: None, list: ListState::new(), options, repositories, brain, comments, events_tx, generation: 0, highlighter: None, repository_worker, context_fetch: ContextFetch::default(), error: None, loading: None, spinner: 0, }; if let Some(commits) = history_commits { session.loading = Some("loading history"); session .repository_worker .send(WorkerCommand::LoadHistory { commits, comments: session.comments.clone(), }) .map_err(Error::Git)?; } else { session.request_commit(0)?; } session.redraw()?; loop { let received = if session.loading.is_some() { match events_rx.recv_timeout(SPINNER_INTERVAL) { Ok(event) => Some(event), Err(RecvTimeoutError::Timeout) => { session.spinner = session.spinner.wrapping_add(1); session.redraw()?; continue; } Err(RecvTimeoutError::Disconnected) => None, } } else { events_rx.recv().ok() }; let Some(event) = received else { break; }; let Some(event) = TerminalEvent::receive(Ok::<_, mpsc::RecvError>(event))? else { break; }; let mut redraw = false; let mut next = Some(event); // Drain queued events before repainting so bursts coalesce into one frame. while let Some(event) = next { match session.update(event) { Ok(Update::Continue) => {} Ok(Update::Redraw) => redraw = true, Ok(Update::Quit) => return Ok(()), Err(error) => { session.error = Some(error.to_string().replace('\n', " · ")); redraw = true; } } next = TerminalEvent::receive(events_rx.try_recv())?; } if redraw { session.redraw()?; } } Ok(()) } /// Returns the interactive history table for regular terminal output. pub(crate) fn history_output_table( commits: Vec, backend: &dyn Backend, brain: &Brain, comments: &ReviewComments, palette: rustik_diff::DiffPalette, width: usize, ) -> Result, Error> { let (mut slots, _) = reviewed_slots(commits, backend, brain, comments)?; slots.reverse(); Ok(history_table(&slots, palette, width)) } /// Builds reviewed commit slots and their aggregate history status. fn reviewed_slots( commits: Vec, backend: &dyn Backend, brain: &Brain, comments: &ReviewComments, ) -> Result<(Vec, HistoryStatus), Error> { let mut reviewed = Vec::with_capacity(commits.len()); for commit in commits { let document = backend.diff_document(commit.id)?.split_hunks(); let identities = brain.hunk_identities(&document, commit.id)?; reviewed.push((commit, document, identities)); } if reviewed.is_empty() { return Err(Error::Empty); } let status_inputs = reviewed .iter() .map(|(commit, document, identities)| (commit.id, document, identities)) .collect::>(); let mut history = HistoryStatus::for_commits(brain, &status_inputs); let slots = reviewed .into_iter() .map(|(commit, document, identities)| { let status = history.commits.entry(commit.id).or_default(); CommitSlot { progress: status.progress, accepted_hunks: status.accepted_hunks, total_hunks: status.total_hunks, comment_count: identities .values() .map(|identity| { comments.matching_count( identity.commit, &identity.patch_id, identity.ordinal, ) }) .sum(), state: status.state, remaining_stats: status.stats, commit, document: Some(document), identities: Some(identities), loaded: None, } }) .collect(); Ok((slots, history)) } /// Builds the commit table shared by interactive and regular history output. fn history_table( commits: &[CommitSlot], palette: rustik_diff::DiffPalette, width: usize, ) -> Table<9, Line> { let now = current_timestamp(); let largest_change_count = commits .iter() .map(|slot| { let stats = slot.remaining_stats(); stats.insertions + stats.deletions }) .max() .unwrap_or(0); let diffstat_width = (width / HISTORY_DIFFSTAT_WIDTH_DIVISOR) .clamp(HISTORY_DIFFSTAT_MIN_WIDTH, HISTORY_DIFFSTAT_MAX_WIDTH); let mut table = Table::<9, Line>::new(TableOptions { spacing: 2, ..TableOptions::default() }) .with_layout([ Column::auto(), Column::auto(), Column::auto(), Column::flex(1), Column::collapse(2), Column::collapse(3), Column::collapse(1), Column::auto(), Column::collapse(4), ]); for slot in commits { let [state, id, summary] = commit_row(slot, palette); let [hunks, author, age, branches, comments, diffstat] = commit_row_suffix(slot, palette, now, largest_change_count, diffstat_width); table.push([ state, hunks, id, summary, author, age, branches, comments, diffstat, ]); } table } /// Commit-local hunk location used by acceptance and undo state. type HunkLocation = (usize, rustik_diff::HunkId); /// Viewer state around one optimistic acceptance. struct NavigationRollback { /// Commit whose viewer changed. commit: usize, /// Viewer state before the optimistic change. before: DiffState, /// Viewer state after automatic navigation. after: DiffState, } /// State around one optimistic acceptance. struct AcceptancePending { /// Review state restored if persistence fails. rollback: Box, /// Undo stack installed after successful persistence. undo: Vec, /// Navigation restored if the user has not moved again. navigation: Option, } /// Comment state restored if persistence fails. struct CommentRollback { /// Commit whose comment view changed. commit: usize, /// Review-wide store before the optimistic mutation. store: ReviewComments, /// Commit-local view before the optimistic mutation. comments: Comments, } /// Optimistic state restored or finalized when persistence completes. enum Pending { /// Hunk acceptance currently writing to the repository. Acceptance(AcceptancePending), /// Commit decision currently writing to the repository. Decision, /// Comment mutation currently writing to the repository. Comments(CommentRollback), } /// Repository mutation waiting for the active persistence command. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum DeferredMutation { /// Toggle acceptance at the current focus. ToggleAcceptance, /// Toggle acceptance of the focused file. ToggleFileAcceptance, /// Undo the latest accepted hunk. UndoAcceptance, /// Toggle rejection of the selected commit. ToggleRejection, /// Toggle dropping of the selected commit. ToggleDrop, /// Delete the selected hunk comment. DeleteComment, } /// Interactive terminal session state. struct Session<'a, T: TuiBackend> { /// Terminal frame target. terminal: &'a mut Terminal, /// Per-commit review slots, newest first. commits: Vec, /// User-facing revision range under review. range: String, /// Lazily cached global progress and remaining statistics for history. history_status: Option, /// Hunk acceptances available to undo, in acceptance order. accepted: Vec, /// Optimistic state currently writing to the repository. pending: Option, /// Semantic repository mutation waiting for active persistence to finish. deferred_mutation: Option, /// Index of the commit currently displayed. current: usize, /// Set of hunks visible across commit viewers. hunk_visibility: HunkVisibility, /// Active view: the commit list, the diff, or a hunk's comment box. mode: Mode, /// Hunk view kept alive while another tab is active, for Tab round-trips. parked: Option>, /// Selection and scroll state for the commit-list tab. list: ListState, /// Viewer options used to build commit and per-hunk viewers. options: DiffOptions, /// Git contexts used only by background highlighters. repositories: Vec, /// Serialized command interface for every UI-initiated repository operation. repository_worker: Worker, /// Hidden review state storing accepted identities, derived content, and comments. brain: Brain, /// Review-wide persistent comment store. comments: ReviewComments, /// Sender used to respawn the highlighter for the current commit. events_tx: Sender, /// Generation of the active highlighter; stale output is ignored. generation: u64, /// Highlighter for the current commit, respawned on each switch. highlighter: Option, /// Whether a context refetch is in flight. context_fetch: ContextFetch, /// Repository operation currently represented by the status spinner. loading: Option<&'static str>, /// Current spinner animation frame. spinner: usize, /// Most recent recoverable session error shown in the status bar. error: Option, } impl> Session<'_, T> { /// Returns the current commit's cached diff state. fn current(&mut self) -> Result<&mut CommitReview, Error> { self.load(self.current) } /// Returns commit `index`'s cached diff state. fn load(&mut self, index: usize) -> Result<&mut CommitReview, Error> { self.commits[index] .loaded .as_mut() .ok_or_else(|| Error::Git("commit is still loading".to_owned())) } /// Queues construction of one uncached commit viewer. fn request_commit(&mut self, index: usize) -> Result<(), Error> { if self.commits[index].loaded.is_some() { return Ok(()); } let slot = &mut self.commits[index]; let command = WorkerCommand::LoadCommit(Box::new(LoadCommit { index, commit: slot.commit.clone(), document: slot.document.take(), identities: slot.identities.take(), options: self.options.clone(), comments: self.comments.clone(), })); self.repository_worker.send(command).map_err(Error::Git)?; self.loading = Some("loading commit"); Ok(()) } /// Applies one terminal or worker event and records redraw work. /// /// Input is routed by active mode first so the commit list and hunk editor /// can reserve keys that would otherwise belong to the diff viewer. Worker /// output is tagged with a generation, letting stale highlighter results /// from a previous commit be ignored after a commit switch. fn update(&mut self, event: TerminalEvent) -> Result { match event { TerminalEvent::Input(event) => { self.error = None; let event = event?; if self.action_context() != ActionContext::HunkEdit && matches!(event, Event::Key(Key::Ctrl('c'))) { return self.try_quit(); } if self.loading.is_some() && !matches!(event, Event::Resize(_)) { if self.pending.is_none() { return Ok(Update::Continue); } if let Some(mutation) = self.deferred_mutation(&event) { self.deferred_mutation.get_or_insert(mutation); return Ok(Update::Continue); } if !self.allows_navigation_during_persistence(&event) { return Ok(Update::Continue); } } let resize = if matches!(event, Event::Resize(_)) { Resize::Changed } else { Resize::Stable }; let control = match self.mode { Mode::Hunk(_) => { let area = viewer_area(self.terminal.area()); self.handle_hunk_key(event, area)? } Mode::Commits => self.handle_commits_key(event)?, Mode::Diff => { if let Some(change) = context_change(&event) { // Context expansion is asynchronous and may not // redraw immediately, so it bypasses the ordinary // diff input path. self.request_context(change); return Ok(Update::Continue); } let area = viewer_area(self.terminal.area()); self.handle_key(event, area)? } }; let update = Update::from_control(control, resize); if update == Update::Quit { self.try_quit() } else { Ok(update) } } TerminalEvent::Highlight(generation, HighlightOutput::Highlights(results)) => { if generation == self.generation && self .active_viewer() .is_some_and(|viewer| viewer.apply_highlights(results)) { self.draw_frame()?; } Ok(Update::Continue) } TerminalEvent::Highlight(generation, HighlightOutput::Context(update)) => { if generation != self.generation { return Ok(Update::Continue); } let redraw = if let Some(update) = update { let area = viewer_area(self.terminal.area()); if let Some(loaded) = &mut self.commits[self.current].loaded { loaded.apply_context_update(update, &self.brain, area)?; } self.refresh_visibility()?; true } else { false }; let desired = self.context_fetch.complete(generation); if let Some(change) = desired { self.request_context(change); } Ok(if redraw { Update::Redraw } else { Update::Continue }) } TerminalEvent::Worker(output) => self.handle_worker_output(*output), } } /// Leaves the session unless repository work is still pending. fn try_quit(&mut self) -> Result { Ok(if self.loading.is_some() || self.error.is_some() { Update::Redraw } else { Update::Quit }) } /// Applies one completed repository command without performing I/O. fn handle_worker_output(&mut self, output: WorkerOutput) -> Result { self.loading = None; match output { WorkerOutput::CommitLoaded { index, result } => match *result { Ok(loaded) => { self.commits[index].loaded = Some(loaded); self.reconcile_state(); if index == self.current && matches!(self.mode, Mode::Diff) { self.activate()?; } else if self.commits[self.current].loaded.is_none() { self.request_commit(self.current)?; } } Err(message) => self.error = Some(message.replace('\n', " · ")), }, WorkerOutput::HistoryLoaded(result) => match *result { Ok((mut commits, status)) => { commits.reverse(); self.commits = commits; self.history_status = Some(status); } Err(message) => self.error = Some(message.replace('\n', " · ")), }, WorkerOutput::SourcesLoaded { hunk, result } => match *result { Ok(viewer) => { let mut view = HunkView::new(hunk, viewer, self.comments.author().to_owned()); view.enter(); self.mode = Mode::Hunk(Box::new(view)); self.restart_highlighter()?; } Err(message) => self.error = Some(message.replace('\n', " · ")), }, WorkerOutput::Persisted(result) => { self.finish_persistence(*result)?; if let Some(mutation) = self.deferred_mutation.take() { self.apply_deferred_mutation(mutation)?; } } } Ok(Update::Redraw) } /// Returns the repository mutation represented by `event` in the active view. fn deferred_mutation(&self, event: &Event<()>) -> Option { if let Some(mutation) = self.mode.deferred_mutation(event) { return Some(mutation); } match (&self.mode, event) { (Mode::Diff, Event::Key(Key::Char('r' | 'd'))) if matches!( self.commits[self.current] .loaded .as_ref() .and_then(|loaded| loaded.viewer.state().focus), Some(DiffFocus::Commit) ) => { Some(if matches!(event, Event::Key(Key::Char('r'))) { DeferredMutation::ToggleRejection } else { DeferredMutation::ToggleDrop }) } (Mode::Hunk(view), Event::Key(Key::Char('r'))) if !view.is_editing() => { Some(DeferredMutation::ToggleRejection) } (Mode::Hunk(view), Event::Key(Key::Char('d'))) if !view.is_editing() => { Some(DeferredMutation::DeleteComment) } _ => None, } } /// Returns whether `event` is safe while repository persistence is pending. fn allows_navigation_during_persistence(&self, event: &Event<()>) -> bool { if self.mode.allows_navigation_during_persistence(event) { return true; } match &self.mode { Mode::Hunk(view) if !view.is_editing() => { matches!(event, Event::Key(Key::Char('n' | 'p'))) || Self::hunk_scroll_event(event) } Mode::Commits | Mode::Diff | Mode::Hunk(_) => false, } } /// Applies one queued mutation against the current semantic focus. fn apply_deferred_mutation(&mut self, mutation: DeferredMutation) -> Result<(), Error> { match mutation { DeferredMutation::ToggleAcceptance => match self.mode { Mode::Commits => self.toggle_commit_accepted(self.list.selected())?, Mode::Diff => { let area = viewer_area(self.terminal.area()); match self.current()?.viewer.state().focus { Some(DiffFocus::Commit) => self.toggle_commit_accepted(self.current)?, Some(DiffFocus::File(_)) => self.toggle_focused_file(area)?, Some(DiffFocus::Hunk(_)) | None => self.toggle_focused_hunk(area)?, } } Mode::Hunk(_) => {} }, DeferredMutation::ToggleFileAcceptance => { if matches!(self.mode, Mode::Diff) { let area = viewer_area(self.terminal.area()); self.toggle_focused_file(area)?; } } DeferredMutation::UndoAcceptance => { if matches!(self.mode, Mode::Diff) { self.undo_last_hunk_accept()?; } } DeferredMutation::ToggleRejection => { let index = if matches!(self.mode, Mode::Commits) { self.list.selected() } else { self.current }; self.toggle_commit_rejected(index)?; if matches!(self.mode, Mode::Hunk(_)) { self.next_tab()?; } } DeferredMutation::ToggleDrop => { let index = if matches!(self.mode, Mode::Commits) { self.list.selected() } else { self.current }; self.toggle_commit_dropped(index)?; } DeferredMutation::DeleteComment => { if matches!(self.mode, Mode::Hunk(_)) { self.delete_selected_comment()?; } } } Ok(()) } /// Dispatches one input event, handling review keys before the viewer. fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result { match event { Event::Key(Key::Char('a')) => { match self.current()?.viewer.state().focus { Some(DiffFocus::Commit) => self.toggle_commit_accepted(self.current)?, Some(DiffFocus::File(_)) => self.toggle_focused_file(area)?, Some(DiffFocus::Hunk(_)) | None => self.toggle_focused_hunk(area)?, } Ok(Control::Redraw) } Event::Key(Key::Char('u')) => { self.undo_last_hunk_accept()?; Ok(Control::Redraw) } Event::Key(Key::Char('A')) => { self.toggle_focused_file(area)?; Ok(Control::Redraw) } Event::Key(Key::Char('r')) => { if matches!( self.current()?.viewer.state().focus, Some(DiffFocus::Commit) ) { self.toggle_commit_rejected(self.current)?; self.next_tab()?; } Ok(Control::Redraw) } Event::Key(Key::Char('d')) => { if matches!( self.current()?.viewer.state().focus, Some(DiffFocus::Commit) ) { self.toggle_commit_dropped(self.current)?; } Ok(Control::Redraw) } Event::Key(Key::Char('v')) => { self.hunk_visibility.toggle(); self.refresh_visibility()?; Ok(Control::Redraw) } Event::Key(Key::Char('j')) => self.apply(DiffAction::NextHunk, area), Event::Key(Key::Char('k')) => self.apply(DiffAction::PreviousHunk, area), Event::Key(Key::Char('n')) => self.apply(DiffAction::FocusNext, area), Event::Key(Key::Char('p')) => self.apply(DiffAction::FocusPrevious, area), Event::Key(Key::Char('c')) => { self.enter_hunk_view(area)?; Ok(Control::Redraw) } Event::Key(Key::Enter) => { self.enter_hunk_view(area)?; Ok(Control::Redraw) } Event::Key(Key::Char(']')) => self.switch(1), Event::Key(Key::Char('[')) => self.switch(-1), Event::Key(Key::Tab) => { self.next_tab()?; Ok(Control::Redraw) } _ => Ok(self.current()?.viewer.handle_input(event, area)), } } /// Applies a viewer action, returning `Redraw` if the view changed. fn apply(&mut self, action: DiffAction, area: Rect) -> Result { if self.current()?.viewer.apply(action, area) == ViewChange::Changed { Ok(Control::Redraw) } else { Ok(Control::Continue) } } /// Moves to another commit by `delta`. fn switch(&mut self, delta: isize) -> Result { let last = self.commits.len().saturating_sub(1); let next = (self.current as isize + delta).clamp(0, last as isize) as usize; if next == self.current { return Ok(Control::Continue); } self.select_commit(next)?; Ok(Control::Redraw) } /// Displays the commit at `index`, loading it and respawning workers. fn select_commit(&mut self, index: usize) -> Result<(), Error> { if index != self.current { self.parked = None; } self.current = index; self.mode = Mode::Diff; if self.commits[index].loaded.is_some() { self.activate()?; } else { self.request_commit(index)?; } Ok(()) } /// Routes one key while the commit-list tab is open. fn handle_commits_key(&mut self, event: Event<()>) -> Result { let delta = match event { Event::Key(Key::Char('q')) => return Ok(Control::Quit), Event::Key(Key::Char('j') | Key::Down) | Event::Mouse(Mouse::Press { button: MouseButton::WheelDown, .. }) => 1, Event::Key(Key::Char('k') | Key::Up) | Event::Mouse(Mouse::Press { button: MouseButton::WheelUp, .. }) => -1, Event::Key(Key::Char('a')) => { self.toggle_commit_accepted(self.list.selected())?; return Ok(Control::Redraw); } Event::Key(Key::Char('r')) => { self.toggle_commit_rejected(self.list.selected())?; return Ok(Control::Redraw); } Event::Key(Key::Char('d')) => { self.toggle_commit_dropped(self.list.selected())?; return Ok(Control::Redraw); } Event::Key(Key::Enter) => { self.select_commit(self.list.selected())?; return Ok(Control::Redraw); } Event::Key(Key::Tab) => { self.next_tab()?; return Ok(Control::Redraw); } Event::Resize(_) => return Ok(Control::Redraw), _ => return Ok(Control::Continue), }; if self.list.move_by(delta, self.commits.len()) { Ok(Control::Redraw) } else { Ok(Control::Continue) } } /// Toggles acceptance of every hunk in one commit. fn toggle_commit_accepted(&mut self, index: usize) -> Result<(), Error> { let identities = self.commits[index].identities()?; let accepted = !identities.is_empty() && identities .values() .all(|identity| self.brain.accepted.contains(identity)); let hunks = identities .keys() .map(|hunk| (index, *hunk)) .collect::>(); if accepted { self.reject_hunks(hunks)?; } else { self.accept_hunks(hunks)?; } Ok(()) } /// Queues a toggle of one commit's rejected decision. fn toggle_commit_rejected(&mut self, index: usize) -> Result<(), Error> { let commit = self.commits[index].commit.id; self.persist_commit_decision(ReviewMutation::ToggleRejected { commit }) } /// Queues a toggle of one commit's dropped decision. fn toggle_commit_dropped(&mut self, index: usize) -> Result<(), Error> { let commit = self.commits[index].commit.id; self.persist_commit_decision(ReviewMutation::ToggleDropped { commit }) } /// Starts persistence for a commit decision under the common pending state. fn persist_commit_decision(&mut self, mutation: ReviewMutation) -> Result<(), Error> { debug_assert!(self.pending.is_none()); self.repository_worker .send(WorkerCommand::Mutate(mutation)) .map_err(Error::Git)?; self.pending = Some(Pending::Decision); self.loading = Some("saving review"); Ok(()) } /// Toggles acceptance of the focused hunk. fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> { let current = self.current; let pending_only = matches!(self.hunk_visibility, HunkVisibility::Pending); let before = self.current()?.viewer.state().clone(); let loaded = self.current()?; let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else { return Ok(()); }; if !loaded.identities.contains_key(&hunk) { return Ok(()); } let accepted = loaded.review.is_accepted(hunk); let next = (!accepted && pending_only) .then(|| { loaded .document .files .iter() .flat_map(|file| &file.hunks) .skip_while(|candidate| candidate.id != hunk) .skip(1) .find(|candidate| { loaded.identities.contains_key(&candidate.id) && !loaded.review.is_accepted(candidate.id) }) .map(|candidate| candidate.id) }) .flatten(); if accepted { self.reject_hunks(BTreeSet::from([(current, hunk)]))?; } else { self.accept_hunks(BTreeSet::from([(current, hunk)]))?; } if let Some(next) = next { self.current()?.viewer.focus_hunk(next, area); } self.record_navigation_rollback(current, before)?; Ok(()) } /// Rejects the most recently accepted hunk that remains accepted. fn undo_last_hunk_accept(&mut self) -> Result<(), Error> { while let Some(&(index, hunk)) = self.accepted.last() { let accepted = self.load(index)?.review.is_accepted(hunk); if accepted { let before = self.load(index)?.viewer.state().clone(); self.reject_hunks(BTreeSet::from([(index, hunk)]))?; self.record_navigation_rollback(index, before)?; break; } self.accepted.pop(); } Ok(()) } /// Persists acceptance or rejection of every hunk in the focused file. fn toggle_focused_file(&mut self, area: Rect) -> Result<(), Error> { let current = self.current; let pending_only = matches!(self.hunk_visibility, HunkVisibility::Pending); let before = self.current()?.viewer.state().clone(); let loaded = self.current()?; let Some(file) = loaded.viewer.focused_file() else { loaded.viewer.apply(DiffAction::NextHunk, area); return Ok(()); }; let Some(file) = loaded .document .files .iter() .find(|candidate| candidate.id == file) else { return Ok(()); }; let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::>(); let accepted = loaded.review.accepts_all(hunk_ids.iter().copied()); if !accepted && pending_only { loaded.viewer.apply(DiffAction::FocusNext, area); } let hunks = hunk_ids .into_iter() .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted) .filter(|hunk| loaded.identities.contains_key(hunk)) .map(|hunk| (current, hunk)) .collect::>(); if accepted { self.reject_hunks(hunks)?; if pending_only { self.current()?.viewer.apply(DiffAction::NextHunk, area); } } else { self.accept_hunks(hunks)?; } self.record_navigation_rollback(current, before)?; Ok(()) } /// Optimistically accepts the selected hunks and starts persistence. fn accept_hunks(&mut self, hunks: BTreeSet) -> Result<(), Error> { let identities = hunks .iter() .map(|(index, hunk)| { self.commits[*index] .identities()? .get(hunk) .cloned() .ok_or_else(|| Error::Git(format!("hunk {hunk:?} has no identity"))) }) .collect::, Error>>()?; let mut accepted = self.brain.accepted.clone(); accepted.extend(identities.iter().cloned()); let mut undo = self.accepted.clone(); undo.extend(hunks); self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Accept { identities, patches, }) } /// Optimistically rejects the selected hunks and starts persistence. fn reject_hunks(&mut self, hunks: BTreeSet) -> Result<(), Error> { let identities = hunks .iter() .map(|(index, hunk)| { self.commits[*index] .identities()? .get(hunk) .cloned() .ok_or_else(|| Error::Git(format!("hunk {hunk:?} has no identity"))) }) .collect::, Error>>()?; let mut accepted = self.brain.accepted.clone(); accepted.retain(|identity| !identities.contains(identity)); let mut undo = self.accepted.clone(); undo.retain(|hunk| !hunks.contains(hunk)); self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Reject { identities, patches, }) } /// Records automatic navigation for the pending rollback. fn record_navigation_rollback( &mut self, commit: usize, before: DiffState, ) -> Result<(), Error> { let after = self.load(commit)?.viewer.state().clone(); if let Some(Pending::Acceptance(pending)) = &mut self.pending { pending.navigation = Some(NavigationRollback { commit, before, after, }); } Ok(()) } /// Shows optimistic state, prepares its projection, and starts persistence. fn persist_acceptance( &mut self, accepted: Accepted, undo: Vec, mutation: impl FnOnce(Vec) -> ReviewMutation, ) -> Result<(), Error> { debug_assert!(self.pending.is_none()); let rollback = self.brain.clone(); self.brain.rollback(accepted); if let Err(error) = self.reconcile_reviews() { self.brain = rollback; self.reconcile_state(); return Err(error); } let result = (|| -> Result<(), Error> { let mut patches = Vec::new(); for slot in &self.commits { let identities = slot.identities()?; let document = slot.document()?; for file in &document.files { let hunks = file .hunks .iter() .filter(|hunk| { identities .get(&hunk.id) .is_some_and(|identity| self.brain.accepted.contains(identity)) }) .cloned() .collect::>(); if !hunks.is_empty() { let patch = FilePatches::new(file, hunks)?; patches.push(patch); } } } self.repository_worker .send(WorkerCommand::Mutate(mutation(patches))) .map_err(Error::Git) })(); if let Err(error) = result { self.brain = rollback; self.reconcile_reviews()?; return Err(error); } self.loading = Some("saving review"); self.pending = Some(Pending::Acceptance(AcceptancePending { rollback: Box::new(rollback), undo, navigation: None, })); Ok(()) } /// Finalizes one persisted state mutation or restores its optimistic state. fn finish_persistence(&mut self, result: Result, String>) -> Result<(), Error> { let Some(pending) = self.pending.take() else { return Err(Error::Git( "persistence completed without pending state".to_owned(), )); }; let committed = match result { Ok(committed) => committed, Err(message) => { match pending { Pending::Acceptance(pending) => { let navigation = pending.navigation.and_then(|navigation| { let loaded = self.commits.get(navigation.commit)?.loaded.as_ref()?; (loaded.viewer.state() == &navigation.after) .then_some((navigation.commit, navigation.before)) }); self.brain = *pending.rollback; self.reconcile_reviews()?; if let Some((commit, state)) = navigation { self.load(commit)?.viewer.set_state(state); } } Pending::Decision => {} Pending::Comments(rollback) => { self.comments = rollback.store; if let Some(loaded) = &mut self.commits[rollback.commit].loaded { loaded.comments = rollback.comments; loaded.refresh_decorations(); } } } self.error = Some(message.replace('\n', " · ")); return Ok(()); } }; match pending { Pending::Acceptance(pending) => { let Some(brain) = committed else { return Err(Error::Git( "review persistence completed without review state".to_owned(), )); }; self.brain = brain; self.accepted = pending.undo; } Pending::Decision => { let Some(brain) = committed else { return Err(Error::Git( "decision persistence completed without review state".to_owned(), )); }; self.brain = brain; self.reconcile_reviews()?; } Pending::Comments(_) => { debug_assert!(committed.is_none()); } } Ok(()) } /// Opens the hunk view for the focused hunk to author a comment. fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> { if !matches!( self.current()?.viewer.state().focus, Some(DiffFocus::Hunk(_)) ) { self.current()?.viewer.apply(DiffAction::NextHunk, area); } let Some(DiffFocus::Hunk(hunk)) = self.current()?.viewer.state().focus else { return Ok(()); }; // Resume a parked draft on the same hunk instead of discarding it. if let Some(mut parked) = self.parked.take_if(|parked| parked.hunk == hunk) { if !parked.is_editing() { parked.enter(); } self.mode = Mode::Hunk(parked); self.restart_highlighter()?; return Ok(()); } self.parked = None; let mut options = self.options.clone(); options.file_tree = FileTreeMode::Hidden; options.hunk_focus = HunkFocus::Plain; let loaded = self.current()?; let Some((file, focused)) = loaded.document.files.iter().find_map(|file| { let focused = file.hunks.iter().find(|candidate| candidate.id == hunk)?; Some((file, focused)) }) else { return Ok(()); }; let document = DiffDocument::for_hunks(file, [focused.clone()]); let viewer = DiffViewer::new(document, options); self.repository_worker .send(WorkerCommand::LoadSources { viewer: Box::new(viewer), hunk, }) .map_err(Error::Git)?; self.loading = Some("loading file"); Ok(()) } /// Caches global progress and remaining statistics without loading commits. fn ensure_history_status(&mut self) -> Result<(), Error> { if self.history_status.is_none() { self.reconcile_state(); let status_inputs = self .commits .iter() .map(|slot| { let identities = slot.identities()?; Ok((slot.commit.id, slot.document()?, identities)) }) .collect::, Error>>()?; let status = HistoryStatus::for_commits(&self.brain, &status_inputs); for slot in &mut self.commits { if let Some(commit) = status.commits.get(&slot.commit.id) { slot.progress = commit.progress; slot.accepted_hunks = commit.accepted_hunks; slot.total_hunks = commit.total_hunks; slot.state = commit.state; slot.remaining_stats = commit.stats; } } self.history_status = Some(status); } Ok(()) } /// Switches to the next review tab, parking any open hunk view. fn next_tab(&mut self) -> Result<(), Error> { let opens_history = matches!(&self.mode, Mode::Hunk(_)) || matches!(&self.mode, Mode::Diff) && self.parked.is_none(); if opens_history { self.ensure_history_status()?; self.stop_highlighter(); } match mem::replace(&mut self.mode, Mode::Diff) { Mode::Commits => { self.select_commit(self.list.selected())?; } Mode::Diff => { if let Some(parked) = self.parked.take() { self.mode = Mode::Hunk(parked); self.restart_highlighter()?; } else { self.list.select(self.current, self.commits.len()); self.mode = Mode::Commits; } } Mode::Hunk(view) => { self.parked = Some(view); self.list.select(self.current, self.commits.len()); self.mode = Mode::Commits; } } Ok(()) } /// Routes one key to the comment editor while the hunk view is open. fn handle_hunk_key(&mut self, event: Event<()>, area: Rect) -> Result { let comment_count = self.hunk_comment_count(); let hunk_area = self.active_viewer_area(area); if let Mode::Hunk(view) = &mut self.mode && !view.is_editing() { match event { Event::Key(Key::Esc) => { self.stop_highlighter(); self.mode = Mode::Diff; self.restart_highlighter()?; return Ok(Control::Redraw); } Event::Key(Key::Tab) => { self.next_tab()?; return Ok(Control::Redraw); } Event::Key(Key::Char('r')) => { self.toggle_commit_rejected(self.current)?; self.next_tab()?; return Ok(Control::Redraw); } Event::Key(Key::Char('c') | Key::Enter) => { view.enter(); return Ok(Control::Redraw); } Event::Key(Key::Char('n')) => { view.select_next(comment_count); return Ok(Control::Redraw); } Event::Key(Key::Char('p')) => { view.select_previous(); return Ok(Control::Redraw); } Event::Key(Key::Char('e')) => { self.edit_selected_comment(); return Ok(Control::Redraw); } Event::Key(Key::Char('d')) => { self.delete_selected_comment()?; return Ok(Control::Redraw); } _ if Self::hunk_scroll_event(&event) => { return Ok(view.viewer.handle_input(event, hunk_area)); } Event::Resize(_) => return Ok(Control::Redraw), _ => return Ok(Control::Continue), } } match event { Event::Key(Key::Esc) => { if let Mode::Hunk(view) = &mut self.mode { view.cancel_edit(); } return Ok(Control::Redraw); } Event::Key(Key::Tab) => { self.next_tab()?; return Ok(Control::Redraw); } // Ctrl+Enter submits; the enhanced keyboard protocol reports it as // a control Return distinct from a plain Enter. Event::Key(Key::Ctrl('\r')) => { self.save_comment()?; return Ok(Control::Redraw); } _ => {} } let Mode::Hunk(view) = &mut self.mode else { return Ok(Control::Continue); }; let changed = match event { Event::Key(Key::Enter) => view.newline(), Event::Key(key) => view.input(key), Event::Resize(_) => { view.viewer.apply(DiffAction::Resize, hunk_area) == ViewChange::Changed } Event::Mouse(_) => view.viewer.handle_input(event, hunk_area) == Control::Redraw, _ => false, }; Ok(if changed { Control::Redraw } else { Control::Continue }) } /// Stores the authored comment, if any, and clears the input box. fn save_comment(&mut self) -> Result<(), Error> { let Mode::Hunk(view) = &mut self.mode else { return Ok(()); }; let hunk = view.hunk; let Some((target, body)) = view.pending_edit() else { view.cancel_edit(); return Ok(()); }; let Some(loaded) = &mut self.commits[self.current].loaded else { return Ok(()); }; let added = matches!(target, CommentEdit::Add); let rollback = CommentRollback { commit: self.current, store: self.comments.clone(), comments: loaded.comments.clone(), }; let encoded = loaded .comments .transact(&mut self.comments, |comments, store| match target { CommentEdit::Add => comments.author(store, hunk, body), CommentEdit::Edit(id) => comments.edit(store, hunk, &id, body), }); if let Some(encoded) = encoded { if let Err(message) = self .repository_worker .send(WorkerCommand::WriteComments { encoded }) { self.comments = rollback.store; loaded.comments = rollback.comments; loaded.refresh_decorations(); return Err(Error::Git(message)); } loaded.refresh_decorations(); if added { let comments = loaded.comments.for_hunk(hunk).len(); view.select_comment(comments.saturating_sub(1)); } self.pending = Some(Pending::Comments(rollback)); self.loading = Some("saving comment"); } view.cancel_edit(); Ok(()) } /// Returns the number of comments on the active hunk. fn hunk_comment_count(&self) -> usize { let Mode::Hunk(view) = &self.mode else { return 0; }; self.commits[self.current] .loaded .as_ref() .map_or(0, |loaded| loaded.comments.for_hunk(view.hunk).len()) } /// Returns rendered comment rows for the active hunk view. fn hunk_comment_rows(&self) -> usize { let Mode::Hunk(view) = &self.mode else { return 0; }; view.comment_rows(self.hunk_comment_count()) } /// Returns whether an event should scroll the nested hunk diff viewer. fn hunk_scroll_event(event: &Event<()>) -> bool { if Self::non_text_hunk_scroll_event(event) { return true; } matches!(event, Event::Key(Key::Char('j' | 'k' | 'g' | 'G' | ' '))) } /// Returns whether an event should scroll without being inserted as text. fn non_text_hunk_scroll_event(event: &Event<()>) -> bool { matches!( event, Event::Key( Key::Down | Key::Up | Key::PageDown | Key::PageUp | Key::Ctrl('d' | 'u') | Key::Home | Key::End ) | Event::Mouse(Mouse::Press { button: MouseButton::WheelDown | MouseButton::WheelUp, .. }) ) } /// Starts editing the selected hunk comment. fn edit_selected_comment(&mut self) { let Mode::Hunk(view) = &mut self.mode else { return; }; let Some(loaded) = &self.commits[self.current].loaded else { return; }; let comments = loaded.comments.for_hunk(view.hunk); view.clamp_selection(comments.len()); let Some(comment) = comments.get(view.selected()) else { return; }; view.start_edit(comment); } /// Deletes the selected hunk comment. fn delete_selected_comment(&mut self) -> Result<(), Error> { let Mode::Hunk(view) = &mut self.mode else { return Ok(()); }; let Some(loaded) = &mut self.commits[self.current].loaded else { return Ok(()); }; let comments = loaded.comments.for_hunk(view.hunk); view.clamp_selection(comments.len()); let Some(comment) = comments.get(view.selected()) else { return Ok(()); }; let id = comment.id.clone(); let hunk = view.hunk; let rollback = CommentRollback { commit: self.current, store: self.comments.clone(), comments: loaded.comments.clone(), }; let encoded = loaded .comments .transact(&mut self.comments, |comments, store| { comments.delete(store, hunk, &id) }); if let Some(encoded) = encoded { if let Err(message) = self .repository_worker .send(WorkerCommand::WriteComments { encoded }) { self.comments = rollback.store; loaded.comments = rollback.comments; loaded.refresh_decorations(); return Err(Error::Git(message)); } loaded.refresh_decorations(); let comments = loaded.comments.for_hunk(hunk).len(); view.clamp_selection(comments); self.pending = Some(Pending::Comments(rollback)); self.loading = Some("saving comment"); } Ok(()) } /// Applies current visibility and starts workers for the active commit. /// /// Every activation increments `generation`. Highlight and context results /// carry that value back through the event channel, which prevents output /// from an older commit viewer from mutating the newly active viewer. fn activate(&mut self) -> Result<(), Error> { self.refresh_visibility()?; self.restart_highlighter()?; Ok(()) } /// Rebuilds the current commit's files to match accepted-hunk visibility. /// /// The original decoded document is kept in `CommitReview::document`; the /// viewer receives a filtered copy when accepted hunks are hidden. fn refresh_visibility(&mut self) -> Result<(), Error> { let hunk_visibility = self.hunk_visibility; let area = viewer_area(self.terminal.area()); let loaded = self.current()?; let files: Vec = loaded .document .files .iter() .map(|original| { if loaded.viewer.is_file_expanded(original.id) { return loaded .viewer .document() .files .iter() .find(|file| file.id == original.id) .cloned() .unwrap_or_else(|| original.clone()); } let mut file = original.clone(); if matches!(hunk_visibility, HunkVisibility::Pending) { file.hunks .retain(|hunk| !loaded.review.is_accepted(hunk.id)); } file }) .collect(); loaded.viewer.replace_file_diffs_anchored(files, area); Ok(()) } /// Reconciles per-commit review state from persisted decisions. /// /// This is the only place that replaces `Review` sets and commit states. /// Keeping it as a full recomputation keeps the persisted decisions, /// current commit list, and per-viewer decorations consistent. Persisted /// hunk totals provide progress for commits not yet decoded. fn reconcile_state(&mut self) { let commits = self .commits .iter() .map(|slot| CommitHunks { commit: slot.commit.id, hunks: slot.loaded.as_ref().map(|loaded| &loaded.identities), }) .collect::>(); let reconciled = self.brain.reconcile(&commits); for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) { slot.progress = reconciled.progress; slot.accepted_hunks = reconciled.accepted.len(); slot.total_hunks = slot.hunk_count(); slot.state = reconciled.state; if let Some(loaded) = &mut slot.loaded { loaded.review.replace(reconciled.accepted); loaded.refresh_decorations(); } } } /// Reconciles review state and refreshes the active viewer when needed. fn reconcile_reviews(&mut self) -> Result<(), Error> { self.reconcile_state(); self.history_status = None; if matches!(self.mode, Mode::Commits) { self.ensure_history_status()?; } else if matches!(self.hunk_visibility, HunkVisibility::Pending) { self.refresh_visibility()?; } Ok(()) } /// Draws a frame, requesting highlights for visible rows before it and /// lookahead rows after it. fn redraw(&mut self) -> io::Result<()> { let area = self.active_viewer_area(viewer_area(self.terminal.area())); let requests = self .active_viewer() .map_or_else(Vec::new, |viewer| viewer.visible_highlight_requests(area)); self.queue_highlights(requests); self.draw_frame()?; let requests = self .active_viewer() .map_or_else(Vec::new, |viewer| viewer.lookahead_highlight_requests(area)); self.queue_highlights(requests); Ok(()) } /// Returns the diff viewer shown by the active mode, if any. fn active_viewer(&mut self) -> Option<&mut DiffViewer> { match &mut self.mode { Mode::Hunk(view) => Some(&mut view.viewer), Mode::Diff => self.commits[self.current] .loaded .as_mut() .map(|loaded| &mut loaded.viewer), Mode::Commits => None, } } /// Returns the area the active mode's diff viewer occupies within `area`. fn active_viewer_area(&self, area: Rect) -> Rect { match &self.mode { Mode::Hunk(view) => view.viewer_area(area, self.hunk_comment_rows()), _ => area, } } /// Queues highlight work, cancelling rows the worker cannot accept. /// /// The worker may drop requests when its queue is full or stale. Dropped /// rows are removed from the viewer's pending cache so they can be requested /// again on a later redraw. fn queue_highlights(&mut self, requests: Vec) { if requests.is_empty() { return; } let dropped = self .highlighter .as_ref() .and_then(|highlighter| highlighter.highlight(requests)); if let Some(dropped) = dropped && let Some(viewer) = self.active_viewer() { viewer.cancel_highlights(dropped); } } /// Stops asynchronous work and invalidates results from the active generation. fn stop_highlighter(&mut self) { if let Some(viewer) = self.active_viewer() { viewer.retry_pending_highlights(); } self.generation += 1; self.highlighter = None; self.context_fetch = ContextFetch::Idle; } /// Restarts asynchronous syntax highlighting for the active generation. fn restart_highlighter(&mut self) -> Result<(), Error> { self.stop_highlighter(); let generation = self.generation; let tx = self.events_tx.clone(); let highlighter = if let Mode::Hunk(view) = &self.mode { spawn_highlighter(view.viewer.document(), None, move |output| { let _ = tx.send(TerminalEvent::Highlight(generation, output)); }) } else { let repo = Some(self.repositories[self.current].clone()); let loaded = self.current()?; spawn_highlighter(loaded.viewer.document(), repo, move |output| { let _ = tx.send(TerminalEvent::Highlight(generation, output)); }) }; self.highlighter = Some(highlighter); Ok(()) } /// Requests context refetch work for one context change. /// /// One request runs per active generation. A change received while it runs /// becomes a bounded desired follow-up, which starts after the viewer /// applies the current result. fn request_context(&mut self, change: ContextChange) { let generation = self.generation; if !self.context_fetch.request(generation, change) { return; } let request = self.commits[self.current] .loaded .as_ref() .and_then(|loaded| loaded.viewer.context_request(change)); let queued = request.is_some_and(|request| { self.highlighter .as_ref() .is_some_and(|highlighter| highlighter.context(request)) }); if !queued { self.context_fetch.cancel(generation); } } /// Draws one terminal frame without scheduling highlight work. fn draw_frame(&mut self) -> io::Result<()> { let mut chrome = self.chrome(); let current = self.current; match &mut self.mode { Mode::Hunk(view) => { let mut comments = self.commits[current] .loaded .as_ref() .map_or_else(Vec::new, |loaded| { loaded.comments.for_hunk(view.hunk).to_vec() }); self.terminal.draw(|frame| { let (body, chrome_area) = Chrome::areas(frame.area); frame.render_stateful_widget(&mut **view, body, &mut comments); frame.render_widget(&mut chrome, chrome_area); })?; } Mode::Commits => { let palette = self.options.diff_palette; self.terminal.draw(|frame| { let (body, chrome_area) = Chrome::areas(frame.area); let cols = ScrollView::body_cols(body); let table = history_table(&self.commits, palette, cols); let rows = table.lines(Constraint::tight(cols)); let selected = Style::default().bg(SELECTED_COMMIT_BG); let list = List::new(rows) .selected_styles(selected, selected) .scrollbar(DiffViewer::scrollbar_style()); frame.render_stateful_widget(list, body, &mut self.list); frame.render_widget(&mut chrome, chrome_area); })?; } Mode::Diff => { self.terminal.draw(|frame| { let (body, chrome_area) = Chrome::areas(frame.area); if let Some(loaded) = &mut self.commits[current].loaded { frame.render_widget(&mut loaded.viewer, body); } frame.render_widget(&mut chrome, chrome_area); })?; } } // The terminal caret is a pure function of the active view: only the // hunk view's comment editor shows it. self.terminal .set_cursor_visible(matches!(self.mode, Mode::Hunk(ref view) if view.is_editing())) } /// Returns the footer chrome for the current session mode. fn chrome(&self) -> Chrome { let visibility = Visibility { hunks: self.hunk_visibility, file: self .mode .file_visibility(self.commits[self.current].loaded.as_ref()), }; let (context, progress, stats) = if matches!(self.mode, Mode::Commits) { let status = self.history_status.as_ref(); ( StatusContext::Range(self.range.clone()), status.map_or_else(ReviewProgress::default, |status| status.progress), status.map_or_else(DiffStat::default, |status| status.stats), ) } else { let slot = &self.commits[self.current]; let progress = slot.progress; let stats = slot.loaded.as_ref().map_or_else( || { if slot.progress.is_complete() { DiffStat::default() } else { slot.commit.stats } }, CommitReview::remaining_stats, ); ( StatusContext::Commit { short: slot.commit.id.short(), summary: slot.commit.summary.clone(), }, progress, stats, ) }; Chrome { status: Status { mode: self.mode.label(), context, progress, stats, palette: self.options.diff_palette, visibility, error: self.error.clone(), loading: self.loading.map(|operation| (operation, self.spinner)), }, actions: self.action_context(), } } /// Returns the action-bar context for the current session mode. fn action_context(&self) -> ActionContext { match &self.mode { Mode::Commits => ActionContext::Commits, Mode::Diff => ActionContext::Commit, Mode::Hunk(view) if view.is_editing() => ActionContext::HunkEdit, Mode::Hunk(_) => ActionContext::HunkBrowse, } } } #[cfg(test)] mod tests { use std::collections::BTreeMap; use rustik_diff::{ContextChange, Decode as _}; use super::*; use crate::comments::Comments; use crate::review::Review; #[test] fn file_visibility_follows_the_selected_commit_viewer() { let patch = "\ diff --git a/a.rs b/a.rs index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 --- a/a.rs +++ b/a.rs @@ -1,3 +1,4 @@ fn main context -old +new +extra tail "; let document = DiffDocument::decode_str(patch).unwrap(); let loaded = |document: DiffDocument| { let viewer = DiffViewer::new(document.clone(), DiffOptions::default()); let store = ReviewComments::parse("").unwrap(); CommitReview { viewer, review: Review::new(), comments: Comments::new(&store, BTreeMap::new()), identities: BTreeMap::new(), document, file_hunks: BTreeMap::new(), hunk_stats: BTreeMap::new(), } }; let mut commits = [loaded(document.clone()), loaded(document.clone())]; let area = Rect::new(0, 0, 64, 9); let update = commits[0] .viewer .context_request(ContextChange::ToggleFile) .unwrap() .decode(patch.as_bytes()) .unwrap() .unwrap(); commits[0].viewer.apply_context_update(update, area); assert_eq!( Mode::Diff.file_visibility(Some(&commits[0])), FileVisibility::Full ); let current = 1; assert_eq!( Mode::Diff.file_visibility(Some(&commits[current])), FileVisibility::Context ); let update = commits[current] .viewer .context_request(ContextChange::ToggleFile) .unwrap() .decode(patch.as_bytes()) .unwrap() .unwrap(); assert_eq!( Mode::Diff.file_visibility(Some(&commits[current])), FileVisibility::Context ); commits[current].viewer.apply_context_update(update, area); assert_eq!( Mode::Diff.file_visibility(Some(&commits[current])), FileVisibility::Full ); let mut pathless_document = document; pathless_document.files[0].header.old_path = None; pathless_document.files[0].header.new_path = None; let pathless = loaded(pathless_document); assert!( pathless .viewer .context_request(ContextChange::ToggleFile) .is_none() ); assert_eq!( Mode::Diff.file_visibility(Some(&pathless)), FileVisibility::Context ); } #[test] fn pending_events_are_discarded_before_interaction() { let (tx, rx) = mpsc::channel(); let events = Events { tx, rx }; events .tx .send(TerminalEvent::Input(Ok(Event::Key(Key::Char('a'))))) .unwrap(); events.discard_pending(); assert!(matches!( events.rx.try_recv(), Err(mpsc::TryRecvError::Empty) )); } #[test] fn persistence_input_is_classified_semantically() { let accept = Event::Key(Key::Char('a')); let previous = Event::Key(Key::Char('k')); assert_eq!( Mode::Diff.deferred_mutation(&accept), Some(DeferredMutation::ToggleAcceptance) ); assert!(Mode::Diff.allows_navigation_during_persistence(&previous)); assert!(Mode::Commits.allows_navigation_during_persistence(&previous)); assert_eq!(Mode::Diff.deferred_mutation(&previous), None); } }