plannotator-tui 0.15.0

Annotate Markdown in the terminal - standalone, and as a Herdr plugin.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! The change picker: what to review, from a fixed list whose rows never move. Uncommitted,
//! Unstaged and Staged first, the branch against its base when it has moved past it, then
//! the last 20 commits newest first and `more…` for 20 older ones.
//!
//! It opens on its own (`review --pick`, or a bare `review` with nothing to show), or over a
//! review (`pick-changes`, `p`). The first frame needs no git at all beyond the commit list
//! taken before it; each row's size (`+12 −3 · 4 files`, or `(no changes)`) and its unsent
//! notes fill in from background threads, the rows on screen first ([`source`]). Until the
//! person moves it, the cursor sits on the first row not known to be empty, so with a clean
//! tree after the agent committed it lands on that commit.
//!
//! Space (`mark-commit`) marks commits ([`marks`]): with two or more marked, Enter reviews
//! every commit from the newest mark to the oldest as one diff ([`Scope::Range`]), with one
//! the marked commit; Esc clears the marks before it does anything else.
//!
//! Enter captures the row's scope exactly ([`plannotator_tui_review::Repo::capture`]: no
//! fallback to another scope), also in the background; what fails says so in the footer and
//! the picker stays. At most two jobs run at once ([`source::AT_ONCE`]), so at most two git
//! commands; a reload, a choice or closing the picker kills what runs. [`shown`] turns a capture into a review, carrying the open review's
//! delivery, settings, keys and chosen agent over.

mod draw;
mod marks;
#[cfg(test)]
mod range_tests;
mod rows;
pub(crate) mod shown;
pub(crate) mod source;
#[cfg(test)]
mod tests;

use std::sync::Arc;
use std::sync::mpsc::SyncSender;

use plannotator_tui_review::{Capture, Repo, Scope};
use ratatui::crossterm::event::{KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use ratatui::layout::Rect;

use crate::keys::{self, Action, Keymap};
use marks::Marks;
use rows::{Kind, Row, Sized};
use source::{Done, Job, Listing, PAGE, Source, Work};

/// What the footer says while the list is read again.
const RELOADING: &str = "reloading\u{2026}";

/// The most older pages listed on their own to reach a marked commit that is not listed yet.
const REACH_PAGES: usize = 10;

/// What a key or click asks of whoever shows the picker.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
    Stay,
    /// Back to the review it was opened over.
    Close,
    Quit,
}

/// Older commits: none, ready to list, or being listed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum More {
    None,
    Ready,
    Loading,
}

/// Where the rows were drawn last frame, for the mouse and for which sizes come first.
#[derive(Debug, Default, Clone)]
struct Geometry {
    rows: Vec<(Rect, usize)>,
    /// The whole picker: the screen, or the box over the review.
    area: Rect,
    /// Rows that fit.
    visible: usize,
}

pub(crate) struct Picker {
    work: Work,
    name: String,
    rows: Vec<Row>,
    /// The first page of commits arrived.
    listed: bool,
    more: More,
    cursor: usize,
    /// The person moved the cursor: it no longer follows the first row with changes.
    pinned: bool,
    scroll: usize,
    status: Option<String>,
    /// The scope of the review it was opened over; `None` on its own.
    over: Option<Scope>,
    help: bool,
    /// Moves on with every reload, so answers to an older round are dropped.
    generation: u64,
    /// The scope being captured: a row's, or the marked range.
    opening: Option<Scope>,
    opened: Option<(Repo, Capture)>,
    /// The row to keep the cursor on across a reload.
    keep: Option<Scope>,
    /// The commits marked for a range.
    marks: Marks,
    /// The range the picker marked on its own as it opened (the review it is over, or the one
    /// "go to it" named): its marks only show it until Space makes them the person's own.
    aimed: Option<Scope>,
    /// The range whose commits are being counted, and the counts known.
    counting: Option<Scope>,
    counts: Vec<(Scope, Result<usize, String>)>,
    /// Older pages listed on their own this round to reach a marked commit ([`REACH_PAGES`]).
    reached: usize,
    keys: Keymap,
    geometry: Geometry,
}

