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