rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! The review panel: choose a change, then be walked through it stage by stage (see
//! [`guide`]): read each part's files, look at what was found, try it, then approve.
//! This is its state and input handling; `draw.rs` draws it and the app carries out what it
//! asks for (see [`Request`]).

mod create;
mod draw;
mod menu;
mod workspace;
pub use create::{CreateView, Field, Press, Stage as CreateStage};
pub use menu::Menu;
pub use workspace::{GitJob, GitReply, GitView};

#[cfg(test)]
mod tests;

use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

pub use draw::draw;

use crate::review::diff::Kind;
use crate::review::forge::{self, Method, PullRequest};
use crate::review::guide::{self, Stage};
use crate::review::propose::{self, Proposal};
use crate::review::session::{self, Item, Seen, Session, State, Verdict};
use crate::review::source::{self, Change, Entry, Loaded, Local};
use crate::review::{Options, Parsed, parse_args};
use crate::terminal::layout::Rect;
use crate::ui::settings::Input;

mod jobs;
mod model;

pub use jobs::*;
pub use model::*;

mod actions;
mod input;

pub struct ReviewView {
    pub cwd: PathBuf,
    pub screen: Screen,
    /// Its pane is the focused one, so the keys are its own.
    pub focused: bool,
    /// Switched away from, to the pane's terminal or something else over it.
    pub hidden: bool,
    /// The job whose answers are wanted.
    pub number: u64,
    pub job: Job,
    /// Where test results are kept.
    results: Option<PathBuf>,
    /// What just happened, shown at the bottom: (text, is it a problem).
    pub status: Option<(String, bool)>,
    /// How far the main area is scrolled, and how far it can be.
    pub scroll: f32,
    pub max_scroll: f32,
    /// The step list of the wide layout, which scrolls on its own.
    pub list_scroll: f32,
    pub list_max: f32,
    /// Bring the selection into view when next drawn.
    pub reveal: bool,
    /// Where the selection was last drawn, (top, height) from the top of what scrolls, and
    /// how much of that shows. The arrows read through something taller before moving on.
    pub chosen: Option<(f32, f32)>,
    pub view_h: f32,
    /// What was last opened from the list.
    last_choice: Option<String>,
    /// Read a newly entered stage from its introduction, while revealing it in the rail.
    pub at_top: bool,
    /// Set by the drawing code, for the mouse.
    pub rect: Rect,
    pub list_rect: Rect,
    pub hits: Vec<(Rect, Click)>,
    pub mouse: (f32, f32),
}

impl ReviewView {
    pub fn new(cwd: PathBuf, job: Job, results: Option<PathBuf>) -> ReviewView {
        let mut view = ReviewView {
            cwd,
            screen: Screen::Message { text: String::new(), error: false },
            focused: true,
            hidden: false,
            number: 0,
            job: Job::List,
            results,
            status: None,
            scroll: 0.0,
            max_scroll: 0.0,
            list_scroll: 0.0,
            list_max: 0.0,
            reveal: false,
            chosen: None,
            view_h: 0.0,
            last_choice: None,
            at_top: false,
            rect: Rect::default(),
            list_rect: Rect::default(),
            hits: Vec::new(),
            mouse: (-1.0, -1.0),
        };
        view.start(job);
        view
    }

    /// Switch to a new job. The app then starts it with [`spawn`].
    pub fn start(&mut self, job: Job) {
        self.number = next_number();
        self.scroll = 0.0;
        self.list_scroll = 0.0;
        self.at_top = false;
        self.chosen = None;
        self.view_h = 0.0;
        self.status = None;
        self.screen = match &job {
            Job::Git(_) => Screen::Git(Box::new(GitView { busy: true, ..Default::default() })),
            Job::List => Screen::Pick(Picker { want: self.last_choice.clone(), ..Default::default() }),
            Job::Open(args) => Screen::Loading(describe(args)),
            Job::Propose(_) => Screen::Create(Box::default()),
        };
        self.job = job;
    }

    pub fn receive(&mut self, message: Message) {
        match message {
            Message::Git(n, result) if n == self.number => self.git_receive(result.map(|r| *r)),
            Message::Proposed(n, result) if n == self.number => {
                if let Screen::Create(view) = &mut self.screen {
                    view.receive_start(result);
                    self.reveal = true;
                }
            }
            Message::Created(n, result) if n == self.number => {
                if let Screen::Create(view) = &mut self.screen {
                    self.status = Some(view.receive_created(result));
                    self.reveal = true;
                }
            }
            Message::Local(n, local) if n == self.number => {
                if let Screen::Pick(p) = &mut self.screen {
                    p.local = Some(local);
                    self.reveal |= p.select_wanted();
                }
            }
            Message::Pulls(n, pulls) if n == self.number => {
                if let Screen::Pick(p) = &mut self.screen {
                    // The new rows go above the others; keep the same one selected.
                    let chosen = p.entries().get(p.selected).map(|e| e.target.clone());
                    let moved = p.selected > 0;
                    p.pulls = match pulls {
                        Ok((host, list)) => Pulls::Done(host, list.iter().map(source::pull_request_entry).collect()),
                        Err(why) => Pulls::Failed(why),
                    };
                    if moved && let Some(i) = chosen.and_then(|t| p.entries().iter().position(|e| e.target == t)) {
                        p.selected = i;
                    }
                    self.reveal |= p.select_wanted();
                }
            }
            Message::Approved(n, result) if n == self.number => {
                let Some(o) = self.opened() else { return };
                o.approving = false;
                let number = o.change.pull.as_ref().map_or(0, |p| p.0);
                let status = match result {
                    Ok(host) => match o.session.set_approved() {
                        Ok(()) => (format!("Approved #{number} on {host}"), false),
                        Err(e) => (format!("Approved #{number} on {host}, but {e}"), true),
                    },
                    Err(why) => (why, true),
                };
                self.status = Some(status);
            }
            Message::Merged(n, result) if n == self.number => {
                let Some(o) = self.opened() else { return };
                o.merging = false;
                let number = o.change.pull.as_ref().map_or(0, |p| p.0);
                let status = match result {
                    Ok((host, finished)) => {
                        o.merged = true;
                        let said = if finished {
                            format!("Merged #{number} on {host}. Fetch to update your branches")
                        } else {
                            format!("{host} is still merging #{number}; check there that it finishes")
                        };
                        (said, false)
                    }
                    Err(why) => (why, true),
                };
                self.status = Some(status);
            }
            Message::Loaded(n, loaded) if n == self.number => {
                self.screen = match loaded {
                    Ok(Loaded::Change(change)) => {
                        let opened = Opened::new(change, self.results.as_deref());
                        self.reveal = true;
                        self.at_top = true;
                        Screen::Open(Box::new(opened))
                    }
                    Ok(Loaded::Empty(why)) => Screen::Message { text: why, error: false },
                    Err(why) => Screen::Message { text: why, error: true },
                };
            }
            _ => {}
        }
    }

    /// The person has gone to something else: put away the list of actions, and forget any
    /// first press, so that coming back and pressing once only asks again.
    pub fn blur(&mut self) {
        self.close_menu();
        if let Some(o) = self.opened() {
            o.confirm_approve = false;
            o.confirm_merge = None;
            o.confirm_reset = false;
        }
    }

    /// Whether something is on its way to the host, with an answer still to come.
    pub fn working(&self) -> bool {
        match &self.screen {
            Screen::Open(o) => o.approving || o.merging,
            Screen::Create(c) => c.sending(),
            _ => false,
        }
    }

    pub fn opened(&mut self) -> Option<&mut Opened> {
        match &mut self.screen {
            Screen::Open(o) => Some(o),
            _ => None,
        }
    }

    fn saved(&mut self, result: Result<(), String>) {
        if let Err(e) = result {
            self.status = Some((e, true));
        }
    }

    /// Choose a thing in a stage, on the guide.
    fn go(&mut self, stage: usize, cursor: usize) {
        let Some(o) = self.opened() else { return };
        let moved = stage != o.stage;
        o.tab = Tab::Guide;
        o.focus(stage, cursor);
        self.chosen = None;
        if moved {
            self.scroll = 0.0;
        }
        self.at_top = moved;
        self.reveal = true;
    }

    fn go_to(&mut self, t: Thing) {
        if let Some((stage, cursor)) = self.opened().and_then(|o| o.locate(t)) {
            self.go(stage, cursor);
        }
    }

    /// On to the next thing still to do in this stage. When there is none, say so: moving
    /// to the next stage is left to the person, so nothing jumps away unasked.
    fn advance(&mut self) {
        let Some(o) = self.opened() else { return };
        match o.next_undone() {
            Some(c) => {
                let stage = o.stage;
                self.go(stage, c);
            }
            None if o.stage + 1 < o.stages.len() => {
                let next = o.stages[o.stage + 1].title.clone();
                self.status = Some((format!("Done here. Enter goes on to {next}"), false));
            }
            None => {}
        }
    }

    /// The next thing still to do here, or else the next stage.
    fn proceed(&mut self) {
        let Some(o) = self.opened() else { return };
        match o.next_undone() {
            Some(c) if !o.stage_done(o.stage) => {
                let stage = o.stage;
                self.go(stage, c);
            }
            _ if o.stage + 1 < o.stages.len() => {
                let next = o.stage + 1;
                let cursor = o.things(next).iter().position(|&t| !o.done(t)).unwrap_or(0);
                self.status = None;
                self.go(next, cursor);
            }
            _ => {}
        }
    }

    fn judge(&mut self, verdict: Verdict) {
        let Some(o) = self.opened() else { return };
        let Some(id) = o.current().map(|i| i.id.clone()) else { return };
        let result = o.session.set(&id, verdict);
        o.confirm_reset = false;
        o.tab = Tab::Guide;
        // A failure wants saying what went wrong before moving on.
        o.note =
            (verdict == Verdict::Failed).then(|| o.session.record(&id).map(|r| r.note.clone()).unwrap_or_default());
        self.status = None;
        self.saved(result);
        if verdict != Verdict::Failed {
            self.advance();
        }
    }

    fn finish_note(&mut self) {
        let Some(o) = self.opened() else { return };
        let (Some(note), Some(id)) = (o.note.take(), o.current().map(|i| i.id.clone())) else { return };
        let result = o.session.set_note(&id, &note);
        self.saved(result);
    }

    pub fn click_at(&self, x: f32, y: f32) -> Option<Click> {
        // The last drawn is on top.
        self.hits.iter().rev().find(|(r, _)| r.contains(x, y)).map(|(_, c)| c.clone())
    }

    pub fn click(&mut self, x: f32, y: f32) -> Request {
        self.focused = true;
        match self.click_at(x, y) {
            Some(c) => self.activate(c),
            None => Request::Nothing,
        }
    }

    /// The thing before or after the chosen one, going on into the neighbouring stage.
    fn step_over(&mut self, back: bool) {
        let Some(o) = self.opened() else { return };
        let (stage, cursor, count) = (o.stage, o.cursor, o.things(o.stage).len());
        if back && cursor > 0 {
            self.go(stage, cursor - 1);
        } else if back && stage > 0 {
            let last = o.things(stage - 1).len().saturating_sub(1);
            self.go(stage - 1, last);
            // Coming from below, it is the thing to show, not the stage's introduction.
            self.at_top = false;
        } else if !back && cursor + 1 < count {
            self.go(stage, cursor + 1);
        } else if !back && stage + 1 < o.stages.len() {
            self.go(stage + 1, 0);
        }
    }

    /// Scroll a bit further through the selection, if there is more of it that way. At the
    /// first thing, upwards also takes in what comes before it. False when all of it has
    /// been shown, and the arrow can move on.
    fn read_on(&mut self, up: bool, first: bool) -> bool {
        if self.view_h <= 0.0 {
            return false;
        }
        let step = (self.view_h * 0.25).max(40.0);
        if up {
            let end = match self.chosen {
                Some((top, _)) if !first => top.min(self.max_scroll),
                _ => 0.0,
            };
            if self.scroll <= end + 1.0 {
                return false;
            }
            self.scroll = (self.scroll - step).max(end);
        } else {
            let end = self.chosen.map_or(self.max_scroll, |(top, h)| top + h - self.view_h).min(self.max_scroll);
            if self.scroll >= end - 1.0 {
                return false;
            }
            self.scroll = (self.scroll + step).min(end);
        }
        self.reveal = false;
        true
    }

    fn scroll_to(&mut self, to: f32) {
        self.scroll = to.clamp(0.0, self.max_scroll);
        self.reveal = false;
    }

    pub fn scroll_by(&mut self, pixels: f32) {
        // Over the list of actions, the wheel moves through it.
        if let Screen::Open(o) = &mut self.screen
            && o.menu.is_some()
        {
            let last = o.menu_actions().len().saturating_sub(1);
            if let Some(m) = o.menu.as_mut() {
                m.selected = if pixels < 0.0 { m.selected.saturating_sub(1) } else { (m.selected + 1).min(last) };
            }
            return;
        }
        let (x, y) = self.mouse;
        if self.list_rect.contains(x, y) {
            self.list_scroll = (self.list_scroll + pixels).clamp(0.0, self.list_max);
        } else {
            self.scroll = (self.scroll + pixels).clamp(0.0, self.max_scroll);
        }
        self.reveal = false;
    }
}

/// What is being opened, for the loading screen.
fn describe(args: &[String]) -> String {
    match parse_args(args) {
        Ok(Parsed::Review(Options { target: Some(t), .. })) => {
            format!("Reading {}", t.strip_suffix("^{commit}").unwrap_or(&t))
        }
        _ => "Reading the change".to_string(),
    }
}