impl std::fmt::Debug for Picker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Picker")
            .field("name", &self.name)
            .field("rows", &self.rows.len())
            .finish_non_exhaustive()
    }
}

impl Picker {
    /// The picker over `source`. `listing` is the first page when it was taken before the
    /// first frame; without it the picker asks in the background. `over` is the scope of the
    /// review it opens over. `wake` is the event loop's.
    pub(crate) fn open(
        source: Arc<dyn Source>,
        listing: Option<Listing>,
        over: Option<Scope>,
        keys: Keymap,
        wake: SyncSender<()>,
    ) -> Self {
        let name = rows::clean(&source.name());
        let mut picker = Self {
            work: Work::new(source, wake),
            name,
            rows: [Kind::Uncommitted, Kind::Unstaged, Kind::Staged].map(Row::new).into(),
            listed: false,
            more: More::None,
            cursor: 0,
            pinned: false,
            scroll: 0,
            status: None,
            keep: None,
            over: over.clone(),
            help: false,
            generation: 0,
            opening: None,
            opened: None,
            marks: Marks::default(),
            aimed: None,
            counting: None,
            counts: Vec::new(),
            reached: 0,
            keys,
            geometry: Geometry::default(),
        };
        // Over a review, the cursor starts on the row it shows; over a range, its ends are
        // marked.
        if let Some(over) = over {
            picker.aim(over);
        }
        if let Some(listing) = listing {
            picker.take_listing(0, Ok(listing));
        } else {
            picker.keep_cursor(false);
            picker.ask(Job::List { skip: 0, count: PAGE });
        }
        picker.ask_sizes();
        picker
    }

    /// Say `status` in the footer.
    pub(crate) fn say(&mut self, status: String) {
        self.status = Some(status);
    }

    /// Take the answers that arrived and ask for the next sizes. True when the picker changed.
    pub(crate) fn tick(&mut self) -> bool {
        let answers = self.work.take();
        let changed = !answers.is_empty();
        for done in answers {
            self.take(done);
        }
        if !self.work.pump() {
            self.status = Some("could not start a thread to ask git".into());
        }
        self.ask_sizes();
        self.ask_count();
        self.settle_cursor();
        changed
    }

    /// The capture Enter asked for, once it is ready.
    pub(crate) fn take_opened(&mut self) -> Option<(Repo, Capture)> {
        self.opened.take()
    }

    /// Ask `job` in the background. False, with a word in the footer, when no thread could
    /// be started for it.
    fn ask(&mut self, job: Job) -> bool {
        let asked = self.work.ask(self.generation, job);
        if !asked {
            self.status = Some("could not start a thread to ask git".into());
        }
        asked
    }

    fn take(&mut self, done: Done) {
        match done {
            Done::List { generation, skip, listing } if generation == self.generation => {
                self.take_listing(skip, listing);
            }
            Done::Size { generation, row, size } if generation == self.generation => {
                if let Some(row) = self.rows.get_mut(row) {
                    row.size = match size {
                        Ok(size) => Sized::Known(size),
                        Err(error) => Sized::Failed(error),
                    };
                }
            }
            Done::Capture { generation, scope, captured } if generation == self.generation => {
                if self.opening.as_ref() != Some(&scope) {
                    return;
                }
                self.opening = None;
                let name = scope.title();
                match *captured {
                    Ok((_, capture)) if capture.is_empty() => {
                        self.status = Some(format!("{name} has no changes"));
                    }
                    Ok(opened) => {
                        self.status = None;
                        self.opened = Some(opened);
                    }
                    Err(error) => {
                        // A commit pruned or rewritten since the list was read.
                        let stale = matches!(
                            scope,
                            Scope::Commit { .. } | Scope::Range { .. } | Scope::Branch { .. }
                        ) && !error.contains("too large");
                        let key = self.keys.hint(Action::Reload);
                        self.status = Some(if stale && !key.is_empty() {
                            format!("{name}: {error} \u{b7} press {key} to reload")
                        } else {
                            format!("{name}: {error}")
                        });
                    }
                }
            }
            Done::Count { generation, scope, count } if generation == self.generation => {
                self.take_count(scope, count);
            }
            // An answer to the round before a reload.
            Done::List { .. } | Done::Size { .. } | Done::Capture { .. } | Done::Count { .. } => {}
        }
    }

