.cargo/
crates/
brain/
src/
session/
backend.rs
104.7 KiB
comments.rs
22.1 KiB
decorate.rs
6.7 KiB
error.rs
2.6 KiB
main.rs
29.2 KiB
review.rs
2.3 KiB
session.rs
74.7 KiB
Cargo.toml
552 B
diff/
files/
highlight/
repo/
signals/
tui/
tui-core/
tui-termion/
tui-widgets/
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/brain/src/session.rs
raw
| 1 | //! Terminal session loop for the `brain` review TUI. |
| 2 | |
| 3 | use std::collections::BTreeSet; |
| 4 | use std::io; |
| 5 | use std::mem; |
| 6 | use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use rustik_diff::{ |
| 10 | ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffState, DiffViewer, |
| 11 | FileDiff, FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, HunkFocus, |
| 12 | ReviewProgress, ViewChange, spawn_highlighter, |
| 13 | }; |
| 14 | use rustik_repo::{DiffStat, git}; |
| 15 | use rustik_tui::{ |
| 16 | Backend as TuiBackend, Column, Constraint, Control, Event, Key, Line, List, ListState, Mouse, |
| 17 | MouseButton, Rect, ScrollView, Style, Table, TableOptions, Terminal, |
| 18 | }; |
| 19 | use rustik_tui_termion as tui_termion; |
| 20 | |
| 21 | use crate::backend::{ |
| 22 | Accepted, Backend, Brain, Commit, CommitHunks, CommitReviewState, FilePatches, HistoryStatus, |
| 23 | }; |
| 24 | use crate::comments::{Comments, ReviewComments}; |
| 25 | use crate::error::Error; |
| 26 | use crate::review::{FileVisibility, HunkVisibility, Visibility}; |
| 27 | |
| 28 | mod commit; |
| 29 | mod event; |
| 30 | mod hunk; |
| 31 | mod status; |
| 32 | mod worker; |
| 33 | |
| 34 | use commit::{CommitReview, CommitSlot}; |
| 35 | use event::{ContextFetch, Resize, TerminalEvent, Update, context_change}; |
| 36 | use hunk::{CommentEdit, HunkView}; |
| 37 | pub(crate) use status::BRAIN_BADGE_BG; |
| 38 | use status::{ |
| 39 | ActionContext, Chrome, HISTORY_DIFFSTAT_MAX_WIDTH, SELECTED_COMMIT_BG, Status, StatusContext, |
| 40 | commit_row, commit_row_suffix, current_timestamp, viewer_area, |
| 41 | }; |
| 42 | use worker::{ |
| 43 | Command as WorkerCommand, LoadCommit, Output as WorkerOutput, ReviewMutation, Worker, |
| 44 | }; |
| 45 | |
| 46 | /// Terminal backend used by the interactive viewer. |
| 47 | type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>; |
| 48 | |
| 49 | /// Minimum width of a history diffstat graph. |
| 50 | const HISTORY_DIFFSTAT_MIN_WIDTH: usize = 8; |
| 51 | /// Spinner repaint interval while repository work is pending. |
| 52 | const SPINNER_INTERVAL: Duration = Duration::from_millis(80); |
| 53 | /// Fraction of the history panel available to the diffstat graph. |
| 54 | const HISTORY_DIFFSTAT_WIDTH_DIVISOR: usize = 6; |
| 55 | /// Active view in the session. |
| 56 | enum Mode { |
| 57 | /// The commit list. |
| 58 | Commits, |
| 59 | /// The diff of the current commit. |
| 60 | Diff, |
| 61 | /// A single hunk with an inline comment box. |
| 62 | /// |
| 63 | /// Boxed because the hunk view owns its own diff viewer, which would |
| 64 | /// otherwise dominate the size of every mode value. |
| 65 | Hunk(Box<HunkView>), |
| 66 | } |
| 67 | |
| 68 | impl Mode { |
| 69 | /// Returns the footer label for this active view. |
| 70 | fn label(&self) -> &'static str { |
| 71 | match self { |
| 72 | Self::Commits => "history", |
| 73 | Self::Diff => "commit", |
| 74 | Self::Hunk(_) => "hunk", |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Returns the active file's visibility for this view. |
| 79 | fn file_visibility(&self, loaded: Option<&CommitReview>) -> FileVisibility { |
| 80 | if matches!(self, Self::Diff) && loaded.is_some_and(CommitReview::is_full_file) { |
| 81 | FileVisibility::Full |
| 82 | } else { |
| 83 | FileVisibility::Context |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Returns the focus-independent mutation represented by `event`. |
| 88 | fn deferred_mutation(&self, event: &Event<()>) -> Option<DeferredMutation> { |
| 89 | match (self, event) { |
| 90 | (Self::Commits | Self::Diff, Event::Key(Key::Char('a'))) => { |
| 91 | Some(DeferredMutation::ToggleAcceptance) |
| 92 | } |
| 93 | (Self::Diff, Event::Key(Key::Char('A'))) => { |
| 94 | Some(DeferredMutation::ToggleFileAcceptance) |
| 95 | } |
| 96 | (Self::Diff, Event::Key(Key::Char('u'))) => Some(DeferredMutation::UndoAcceptance), |
| 97 | (Self::Commits, Event::Key(Key::Char('r'))) => Some(DeferredMutation::ToggleRejection), |
| 98 | (Self::Commits, Event::Key(Key::Char('d'))) => Some(DeferredMutation::ToggleDrop), |
| 99 | _ => None, |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Returns whether `event` is read-only navigation in this view. |
| 104 | fn allows_navigation_during_persistence(&self, event: &Event<()>) -> bool { |
| 105 | match self { |
| 106 | Self::Commits => matches!( |
| 107 | event, |
| 108 | Event::Key(Key::Char('j' | 'k') | Key::Down | Key::Up) |
| 109 | | Event::Mouse(Mouse::Press { |
| 110 | button: MouseButton::WheelDown | MouseButton::WheelUp, |
| 111 | .. |
| 112 | }) |
| 113 | ), |
| 114 | Self::Diff => matches!( |
| 115 | event, |
| 116 | Event::Key( |
| 117 | Key::Char('j' | 'k' | 'n' | 'p' | 'g' | 'G' | ' ') |
| 118 | | Key::Down |
| 119 | | Key::Up |
| 120 | | Key::PageDown |
| 121 | | Key::PageUp |
| 122 | | Key::Ctrl('d' | 'u') |
| 123 | | Key::Home |
| 124 | | Key::End |
| 125 | ) | Event::Mouse(Mouse::Press { |
| 126 | button: MouseButton::WheelDown | MouseButton::WheelUp, |
| 127 | .. |
| 128 | }) |
| 129 | ), |
| 130 | Self::Hunk(_) => false, |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | /// Terminal event channel shared by pre-session prompts and the session loop. |
| 136 | /// |
| 137 | /// Reading terminal input consumes it, so one input worker must feed every |
| 138 | /// consumer; creating a second stream would steal keystrokes from the first. |
| 139 | pub struct Events { |
| 140 | /// Sender cloned by background workers. |
| 141 | tx: Sender<TerminalEvent>, |
| 142 | /// Receiver drained by the session loop. |
| 143 | rx: Receiver<TerminalEvent>, |
| 144 | } |
| 145 | |
| 146 | impl Events { |
| 147 | /// Creates the channel and spawns the blocking terminal input worker. |
| 148 | pub fn spawn() -> Self { |
| 149 | let (tx, rx) = mpsc::channel(); |
| 150 | TerminalEvent::spawn_input_worker(tx.clone()); |
| 151 | Self { tx, rx } |
| 152 | } |
| 153 | |
| 154 | /// Blocks until the next terminal input event, skipping other events. |
| 155 | /// |
| 156 | /// Returns `None` once the input worker has disconnected. |
| 157 | pub fn next_input(&self) -> Option<io::Result<Event<()>>> { |
| 158 | loop { |
| 159 | match self.rx.recv() { |
| 160 | Ok(TerminalEvent::Input(event)) => return Some(event), |
| 161 | Ok(_) => {} |
| 162 | Err(_) => return None, |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// Discards input received while no interactive screen was visible. |
| 168 | pub fn discard_pending(&self) { |
| 169 | while self.rx.try_recv().is_ok() {} |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// Runs the terminal event loop until the reviewer quits. |
| 174 | pub fn run( |
| 175 | terminal: &mut BrainTerminal, |
| 176 | events: Events, |
| 177 | commits: Vec<Commit>, |
| 178 | backend: Box<dyn Backend>, |
| 179 | brain: Brain, |
| 180 | comments: ReviewComments, |
| 181 | options: DiffOptions, |
| 182 | ) -> Result<(), Error> { |
| 183 | let Events { |
| 184 | tx: events_tx, |
| 185 | rx: events_rx, |
| 186 | } = events; |
| 187 | |
| 188 | let range = backend.range_label(); |
| 189 | let history_commits = (commits.len() > 1).then(|| commits.clone()); |
| 190 | let mut repositories = commits |
| 191 | .iter() |
| 192 | .map(|commit| backend.repo(commit)) |
| 193 | .collect::<Vec<_>>(); |
| 194 | let mut slots = commits |
| 195 | .into_iter() |
| 196 | .map(|commit| CommitSlot { |
| 197 | remaining_stats: commit.stats, |
| 198 | commit, |
| 199 | progress: ReviewProgress::default(), |
| 200 | accepted_hunks: 0, |
| 201 | total_hunks: 0, |
| 202 | comment_count: 0, |
| 203 | state: CommitReviewState::Pending, |
| 204 | document: None, |
| 205 | identities: None, |
| 206 | loaded: None, |
| 207 | }) |
| 208 | .collect::<Vec<_>>(); |
| 209 | slots.reverse(); |
| 210 | repositories.reverse(); |
| 211 | let mode = if slots.len() > 1 { |
| 212 | Mode::Commits |
| 213 | } else { |
| 214 | Mode::Diff |
| 215 | }; |
| 216 | |
| 217 | let repository_worker = Worker::spawn(backend, brain.clone(), events_tx.clone()); |
| 218 | let mut session = Session { |
| 219 | terminal, |
| 220 | commits: slots, |
| 221 | range, |
| 222 | history_status: None, |
| 223 | accepted: Vec::new(), |
| 224 | pending: None, |
| 225 | deferred_mutation: None, |
| 226 | current: 0, |
| 227 | hunk_visibility: HunkVisibility::default(), |
| 228 | mode, |
| 229 | parked: None, |
| 230 | list: ListState::new(), |
| 231 | options, |
| 232 | repositories, |
| 233 | brain, |
| 234 | comments, |
| 235 | events_tx, |
| 236 | generation: 0, |
| 237 | highlighter: None, |
| 238 | repository_worker, |
| 239 | context_fetch: ContextFetch::default(), |
| 240 | error: None, |
| 241 | loading: None, |
| 242 | spinner: 0, |
| 243 | }; |
| 244 | |
| 245 | if let Some(commits) = history_commits { |
| 246 | session.loading = Some("loading history"); |
| 247 | session |
| 248 | .repository_worker |
| 249 | .send(WorkerCommand::LoadHistory { |
| 250 | commits, |
| 251 | comments: session.comments.clone(), |
| 252 | }) |
| 253 | .map_err(Error::Git)?; |
| 254 | } else { |
| 255 | session.request_commit(0)?; |
| 256 | } |
| 257 | session.redraw()?; |
| 258 | |
| 259 | loop { |
| 260 | let received = if session.loading.is_some() { |
| 261 | match events_rx.recv_timeout(SPINNER_INTERVAL) { |
| 262 | Ok(event) => Some(event), |
| 263 | Err(RecvTimeoutError::Timeout) => { |
| 264 | session.spinner = session.spinner.wrapping_add(1); |
| 265 | session.redraw()?; |
| 266 | continue; |
| 267 | } |
| 268 | Err(RecvTimeoutError::Disconnected) => None, |
| 269 | } |
| 270 | } else { |
| 271 | events_rx.recv().ok() |
| 272 | }; |
| 273 | let Some(event) = received else { |
| 274 | break; |
| 275 | }; |
| 276 | let Some(event) = TerminalEvent::receive(Ok::<_, mpsc::RecvError>(event))? else { |
| 277 | break; |
| 278 | }; |
| 279 | let mut redraw = false; |
| 280 | let mut next = Some(event); |
| 281 | // Drain queued events before repainting so bursts coalesce into one frame. |
| 282 | while let Some(event) = next { |
| 283 | match session.update(event) { |
| 284 | Ok(Update::Continue) => {} |
| 285 | Ok(Update::Redraw) => redraw = true, |
| 286 | Ok(Update::Quit) => return Ok(()), |
| 287 | Err(error) => { |
| 288 | session.error = Some(error.to_string().replace('\n', " ยท ")); |
| 289 | redraw = true; |
| 290 | } |
| 291 | } |
| 292 | next = TerminalEvent::receive(events_rx.try_recv())?; |
| 293 | } |
| 294 | if redraw { |
| 295 | session.redraw()?; |
| 296 | } |
| 297 | } |
| 298 | Ok(()) |
| 299 | } |
| 300 | |
| 301 | /// Returns the interactive history table for regular terminal output. |
| 302 | pub(crate) fn history_output_table( |
| 303 | commits: Vec<Commit>, |
| 304 | backend: &dyn Backend, |
| 305 | brain: &Brain, |
| 306 | comments: &ReviewComments, |
| 307 | palette: rustik_diff::DiffPalette, |
| 308 | width: usize, |
| 309 | ) -> Result<Table<9, Line>, Error> { |
| 310 | let (mut slots, _) = reviewed_slots(commits, backend, brain, comments)?; |
| 311 | slots.reverse(); |
| 312 | Ok(history_table(&slots, palette, width)) |
| 313 | } |
| 314 | |
| 315 | /// Builds reviewed commit slots and their aggregate history status. |
| 316 | fn reviewed_slots( |
| 317 | commits: Vec<Commit>, |
| 318 | backend: &dyn Backend, |
| 319 | brain: &Brain, |
| 320 | comments: &ReviewComments, |
| 321 | ) -> Result<(Vec<CommitSlot>, HistoryStatus), Error> { |
| 322 | let mut reviewed = Vec::with_capacity(commits.len()); |
| 323 | for commit in commits { |
| 324 | let document = backend.diff_document(commit.id)?.split_hunks(); |
| 325 | let identities = brain.hunk_identities(&document, commit.id)?; |
| 326 | reviewed.push((commit, document, identities)); |
| 327 | } |
| 328 | if reviewed.is_empty() { |
| 329 | return Err(Error::Empty); |
| 330 | } |
| 331 | let status_inputs = reviewed |
| 332 | .iter() |
| 333 | .map(|(commit, document, identities)| (commit.id, document, identities)) |
| 334 | .collect::<Vec<_>>(); |
| 335 | let mut history = HistoryStatus::for_commits(brain, &status_inputs); |
| 336 | let slots = reviewed |
| 337 | .into_iter() |
| 338 | .map(|(commit, document, identities)| { |
| 339 | let status = history.commits.entry(commit.id).or_default(); |
| 340 | CommitSlot { |
| 341 | progress: status.progress, |
| 342 | accepted_hunks: status.accepted_hunks, |
| 343 | total_hunks: status.total_hunks, |
| 344 | comment_count: identities |
| 345 | .values() |
| 346 | .map(|identity| { |
| 347 | comments.matching_count( |
| 348 | identity.commit, |
| 349 | &identity.patch_id, |
| 350 | identity.ordinal, |
| 351 | ) |
| 352 | }) |
| 353 | .sum(), |
| 354 | state: status.state, |
| 355 | remaining_stats: status.stats, |
| 356 | commit, |
| 357 | document: Some(document), |
| 358 | identities: Some(identities), |
| 359 | loaded: None, |
| 360 | } |
| 361 | }) |
| 362 | .collect(); |
| 363 | Ok((slots, history)) |
| 364 | } |
| 365 | |
| 366 | /// Builds the commit table shared by interactive and regular history output. |
| 367 | fn history_table( |
| 368 | commits: &[CommitSlot], |
| 369 | palette: rustik_diff::DiffPalette, |
| 370 | width: usize, |
| 371 | ) -> Table<9, Line> { |
| 372 | let now = current_timestamp(); |
| 373 | let largest_change_count = commits |
| 374 | .iter() |
| 375 | .map(|slot| { |
| 376 | let stats = slot.remaining_stats(); |
| 377 | stats.insertions + stats.deletions |
| 378 | }) |
| 379 | .max() |
| 380 | .unwrap_or(0); |
| 381 | let diffstat_width = (width / HISTORY_DIFFSTAT_WIDTH_DIVISOR) |
| 382 | .clamp(HISTORY_DIFFSTAT_MIN_WIDTH, HISTORY_DIFFSTAT_MAX_WIDTH); |
| 383 | let mut table = Table::<9, Line>::new(TableOptions { |
| 384 | spacing: 2, |
| 385 | ..TableOptions::default() |
| 386 | }) |
| 387 | .with_layout([ |
| 388 | Column::auto(), |
| 389 | Column::auto(), |
| 390 | Column::auto(), |
| 391 | Column::flex(1), |
| 392 | Column::collapse(2), |
| 393 | Column::collapse(3), |
| 394 | Column::collapse(1), |
| 395 | Column::auto(), |
| 396 | Column::collapse(4), |
| 397 | ]); |
| 398 | for slot in commits { |
| 399 | let [state, id, summary] = commit_row(slot, palette); |
| 400 | let [hunks, author, age, branches, comments, diffstat] = |
| 401 | commit_row_suffix(slot, palette, now, largest_change_count, diffstat_width); |
| 402 | table.push([ |
| 403 | state, hunks, id, summary, author, age, branches, comments, diffstat, |
| 404 | ]); |
| 405 | } |
| 406 | table |
| 407 | } |
| 408 | |
| 409 | /// Commit-local hunk location used by acceptance and undo state. |
| 410 | type HunkLocation = (usize, rustik_diff::HunkId); |
| 411 | |
| 412 | /// Viewer state around one optimistic acceptance. |
| 413 | struct NavigationRollback { |
| 414 | /// Commit whose viewer changed. |
| 415 | commit: usize, |
| 416 | /// Viewer state before the optimistic change. |
| 417 | before: DiffState, |
| 418 | /// Viewer state after automatic navigation. |
| 419 | after: DiffState, |
| 420 | } |
| 421 | |
| 422 | /// State around one optimistic acceptance. |
| 423 | struct AcceptancePending { |
| 424 | /// Review state restored if persistence fails. |
| 425 | rollback: Box<Brain>, |
| 426 | /// Undo stack installed after successful persistence. |
| 427 | undo: Vec<HunkLocation>, |
| 428 | /// Navigation restored if the user has not moved again. |
| 429 | navigation: Option<NavigationRollback>, |
| 430 | } |
| 431 | |
| 432 | /// Comment state restored if persistence fails. |
| 433 | struct CommentRollback { |
| 434 | /// Commit whose comment view changed. |
| 435 | commit: usize, |
| 436 | /// Review-wide store before the optimistic mutation. |
| 437 | store: ReviewComments, |
| 438 | /// Commit-local view before the optimistic mutation. |
| 439 | comments: Comments, |
| 440 | } |
| 441 | |
| 442 | /// Optimistic state restored or finalized when persistence completes. |
| 443 | enum Pending { |
| 444 | /// Hunk acceptance currently writing to the repository. |
| 445 | Acceptance(AcceptancePending), |
| 446 | /// Commit decision currently writing to the repository. |
| 447 | Decision, |
| 448 | /// Comment mutation currently writing to the repository. |
| 449 | Comments(CommentRollback), |
| 450 | } |
| 451 | |
| 452 | /// Repository mutation waiting for the active persistence command. |
| 453 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 454 | enum DeferredMutation { |
| 455 | /// Toggle acceptance at the current focus. |
| 456 | ToggleAcceptance, |
| 457 | /// Toggle acceptance of the focused file. |
| 458 | ToggleFileAcceptance, |
| 459 | /// Undo the latest accepted hunk. |
| 460 | UndoAcceptance, |
| 461 | /// Toggle rejection of the selected commit. |
| 462 | ToggleRejection, |
| 463 | /// Toggle dropping of the selected commit. |
| 464 | ToggleDrop, |
| 465 | /// Delete the selected hunk comment. |
| 466 | DeleteComment, |
| 467 | } |
| 468 | |
| 469 | /// Interactive terminal session state. |
| 470 | struct Session<'a, T: TuiBackend<Error = io::Error>> { |
| 471 | /// Terminal frame target. |
| 472 | terminal: &'a mut Terminal<T>, |
| 473 | /// Per-commit review slots, newest first. |
| 474 | commits: Vec<CommitSlot>, |
| 475 | /// User-facing revision range under review. |
| 476 | range: String, |
| 477 | /// Lazily cached global progress and remaining statistics for history. |
| 478 | history_status: Option<HistoryStatus>, |
| 479 | /// Hunk acceptances available to undo, in acceptance order. |
| 480 | accepted: Vec<HunkLocation>, |
| 481 | /// Optimistic state currently writing to the repository. |
| 482 | pending: Option<Pending>, |
| 483 | /// Semantic repository mutation waiting for active persistence to finish. |
| 484 | deferred_mutation: Option<DeferredMutation>, |
| 485 | /// Index of the commit currently displayed. |
| 486 | current: usize, |
| 487 | /// Set of hunks visible across commit viewers. |
| 488 | hunk_visibility: HunkVisibility, |
| 489 | /// Active view: the commit list, the diff, or a hunk's comment box. |
| 490 | mode: Mode, |
| 491 | /// Hunk view kept alive while another tab is active, for Tab round-trips. |
| 492 | parked: Option<Box<HunkView>>, |
| 493 | /// Selection and scroll state for the commit-list tab. |
| 494 | list: ListState, |
| 495 | /// Viewer options used to build commit and per-hunk viewers. |
| 496 | options: DiffOptions, |
| 497 | /// Git contexts used only by background highlighters. |
| 498 | repositories: Vec<git::Repository>, |
| 499 | /// Serialized command interface for every UI-initiated repository operation. |
| 500 | repository_worker: Worker, |
| 501 | /// Hidden review state storing accepted identities, derived content, and comments. |
| 502 | brain: Brain, |
| 503 | /// Review-wide persistent comment store. |
| 504 | comments: ReviewComments, |
| 505 | /// Sender used to respawn the highlighter for the current commit. |
| 506 | events_tx: Sender<TerminalEvent>, |
| 507 | /// Generation of the active highlighter; stale output is ignored. |
| 508 | generation: u64, |
| 509 | /// Highlighter for the current commit, respawned on each switch. |
| 510 | highlighter: Option<Highlighter>, |
| 511 | /// Whether a context refetch is in flight. |
| 512 | context_fetch: ContextFetch, |
| 513 | /// Repository operation currently represented by the status spinner. |
| 514 | loading: Option<&'static str>, |
| 515 | /// Current spinner animation frame. |
| 516 | spinner: usize, |
| 517 | /// Most recent recoverable session error shown in the status bar. |
| 518 | error: Option<String>, |
| 519 | } |
| 520 | |
| 521 | impl<T: TuiBackend<Error = io::Error>> Session<'_, T> { |
| 522 | /// Returns the current commit's cached diff state. |
| 523 | fn current(&mut self) -> Result<&mut CommitReview, Error> { |
| 524 | self.load(self.current) |
| 525 | } |
| 526 | |
| 527 | /// Returns commit `index`'s cached diff state. |
| 528 | fn load(&mut self, index: usize) -> Result<&mut CommitReview, Error> { |
| 529 | self.commits[index] |
| 530 | .loaded |
| 531 | .as_mut() |
| 532 | .ok_or_else(|| Error::Git("commit is still loading".to_owned())) |
| 533 | } |
| 534 | /// Queues construction of one uncached commit viewer. |
| 535 | fn request_commit(&mut self, index: usize) -> Result<(), Error> { |
| 536 | if self.commits[index].loaded.is_some() { |
| 537 | return Ok(()); |
| 538 | } |
| 539 | let slot = &mut self.commits[index]; |
| 540 | let command = WorkerCommand::LoadCommit(Box::new(LoadCommit { |
| 541 | index, |
| 542 | commit: slot.commit.clone(), |
| 543 | document: slot.document.take(), |
| 544 | identities: slot.identities.take(), |
| 545 | options: self.options.clone(), |
| 546 | comments: self.comments.clone(), |
| 547 | })); |
| 548 | self.repository_worker.send(command).map_err(Error::Git)?; |
| 549 | self.loading = Some("loading commit"); |
| 550 | Ok(()) |
| 551 | } |
| 552 | |
| 553 | /// Applies one terminal or worker event and records redraw work. |
| 554 | /// |
| 555 | /// Input is routed by active mode first so the commit list and hunk editor |
| 556 | /// can reserve keys that would otherwise belong to the diff viewer. Worker |
| 557 | /// output is tagged with a generation, letting stale highlighter results |
| 558 | /// from a previous commit be ignored after a commit switch. |
| 559 | fn update(&mut self, event: TerminalEvent) -> Result<Update, Error> { |
| 560 | match event { |
| 561 | TerminalEvent::Input(event) => { |
| 562 | self.error = None; |
| 563 | let event = event?; |
| 564 | if self.action_context() != ActionContext::HunkEdit |
| 565 | && matches!(event, Event::Key(Key::Ctrl('c'))) |
| 566 | { |
| 567 | return self.try_quit(); |
| 568 | } |
| 569 | if self.loading.is_some() && !matches!(event, Event::Resize(_)) { |
| 570 | if self.pending.is_none() { |
| 571 | return Ok(Update::Continue); |
| 572 | } |
| 573 | if let Some(mutation) = self.deferred_mutation(&event) { |
| 574 | self.deferred_mutation.get_or_insert(mutation); |
| 575 | return Ok(Update::Continue); |
| 576 | } |
| 577 | if !self.allows_navigation_during_persistence(&event) { |
| 578 | return Ok(Update::Continue); |
| 579 | } |
| 580 | } |
| 581 | let resize = if matches!(event, Event::Resize(_)) { |
| 582 | Resize::Changed |
| 583 | } else { |
| 584 | Resize::Stable |
| 585 | }; |
| 586 | let control = match self.mode { |
| 587 | Mode::Hunk(_) => { |
| 588 | let area = viewer_area(self.terminal.area()); |
| 589 | self.handle_hunk_key(event, area)? |
| 590 | } |
| 591 | Mode::Commits => self.handle_commits_key(event)?, |
| 592 | Mode::Diff => { |
| 593 | if let Some(change) = context_change(&event) { |
| 594 | // Context expansion is asynchronous and may not |
| 595 | // redraw immediately, so it bypasses the ordinary |
| 596 | // diff input path. |
| 597 | self.request_context(change); |
| 598 | return Ok(Update::Continue); |
| 599 | } |
| 600 | let area = viewer_area(self.terminal.area()); |
| 601 | self.handle_key(event, area)? |
| 602 | } |
| 603 | }; |
| 604 | let update = Update::from_control(control, resize); |
| 605 | if update == Update::Quit { |
| 606 | self.try_quit() |
| 607 | } else { |
| 608 | Ok(update) |
| 609 | } |
| 610 | } |
| 611 | TerminalEvent::Highlight(generation, HighlightOutput::Highlights(results)) => { |
| 612 | if generation == self.generation |
| 613 | && self |
| 614 | .active_viewer() |
| 615 | .is_some_and(|viewer| viewer.apply_highlights(results)) |
| 616 | { |
| 617 | self.draw_frame()?; |
| 618 | } |
| 619 | Ok(Update::Continue) |
| 620 | } |
| 621 | TerminalEvent::Highlight(generation, HighlightOutput::Context(update)) => { |
| 622 | if generation != self.generation { |
| 623 | return Ok(Update::Continue); |
| 624 | } |
| 625 | let redraw = if let Some(update) = update { |
| 626 | let area = viewer_area(self.terminal.area()); |
| 627 | if let Some(loaded) = &mut self.commits[self.current].loaded { |
| 628 | loaded.apply_context_update(update, &self.brain, area)?; |
| 629 | } |
| 630 | self.refresh_visibility()?; |
| 631 | true |
| 632 | } else { |
| 633 | false |
| 634 | }; |
| 635 | let desired = self.context_fetch.complete(generation); |
| 636 | if let Some(change) = desired { |
| 637 | self.request_context(change); |
| 638 | } |
| 639 | Ok(if redraw { |
| 640 | Update::Redraw |
| 641 | } else { |
| 642 | Update::Continue |
| 643 | }) |
| 644 | } |
| 645 | TerminalEvent::Worker(output) => self.handle_worker_output(*output), |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | /// Leaves the session unless repository work is still pending. |
| 650 | fn try_quit(&mut self) -> Result<Update, Error> { |
| 651 | Ok(if self.loading.is_some() || self.error.is_some() { |
| 652 | Update::Redraw |
| 653 | } else { |
| 654 | Update::Quit |
| 655 | }) |
| 656 | } |
| 657 | |
| 658 | /// Applies one completed repository command without performing I/O. |
| 659 | fn handle_worker_output(&mut self, output: WorkerOutput) -> Result<Update, Error> { |
| 660 | self.loading = None; |
| 661 | match output { |
| 662 | WorkerOutput::CommitLoaded { index, result } => match *result { |
| 663 | Ok(loaded) => { |
| 664 | self.commits[index].loaded = Some(loaded); |
| 665 | self.reconcile_state(); |
| 666 | if index == self.current && matches!(self.mode, Mode::Diff) { |
| 667 | self.activate()?; |
| 668 | } else if self.commits[self.current].loaded.is_none() { |
| 669 | self.request_commit(self.current)?; |
| 670 | } |
| 671 | } |
| 672 | Err(message) => self.error = Some(message.replace('\n', " ยท ")), |
| 673 | }, |
| 674 | WorkerOutput::HistoryLoaded(result) => match *result { |
| 675 | Ok((mut commits, status)) => { |
| 676 | commits.reverse(); |
| 677 | self.commits = commits; |
| 678 | self.history_status = Some(status); |
| 679 | } |
| 680 | Err(message) => self.error = Some(message.replace('\n', " ยท ")), |
| 681 | }, |
| 682 | WorkerOutput::SourcesLoaded { hunk, result } => match *result { |
| 683 | Ok(viewer) => { |
| 684 | let mut view = HunkView::new(hunk, viewer, self.comments.author().to_owned()); |
| 685 | view.enter(); |
| 686 | self.mode = Mode::Hunk(Box::new(view)); |
| 687 | self.restart_highlighter()?; |
| 688 | } |
| 689 | Err(message) => self.error = Some(message.replace('\n', " ยท ")), |
| 690 | }, |
| 691 | WorkerOutput::Persisted(result) => { |
| 692 | self.finish_persistence(*result)?; |
| 693 | if let Some(mutation) = self.deferred_mutation.take() { |
| 694 | self.apply_deferred_mutation(mutation)?; |
| 695 | } |
| 696 | } |
| 697 | } |
| 698 | Ok(Update::Redraw) |
| 699 | } |
| 700 | |
| 701 | /// Returns the repository mutation represented by `event` in the active view. |
| 702 | fn deferred_mutation(&self, event: &Event<()>) -> Option<DeferredMutation> { |
| 703 | if let Some(mutation) = self.mode.deferred_mutation(event) { |
| 704 | return Some(mutation); |
| 705 | } |
| 706 | match (&self.mode, event) { |
| 707 | (Mode::Diff, Event::Key(Key::Char('r' | 'd'))) |
| 708 | if matches!( |
| 709 | self.commits[self.current] |
| 710 | .loaded |
| 711 | .as_ref() |
| 712 | .and_then(|loaded| loaded.viewer.state().focus), |
| 713 | Some(DiffFocus::Commit) |
| 714 | ) => |
| 715 | { |
| 716 | Some(if matches!(event, Event::Key(Key::Char('r'))) { |
| 717 | DeferredMutation::ToggleRejection |
| 718 | } else { |
| 719 | DeferredMutation::ToggleDrop |
| 720 | }) |
| 721 | } |
| 722 | (Mode::Hunk(view), Event::Key(Key::Char('r'))) if !view.is_editing() => { |
| 723 | Some(DeferredMutation::ToggleRejection) |
| 724 | } |
| 725 | (Mode::Hunk(view), Event::Key(Key::Char('d'))) if !view.is_editing() => { |
| 726 | Some(DeferredMutation::DeleteComment) |
| 727 | } |
| 728 | _ => None, |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | /// Returns whether `event` is safe while repository persistence is pending. |
| 733 | fn allows_navigation_during_persistence(&self, event: &Event<()>) -> bool { |
| 734 | if self.mode.allows_navigation_during_persistence(event) { |
| 735 | return true; |
| 736 | } |
| 737 | match &self.mode { |
| 738 | Mode::Hunk(view) if !view.is_editing() => { |
| 739 | matches!(event, Event::Key(Key::Char('n' | 'p'))) || Self::hunk_scroll_event(event) |
| 740 | } |
| 741 | Mode::Commits | Mode::Diff | Mode::Hunk(_) => false, |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | /// Applies one queued mutation against the current semantic focus. |
| 746 | fn apply_deferred_mutation(&mut self, mutation: DeferredMutation) -> Result<(), Error> { |
| 747 | match mutation { |
| 748 | DeferredMutation::ToggleAcceptance => match self.mode { |
| 749 | Mode::Commits => self.toggle_commit_accepted(self.list.selected())?, |
| 750 | Mode::Diff => { |
| 751 | let area = viewer_area(self.terminal.area()); |
| 752 | match self.current()?.viewer.state().focus { |
| 753 | Some(DiffFocus::Commit) => self.toggle_commit_accepted(self.current)?, |
| 754 | Some(DiffFocus::File(_)) => self.toggle_focused_file(area)?, |
| 755 | Some(DiffFocus::Hunk(_)) | None => self.toggle_focused_hunk(area)?, |
| 756 | } |
| 757 | } |
| 758 | Mode::Hunk(_) => {} |
| 759 | }, |
| 760 | DeferredMutation::ToggleFileAcceptance => { |
| 761 | if matches!(self.mode, Mode::Diff) { |
| 762 | let area = viewer_area(self.terminal.area()); |
| 763 | self.toggle_focused_file(area)?; |
| 764 | } |
| 765 | } |
| 766 | DeferredMutation::UndoAcceptance => { |
| 767 | if matches!(self.mode, Mode::Diff) { |
| 768 | self.undo_last_hunk_accept()?; |
| 769 | } |
| 770 | } |
| 771 | DeferredMutation::ToggleRejection => { |
| 772 | let index = if matches!(self.mode, Mode::Commits) { |
| 773 | self.list.selected() |
| 774 | } else { |
| 775 | self.current |
| 776 | }; |
| 777 | self.toggle_commit_rejected(index)?; |
| 778 | if matches!(self.mode, Mode::Hunk(_)) { |
| 779 | self.next_tab()?; |
| 780 | } |
| 781 | } |
| 782 | DeferredMutation::ToggleDrop => { |
| 783 | let index = if matches!(self.mode, Mode::Commits) { |
| 784 | self.list.selected() |
| 785 | } else { |
| 786 | self.current |
| 787 | }; |
| 788 | self.toggle_commit_dropped(index)?; |
| 789 | } |
| 790 | DeferredMutation::DeleteComment => { |
| 791 | if matches!(self.mode, Mode::Hunk(_)) { |
| 792 | self.delete_selected_comment()?; |
| 793 | } |
| 794 | } |
| 795 | } |
| 796 | Ok(()) |
| 797 | } |
| 798 | |
| 799 | /// Dispatches one input event, handling review keys before the viewer. |
| 800 | fn handle_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> { |
| 801 | match event { |
| 802 | Event::Key(Key::Char('a')) => { |
| 803 | match self.current()?.viewer.state().focus { |
| 804 | Some(DiffFocus::Commit) => self.toggle_commit_accepted(self.current)?, |
| 805 | Some(DiffFocus::File(_)) => self.toggle_focused_file(area)?, |
| 806 | Some(DiffFocus::Hunk(_)) | None => self.toggle_focused_hunk(area)?, |
| 807 | } |
| 808 | Ok(Control::Redraw) |
| 809 | } |
| 810 | Event::Key(Key::Char('u')) => { |
| 811 | self.undo_last_hunk_accept()?; |
| 812 | Ok(Control::Redraw) |
| 813 | } |
| 814 | Event::Key(Key::Char('A')) => { |
| 815 | self.toggle_focused_file(area)?; |
| 816 | Ok(Control::Redraw) |
| 817 | } |
| 818 | Event::Key(Key::Char('r')) => { |
| 819 | if matches!( |
| 820 | self.current()?.viewer.state().focus, |
| 821 | Some(DiffFocus::Commit) |
| 822 | ) { |
| 823 | self.toggle_commit_rejected(self.current)?; |
| 824 | self.next_tab()?; |
| 825 | } |
| 826 | Ok(Control::Redraw) |
| 827 | } |
| 828 | Event::Key(Key::Char('d')) => { |
| 829 | if matches!( |
| 830 | self.current()?.viewer.state().focus, |
| 831 | Some(DiffFocus::Commit) |
| 832 | ) { |
| 833 | self.toggle_commit_dropped(self.current)?; |
| 834 | } |
| 835 | Ok(Control::Redraw) |
| 836 | } |
| 837 | Event::Key(Key::Char('v')) => { |
| 838 | self.hunk_visibility.toggle(); |
| 839 | self.refresh_visibility()?; |
| 840 | Ok(Control::Redraw) |
| 841 | } |
| 842 | Event::Key(Key::Char('j')) => self.apply(DiffAction::NextHunk, area), |
| 843 | Event::Key(Key::Char('k')) => self.apply(DiffAction::PreviousHunk, area), |
| 844 | Event::Key(Key::Char('n')) => self.apply(DiffAction::FocusNext, area), |
| 845 | Event::Key(Key::Char('p')) => self.apply(DiffAction::FocusPrevious, area), |
| 846 | Event::Key(Key::Char('c')) => { |
| 847 | self.enter_hunk_view(area)?; |
| 848 | Ok(Control::Redraw) |
| 849 | } |
| 850 | Event::Key(Key::Enter) => { |
| 851 | self.enter_hunk_view(area)?; |
| 852 | Ok(Control::Redraw) |
| 853 | } |
| 854 | Event::Key(Key::Char(']')) => self.switch(1), |
| 855 | Event::Key(Key::Char('[')) => self.switch(-1), |
| 856 | Event::Key(Key::Tab) => { |
| 857 | self.next_tab()?; |
| 858 | Ok(Control::Redraw) |
| 859 | } |
| 860 | _ => Ok(self.current()?.viewer.handle_input(event, area)), |
| 861 | } |
| 862 | } |
| 863 | |
| 864 | /// Applies a viewer action, returning `Redraw` if the view changed. |
| 865 | fn apply(&mut self, action: DiffAction, area: Rect) -> Result<Control, Error> { |
| 866 | if self.current()?.viewer.apply(action, area) == ViewChange::Changed { |
| 867 | Ok(Control::Redraw) |
| 868 | } else { |
| 869 | Ok(Control::Continue) |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | /// Moves to another commit by `delta`. |
| 874 | fn switch(&mut self, delta: isize) -> Result<Control, Error> { |
| 875 | let last = self.commits.len().saturating_sub(1); |
| 876 | let next = (self.current as isize + delta).clamp(0, last as isize) as usize; |
| 877 | if next == self.current { |
| 878 | return Ok(Control::Continue); |
| 879 | } |
| 880 | self.select_commit(next)?; |
| 881 | |
| 882 | Ok(Control::Redraw) |
| 883 | } |
| 884 | |
| 885 | /// Displays the commit at `index`, loading it and respawning workers. |
| 886 | fn select_commit(&mut self, index: usize) -> Result<(), Error> { |
| 887 | if index != self.current { |
| 888 | self.parked = None; |
| 889 | } |
| 890 | self.current = index; |
| 891 | self.mode = Mode::Diff; |
| 892 | if self.commits[index].loaded.is_some() { |
| 893 | self.activate()?; |
| 894 | } else { |
| 895 | self.request_commit(index)?; |
| 896 | } |
| 897 | Ok(()) |
| 898 | } |
| 899 | |
| 900 | /// Routes one key while the commit-list tab is open. |
| 901 | fn handle_commits_key(&mut self, event: Event<()>) -> Result<Control, Error> { |
| 902 | let delta = match event { |
| 903 | Event::Key(Key::Char('q')) => return Ok(Control::Quit), |
| 904 | Event::Key(Key::Char('j') | Key::Down) |
| 905 | | Event::Mouse(Mouse::Press { |
| 906 | button: MouseButton::WheelDown, |
| 907 | .. |
| 908 | }) => 1, |
| 909 | Event::Key(Key::Char('k') | Key::Up) |
| 910 | | Event::Mouse(Mouse::Press { |
| 911 | button: MouseButton::WheelUp, |
| 912 | .. |
| 913 | }) => -1, |
| 914 | Event::Key(Key::Char('a')) => { |
| 915 | self.toggle_commit_accepted(self.list.selected())?; |
| 916 | return Ok(Control::Redraw); |
| 917 | } |
| 918 | Event::Key(Key::Char('r')) => { |
| 919 | self.toggle_commit_rejected(self.list.selected())?; |
| 920 | return Ok(Control::Redraw); |
| 921 | } |
| 922 | Event::Key(Key::Char('d')) => { |
| 923 | self.toggle_commit_dropped(self.list.selected())?; |
| 924 | return Ok(Control::Redraw); |
| 925 | } |
| 926 | Event::Key(Key::Enter) => { |
| 927 | self.select_commit(self.list.selected())?; |
| 928 | return Ok(Control::Redraw); |
| 929 | } |
| 930 | Event::Key(Key::Tab) => { |
| 931 | self.next_tab()?; |
| 932 | return Ok(Control::Redraw); |
| 933 | } |
| 934 | Event::Resize(_) => return Ok(Control::Redraw), |
| 935 | _ => return Ok(Control::Continue), |
| 936 | }; |
| 937 | if self.list.move_by(delta, self.commits.len()) { |
| 938 | Ok(Control::Redraw) |
| 939 | } else { |
| 940 | Ok(Control::Continue) |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | /// Toggles acceptance of every hunk in one commit. |
| 945 | fn toggle_commit_accepted(&mut self, index: usize) -> Result<(), Error> { |
| 946 | let identities = self.commits[index].identities()?; |
| 947 | let accepted = !identities.is_empty() |
| 948 | && identities |
| 949 | .values() |
| 950 | .all(|identity| self.brain.accepted.contains(identity)); |
| 951 | let hunks = identities |
| 952 | .keys() |
| 953 | .map(|hunk| (index, *hunk)) |
| 954 | .collect::<BTreeSet<_>>(); |
| 955 | if accepted { |
| 956 | self.reject_hunks(hunks)?; |
| 957 | } else { |
| 958 | self.accept_hunks(hunks)?; |
| 959 | } |
| 960 | Ok(()) |
| 961 | } |
| 962 | |
| 963 | /// Queues a toggle of one commit's rejected decision. |
| 964 | fn toggle_commit_rejected(&mut self, index: usize) -> Result<(), Error> { |
| 965 | let commit = self.commits[index].commit.id; |
| 966 | self.persist_commit_decision(ReviewMutation::ToggleRejected { commit }) |
| 967 | } |
| 968 | |
| 969 | /// Queues a toggle of one commit's dropped decision. |
| 970 | fn toggle_commit_dropped(&mut self, index: usize) -> Result<(), Error> { |
| 971 | let commit = self.commits[index].commit.id; |
| 972 | self.persist_commit_decision(ReviewMutation::ToggleDropped { commit }) |
| 973 | } |
| 974 | |
| 975 | /// Starts persistence for a commit decision under the common pending state. |
| 976 | fn persist_commit_decision(&mut self, mutation: ReviewMutation) -> Result<(), Error> { |
| 977 | debug_assert!(self.pending.is_none()); |
| 978 | self.repository_worker |
| 979 | .send(WorkerCommand::Mutate(mutation)) |
| 980 | .map_err(Error::Git)?; |
| 981 | self.pending = Some(Pending::Decision); |
| 982 | self.loading = Some("saving review"); |
| 983 | Ok(()) |
| 984 | } |
| 985 | |
| 986 | /// Toggles acceptance of the focused hunk. |
| 987 | fn toggle_focused_hunk(&mut self, area: Rect) -> Result<(), Error> { |
| 988 | let current = self.current; |
| 989 | let pending_only = matches!(self.hunk_visibility, HunkVisibility::Pending); |
| 990 | let before = self.current()?.viewer.state().clone(); |
| 991 | let loaded = self.current()?; |
| 992 | let Some(DiffFocus::Hunk(hunk)) = loaded.viewer.state().focus else { |
| 993 | return Ok(()); |
| 994 | }; |
| 995 | if !loaded.identities.contains_key(&hunk) { |
| 996 | return Ok(()); |
| 997 | } |
| 998 | let accepted = loaded.review.is_accepted(hunk); |
| 999 | let next = (!accepted && pending_only) |
| 1000 | .then(|| { |
| 1001 | loaded |
| 1002 | .document |
| 1003 | .files |
| 1004 | .iter() |
| 1005 | .flat_map(|file| &file.hunks) |
| 1006 | .skip_while(|candidate| candidate.id != hunk) |
| 1007 | .skip(1) |
| 1008 | .find(|candidate| { |
| 1009 | loaded.identities.contains_key(&candidate.id) |
| 1010 | && !loaded.review.is_accepted(candidate.id) |
| 1011 | }) |
| 1012 | .map(|candidate| candidate.id) |
| 1013 | }) |
| 1014 | .flatten(); |
| 1015 | if accepted { |
| 1016 | self.reject_hunks(BTreeSet::from([(current, hunk)]))?; |
| 1017 | } else { |
| 1018 | self.accept_hunks(BTreeSet::from([(current, hunk)]))?; |
| 1019 | } |
| 1020 | if let Some(next) = next { |
| 1021 | self.current()?.viewer.focus_hunk(next, area); |
| 1022 | } |
| 1023 | self.record_navigation_rollback(current, before)?; |
| 1024 | |
| 1025 | Ok(()) |
| 1026 | } |
| 1027 | |
| 1028 | /// Rejects the most recently accepted hunk that remains accepted. |
| 1029 | fn undo_last_hunk_accept(&mut self) -> Result<(), Error> { |
| 1030 | while let Some(&(index, hunk)) = self.accepted.last() { |
| 1031 | let accepted = self.load(index)?.review.is_accepted(hunk); |
| 1032 | if accepted { |
| 1033 | let before = self.load(index)?.viewer.state().clone(); |
| 1034 | self.reject_hunks(BTreeSet::from([(index, hunk)]))?; |
| 1035 | self.record_navigation_rollback(index, before)?; |
| 1036 | break; |
| 1037 | } |
| 1038 | self.accepted.pop(); |
| 1039 | } |
| 1040 | Ok(()) |
| 1041 | } |
| 1042 | |
| 1043 | /// Persists acceptance or rejection of every hunk in the focused file. |
| 1044 | fn toggle_focused_file(&mut self, area: Rect) -> Result<(), Error> { |
| 1045 | let current = self.current; |
| 1046 | let pending_only = matches!(self.hunk_visibility, HunkVisibility::Pending); |
| 1047 | let before = self.current()?.viewer.state().clone(); |
| 1048 | let loaded = self.current()?; |
| 1049 | let Some(file) = loaded.viewer.focused_file() else { |
| 1050 | loaded.viewer.apply(DiffAction::NextHunk, area); |
| 1051 | return Ok(()); |
| 1052 | }; |
| 1053 | let Some(file) = loaded |
| 1054 | .document |
| 1055 | .files |
| 1056 | .iter() |
| 1057 | .find(|candidate| candidate.id == file) |
| 1058 | else { |
| 1059 | return Ok(()); |
| 1060 | }; |
| 1061 | let hunk_ids = file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(); |
| 1062 | let accepted = loaded.review.accepts_all(hunk_ids.iter().copied()); |
| 1063 | if !accepted && pending_only { |
| 1064 | loaded.viewer.apply(DiffAction::FocusNext, area); |
| 1065 | } |
| 1066 | let hunks = hunk_ids |
| 1067 | .into_iter() |
| 1068 | .filter(|hunk| loaded.review.is_accepted(*hunk) == accepted) |
| 1069 | .filter(|hunk| loaded.identities.contains_key(hunk)) |
| 1070 | .map(|hunk| (current, hunk)) |
| 1071 | .collect::<BTreeSet<_>>(); |
| 1072 | if accepted { |
| 1073 | self.reject_hunks(hunks)?; |
| 1074 | if pending_only { |
| 1075 | self.current()?.viewer.apply(DiffAction::NextHunk, area); |
| 1076 | } |
| 1077 | } else { |
| 1078 | self.accept_hunks(hunks)?; |
| 1079 | } |
| 1080 | self.record_navigation_rollback(current, before)?; |
| 1081 | Ok(()) |
| 1082 | } |
| 1083 | |
| 1084 | /// Optimistically accepts the selected hunks and starts persistence. |
| 1085 | fn accept_hunks(&mut self, hunks: BTreeSet<HunkLocation>) -> Result<(), Error> { |
| 1086 | let identities = hunks |
| 1087 | .iter() |
| 1088 | .map(|(index, hunk)| { |
| 1089 | self.commits[*index] |
| 1090 | .identities()? |
| 1091 | .get(hunk) |
| 1092 | .cloned() |
| 1093 | .ok_or_else(|| Error::Git(format!("hunk {hunk:?} has no identity"))) |
| 1094 | }) |
| 1095 | .collect::<Result<Vec<_>, Error>>()?; |
| 1096 | |
| 1097 | let mut accepted = self.brain.accepted.clone(); |
| 1098 | accepted.extend(identities.iter().cloned()); |
| 1099 | |
| 1100 | let mut undo = self.accepted.clone(); |
| 1101 | undo.extend(hunks); |
| 1102 | |
| 1103 | self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Accept { |
| 1104 | identities, |
| 1105 | patches, |
| 1106 | }) |
| 1107 | } |
| 1108 | |
| 1109 | /// Optimistically rejects the selected hunks and starts persistence. |
| 1110 | fn reject_hunks(&mut self, hunks: BTreeSet<HunkLocation>) -> Result<(), Error> { |
| 1111 | let identities = hunks |
| 1112 | .iter() |
| 1113 | .map(|(index, hunk)| { |
| 1114 | self.commits[*index] |
| 1115 | .identities()? |
| 1116 | .get(hunk) |
| 1117 | .cloned() |
| 1118 | .ok_or_else(|| Error::Git(format!("hunk {hunk:?} has no identity"))) |
| 1119 | }) |
| 1120 | .collect::<Result<BTreeSet<_>, Error>>()?; |
| 1121 | |
| 1122 | let mut accepted = self.brain.accepted.clone(); |
| 1123 | accepted.retain(|identity| !identities.contains(identity)); |
| 1124 | |
| 1125 | let mut undo = self.accepted.clone(); |
| 1126 | undo.retain(|hunk| !hunks.contains(hunk)); |
| 1127 | |
| 1128 | self.persist_acceptance(accepted, undo, move |patches| ReviewMutation::Reject { |
| 1129 | identities, |
| 1130 | patches, |
| 1131 | }) |
| 1132 | } |
| 1133 | |
| 1134 | /// Records automatic navigation for the pending rollback. |
| 1135 | fn record_navigation_rollback( |
| 1136 | &mut self, |
| 1137 | commit: usize, |
| 1138 | before: DiffState, |
| 1139 | ) -> Result<(), Error> { |
| 1140 | let after = self.load(commit)?.viewer.state().clone(); |
| 1141 | if let Some(Pending::Acceptance(pending)) = &mut self.pending { |
| 1142 | pending.navigation = Some(NavigationRollback { |
| 1143 | commit, |
| 1144 | before, |
| 1145 | after, |
| 1146 | }); |
| 1147 | } |
| 1148 | Ok(()) |
| 1149 | } |
| 1150 | |
| 1151 | /// Shows optimistic state, prepares its projection, and starts persistence. |
| 1152 | fn persist_acceptance( |
| 1153 | &mut self, |
| 1154 | accepted: Accepted, |
| 1155 | undo: Vec<HunkLocation>, |
| 1156 | mutation: impl FnOnce(Vec<FilePatches>) -> ReviewMutation, |
| 1157 | ) -> Result<(), Error> { |
| 1158 | debug_assert!(self.pending.is_none()); |
| 1159 | |
| 1160 | let rollback = self.brain.clone(); |
| 1161 | self.brain.rollback(accepted); |
| 1162 | if let Err(error) = self.reconcile_reviews() { |
| 1163 | self.brain = rollback; |
| 1164 | self.reconcile_state(); |
| 1165 | return Err(error); |
| 1166 | } |
| 1167 | |
| 1168 | let result = (|| -> Result<(), Error> { |
| 1169 | let mut patches = Vec::new(); |
| 1170 | for slot in &self.commits { |
| 1171 | let identities = slot.identities()?; |
| 1172 | let document = slot.document()?; |
| 1173 | for file in &document.files { |
| 1174 | let hunks = file |
| 1175 | .hunks |
| 1176 | .iter() |
| 1177 | .filter(|hunk| { |
| 1178 | identities |
| 1179 | .get(&hunk.id) |
| 1180 | .is_some_and(|identity| self.brain.accepted.contains(identity)) |
| 1181 | }) |
| 1182 | .cloned() |
| 1183 | .collect::<Vec<_>>(); |
| 1184 | if !hunks.is_empty() { |
| 1185 | let patch = FilePatches::new(file, hunks)?; |
| 1186 | patches.push(patch); |
| 1187 | } |
| 1188 | } |
| 1189 | } |
| 1190 | |
| 1191 | self.repository_worker |
| 1192 | .send(WorkerCommand::Mutate(mutation(patches))) |
| 1193 | .map_err(Error::Git) |
| 1194 | })(); |
| 1195 | if let Err(error) = result { |
| 1196 | self.brain = rollback; |
| 1197 | self.reconcile_reviews()?; |
| 1198 | return Err(error); |
| 1199 | } |
| 1200 | self.loading = Some("saving review"); |
| 1201 | self.pending = Some(Pending::Acceptance(AcceptancePending { |
| 1202 | rollback: Box::new(rollback), |
| 1203 | undo, |
| 1204 | navigation: None, |
| 1205 | })); |
| 1206 | Ok(()) |
| 1207 | } |
| 1208 | |
| 1209 | /// Finalizes one persisted state mutation or restores its optimistic state. |
| 1210 | fn finish_persistence(&mut self, result: Result<Option<Brain>, String>) -> Result<(), Error> { |
| 1211 | let Some(pending) = self.pending.take() else { |
| 1212 | return Err(Error::Git( |
| 1213 | "persistence completed without pending state".to_owned(), |
| 1214 | )); |
| 1215 | }; |
| 1216 | let committed = match result { |
| 1217 | Ok(committed) => committed, |
| 1218 | Err(message) => { |
| 1219 | match pending { |
| 1220 | Pending::Acceptance(pending) => { |
| 1221 | let navigation = pending.navigation.and_then(|navigation| { |
| 1222 | let loaded = self.commits.get(navigation.commit)?.loaded.as_ref()?; |
| 1223 | (loaded.viewer.state() == &navigation.after) |
| 1224 | .then_some((navigation.commit, navigation.before)) |
| 1225 | }); |
| 1226 | self.brain = *pending.rollback; |
| 1227 | self.reconcile_reviews()?; |
| 1228 | if let Some((commit, state)) = navigation { |
| 1229 | self.load(commit)?.viewer.set_state(state); |
| 1230 | } |
| 1231 | } |
| 1232 | Pending::Decision => {} |
| 1233 | Pending::Comments(rollback) => { |
| 1234 | self.comments = rollback.store; |
| 1235 | if let Some(loaded) = &mut self.commits[rollback.commit].loaded { |
| 1236 | loaded.comments = rollback.comments; |
| 1237 | loaded.refresh_decorations(); |
| 1238 | } |
| 1239 | } |
| 1240 | } |
| 1241 | self.error = Some(message.replace('\n', " ยท ")); |
| 1242 | return Ok(()); |
| 1243 | } |
| 1244 | }; |
| 1245 | match pending { |
| 1246 | Pending::Acceptance(pending) => { |
| 1247 | let Some(brain) = committed else { |
| 1248 | return Err(Error::Git( |
| 1249 | "review persistence completed without review state".to_owned(), |
| 1250 | )); |
| 1251 | }; |
| 1252 | self.brain = brain; |
| 1253 | self.accepted = pending.undo; |
| 1254 | } |
| 1255 | Pending::Decision => { |
| 1256 | let Some(brain) = committed else { |
| 1257 | return Err(Error::Git( |
| 1258 | "decision persistence completed without review state".to_owned(), |
| 1259 | )); |
| 1260 | }; |
| 1261 | self.brain = brain; |
| 1262 | self.reconcile_reviews()?; |
| 1263 | } |
| 1264 | Pending::Comments(_) => { |
| 1265 | debug_assert!(committed.is_none()); |
| 1266 | } |
| 1267 | } |
| 1268 | Ok(()) |
| 1269 | } |
| 1270 | |
| 1271 | /// Opens the hunk view for the focused hunk to author a comment. |
| 1272 | fn enter_hunk_view(&mut self, area: Rect) -> Result<(), Error> { |
| 1273 | if !matches!( |
| 1274 | self.current()?.viewer.state().focus, |
| 1275 | Some(DiffFocus::Hunk(_)) |
| 1276 | ) { |
| 1277 | self.current()?.viewer.apply(DiffAction::NextHunk, area); |
| 1278 | } |
| 1279 | let Some(DiffFocus::Hunk(hunk)) = self.current()?.viewer.state().focus else { |
| 1280 | return Ok(()); |
| 1281 | }; |
| 1282 | // Resume a parked draft on the same hunk instead of discarding it. |
| 1283 | if let Some(mut parked) = self.parked.take_if(|parked| parked.hunk == hunk) { |
| 1284 | if !parked.is_editing() { |
| 1285 | parked.enter(); |
| 1286 | } |
| 1287 | self.mode = Mode::Hunk(parked); |
| 1288 | self.restart_highlighter()?; |
| 1289 | return Ok(()); |
| 1290 | } |
| 1291 | self.parked = None; |
| 1292 | let mut options = self.options.clone(); |
| 1293 | options.file_tree = FileTreeMode::Hidden; |
| 1294 | options.hunk_focus = HunkFocus::Plain; |
| 1295 | |
| 1296 | let loaded = self.current()?; |
| 1297 | let Some((file, focused)) = loaded.document.files.iter().find_map(|file| { |
| 1298 | let focused = file.hunks.iter().find(|candidate| candidate.id == hunk)?; |
| 1299 | Some((file, focused)) |
| 1300 | }) else { |
| 1301 | return Ok(()); |
| 1302 | }; |
| 1303 | let document = DiffDocument::for_hunks(file, [focused.clone()]); |
| 1304 | let viewer = DiffViewer::new(document, options); |
| 1305 | self.repository_worker |
| 1306 | .send(WorkerCommand::LoadSources { |
| 1307 | viewer: Box::new(viewer), |
| 1308 | hunk, |
| 1309 | }) |
| 1310 | .map_err(Error::Git)?; |
| 1311 | self.loading = Some("loading file"); |
| 1312 | |
| 1313 | Ok(()) |
| 1314 | } |
| 1315 | |
| 1316 | /// Caches global progress and remaining statistics without loading commits. |
| 1317 | fn ensure_history_status(&mut self) -> Result<(), Error> { |
| 1318 | if self.history_status.is_none() { |
| 1319 | self.reconcile_state(); |
| 1320 | let status_inputs = self |
| 1321 | .commits |
| 1322 | .iter() |
| 1323 | .map(|slot| { |
| 1324 | let identities = slot.identities()?; |
| 1325 | Ok((slot.commit.id, slot.document()?, identities)) |
| 1326 | }) |
| 1327 | .collect::<Result<Vec<_>, Error>>()?; |
| 1328 | let status = HistoryStatus::for_commits(&self.brain, &status_inputs); |
| 1329 | for slot in &mut self.commits { |
| 1330 | if let Some(commit) = status.commits.get(&slot.commit.id) { |
| 1331 | slot.progress = commit.progress; |
| 1332 | slot.accepted_hunks = commit.accepted_hunks; |
| 1333 | slot.total_hunks = commit.total_hunks; |
| 1334 | slot.state = commit.state; |
| 1335 | slot.remaining_stats = commit.stats; |
| 1336 | } |
| 1337 | } |
| 1338 | self.history_status = Some(status); |
| 1339 | } |
| 1340 | Ok(()) |
| 1341 | } |
| 1342 | |
| 1343 | /// Switches to the next review tab, parking any open hunk view. |
| 1344 | fn next_tab(&mut self) -> Result<(), Error> { |
| 1345 | let opens_history = matches!(&self.mode, Mode::Hunk(_)) |
| 1346 | || matches!(&self.mode, Mode::Diff) && self.parked.is_none(); |
| 1347 | if opens_history { |
| 1348 | self.ensure_history_status()?; |
| 1349 | self.stop_highlighter(); |
| 1350 | } |
| 1351 | match mem::replace(&mut self.mode, Mode::Diff) { |
| 1352 | Mode::Commits => { |
| 1353 | self.select_commit(self.list.selected())?; |
| 1354 | } |
| 1355 | Mode::Diff => { |
| 1356 | if let Some(parked) = self.parked.take() { |
| 1357 | self.mode = Mode::Hunk(parked); |
| 1358 | self.restart_highlighter()?; |
| 1359 | } else { |
| 1360 | self.list.select(self.current, self.commits.len()); |
| 1361 | self.mode = Mode::Commits; |
| 1362 | } |
| 1363 | } |
| 1364 | Mode::Hunk(view) => { |
| 1365 | self.parked = Some(view); |
| 1366 | self.list.select(self.current, self.commits.len()); |
| 1367 | self.mode = Mode::Commits; |
| 1368 | } |
| 1369 | } |
| 1370 | Ok(()) |
| 1371 | } |
| 1372 | |
| 1373 | /// Routes one key to the comment editor while the hunk view is open. |
| 1374 | fn handle_hunk_key(&mut self, event: Event<()>, area: Rect) -> Result<Control, Error> { |
| 1375 | let comment_count = self.hunk_comment_count(); |
| 1376 | let hunk_area = self.active_viewer_area(area); |
| 1377 | if let Mode::Hunk(view) = &mut self.mode |
| 1378 | && !view.is_editing() |
| 1379 | { |
| 1380 | match event { |
| 1381 | Event::Key(Key::Esc) => { |
| 1382 | self.stop_highlighter(); |
| 1383 | self.mode = Mode::Diff; |
| 1384 | self.restart_highlighter()?; |
| 1385 | return Ok(Control::Redraw); |
| 1386 | } |
| 1387 | Event::Key(Key::Tab) => { |
| 1388 | self.next_tab()?; |
| 1389 | return Ok(Control::Redraw); |
| 1390 | } |
| 1391 | Event::Key(Key::Char('r')) => { |
| 1392 | self.toggle_commit_rejected(self.current)?; |
| 1393 | self.next_tab()?; |
| 1394 | return Ok(Control::Redraw); |
| 1395 | } |
| 1396 | Event::Key(Key::Char('c') | Key::Enter) => { |
| 1397 | view.enter(); |
| 1398 | return Ok(Control::Redraw); |
| 1399 | } |
| 1400 | Event::Key(Key::Char('n')) => { |
| 1401 | view.select_next(comment_count); |
| 1402 | return Ok(Control::Redraw); |
| 1403 | } |
| 1404 | Event::Key(Key::Char('p')) => { |
| 1405 | view.select_previous(); |
| 1406 | return Ok(Control::Redraw); |
| 1407 | } |
| 1408 | Event::Key(Key::Char('e')) => { |
| 1409 | self.edit_selected_comment(); |
| 1410 | return Ok(Control::Redraw); |
| 1411 | } |
| 1412 | Event::Key(Key::Char('d')) => { |
| 1413 | self.delete_selected_comment()?; |
| 1414 | return Ok(Control::Redraw); |
| 1415 | } |
| 1416 | _ if Self::hunk_scroll_event(&event) => { |
| 1417 | return Ok(view.viewer.handle_input(event, hunk_area)); |
| 1418 | } |
| 1419 | Event::Resize(_) => return Ok(Control::Redraw), |
| 1420 | _ => return Ok(Control::Continue), |
| 1421 | } |
| 1422 | } |
| 1423 | match event { |
| 1424 | Event::Key(Key::Esc) => { |
| 1425 | if let Mode::Hunk(view) = &mut self.mode { |
| 1426 | view.cancel_edit(); |
| 1427 | } |
| 1428 | return Ok(Control::Redraw); |
| 1429 | } |
| 1430 | Event::Key(Key::Tab) => { |
| 1431 | self.next_tab()?; |
| 1432 | return Ok(Control::Redraw); |
| 1433 | } |
| 1434 | // Ctrl+Enter submits; the enhanced keyboard protocol reports it as |
| 1435 | // a control Return distinct from a plain Enter. |
| 1436 | Event::Key(Key::Ctrl('\r')) => { |
| 1437 | self.save_comment()?; |
| 1438 | return Ok(Control::Redraw); |
| 1439 | } |
| 1440 | _ => {} |
| 1441 | } |
| 1442 | let Mode::Hunk(view) = &mut self.mode else { |
| 1443 | return Ok(Control::Continue); |
| 1444 | }; |
| 1445 | let changed = match event { |
| 1446 | Event::Key(Key::Enter) => view.newline(), |
| 1447 | Event::Key(key) => view.input(key), |
| 1448 | Event::Resize(_) => { |
| 1449 | view.viewer.apply(DiffAction::Resize, hunk_area) == ViewChange::Changed |
| 1450 | } |
| 1451 | Event::Mouse(_) => view.viewer.handle_input(event, hunk_area) == Control::Redraw, |
| 1452 | _ => false, |
| 1453 | }; |
| 1454 | Ok(if changed { |
| 1455 | Control::Redraw |
| 1456 | } else { |
| 1457 | Control::Continue |
| 1458 | }) |
| 1459 | } |
| 1460 | |
| 1461 | /// Stores the authored comment, if any, and clears the input box. |
| 1462 | fn save_comment(&mut self) -> Result<(), Error> { |
| 1463 | let Mode::Hunk(view) = &mut self.mode else { |
| 1464 | return Ok(()); |
| 1465 | }; |
| 1466 | let hunk = view.hunk; |
| 1467 | let Some((target, body)) = view.pending_edit() else { |
| 1468 | view.cancel_edit(); |
| 1469 | return Ok(()); |
| 1470 | }; |
| 1471 | let Some(loaded) = &mut self.commits[self.current].loaded else { |
| 1472 | return Ok(()); |
| 1473 | }; |
| 1474 | let added = matches!(target, CommentEdit::Add); |
| 1475 | let rollback = CommentRollback { |
| 1476 | commit: self.current, |
| 1477 | store: self.comments.clone(), |
| 1478 | comments: loaded.comments.clone(), |
| 1479 | }; |
| 1480 | let encoded = |
| 1481 | loaded |
| 1482 | .comments |
| 1483 | .transact(&mut self.comments, |comments, store| match target { |
| 1484 | CommentEdit::Add => comments.author(store, hunk, body), |
| 1485 | CommentEdit::Edit(id) => comments.edit(store, hunk, &id, body), |
| 1486 | }); |
| 1487 | if let Some(encoded) = encoded { |
| 1488 | if let Err(message) = self |
| 1489 | .repository_worker |
| 1490 | .send(WorkerCommand::WriteComments { encoded }) |
| 1491 | { |
| 1492 | self.comments = rollback.store; |
| 1493 | loaded.comments = rollback.comments; |
| 1494 | loaded.refresh_decorations(); |
| 1495 | return Err(Error::Git(message)); |
| 1496 | } |
| 1497 | loaded.refresh_decorations(); |
| 1498 | if added { |
| 1499 | let comments = loaded.comments.for_hunk(hunk).len(); |
| 1500 | view.select_comment(comments.saturating_sub(1)); |
| 1501 | } |
| 1502 | self.pending = Some(Pending::Comments(rollback)); |
| 1503 | self.loading = Some("saving comment"); |
| 1504 | } |
| 1505 | view.cancel_edit(); |
| 1506 | Ok(()) |
| 1507 | } |
| 1508 | |
| 1509 | /// Returns the number of comments on the active hunk. |
| 1510 | fn hunk_comment_count(&self) -> usize { |
| 1511 | let Mode::Hunk(view) = &self.mode else { |
| 1512 | return 0; |
| 1513 | }; |
| 1514 | self.commits[self.current] |
| 1515 | .loaded |
| 1516 | .as_ref() |
| 1517 | .map_or(0, |loaded| loaded.comments.for_hunk(view.hunk).len()) |
| 1518 | } |
| 1519 | |
| 1520 | /// Returns rendered comment rows for the active hunk view. |
| 1521 | fn hunk_comment_rows(&self) -> usize { |
| 1522 | let Mode::Hunk(view) = &self.mode else { |
| 1523 | return 0; |
| 1524 | }; |
| 1525 | view.comment_rows(self.hunk_comment_count()) |
| 1526 | } |
| 1527 | |
| 1528 | /// Returns whether an event should scroll the nested hunk diff viewer. |
| 1529 | fn hunk_scroll_event(event: &Event<()>) -> bool { |
| 1530 | if Self::non_text_hunk_scroll_event(event) { |
| 1531 | return true; |
| 1532 | } |
| 1533 | matches!(event, Event::Key(Key::Char('j' | 'k' | 'g' | 'G' | ' '))) |
| 1534 | } |
| 1535 | |
| 1536 | /// Returns whether an event should scroll without being inserted as text. |
| 1537 | fn non_text_hunk_scroll_event(event: &Event<()>) -> bool { |
| 1538 | matches!( |
| 1539 | event, |
| 1540 | Event::Key( |
| 1541 | Key::Down |
| 1542 | | Key::Up |
| 1543 | | Key::PageDown |
| 1544 | | Key::PageUp |
| 1545 | | Key::Ctrl('d' | 'u') |
| 1546 | | Key::Home |
| 1547 | | Key::End |
| 1548 | ) | Event::Mouse(Mouse::Press { |
| 1549 | button: MouseButton::WheelDown | MouseButton::WheelUp, |
| 1550 | .. |
| 1551 | }) |
| 1552 | ) |
| 1553 | } |
| 1554 | |
| 1555 | /// Starts editing the selected hunk comment. |
| 1556 | fn edit_selected_comment(&mut self) { |
| 1557 | let Mode::Hunk(view) = &mut self.mode else { |
| 1558 | return; |
| 1559 | }; |
| 1560 | let Some(loaded) = &self.commits[self.current].loaded else { |
| 1561 | return; |
| 1562 | }; |
| 1563 | let comments = loaded.comments.for_hunk(view.hunk); |
| 1564 | view.clamp_selection(comments.len()); |
| 1565 | let Some(comment) = comments.get(view.selected()) else { |
| 1566 | return; |
| 1567 | }; |
| 1568 | view.start_edit(comment); |
| 1569 | } |
| 1570 | |
| 1571 | /// Deletes the selected hunk comment. |
| 1572 | fn delete_selected_comment(&mut self) -> Result<(), Error> { |
| 1573 | let Mode::Hunk(view) = &mut self.mode else { |
| 1574 | return Ok(()); |
| 1575 | }; |
| 1576 | let Some(loaded) = &mut self.commits[self.current].loaded else { |
| 1577 | return Ok(()); |
| 1578 | }; |
| 1579 | let comments = loaded.comments.for_hunk(view.hunk); |
| 1580 | view.clamp_selection(comments.len()); |
| 1581 | let Some(comment) = comments.get(view.selected()) else { |
| 1582 | return Ok(()); |
| 1583 | }; |
| 1584 | let id = comment.id.clone(); |
| 1585 | let hunk = view.hunk; |
| 1586 | let rollback = CommentRollback { |
| 1587 | commit: self.current, |
| 1588 | store: self.comments.clone(), |
| 1589 | comments: loaded.comments.clone(), |
| 1590 | }; |
| 1591 | let encoded = loaded |
| 1592 | .comments |
| 1593 | .transact(&mut self.comments, |comments, store| { |
| 1594 | comments.delete(store, hunk, &id) |
| 1595 | }); |
| 1596 | if let Some(encoded) = encoded { |
| 1597 | if let Err(message) = self |
| 1598 | .repository_worker |
| 1599 | .send(WorkerCommand::WriteComments { encoded }) |
| 1600 | { |
| 1601 | self.comments = rollback.store; |
| 1602 | loaded.comments = rollback.comments; |
| 1603 | loaded.refresh_decorations(); |
| 1604 | return Err(Error::Git(message)); |
| 1605 | } |
| 1606 | loaded.refresh_decorations(); |
| 1607 | let comments = loaded.comments.for_hunk(hunk).len(); |
| 1608 | view.clamp_selection(comments); |
| 1609 | self.pending = Some(Pending::Comments(rollback)); |
| 1610 | self.loading = Some("saving comment"); |
| 1611 | } |
| 1612 | Ok(()) |
| 1613 | } |
| 1614 | |
| 1615 | /// Applies current visibility and starts workers for the active commit. |
| 1616 | /// |
| 1617 | /// Every activation increments `generation`. Highlight and context results |
| 1618 | /// carry that value back through the event channel, which prevents output |
| 1619 | /// from an older commit viewer from mutating the newly active viewer. |
| 1620 | fn activate(&mut self) -> Result<(), Error> { |
| 1621 | self.refresh_visibility()?; |
| 1622 | self.restart_highlighter()?; |
| 1623 | |
| 1624 | Ok(()) |
| 1625 | } |
| 1626 | |
| 1627 | /// Rebuilds the current commit's files to match accepted-hunk visibility. |
| 1628 | /// |
| 1629 | /// The original decoded document is kept in `CommitReview::document`; the |
| 1630 | /// viewer receives a filtered copy when accepted hunks are hidden. |
| 1631 | fn refresh_visibility(&mut self) -> Result<(), Error> { |
| 1632 | let hunk_visibility = self.hunk_visibility; |
| 1633 | let area = viewer_area(self.terminal.area()); |
| 1634 | let loaded = self.current()?; |
| 1635 | |
| 1636 | let files: Vec<FileDiff> = loaded |
| 1637 | .document |
| 1638 | .files |
| 1639 | .iter() |
| 1640 | .map(|original| { |
| 1641 | if loaded.viewer.is_file_expanded(original.id) { |
| 1642 | return loaded |
| 1643 | .viewer |
| 1644 | .document() |
| 1645 | .files |
| 1646 | .iter() |
| 1647 | .find(|file| file.id == original.id) |
| 1648 | .cloned() |
| 1649 | .unwrap_or_else(|| original.clone()); |
| 1650 | } |
| 1651 | let mut file = original.clone(); |
| 1652 | if matches!(hunk_visibility, HunkVisibility::Pending) { |
| 1653 | file.hunks |
| 1654 | .retain(|hunk| !loaded.review.is_accepted(hunk.id)); |
| 1655 | } |
| 1656 | file |
| 1657 | }) |
| 1658 | .collect(); |
| 1659 | loaded.viewer.replace_file_diffs_anchored(files, area); |
| 1660 | |
| 1661 | Ok(()) |
| 1662 | } |
| 1663 | |
| 1664 | /// Reconciles per-commit review state from persisted decisions. |
| 1665 | /// |
| 1666 | /// This is the only place that replaces `Review` sets and commit states. |
| 1667 | /// Keeping it as a full recomputation keeps the persisted decisions, |
| 1668 | /// current commit list, and per-viewer decorations consistent. Persisted |
| 1669 | /// hunk totals provide progress for commits not yet decoded. |
| 1670 | fn reconcile_state(&mut self) { |
| 1671 | let commits = self |
| 1672 | .commits |
| 1673 | .iter() |
| 1674 | .map(|slot| CommitHunks { |
| 1675 | commit: slot.commit.id, |
| 1676 | hunks: slot.loaded.as_ref().map(|loaded| &loaded.identities), |
| 1677 | }) |
| 1678 | .collect::<Vec<_>>(); |
| 1679 | let reconciled = self.brain.reconcile(&commits); |
| 1680 | for (slot, reconciled) in self.commits.iter_mut().zip(reconciled) { |
| 1681 | slot.progress = reconciled.progress; |
| 1682 | slot.accepted_hunks = reconciled.accepted.len(); |
| 1683 | slot.total_hunks = slot.hunk_count(); |
| 1684 | slot.state = reconciled.state; |
| 1685 | if let Some(loaded) = &mut slot.loaded { |
| 1686 | loaded.review.replace(reconciled.accepted); |
| 1687 | loaded.refresh_decorations(); |
| 1688 | } |
| 1689 | } |
| 1690 | } |
| 1691 | |
| 1692 | /// Reconciles review state and refreshes the active viewer when needed. |
| 1693 | fn reconcile_reviews(&mut self) -> Result<(), Error> { |
| 1694 | self.reconcile_state(); |
| 1695 | self.history_status = None; |
| 1696 | if matches!(self.mode, Mode::Commits) { |
| 1697 | self.ensure_history_status()?; |
| 1698 | } else if matches!(self.hunk_visibility, HunkVisibility::Pending) { |
| 1699 | self.refresh_visibility()?; |
| 1700 | } |
| 1701 | Ok(()) |
| 1702 | } |
| 1703 | |
| 1704 | /// Draws a frame, requesting highlights for visible rows before it and |
| 1705 | /// lookahead rows after it. |
| 1706 | fn redraw(&mut self) -> io::Result<()> { |
| 1707 | let area = self.active_viewer_area(viewer_area(self.terminal.area())); |
| 1708 | let requests = self |
| 1709 | .active_viewer() |
| 1710 | .map_or_else(Vec::new, |viewer| viewer.visible_highlight_requests(area)); |
| 1711 | self.queue_highlights(requests); |
| 1712 | self.draw_frame()?; |
| 1713 | let requests = self |
| 1714 | .active_viewer() |
| 1715 | .map_or_else(Vec::new, |viewer| viewer.lookahead_highlight_requests(area)); |
| 1716 | self.queue_highlights(requests); |
| 1717 | Ok(()) |
| 1718 | } |
| 1719 | |
| 1720 | /// Returns the diff viewer shown by the active mode, if any. |
| 1721 | fn active_viewer(&mut self) -> Option<&mut DiffViewer> { |
| 1722 | match &mut self.mode { |
| 1723 | Mode::Hunk(view) => Some(&mut view.viewer), |
| 1724 | Mode::Diff => self.commits[self.current] |
| 1725 | .loaded |
| 1726 | .as_mut() |
| 1727 | .map(|loaded| &mut loaded.viewer), |
| 1728 | Mode::Commits => None, |
| 1729 | } |
| 1730 | } |
| 1731 | |
| 1732 | /// Returns the area the active mode's diff viewer occupies within `area`. |
| 1733 | fn active_viewer_area(&self, area: Rect) -> Rect { |
| 1734 | match &self.mode { |
| 1735 | Mode::Hunk(view) => view.viewer_area(area, self.hunk_comment_rows()), |
| 1736 | _ => area, |
| 1737 | } |
| 1738 | } |
| 1739 | |
| 1740 | /// Queues highlight work, cancelling rows the worker cannot accept. |
| 1741 | /// |
| 1742 | /// The worker may drop requests when its queue is full or stale. Dropped |
| 1743 | /// rows are removed from the viewer's pending cache so they can be requested |
| 1744 | /// again on a later redraw. |
| 1745 | fn queue_highlights(&mut self, requests: Vec<HighlightRequest>) { |
| 1746 | if requests.is_empty() { |
| 1747 | return; |
| 1748 | } |
| 1749 | let dropped = self |
| 1750 | .highlighter |
| 1751 | .as_ref() |
| 1752 | .and_then(|highlighter| highlighter.highlight(requests)); |
| 1753 | if let Some(dropped) = dropped |
| 1754 | && let Some(viewer) = self.active_viewer() |
| 1755 | { |
| 1756 | viewer.cancel_highlights(dropped); |
| 1757 | } |
| 1758 | } |
| 1759 | |
| 1760 | /// Stops asynchronous work and invalidates results from the active generation. |
| 1761 | fn stop_highlighter(&mut self) { |
| 1762 | if let Some(viewer) = self.active_viewer() { |
| 1763 | viewer.retry_pending_highlights(); |
| 1764 | } |
| 1765 | self.generation += 1; |
| 1766 | self.highlighter = None; |
| 1767 | self.context_fetch = ContextFetch::Idle; |
| 1768 | } |
| 1769 | |
| 1770 | /// Restarts asynchronous syntax highlighting for the active generation. |
| 1771 | fn restart_highlighter(&mut self) -> Result<(), Error> { |
| 1772 | self.stop_highlighter(); |
| 1773 | |
| 1774 | let generation = self.generation; |
| 1775 | let tx = self.events_tx.clone(); |
| 1776 | let highlighter = if let Mode::Hunk(view) = &self.mode { |
| 1777 | spawn_highlighter(view.viewer.document(), None, move |output| { |
| 1778 | let _ = tx.send(TerminalEvent::Highlight(generation, output)); |
| 1779 | }) |
| 1780 | } else { |
| 1781 | let repo = Some(self.repositories[self.current].clone()); |
| 1782 | let loaded = self.current()?; |
| 1783 | spawn_highlighter(loaded.viewer.document(), repo, move |output| { |
| 1784 | let _ = tx.send(TerminalEvent::Highlight(generation, output)); |
| 1785 | }) |
| 1786 | }; |
| 1787 | self.highlighter = Some(highlighter); |
| 1788 | |
| 1789 | Ok(()) |
| 1790 | } |
| 1791 | |
| 1792 | /// Requests context refetch work for one context change. |
| 1793 | /// |
| 1794 | /// One request runs per active generation. A change received while it runs |
| 1795 | /// becomes a bounded desired follow-up, which starts after the viewer |
| 1796 | /// applies the current result. |
| 1797 | fn request_context(&mut self, change: ContextChange) { |
| 1798 | let generation = self.generation; |
| 1799 | if !self.context_fetch.request(generation, change) { |
| 1800 | return; |
| 1801 | } |
| 1802 | let request = self.commits[self.current] |
| 1803 | .loaded |
| 1804 | .as_ref() |
| 1805 | .and_then(|loaded| loaded.viewer.context_request(change)); |
| 1806 | let queued = request.is_some_and(|request| { |
| 1807 | self.highlighter |
| 1808 | .as_ref() |
| 1809 | .is_some_and(|highlighter| highlighter.context(request)) |
| 1810 | }); |
| 1811 | if !queued { |
| 1812 | self.context_fetch.cancel(generation); |
| 1813 | } |
| 1814 | } |
| 1815 | |
| 1816 | /// Draws one terminal frame without scheduling highlight work. |
| 1817 | fn draw_frame(&mut self) -> io::Result<()> { |
| 1818 | let mut chrome = self.chrome(); |
| 1819 | let current = self.current; |
| 1820 | match &mut self.mode { |
| 1821 | Mode::Hunk(view) => { |
| 1822 | let mut comments = self.commits[current] |
| 1823 | .loaded |
| 1824 | .as_ref() |
| 1825 | .map_or_else(Vec::new, |loaded| { |
| 1826 | loaded.comments.for_hunk(view.hunk).to_vec() |
| 1827 | }); |
| 1828 | self.terminal.draw(|frame| { |
| 1829 | let (body, chrome_area) = Chrome::areas(frame.area); |
| 1830 | frame.render_stateful_widget(&mut **view, body, &mut comments); |
| 1831 | frame.render_widget(&mut chrome, chrome_area); |
| 1832 | })?; |
| 1833 | } |
| 1834 | Mode::Commits => { |
| 1835 | let palette = self.options.diff_palette; |
| 1836 | self.terminal.draw(|frame| { |
| 1837 | let (body, chrome_area) = Chrome::areas(frame.area); |
| 1838 | let cols = ScrollView::body_cols(body); |
| 1839 | let table = history_table(&self.commits, palette, cols); |
| 1840 | let rows = table.lines(Constraint::tight(cols)); |
| 1841 | let selected = Style::default().bg(SELECTED_COMMIT_BG); |
| 1842 | let list = List::new(rows) |
| 1843 | .selected_styles(selected, selected) |
| 1844 | .scrollbar(DiffViewer::scrollbar_style()); |
| 1845 | frame.render_stateful_widget(list, body, &mut self.list); |
| 1846 | frame.render_widget(&mut chrome, chrome_area); |
| 1847 | })?; |
| 1848 | } |
| 1849 | Mode::Diff => { |
| 1850 | self.terminal.draw(|frame| { |
| 1851 | let (body, chrome_area) = Chrome::areas(frame.area); |
| 1852 | if let Some(loaded) = &mut self.commits[current].loaded { |
| 1853 | frame.render_widget(&mut loaded.viewer, body); |
| 1854 | } |
| 1855 | frame.render_widget(&mut chrome, chrome_area); |
| 1856 | })?; |
| 1857 | } |
| 1858 | } |
| 1859 | // The terminal caret is a pure function of the active view: only the |
| 1860 | // hunk view's comment editor shows it. |
| 1861 | self.terminal |
| 1862 | .set_cursor_visible(matches!(self.mode, Mode::Hunk(ref view) if view.is_editing())) |
| 1863 | } |
| 1864 | |
| 1865 | /// Returns the footer chrome for the current session mode. |
| 1866 | fn chrome(&self) -> Chrome { |
| 1867 | let visibility = Visibility { |
| 1868 | hunks: self.hunk_visibility, |
| 1869 | file: self |
| 1870 | .mode |
| 1871 | .file_visibility(self.commits[self.current].loaded.as_ref()), |
| 1872 | }; |
| 1873 | let (context, progress, stats) = if matches!(self.mode, Mode::Commits) { |
| 1874 | let status = self.history_status.as_ref(); |
| 1875 | ( |
| 1876 | StatusContext::Range(self.range.clone()), |
| 1877 | status.map_or_else(ReviewProgress::default, |status| status.progress), |
| 1878 | status.map_or_else(DiffStat::default, |status| status.stats), |
| 1879 | ) |
| 1880 | } else { |
| 1881 | let slot = &self.commits[self.current]; |
| 1882 | let progress = slot.progress; |
| 1883 | let stats = slot.loaded.as_ref().map_or_else( |
| 1884 | || { |
| 1885 | if slot.progress.is_complete() { |
| 1886 | DiffStat::default() |
| 1887 | } else { |
| 1888 | slot.commit.stats |
| 1889 | } |
| 1890 | }, |
| 1891 | CommitReview::remaining_stats, |
| 1892 | ); |
| 1893 | ( |
| 1894 | StatusContext::Commit { |
| 1895 | short: slot.commit.id.short(), |
| 1896 | summary: slot.commit.summary.clone(), |
| 1897 | }, |
| 1898 | progress, |
| 1899 | stats, |
| 1900 | ) |
| 1901 | }; |
| 1902 | Chrome { |
| 1903 | status: Status { |
| 1904 | mode: self.mode.label(), |
| 1905 | context, |
| 1906 | progress, |
| 1907 | stats, |
| 1908 | palette: self.options.diff_palette, |
| 1909 | visibility, |
| 1910 | error: self.error.clone(), |
| 1911 | loading: self.loading.map(|operation| (operation, self.spinner)), |
| 1912 | }, |
| 1913 | actions: self.action_context(), |
| 1914 | } |
| 1915 | } |
| 1916 | |
| 1917 | /// Returns the action-bar context for the current session mode. |
| 1918 | fn action_context(&self) -> ActionContext { |
| 1919 | match &self.mode { |
| 1920 | Mode::Commits => ActionContext::Commits, |
| 1921 | Mode::Diff => ActionContext::Commit, |
| 1922 | Mode::Hunk(view) if view.is_editing() => ActionContext::HunkEdit, |
| 1923 | Mode::Hunk(_) => ActionContext::HunkBrowse, |
| 1924 | } |
| 1925 | } |
| 1926 | } |
| 1927 | |
| 1928 | #[cfg(test)] |
| 1929 | mod tests { |
| 1930 | use std::collections::BTreeMap; |
| 1931 | |
| 1932 | use rustik_diff::{ContextChange, Decode as _}; |
| 1933 | |
| 1934 | use super::*; |
| 1935 | use crate::comments::Comments; |
| 1936 | use crate::review::Review; |
| 1937 | |
| 1938 | #[test] |
| 1939 | fn file_visibility_follows_the_selected_commit_viewer() { |
| 1940 | let patch = "\ |
| 1941 | diff --git a/a.rs b/a.rs |
| 1942 | index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644 |
| 1943 | --- a/a.rs |
| 1944 | +++ b/a.rs |
| 1945 | @@ -1,3 +1,4 @@ fn main |
| 1946 | context |
| 1947 | -old |
| 1948 | +new |
| 1949 | +extra |
| 1950 | tail |
| 1951 | "; |
| 1952 | let document = DiffDocument::decode_str(patch).unwrap(); |
| 1953 | let loaded = |document: DiffDocument| { |
| 1954 | let viewer = DiffViewer::new(document.clone(), DiffOptions::default()); |
| 1955 | let store = ReviewComments::parse("").unwrap(); |
| 1956 | CommitReview { |
| 1957 | viewer, |
| 1958 | review: Review::new(), |
| 1959 | comments: Comments::new(&store, BTreeMap::new()), |
| 1960 | identities: BTreeMap::new(), |
| 1961 | document, |
| 1962 | file_hunks: BTreeMap::new(), |
| 1963 | hunk_stats: BTreeMap::new(), |
| 1964 | } |
| 1965 | }; |
| 1966 | let mut commits = [loaded(document.clone()), loaded(document.clone())]; |
| 1967 | let area = Rect::new(0, 0, 64, 9); |
| 1968 | |
| 1969 | let update = commits[0] |
| 1970 | .viewer |
| 1971 | .context_request(ContextChange::ToggleFile) |
| 1972 | .unwrap() |
| 1973 | .decode(patch.as_bytes()) |
| 1974 | .unwrap() |
| 1975 | .unwrap(); |
| 1976 | commits[0].viewer.apply_context_update(update, area); |
| 1977 | |
| 1978 | assert_eq!( |
| 1979 | Mode::Diff.file_visibility(Some(&commits[0])), |
| 1980 | FileVisibility::Full |
| 1981 | ); |
| 1982 | |
| 1983 | let current = 1; |
| 1984 | assert_eq!( |
| 1985 | Mode::Diff.file_visibility(Some(&commits[current])), |
| 1986 | FileVisibility::Context |
| 1987 | ); |
| 1988 | let update = commits[current] |
| 1989 | .viewer |
| 1990 | .context_request(ContextChange::ToggleFile) |
| 1991 | .unwrap() |
| 1992 | .decode(patch.as_bytes()) |
| 1993 | .unwrap() |
| 1994 | .unwrap(); |
| 1995 | assert_eq!( |
| 1996 | Mode::Diff.file_visibility(Some(&commits[current])), |
| 1997 | FileVisibility::Context |
| 1998 | ); |
| 1999 | commits[current].viewer.apply_context_update(update, area); |
| 2000 | assert_eq!( |
| 2001 | Mode::Diff.file_visibility(Some(&commits[current])), |
| 2002 | FileVisibility::Full |
| 2003 | ); |
| 2004 | |
| 2005 | let mut pathless_document = document; |
| 2006 | pathless_document.files[0].header.old_path = None; |
| 2007 | pathless_document.files[0].header.new_path = None; |
| 2008 | let pathless = loaded(pathless_document); |
| 2009 | assert!( |
| 2010 | pathless |
| 2011 | .viewer |
| 2012 | .context_request(ContextChange::ToggleFile) |
| 2013 | .is_none() |
| 2014 | ); |
| 2015 | assert_eq!( |
| 2016 | Mode::Diff.file_visibility(Some(&pathless)), |
| 2017 | FileVisibility::Context |
| 2018 | ); |
| 2019 | } |
| 2020 | |
| 2021 | #[test] |
| 2022 | fn pending_events_are_discarded_before_interaction() { |
| 2023 | let (tx, rx) = mpsc::channel(); |
| 2024 | let events = Events { tx, rx }; |
| 2025 | events |
| 2026 | .tx |
| 2027 | .send(TerminalEvent::Input(Ok(Event::Key(Key::Char('a'))))) |
| 2028 | .unwrap(); |
| 2029 | |
| 2030 | events.discard_pending(); |
| 2031 | |
| 2032 | assert!(matches!( |
| 2033 | events.rx.try_recv(), |
| 2034 | Err(mpsc::TryRecvError::Empty) |
| 2035 | )); |
| 2036 | } |
| 2037 | |
| 2038 | #[test] |
| 2039 | fn persistence_input_is_classified_semantically() { |
| 2040 | let accept = Event::Key(Key::Char('a')); |
| 2041 | let previous = Event::Key(Key::Char('k')); |
| 2042 | |
| 2043 | assert_eq!( |
| 2044 | Mode::Diff.deferred_mutation(&accept), |
| 2045 | Some(DeferredMutation::ToggleAcceptance) |
| 2046 | ); |
| 2047 | assert!(Mode::Diff.allows_navigation_during_persistence(&previous)); |
| 2048 | assert!(Mode::Commits.allows_navigation_during_persistence(&previous)); |
| 2049 | assert_eq!(Mode::Diff.deferred_mutation(&previous), None); |
| 2050 | } |
| 2051 | } |