    /// Add a page of commits: the first page (with the branch) after the fixed rows, an older
    /// one where `more…` was.
    fn take_listing(&mut self, skip: usize, listing: Result<Listing, String>) {
        let listing = match listing {
            Ok(listing) => listing,
            Err(error) => {
                self.status = Some(format!("could not list the commits: {error}"));
                if skip > 0 {
                    self.more = More::Ready;
                }
                self.listed = true;
                return;
            }
        };
        if skip == 0 {
            if self.status.as_deref() == Some(RELOADING) {
                self.status = None;
            }
            self.rows.truncate(3);
            self.rows.extend(listing.branch.map(|scope| Row::new(Kind::Branch(scope))));
        } else if self.rows.last().is_some_and(|row| row.kind == Kind::More) {
            self.rows.pop();
        }
        self.rows.extend(listing.commits.into_iter().map(|commit| Row::new(Kind::Commit(commit))));
        self.more = if listing.more { More::Ready } else { More::None };
        if listing.more {
            self.rows.push(Row::new(Kind::More));
        }
        self.listed = true;
        self.reach_marks();
        self.keep_cursor(true);
        self.cursor = self.cursor.min(self.rows.len().saturating_sub(1));
    }

    /// Put the cursor on the row of `scope` once it is listed, instead of the review's own;
    /// for a range, mark its ends.
    pub(crate) fn keep_at(&mut self, scope: Scope) {
        self.aim(scope);
        if self.listed {
            self.reach_marks();
        }
        self.keep_cursor(self.listed);
    }

    /// Put the cursor on the row it was asked to stay on ([`Self::keep`]), once that row is
    /// listed; after the first page (`listed`), give up on one that is not, unless older
    /// pages are being listed to reach a marked commit.
    fn keep_cursor(&mut self, listed: bool) {
        let Some(keep) = &self.keep else { return };
        if let Some(at) = self.rows.iter().position(|row| row.scope().as_ref() == Some(keep)) {
            self.cursor = at;
            self.pinned = true;
            self.keep = None;
        } else if listed && self.more != More::Loading {
            self.keep = None;
        }
    }

    /// Ask for the sizes not known yet, the rows on screen first, while the work has room and
    /// no capture waits for it or is ready to open.
    fn ask_sizes(&mut self) {
        let shown = self.scroll..self.scroll + self.geometry.visible.max(1);
        while self.work.has_room() && self.opening.is_none() && self.opened.is_none() {
            let waiting = |row: &Row| row.size == Sized::Waiting && row.kind != Kind::More;
            let next = shown
                .clone()
                .find(|&i| self.rows.get(i).is_some_and(waiting))
                .or_else(|| self.rows.iter().position(waiting));
            let Some(index) = next else { return };
            let Some(row) = self.rows.get_mut(index) else { return };
            let Some(scope) = row.scope() else { return };
            row.size = Sized::Asking;
            self.ask(Job::Size { row: index, scope });
        }
    }

    /// Until the person moves it, the cursor is on the first row not known to be empty.
    fn settle_cursor(&mut self) {
        if self.pinned {
            return;
        }
        let first = self.rows.iter().position(|row| row.kind != Kind::More && !row.is_empty());
        self.cursor = first.unwrap_or(0);
    }

    /// Nothing but commits to review: the working tree and the branch are known empty.
    fn nothing_to_review(&self) -> bool {
        self.listed
            && self
                .rows
                .iter()
                .filter(|row| !matches!(row.kind, Kind::Commit(_) | Kind::More))
                .all(Row::is_empty)
    }

    /// Commits are listed.
    fn has_commits(&self) -> bool {
        self.rows.iter().any(|row| matches!(row.kind, Kind::Commit(_)))
    }

    fn move_to(&mut self, index: usize) {
        self.pinned = true;
        self.cursor = index.min(self.rows.len().saturating_sub(1));
    }

    pub(crate) fn key(&mut self, key: &KeyEvent) -> Outcome {
        let action = self.keys.action(key, keys::PICK_CHANGES);
        if self.help {
            match action {
                Some(Action::Quit | Action::Interrupt) => return Outcome::Quit,
                Some(_) => self.help = false,
                None => {}
            }
            return Outcome::Stay;
        }
        let page = self.geometry.visible.saturating_sub(1).max(1);
        let last = self.rows.len().saturating_sub(1);
        match action {
            Some(Action::Down) => self.move_to(self.cursor + 1),
            Some(Action::Up) => self.move_to(self.cursor.saturating_sub(1)),
            Some(Action::PageDown) => self.move_to(self.cursor + page),
            Some(Action::PageUp) => self.move_to(self.cursor.saturating_sub(page)),
            Some(Action::Top) => self.move_to(0),
            Some(Action::Bottom) => self.move_to(last),
            Some(Action::Confirm) => return self.confirm(),
            Some(Action::MarkCommit) => {
                self.mark();
                self.ask_count();
            }
            Some(Action::Reload) => self.reload(),
            Some(Action::Help) => self.help = true,
            // Esc clears the person's marks first; the ones the picker placed are only shown.
            Some(Action::Back) if !self.marks.is_empty() && self.aimed.is_none() => {
                self.marks.clear();
                self.forget_failed_counts();
                self.status = None;
            }
            Some(Action::Back | Action::PickChanges) => {
                if self.over.is_some() {
                    return Outcome::Close;
                }
                self.status = self.keys.labelled(Action::Quit, "quits");
            }
            Some(Action::Quit | Action::Interrupt) => return Outcome::Quit,
            _ => {}
        }
        Outcome::Stay
    }

    pub(crate) fn mouse(&mut self, mouse: MouseEvent) -> Outcome {
        // The keys box takes the mouse: a click closes it, as the review's own help does, and
        // nothing under it is opened or scrolled.
        if self.help {
            if matches!(mouse.kind, MouseEventKind::Down(_)) {
                self.help = false;
            }
            return Outcome::Stay;
        }
        match mouse.kind {
            MouseEventKind::Down(MouseButton::Left) => {
                let hit = self.geometry.rows.iter().find(|(rect, _)| {
                    mouse.row == rect.y && mouse.column >= rect.x && mouse.column < rect.right()
                });
                if let Some(&(_, index)) = hit {
                    self.move_to(index);
                    return self.choose(index);
                }
            }
            MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
                let visible = self.geometry.visible.max(1);
                let most = self.rows.len().saturating_sub(visible);
                self.scroll = if mouse.kind == MouseEventKind::ScrollDown {
                    (self.scroll + 3).min(most)
                } else {
                    self.scroll.saturating_sub(3)
                };
                self.pinned = true;
                self.cursor = self
                    .cursor
                    .clamp(self.scroll, (self.scroll + visible).saturating_sub(1))
                    .min(self.rows.len().saturating_sub(1));
            }
            _ => {}
        }
        Outcome::Stay
    }

    /// `mark-commit`: mark the commit under the cursor, or unmark it. Other rows say why not.
    /// Marks the picker placed on its own become the person's first, so a range shown can be
    /// widened or narrowed.
    fn mark(&mut self) {
        let Some(row) = self.rows.get(self.cursor) else { return };
        if row.scope().is_some_and(|scope| matches!(scope, Scope::Commit { .. })) {
            self.aimed = None;
        }
        self.counts.retain(|(_, count)| count.is_ok());
        if self.marks.toggle(row) {
            self.status = None;
        } else {
            self.status = Some(format!("only commits can be marked; {} is not one", row.name()));
        }
    }

    /// Enter: on `more…`, list older commits, marks or not; with two or more commits marked,
    /// review them all as one; with one, that commit; with none, the row under the cursor.
    /// Marks the picker only shows ([`Self::aimed`]) count as none, except on the range's
    /// newest commit, where the cursor started: there Enter is the range.
    fn confirm(&mut self) -> Outcome {
        if self.rows.get(self.cursor).is_some_and(|row| row.kind == Kind::More) {
            return self.choose(self.cursor);
        }
        if let Some(aimed @ Scope::Range { to, .. }) = &self.aimed {
            let on_newest =
                self.rows.get(self.cursor).and_then(Row::scope) == Some(Scope::Commit { sha: to.clone() });
            if on_newest {
                let aimed = aimed.clone();
                return self.capture(aimed);
            }
            return self.choose(self.cursor);
        }
        if let Some(scope) = self.marks.range(&self.rows) {
            return self.capture(scope);
        }
        match self.marks.span(&self.rows) {
            Some((marked, _)) => self.choose(marked),
            None => self.choose(self.cursor),
        }
    }

    /// Enter on a row: review it, list older commits, or say it has nothing to review. The
    /// row of the review it was opened over just goes back to that review, untouched.
    fn choose(&mut self, index: usize) -> Outcome {
        let Some(row) = self.rows.get(index) else { return Outcome::Stay };
        if row.kind == Kind::More {
            self.list_more();
            return Outcome::Stay;
        }
        if row.is_empty() && row.scope() != self.over {
            self.status = Some(format!("{} has no changes", row.name()));
            return Outcome::Stay;
        }
        let Some(scope) = row.scope() else { return Outcome::Stay };
        self.capture(scope)
    }

    /// List the next page of older commits, where `more…` is.
    fn list_more(&mut self) {
        if self.more == More::Ready {
            self.more = More::Loading;
            let skip = self.rows.iter().filter(|row| matches!(row.kind, Kind::Commit(_))).count();
            self.ask(Job::List { skip, count: PAGE });
        }
    }

    /// Capture `scope` in the background, or go back to the review it was opened over when
    /// that is the one.
    fn capture(&mut self, scope: Scope) -> Outcome {
        if self.over.as_ref() == Some(&scope) {
            return Outcome::Close;
        }
        if self.opening.as_ref() == Some(&scope) {
            return Outcome::Stay;
        }
        // The capture takes the room the sizes (and a count) had; they are asked again if it
        // fails.
        self.work.stop_captures();
        self.work.stop_sizes();
        self.counting = None;
        for row in &mut self.rows {
            if row.size == Sized::Asking {
                row.size = Sized::Waiting;
            }
        }
        self.status = Some(format!("opening {}\u{2026}", scope.title()));
        self.opening = Some(scope.clone());
        self.ask(Job::Capture { scope });
        Outcome::Stay
    }

    /// `r`: list the commits again and work every size out afresh, keeping the cursor's row.
    /// What still runs from before is stopped; until it has ended it counts against the room
    /// the new round has.
    fn reload(&mut self) {
        self.generation += 1;
        self.work.stop_all();
        self.opening = None;
        self.counting = None;
        self.reached = 0;
        self.keep = self.rows.get(self.cursor).and_then(Row::scope).filter(|_| self.pinned);
        let count = self.rows.iter().filter(|row| matches!(row.kind, Kind::Commit(_))).count().max(PAGE);
        // The commits are listed again; until then only the working tree's rows show, so a
        // size can never land on a row that moved.
        self.rows = [Kind::Uncommitted, Kind::Unstaged, Kind::Staged].map(Row::new).into();
        self.listed = false;
        self.more = More::None;
        self.ask(Job::List { skip: 0, count });
        self.status = Some(RELOADING.into());
        self.ask_sizes();
    }
}