use crate::review::forge::Method;
use super::{CreateStage, Field, Press};
use super::{Click, Opened, ReviewView, Row, Screen, Tab, Thing};
use crate::config::Rgba;
use crate::glyphs::STYLE_BOLD;
use crate::gpu::{MODE_SOLID, Quad};
use crate::layout::Rect;
use crate::render::{Ctx, mix, quad, rounded, text, with_alpha};
use crate::review::render::snippet;
use crate::review::rules::{Finding, Level};
use crate::review::diff::{FileDiff, Kind as DiffKind, Status};
use crate::review::guide::{self, Kind as StageKind};
use crate::review::session::{self, Seen, State, Verdict};
pub type Piece = (String, bool);
pub fn wrap(source: &str, cols: usize) -> Vec<Vec<Piece>> {
let cols = cols.max(4);
let paired = source.matches('`').count() / 2 * 2;
let mut seen = 0;
let mut code = false;
let mut words: Vec<Vec<(char, bool)>> = vec![Vec::new()];
for c in source.chars() {
if c == '`' && seen < paired {
seen += 1;
code = !code;
} else if c == ' ' || c == '\n' || c == '\t' {
words.push(Vec::new());
} else if !c.is_control() {
words.last_mut().expect("never empty").push((c, code));
}
}
let mut lines: Vec<Vec<(char, bool)>> = vec![Vec::new()];
for word in words.into_iter().filter(|w| !w.is_empty()) {
let line = lines.last_mut().expect("never empty");
if !line.is_empty() {
if line.len() + 1 + word.len() <= cols {
let inside = line.last().is_some_and(|l| l.1) && word[0].1;
line.push((' ', inside));
} else {
lines.push(Vec::new());
}
}
for c in word {
if lines.last().expect("never empty").len() >= cols {
lines.push(Vec::new());
}
lines.last_mut().expect("never empty").push(c);
}
}
lines
.into_iter()
.map(|line| {
let mut pieces: Vec<Piece> = Vec::new();
for (c, code) in line {
match pieces.last_mut() {
Some(p) if p.1 == code => p.0.push(c),
_ => pieces.push((c.to_string(), code)),
}
}
pieces
})
.collect()
}
#[derive(Clone, Copy)]
struct Colors {
fg: Rgba,
soft: Rgba,
muted: Rgba,
accent: Rgba,
code: Rgba,
panel: Rgba,
raised: Rgba,
line: Rgba,
red: Rgba,
green: Rgba,
yellow: Rgba,
cyan: Rgba,
}
impl Colors {
fn new(ctx: &Ctx) -> Colors {
let p = ctx.palette;
let panel = mix(p.surface, p.foreground, 0.025);
let solid = |c: Rgba| [c[0], c[1], c[2], 1.0];
Colors {
fg: p.foreground,
soft: mix(p.foreground, p.surface, 0.2),
muted: mix(p.foreground, p.surface, 0.5),
accent: p.accent,
code: mix(p.accent, p.foreground, 0.35),
panel: solid(panel),
raised: solid(mix(panel, p.foreground, 0.06)),
line: solid(mix(panel, p.foreground, 0.14)),
red: p.ansi[1],
green: p.ansi[2],
yellow: p.ansi[3],
cyan: p.ansi[6],
}
}
fn level(&self, level: Level) -> Rgba {
match level {
Level::Risk => self.red,
Level::Warn => self.yellow,
Level::Note => self.cyan,
}
}
fn state(&self, state: State) -> (&'static str, Rgba) {
match state {
State::Untested => ("\u{25cb}", self.muted),
State::Done(Verdict::Passed) => ("\u{2713}", self.green),
State::Done(Verdict::Failed) => ("\u{2717}", self.red),
State::Done(Verdict::Skipped) => ("\u{2013}", self.muted),
State::Stale(_) => ("\u{21bb}", self.yellow),
}
}
}
struct Button {
label: String,
click: Click,
tone: Option<Rgba>,
on: bool,
}
fn button(label: &str, click: Click) -> Button {
Button { label: label.to_string(), click, tone: None, on: false }
}
impl Button {
fn tone(mut self, color: Rgba, on: bool) -> Button {
self.tone = Some(color);
self.on = on;
self
}
}
struct Flow<'a, 'c> {
ctx: &'a mut Ctx<'c>,
out: &'a mut Vec<Quad>,
hits: &'a mut Vec<(Rect, Click)>,
colors: Colors,
mouse: (f32, f32),
area: Rect,
x: f32,
w: f32,
y: f32,
cw: f32,
ch: f32,
s: f32,
}
impl<'a, 'c> Flow<'a, 'c> {
fn new(
ctx: &'a mut Ctx<'c>,
out: &'a mut Vec<Quad>,
hits: &'a mut Vec<(Rect, Click)>,
mouse: (f32, f32),
area: Rect,
scroll: f32,
) -> Self {
let colors = Colors::new(ctx);
let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
Flow { ctx, out, hits, colors, mouse, area, x: area.x, w: area.w, y: area.y - scroll.round(), cw, ch, s }
}
fn clip(&self) -> [f32; 4] {
[self.area.x, self.area.y, self.area.right(), self.area.bottom()]
}
fn shows(&self, y: f32, h: f32) -> bool {
y + h >= self.area.y && y <= self.area.bottom()
}
fn line_height(&self) -> f32 {
(self.ch * 1.25).round()
}
fn cols(&self, width: f32) -> usize {
(width / self.cw).floor().max(4.0) as usize
}
fn gap(&mut self, lines: f32) {
self.y += (self.ch * lines).round();
}
fn fill(&mut self, r: Rect, color: Rgba, radius: f32) {
if self.shows(r.y, r.h) {
let clip = self.clip();
self.out.push(rounded(r, color, radius * self.s, 0.0, [0.0; 4], clip));
}
}
fn framed(&mut self, r: Rect, color: Rgba, border: Rgba, radius: f32) {
if self.shows(r.y, r.h) {
let clip = self.clip();
self.out.push(rounded(r, color, radius * self.s, self.s.max(1.0), border, clip));
}
}
fn put(&mut self, x: f32, y: f32, content: &str, color: Rgba, style: u8, max_w: f32) -> f32 {
if !self.shows(y, self.ch) || max_w < self.cw {
return 0.0;
}
let content: String = content.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();
let clip = self.clip();
text(self.ctx, self.out, x.round(), y.round(), &content, color, style, max_w, clip)
}
fn para(&mut self, content: &str, color: Rgba, style: u8, indent: f32) {
let width = self.w - indent;
let lines = wrap(content, self.cols(width));
let (lh, code) = (self.line_height(), self.colors.code);
for line in lines {
let mut x = self.x + indent;
for (piece, is_code) in line {
let chars = piece.chars().count() as f32;
let color = if is_code { code } else { color };
self.put(x, self.y, &piece, color, style, (chars + 0.5) * self.cw);
x += chars * self.cw;
}
self.y += lh;
}
}
fn hit(&mut self, r: Rect, click: Click) {
let (top, bottom) = (r.y.max(self.area.y), r.bottom().min(self.area.bottom()));
if bottom > top {
self.hits.push((Rect::new(r.x, top, r.w, bottom - top), click));
}
}
fn hovered(&self, r: Rect) -> bool {
r.contains(self.mouse.0, self.mouse.1) && self.area.contains(self.mouse.0, self.mouse.1)
}
fn button_width(&self, label: &str) -> f32 {
(label.chars().count() as f32 + 2.0) * self.cw
}
fn button_at(&mut self, r: Rect, b: Button) {
let c = self.colors;
let tone = b.tone.unwrap_or(c.fg);
let hover = self.hovered(r);
let fill = if b.on { mix(c.panel, tone, 0.34) } else if hover { mix(c.raised, c.fg, 0.08) } else { c.raised };
let border = if b.on || (hover && b.tone.is_some()) { tone } else { c.line };
self.framed(r, fill, border, 6.0);
let width = b.label.chars().count() as f32 * self.cw;
let color = if b.tone.is_some() && !b.on { mix(tone, c.fg, 0.25) } else { c.fg };
self.put(r.x + (r.w - width) * 0.5, r.y + (r.h - self.ch) * 0.5, &b.label, color, 0, width + 1.0);
self.hit(r, b.click);
}
fn buttons(&mut self, buttons: Vec<Button>) {
let (h, gap) = ((self.ch * 1.6).round(), (6.0 * self.s).round());
let mut x = self.x;
for b in buttons {
let w = self.button_width(&b.label).min(self.w);
if x > self.x && x + w > self.x + self.w {
x = self.x;
self.y += h + gap;
}
self.button_at(Rect::new(x, self.y, w, h), b);
x += w + gap;
}
self.y += h;
}
fn field(&mut self, content: &str, placeholder: &str, focused: bool, click: Option<Click>) {
let c = self.colors;
let r = Rect::new(self.x, self.y, self.w, (self.ch * 1.8).round());
self.framed(r, c.raised, if focused { c.accent } else { c.line }, 7.0);
let ty = r.y + (r.h - self.ch) * 0.5;
let room = self.cols(r.w - 2.0 * self.cw).saturating_sub(1);
let chars: Vec<char> = content.chars().collect();
let shown: String = chars[chars.len().saturating_sub(room)..].iter().collect();
if shown.is_empty() {
self.put(r.x + self.cw, ty, placeholder, c.muted, 0, r.w - 2.0 * self.cw);
} else {
self.put(r.x + self.cw, ty, &shown, c.fg, 0, r.w - self.cw);
}
if focused && self.shows(r.y, r.h) {
let cx = r.x + self.cw + shown.chars().count() as f32 * self.cw + 1.0;
let caret = Rect::new(cx, ty + self.ch * 0.12, (1.5 * self.s).round().max(1.0), self.ch * 0.76);
let clip = self.clip();
self.out.push(quad(caret, with_alpha(c.accent, self.ctx.cursor_alpha.max(0.25)), clip, MODE_SOLID));
}
if let Some(click) = click {
self.hit(r, click);
}
self.y = r.bottom();
}
fn text_box(&mut self, content: &str, focused: bool, click: Click) {
let c = self.colors;
let cols = self.cols(self.w - 2.0 * self.cw).saturating_sub(1).max(1);
let mut lines: Vec<String> = Vec::new();
for line in content.split('\n') {
let chars: Vec<char> = line.chars().collect();
if chars.is_empty() {
lines.push(String::new());
}
lines.extend(chars.chunks(cols).map(|part| part.iter().collect::<String>()));
}
let lh = self.line_height();
let height = (lines.len().max(5) as f32 * lh + self.ch * 0.6).round();
let r = Rect::new(self.x, self.y, self.w, height);
self.framed(r, c.raised, if focused { c.accent } else { c.line }, 7.0);
let top = r.y + self.ch * 0.3;
for (i, line) in lines.iter().enumerate() {
self.put(r.x + self.cw, top + i as f32 * lh, line, c.fg, 0, r.w - self.cw);
}
if focused {
let last = lines.last().map_or(0, |l| l.chars().count());
let cx = r.x + self.cw * (last as f32 + 1.0) + 1.0;
let cy = top + (lines.len() - 1) as f32 * lh;
if self.shows(cy, self.ch) {
let caret = Rect::new(cx, cy + self.ch * 0.12, (1.5 * self.s).round().max(1.0), self.ch * 0.76);
let clip = self.clip();
self.out.push(quad(caret, with_alpha(c.accent, self.ctx.cursor_alpha.max(0.25)), clip, MODE_SOLID));
}
}
self.hit(r, click);
self.y = r.bottom();
}
fn rule(&mut self) {
let r = Rect::new(self.x, self.y, self.w, self.s.max(1.0).round());
let line = self.colors.line;
self.fill(r, line, 0.0);
self.y = r.bottom();
}
fn callout(&mut self, content: &str, color: Rgba) {
let pad = self.cw;
let height = wrap(content, self.cols(self.w - 2.5 * pad)).len() as f32 * self.line_height() + self.ch * 0.5;
let r = Rect::new(self.x, self.y, self.w, height.round());
let tint = mix(self.colors.panel, color, 0.12);
self.fill(r, tint, 6.0);
self.fill(Rect::new(r.x, r.y, (3.0 * self.s).round(), r.h), color, 1.0);
self.y += (self.ch * 0.25).round();
let (x, w) = (self.x, self.w);
self.x += 1.5 * pad;
self.w -= 2.5 * pad;
let fg = self.colors.fg;
self.para(content, fg, 0, 0.0);
(self.x, self.w) = (x, w);
self.y = r.bottom();
}
fn place(&mut self, f: &Finding) {
let Some(span) = &f.span else { return };
let c = self.colors;
let from_description = span.file == "PR description" || span.file == "commit messages";
let place = format!("{}:{}", span.file, span.line);
let width = (place.chars().count() as f32 * self.cw).min(self.w);
let r = Rect::new(self.x, self.y, width, self.line_height());
let color = if from_description { c.muted } else if self.hovered(r) { c.accent } else { c.code };
self.put(self.x, self.y, &place, color, 0, self.w);
if !from_description {
self.hit(r, Click::File(span.file.clone(), span.line));
}
self.y += self.line_height();
let (shown, col, len) = snippet(span, self.cols(self.w - 2.0 * self.cw));
let r = Rect::new(self.x, self.y, self.w, (self.ch * 1.7).round());
self.fill(r, c.raised, 6.0);
let ty = r.y + self.ch * 0.25;
self.put(r.x + self.cw, ty, &shown, c.fg, 0, r.w - self.cw);
let under = Rect::new(r.x + self.cw * (col as f32 + 1.0), ty + self.ch * 1.08, len as f32 * self.cw, (2.0 * self.s).round());
let color = c.level(f.level);
self.fill(under, color, 1.0);
self.y = r.bottom() + (self.ch * 0.15).round();
self.para(&span.label, color, 0, self.cw);
}
}
fn level_tag(level: Level) -> &'static str {
match level {
Level::Risk => "RISK",
Level::Warn => "WARNING",
Level::Note => "NOTE",
}
}
pub fn draw(ctx: &mut Ctx, view: &mut ReviewView, rect: Rect, out: &mut Vec<Quad>) -> bool {
let colors = Colors::new(ctx);
let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
view.rect = rect;
view.list_rect = Rect::default();
view.hits.clear();
let radius = ctx.config.radius * s;
let edge = if view.focused && ctx.focused { colors.accent } else { colors.line };
out.push(rounded(rect, colors.panel, radius, (1.5 * s).round().max(1.0), edge, crate::render::NO_CLIP));
let pad = (14.0 * s).round().min(rect.w * 0.05);
let inner = Rect::new(rect.x + pad, rect.y + pad, (rect.w - 2.0 * pad).max(0.0), (rect.h - 2.0 * pad).max(0.0));
if inner.w < cw * 12.0 || inner.h < ch * 8.0 {
return false;
}
let (title, subtitle) = titles(view);
let header_h = (ch * 1.6).round();
let wide_label = if view.wide { "Side" } else { "Wide" };
let mut right = inner.right();
{
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, inner, 0.0);
for b in [button("\u{2715}", Click::Close), button(wide_label, Click::Wide)] {
let w = f.button_width(&b.label);
right -= w;
f.button_at(Rect::new(right, inner.y, w, header_h), b);
right -= 6.0 * s;
}
f.put(inner.x, inner.y + (header_h - ch) * 0.5, &title, colors.fg, STYLE_BOLD, right - inner.x);
f.y = inner.y + header_h + (ch * 0.25).round();
f.put(inner.x, f.y, &subtitle, colors.muted, 0, inner.w);
}
let top = inner.y + header_h + (ch * 1.75).round();
let body = Rect::new(inner.x, top, inner.w, (inner.bottom() - top).max(0.0));
let focused = view.focused;
match &view.screen {
Screen::Git(_) => return draw_git(ctx, view, body, out),
Screen::Create(_) => return draw_create(ctx, view, body, out),
Screen::Pick(_) => draw_picker(ctx, view, body, out),
Screen::Open(_) => return draw_change(ctx, view, body, out),
Screen::Loading(what) => {
let what = what.clone();
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
f.gap(1.0);
f.para(&format!("{what}\u{2026}"), colors.soft, 0, 0.0);
f.gap(0.5);
f.para("A pull request is fetched from its host first.", colors.muted, 0, 0.0);
}
Screen::Message { text: message, error } => {
let (message, error) = (message.clone(), *error);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
f.gap(0.5);
f.callout(&message, if error { colors.red } else { colors.cyan });
f.gap(1.0);
f.buttons(vec![button("\u{2039} All changes", Click::Back), button("Try again", Click::Reload)]);
if focused {
f.gap(1.0);
f.para("esc: back to the list r: try again", colors.muted, 0, 0.0);
}
}
}
false
}
fn titles(view: &ReviewView) -> (String, String) {
let folder = view.cwd.to_string_lossy().into_owned();
match &view.screen {
Screen::Git(g) => ("Git".into(), g.snapshot.as_ref().map_or(folder, |s| {
format!("{} \u{00b7} {} changed \u{00b7} {}", s.branch, s.dirty, s.root.display())
})),
Screen::Pick(_) => ("Review a change".to_string(), folder),
Screen::Create(_) => ("New pull request".to_string(), folder),
Screen::Loading(_) | Screen::Message { .. } => ("Review".to_string(), folder),
Screen::Open(o) => {
let r = &o.change.report;
let project = if r.project.is_empty() { String::new() } else { format!(" \u{00b7} {}", r.project.join(", ")) };
let files = if r.files == 1 { "file" } else { "files" };
(o.change.title.clone(), format!("{} \u{00b7} {} {files} +{} \u{2212}{}{project}", r.against, r.files, r.added, r.removed))
}
}
}
fn draw_git(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
use super::workspace::{Control, Form, Tab};
use crate::review::workspace::Action;
let Screen::Git(g) = &view.screen else { return false };
let c = Colors::new(ctx);
let ch = ctx.glyphs.cell_h;
let footer_h = ch * if view.status.is_some() { 6.0 } else { 3.5 };
let area = Rect::new(body.x, body.y, body.w, (body.h - footer_h).max(0.0));
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, area, view.scroll);
let start = f.y;
let mut chosen = None;
let action = |name, control| button(name, Click::GitAction(control));
if let Some(preview) = &g.preview {
let (title, movement) = match preview {
Action::Move(m) => ("Move commits", Some(m)),
Action::Undo(m) => ("Undo move", Some(m)),
Action::Publish { movement, .. } => ("Publish recovery", Some(movement)),
_ => ("Git", None),
};
f.para(title, c.fg, STYLE_BOLD, 0.0);
f.gap(0.7);
if let Some(m) = movement {
let short = |id: &str| id.chars().take(8).collect::<String>();
let (from, to) = if matches!(preview, Action::Undo(_)) { (&m.base, &m.old) } else { (&m.old, &m.base) };
if let Action::Publish { expected, desired, remote, .. } = preview {
f.para(&crate::review::workspace::remote_label(remote), c.soft, 0, 0.0);
f.para(&format!("Remote {}: {} \u{2192} {}", m.source, short(expected), short(desired)), c.fg, 0, 0.0);
f.para("Atomic push \u{00b7} force-with-lease", c.yellow, 0, 0.0);
} else {
f.para(&format!("{}: {} \u{2192} {}", m.source, short(from), short(to)), c.fg, 0, 0.0);
}
f.para(&format!("{}: {} \u{00b7} {} commits", m.destination, short(&m.old), m.count), c.soft, 0, 0.0);
f.gap(0.7);
if !matches!(preview, Action::Publish { .. }) {
f.para("Local only \u{00b7} undo available", c.muted, 0, 0.0);
}
}
f.gap(1.0);
f.buttons(vec![action("Confirm Enter", Control::Accept), action("Cancel Esc", Control::Cancel)]);
} else {
f.buttons(vec![
action(if g.tab == Tab::Branches { "Branches \u{2022}" } else { "Branches" }, Control::Branches),
action(if g.tab == Tab::Commits { "Commits \u{2022}" } else { "Commits" }, Control::Commits),
action("PR p", Control::PullRequest), action("Refresh r", Control::Refresh),
action("Fetch f", Control::Fetch),
]);
f.gap(0.5);
if let Some(form) = g.form {
let label = match form { Form::Create => "New branch", Form::Move(_) => "Move to new branch", Form::Filter => "Filter branches" };
f.para(label, c.soft, 0, 0.0);
f.field(&g.text, "enter name", view.focused, None);
f.gap(0.5);
} else if !g.filter.is_empty() && g.tab == Tab::Branches {
f.para(&format!("/ {}", g.filter), c.muted, 0, 0.0);
}
if let Some(s) = &g.snapshot {
if g.tab == Tab::Commits {
f.para(&format!("{} selected \u{00b7} latest first", (g.oldest + 1).min(s.commits.len())), c.muted, 0, 0.0);
f.gap(0.3);
}
if s.recovery.is_some() {
f.para(if s.undo.is_some() { "Recovery \u{00b7} undo u \u{00b7} publish y" } else { "Restored \u{00b7} publish y" }, c.soft, 0, 0.0);
f.gap(0.4);
}
let rows = g.rows();
if rows.is_empty() { f.para("No matches", c.muted, 0, 0.0); }
for (i, (name, detail)) in rows.iter().enumerate() {
let row = Rect::new(f.x, f.y, f.w, (f.ch * 1.65).round());
let selected = i == g.selected;
if selected { f.fill(row, mix(c.panel, c.accent, 0.18), 6.0); }
else if f.hovered(row) { f.fill(row, c.raised, 6.0); }
let label = if detail == "current" { format!("\u{2022} {name}") }
else if detail == "remote" { format!("{name} \u{00b7} remote") } else { name.clone() };
f.put(row.x + f.cw, row.y + f.ch * 0.25, &label, if selected { c.fg } else { c.soft }, 0, row.w - f.cw * 2.0);
f.hit(row, Click::GitRow(i));
f.y = row.bottom();
if selected { chosen = Some((row.y - start, row.h)); }
}
} else {
f.para(if g.busy { "Loading\u{2026}" } else { "Refresh to retry" }, c.muted, 0, 0.0);
}
}
let height = f.y - start;
view.max_scroll = (height - area.h).max(0.0);
let previous = view.scroll;
if view.reveal {
if let Some(chosen) = chosen.filter(|_| g.form.is_none()) { view.scroll = scrolled_to(view.scroll, chosen, area.h, ch); }
view.reveal = false;
}
view.scroll = view.scroll.clamp(0.0, view.max_scroll);
scrollbar(out, area, view.scroll, view.max_scroll, ctx.scale, c);
let footer = Rect::new(body.x, area.bottom() + ch * 0.3, body.w, footer_h - ch * 0.3);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
f.rule();
f.gap(0.3);
if let Some((message, error)) = &view.status {
for line in wrap(message, f.cols(f.w)).into_iter().take(3) {
let text: String = line.into_iter().map(|(s, _)| s).collect();
f.put(f.x, f.y, &text, if *error { c.red } else { c.green }, 0, f.w);
f.y += f.line_height();
}
}
let hint = if g.busy { "Working\u{2026}" }
else if g.form.is_some() || g.preview.is_some() { "enter confirm esc cancel" }
else if g.tab == Tab::Branches { "enter switch n new / filter tab commits p PR c copy esc close" }
else { "space select through here m move u undo y publish enter review tab branches" };
f.para(hint, c.muted, 0, 0.0);
(previous - view.scroll).abs() > 1.0
}
fn draw_create(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
let Screen::Create(c) = &view.screen else { return false };
let colors = Colors::new(ctx);
let ch = ctx.glyphs.cell_h;
let footer_h = ch * if view.status.is_some() { 5.5 } else { 2.5 };
let area = Rect::new(body.x, body.y, body.w, (body.h - footer_h).max(0.0));
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, area, view.scroll);
let start = f.y;
let mut chosen = None;
let press = |name: &str, p: Press| button(name, Click::Create(p));
let hint = match &c.stage {
CreateStage::Loading => {
f.gap(0.5);
f.para("Looking at the branch and asking the host\u{2026}", colors.soft, 0, 0.0);
"esc back"
}
CreateStage::Failed(why) => {
f.gap(0.5);
f.callout(why, colors.red);
f.gap(1.0);
f.buttons(vec![press("\u{2039} All changes", Press::Cancel)]);
"r try again \u{00b7} esc back"
}
CreateStage::Done { pull, created } => {
f.gap(0.5);
let said = match created {
Some(host) => format!("Created pull request #{} on {host}", pull.number),
None => format!("This branch already has an open pull request, #{}", pull.number),
};
f.callout(&said, colors.green);
f.gap(0.7);
f.para(&pull.title, colors.fg, STYLE_BOLD, 0.0);
f.para(&pull.url, colors.muted, 0, 0.0);
f.gap(1.0);
f.buttons(vec![
press("Review it", Press::Review),
press("Open in browser", Press::Open),
press("Copy link", Press::Copy),
]);
"enter review it \u{00b7} o browser \u{00b7} c copy link \u{00b7} esc back"
}
CreateStage::Form | CreateStage::Confirm | CreateStage::Sending => match &c.proposal {
None => "esc back",
Some(p) => {
f.para(&format!("{} \u{2192} {}", p.pull.head, p.pull.base), colors.accent, STYLE_BOLD, 0.0);
let count = if p.commits.len() == 1 { "1 commit".into() } else { format!("{} commits", p.commits.len()) };
f.para(&format!("{count} \u{00b7} {}", p.host), colors.muted, 0, 0.0);
if p.dirty > 0 {
f.gap(0.4);
let left = format!("Uncommitted changes in {} files are not part of it", p.dirty);
f.callout(&left, colors.yellow);
}
f.gap(0.8);
if matches!(c.stage, CreateStage::Form) {
for (label, field, value) in [
("Title", Field::Title, &p.pull.title),
("Merge into", Field::Base, &p.pull.base),
] {
let top = f.y;
f.para(label, colors.soft, 0, 0.0);
let on = c.field == field;
f.field(value, label, on && view.focused, Some(Click::Create(Press::Focus(field))));
if on {
chosen = Some((top - start, f.y - top));
}
f.gap(0.6);
}
let top = f.y;
f.para("Description", colors.soft, 0, 0.0);
let on = c.field == Field::Description;
f.text_box(&p.pull.body, on && view.focused, Click::Create(Press::Focus(Field::Description)));
if on {
let (from, to) = (top - start, f.y - start);
let shown = (to - from).min(area.h * 0.8);
chosen = Some((to - shown, shown));
}
f.gap(0.8);
let top = f.y;
let mut next = press("Continue \u{203a}", Press::Accept);
if c.field == Field::Continue {
next = next.tone(colors.accent, true);
chosen = Some((top - start, ch * 2.0));
}
f.buttons(vec![next]);
"tab next field \u{00b7} enter new line in the description \u{00b7} esc back"
} else {
f.para(&p.pull.title, colors.fg, STYLE_BOLD, 0.0);
f.gap(0.4);
for line in p.pull.body.lines() {
f.para(line, colors.soft, 0, 0.0);
}
f.gap(0.8);
let push = if p.push {
format!("1. Push {} to {} (not forced). ", p.pull.head, p.remote) + "2. "
} else {
String::new()
};
let will = format!("{push}Create a pull request on {} into {}.", p.host, p.pull.base);
f.callout(&will, colors.yellow);
f.gap(1.0);
if matches!(c.stage, CreateStage::Sending) {
f.para("Sending\u{2026}", colors.soft, 0, 0.0);
"esc close the panel; it carries on"
} else {
f.buttons(vec![press("Create Enter", Press::Accept), press("Back Esc", Press::Cancel)]);
"enter create \u{00b7} esc back to editing"
}
}
}
},
};
let height = f.y - start;
view.max_scroll = (height - area.h).max(0.0);
let previous = view.scroll;
if view.reveal {
if let Some(chosen) = chosen {
view.scroll = scrolled_to(view.scroll, chosen, area.h, ch);
}
view.reveal = false;
}
view.scroll = view.scroll.clamp(0.0, view.max_scroll);
scrollbar(out, area, view.scroll, view.max_scroll, ctx.scale, colors);
let footer = Rect::new(body.x, area.bottom() + ch * 0.3, body.w, footer_h - ch * 0.3);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
f.rule();
f.gap(0.3);
if let Some((message, error)) = &view.status {
let color = if *error { colors.red } else { colors.green };
for line in wrap(message, f.cols(f.w)).into_iter().take(3) {
let text: String = line.into_iter().map(|(s, _)| s).collect();
f.put(f.x, f.y, &text, color, 0, f.w);
f.y += f.line_height();
}
}
f.para(hint, colors.muted, 0, 0.0);
(previous - view.scroll).abs() > 1.0
}
fn draw_picker(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) {
let Screen::Pick(picker) = &view.screen else { return };
let rows = picker.rows();
let (filter, selected) = (picker.filter.clone(), picker.selected);
let (ch, s) = (ctx.glyphs.cell_h, ctx.scale);
let colors = Colors::new(ctx);
let footer_h = (ch * 1.6).round();
let field_end = {
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
f.field(&filter, "Filter, or type a PR number, branch or commit", view.focused, None);
f.y
};
let list = Rect::new(body.x, field_end + (ch * 0.5).round(), body.w, (body.bottom() - footer_h - field_end - ch * 0.5).max(0.0));
let entry_h = (ch * 2.55).round();
let heading_h = (ch * 1.9).round();
let note_h = |text: &str, cols: usize| wrap(text, cols).len() as f32 * (ch * 1.25).round() + (ch * 0.3).round();
let note_cols = ((list.w - 2.0 * ctx.glyphs.cell_w) / ctx.glyphs.cell_w).floor().max(4.0) as usize;
let mut total = 0.0;
let mut chosen = (0.0, 0.0);
let mut n = 0;
for row in &rows {
let h = match row {
Row::Heading(_) => heading_h,
Row::Note(t) => note_h(t, note_cols),
Row::Entry(_) => {
if n == selected {
chosen = (total, entry_h);
}
n += 1;
entry_h
}
};
total += h;
}
view.max_scroll = (total - list.h).max(0.0);
if view.reveal {
view.scroll = scrolled_to(view.scroll, chosen, list.h, heading_h);
view.reveal = false;
}
view.scroll = view.scroll.clamp(0.0, view.max_scroll);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, view.scroll);
let mut n = 0;
for row in &rows {
match row {
Row::Heading(name) => {
f.put(f.x, f.y + ch * 0.7, &name.to_uppercase(), colors.muted, STYLE_BOLD, f.w);
f.y += heading_h;
}
Row::Note(message) => {
let start = f.y;
f.para(message, colors.muted, 0, f.cw);
f.y = start + note_h(message, note_cols);
}
Row::Entry(entry) => {
let r = Rect::new(f.x, f.y, f.w, entry_h - (3.0 * s).round());
let hover = f.hovered(r);
if n == selected {
let fill = mix(colors.panel, colors.accent, 0.18);
f.framed(r, fill, mix(colors.panel, colors.accent, 0.5), 7.0);
} else if hover {
f.fill(r, colors.raised, 7.0);
}
f.put(r.x + f.cw, r.y + ch * 0.15, &entry.title, colors.fg, 0, r.w - 2.0 * f.cw);
f.put(r.x + f.cw, r.y + ch * 1.25, &entry.detail, colors.muted, 0, r.w - 2.0 * f.cw);
f.hit(r, Click::Choose(n));
f.y += entry_h;
n += 1;
}
}
}
scrollbar(out, list, view.scroll, view.max_scroll, s, colors);
let foot = Rect::new(body.x, body.bottom() - ch * 1.2, body.w, ch * 1.2);
let hint = if view.focused { "\u{2191}\u{2193} choose enter review esc close" } else { "click here to type" };
Flow::new(ctx, out, &mut view.hits, view.mouse, foot, 0.0).put(foot.x, foot.y, hint, colors.muted, 0, foot.w);
}
fn scrolled_to(scroll: f32, (top, height): (f32, f32), h: f32, above: f32) -> f32 {
if top - above < scroll {
(top - above).max(0.0)
} else if top + height > scroll + h {
top + height - h
} else {
scroll
}
}
fn scrollbar(out: &mut Vec<Quad>, area: Rect, scroll: f32, max: f32, s: f32, colors: Colors) {
if max <= 0.0 || area.h <= 0.0 {
return;
}
let thumb = (area.h * area.h / (area.h + max)).max(18.0 * s).min(area.h);
let y = area.y + (scroll / max) * (area.h - thumb);
let r = Rect::new(area.right() + 3.0 * s, y, 3.0 * s, thumb);
out.push(rounded(r, with_alpha(colors.fg, 0.25), 1.5 * s, 0.0, [0.0; 4], crate::render::NO_CLIP));
}
fn progress(f: &mut Flow, o: &Opened) {
let c = f.colors;
let (mut done, mut total, mut failed) = (0, 0, 0);
for stage in 0..o.stages.len() {
let (d, t) = o.stage_counts(stage);
done += d;
total += t;
}
for i in &o.items {
failed += usize::from(o.session.state(&i.id) == State::Done(Verdict::Failed));
}
let bar = Rect::new(f.x, f.y, f.w, (6.0 * f.s).round());
f.fill(bar, c.line, 3.0);
if total > 0 {
let color = if failed > 0 { c.red } else { c.green };
f.fill(Rect::new(bar.x, bar.y, bar.w * done as f32 / total as f32, bar.h), color, 2.0);
}
f.y = bar.bottom() + (f.ch * 0.3).round();
let mut line = format!("{done} of {total} done");
if failed > 0 {
line += &format!(" \u{00b7} {failed} failed");
}
if o.session.approved() {
line += " \u{00b7} approved";
}
f.put(f.x, f.y, &line, if failed > 0 { mix(c.red, c.fg, 0.3) } else { c.soft }, 0, f.w);
f.y += f.line_height();
}
fn draw_change(ctx: &mut Ctx, view: &mut ReviewView, body: Rect, out: &mut Vec<Quad>) -> bool {
let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
let colors = Colors::new(ctx);
let focused = view.focused;
let status = view.status.clone();
let Screen::Open(o) = &view.screen else { return false };
let tabs_end = {
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, body, 0.0);
progress(&mut f, o);
f.gap(0.3);
let tabs = Tab::ALL
.iter()
.map(|&t| {
let label = match t {
Tab::Guide => format!("Guide ({}/{})", o.stage + 1, o.stages.len()),
Tab::Findings => format!("Findings ({})", o.change.report.findings.len()),
Tab::Description => "Description".to_string(),
};
button(&label, Click::Tab(t)).tone(colors.accent, o.tab == t)
})
.collect();
f.buttons(tabs);
f.gap(0.4);
f.rule();
f.y
};
let mut actions = vec![button("\u{2039} All changes", Click::Back), button("Reload", Click::Reload)];
if o.change.pull.is_some() {
let (label, on) = if o.approving {
("Approving\u{2026}", false)
} else if o.session.approved() {
("\u{2713} Approved", true)
} else if o.confirm_approve {
("Really approve?", true)
} else {
("Approve", false)
};
actions.push(button(label, Click::Approve).tone(colors.green, on));
actions.extend(merge_buttons(o, colors));
}
if o.change.branch.is_some() {
actions.push(button("Open pull request", Click::Propose).tone(colors.accent, false));
}
if !o.items.is_empty() {
actions.push(button("Copy results", Click::CopyResults));
let label = if o.confirm_reset { "Really reset?" } else { "Reset" };
actions.push(button(label, Click::Reset).tone(colors.red, o.confirm_reset));
}
let hint = if !focused {
"click the panel to use its keys".to_string()
} else if o.note.is_some() {
"type what went wrong enter save and go on esc cancel".to_string()
} else {
match (o.tab, o.thing()) {
(Tab::Guide, Some(Thing::File(_))) => {
"enter read \u{2191}\u{2193} move \u{2190}\u{2192} stage o open esc terminal".to_string()
}
(Tab::Guide, _) => {
"enter fine backspace problem s skip \u{2191}\u{2193} move \u{2190}\u{2192} stage t type esc terminal"
.to_string()
}
(Tab::Findings, _) => "\u{2191}\u{2193} choose enter unfold o open tab next w wide esc terminal".to_string(),
(Tab::Description, _) => "\u{2191}\u{2193} scroll tab next w wide esc terminal".to_string(),
}
};
let hint = if focused && o.note.is_none() && o.change.pull.is_some() && !o.merged {
format!("a approve \u{00b7} q squash and merge \u{00b7} g merge \u{00b7} {hint}")
} else {
hint
};
let hint = if focused && o.note.is_none() && o.change.branch.is_some() {
format!("m pull request \u{00b7} {hint}")
} else {
hint
};
let hint_lines = wrap(&hint, (body.w / cw).floor().max(4.0) as usize).len().min(2);
let mut rows = 1.0;
let mut used = 0.0;
for b in &actions {
let w = (b.label.chars().count() as f32 + 2.0) * cw + (6.0 * s).round();
if used > 0.0 && used + w > body.w + (6.0 * s).round() {
rows += 1.0;
used = 0.0;
}
used += w;
}
let actions_h = rows * (ch * 1.6).round() + (rows - 1.0) * (6.0 * s).round();
let status_lines = status.as_ref().map_or(0, |(m, _)| wrap(m, (body.w / cw).floor().max(4.0) as usize).len().min(3));
let status_h = if status_lines > 0 { status_lines as f32 * (ch * 1.25).round() + (ch * 0.2).round() } else { 0.0 };
let footer_h = actions_h + status_h + hint_lines as f32 * (ch * 1.25).round() + (ch * 0.9).round();
let footer = Rect::new(body.x, (body.bottom() - footer_h).max(tabs_end), body.w, footer_h);
{
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, footer, 0.0);
f.rule();
f.gap(0.35);
if let Some((message, problem)) = &status {
let color = if *problem { colors.red } else { colors.green };
let top = f.y;
for line in wrap(message, f.cols(f.w)).iter().take(status_lines) {
let line: String = line.iter().map(|(piece, _)| piece.as_str()).collect();
f.put(f.x, f.y, &line, color, 0, f.w);
f.y += f.line_height();
}
f.y = top + status_h;
}
f.buttons(actions);
f.gap(0.3);
f.para(&hint, colors.muted, 0, 0.0);
}
let area = Rect::new(body.x, tabs_end + (ch * 0.5).round(), body.w, (footer.y - tabs_end - ch).max(0.0));
let split = o.tab == Tab::Guide && area.w > cw * 96.0;
let main = if split {
let list_w = (area.w * 0.26).clamp(cw * 26.0, cw * 44.0).round();
let list = Rect::new(area.x, area.y, list_w, area.h);
view.list_rect = list;
let row_h = (ch * 1.55).round();
let head_h = (ch * 1.6).round();
view.list_max = (o.stages.len() as f32 * row_h + head_h - list.h).max(0.0);
if view.reveal {
let top = o.stage as f32 * row_h + head_h;
view.list_scroll = scrolled_to(view.list_scroll, (top, row_h), list.h, head_h);
}
view.list_scroll = view.list_scroll.clamp(0.0, view.list_max);
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, list, view.list_scroll);
stage_rail(&mut f, o);
scrollbar(out, list, view.list_scroll, view.list_max, s, colors);
let x = list.right() + (cw * 2.0).round();
Rect::new(x, area.y, area.right() - x, area.h)
} else {
area
};
let mut f = Flow::new(ctx, out, &mut view.hits, view.mouse, main, view.scroll);
let start = f.y;
let mut chosen = None;
match o.tab {
Tab::Guide => chosen = guide_tab(&mut f, o, focused),
Tab::Findings => chosen = findings_tab(&mut f, o),
Tab::Description => description_tab(&mut f, o),
}
f.gap(0.5);
let height = f.y - start;
view.max_scroll = (height - main.h).max(0.0);
let mut again = false;
if view.reveal {
view.reveal = false;
let at_top = std::mem::take(&mut view.at_top);
if let Some((top, h)) = chosen.filter(|_| !at_top) {
let wanted = scrolled_to(view.scroll, (top - start, h.min(main.h)), main.h, 0.0).clamp(0.0, view.max_scroll);
again = (wanted - view.scroll).abs() > 1.0;
view.scroll = wanted;
}
}
if view.scroll > view.max_scroll {
view.scroll = view.max_scroll;
again = true;
}
scrollbar(out, main, view.scroll, view.max_scroll, s, colors);
again
}
fn warnings(f: &mut Flow, o: &Opened) {
let c = f.colors;
if !o.change.checked_out {
f.callout("Your working copy is not on this change. Switch to it before testing, then reload.", c.yellow);
if let Some(command) = &o.change.checkout {
f.gap(0.35);
f.buttons(vec![
button(&format!("Type: {command}"), Click::Type(command.clone())),
button("Copy", Click::Copy(command.clone())),
]);
}
f.gap(0.8);
}
for note in &o.change.notes {
f.callout(note, c.cyan);
f.gap(0.8);
}
}
fn stage_rail(f: &mut Flow, o: &Opened) {
let c = f.colors;
let row_h = (f.ch * 1.55).round();
f.put(f.x, f.y + f.ch * 0.4, "STAGES", c.muted, STYLE_BOLD, f.w);
f.y += (f.ch * 1.6).round();
for (i, stage) in o.stages.iter().enumerate() {
let r = Rect::new(f.x, f.y, f.w, row_h - (2.0 * f.s).round());
let current = i == o.stage;
if current {
f.fill(r, mix(c.panel, c.accent, 0.18), 6.0);
} else if f.hovered(r) {
f.fill(r, c.raised, 6.0);
}
let ty = r.y + (r.h - f.ch) * 0.5;
let (done, total) = o.stage_counts(i);
let failed = stage.items.iter().any(|&k| o.session.state(&o.items[k].id) == State::Done(Verdict::Failed));
let (mark, color) = if failed {
("\u{2717}", c.red)
} else if total > 0 && done == total {
("\u{2713}", c.green)
} else if current {
("\u{25cf}", c.accent)
} else {
("\u{25cb}", c.muted)
};
f.put(r.x + f.cw * 0.5, ty, mark, color, STYLE_BOLD, f.cw * 2.0);
let count = if total > 0 { format!("{done}/{total}") } else { String::new() };
let count_w = count.chars().count() as f32 * f.cw;
f.put(r.right() - f.cw * 0.5 - count_w, ty, &count, c.muted, 0, count_w + 1.0);
let color = if current { c.fg } else if total > 0 && done == total { c.muted } else { c.soft };
f.put(r.x + f.cw * 2.5, ty, &stage.title, color, if current { STYLE_BOLD } else { 0 }, r.w - f.cw * 3.5 - count_w);
f.hit(r, Click::Stage(i));
f.y += row_h;
}
}
fn group_heading(f: &mut Flow, name: &str) {
let c = f.colors;
f.gap(0.6);
f.put(f.x, f.y, name, c.muted, STYLE_BOLD, f.w);
f.y += f.line_height();
f.gap(0.15);
}
fn phase_heading(f: &mut Flow, name: &str) {
let c = f.colors;
f.gap(0.6);
f.rule();
f.gap(0.5);
let pad = f.cw;
let width = f.w - pad * 2.5;
let lines = wrap(name, f.cols(width)).len();
let r = Rect::new(f.x, f.y, f.w, lines as f32 * f.line_height() + f.ch * 0.5);
f.fill(r, mix(c.panel, c.accent, 0.10), 6.0);
f.fill(Rect::new(r.x, r.y, (3.0 * f.s).round(), r.h), c.accent, 1.0);
let (x, w) = (f.x, f.w);
f.x += pad * 1.5;
f.w = width;
f.y += f.ch * 0.25;
f.para(name, c.fg, STYLE_BOLD, 0.0);
(f.x, f.w) = (x, w);
f.y = r.bottom();
f.gap(0.5);
}
fn guide_tab(f: &mut Flow, o: &Opened, focused: bool) -> Option<(f32, f32)> {
let c = f.colors;
let stage = o.stages.get(o.stage)?;
let (done, total) = o.stage_counts(o.stage);
let heading = format!("STAGE {} OF {}", o.stage + 1, o.stages.len());
let used = f.put(f.x, f.y, &heading, c.muted, STYLE_BOLD, f.w);
if total > 0 {
let x = f.x + used + 2.0 * f.cw;
let color = if done == total { c.green } else { c.soft };
f.put(x, f.y, &format!("{done} of {total} done"), color, 0, f.x + f.w - x);
}
f.y += f.line_height();
f.gap(0.2);
f.para(&stage.title, c.fg, STYLE_BOLD, 0.0);
f.gap(0.6);
match stage.kind {
StageKind::Overview => overview(f, o),
StageKind::Setup => warnings(f, o),
StageKind::Finish => finish(f, o),
_ => {}
}
let mut chosen = None;
let things = o.things(o.stage);
let mut group = None;
for (k, &thing) in things.iter().enumerate() {
let name = match thing {
Thing::File(_) => "Code",
Thing::Item(i) => match guide::order(&o.items[i]) {
0 => "Inspect",
1 => "PR tests",
2 => "Try it",
_ => "Run checks",
},
};
let start = f.y;
if group != Some(name) {
group = Some(name);
phase_heading(f, name);
}
let selected = k == o.cursor && o.tab == Tab::Guide;
match thing {
Thing::File(i) => {
file_row(f, o, i, selected);
if selected && o.file_open {
let found = o.findings_in(&o.change.files[i].path);
file_detail(f, o, &o.change.files[i], i, &found);
f.gap(0.6);
}
}
Thing::Item(i) => {
item_row(f, o, i, selected);
if selected {
item_detail(f, o, i, focused);
f.gap(0.6);
}
}
}
if selected {
chosen = Some((start, f.y - start));
}
}
if let Some(next) = o.stages.get(o.stage + 1) {
f.gap(1.0);
let mut buttons = Vec::new();
if o.stage > 0 {
buttons.push(button("\u{2039} Back", Click::Stage(o.stage - 1)));
}
let label = format!("Next: {} \u{203a}", next.title);
buttons.push(button(&label, Click::Stage(o.stage + 1)).tone(c.accent, total > 0 && done == total));
f.buttons(buttons);
}
chosen
}
fn overview(f: &mut Flow, o: &Opened) {
let c = f.colors;
warnings(f, o);
let text = o.change.description.trim();
if text.is_empty() {
f.para("No description.", c.muted, 0, 0.0);
} else {
const SHOWN: usize = 14;
let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with("<!--")).collect();
for line in lines.iter().take(SHOWN) {
let heading = line.trim_start().starts_with('#');
let shown = line.trim_start().trim_start_matches('#').trim_start();
f.para(shown, if heading { c.fg } else { c.soft }, if heading { STYLE_BOLD } else { 0 }, 0.0);
}
if lines.len() > SHOWN {
f.para(&format!("\u{2026} {} more lines on the Description tab", lines.len() - SHOWN), c.muted, 0, 0.0);
}
}
}
fn finish(f: &mut Flow, o: &Opened) {
let c = f.colors;
let files = &o.change.files;
let (checks, tests): (Vec<&session::Item>, Vec<&session::Item>) = o.items.iter().partition(|i| i.check);
let judged = |list: &[&session::Item]| list.iter().filter(|i| matches!(o.session.state(&i.id), State::Done(_))).count();
for (label, n, total) in [
("Files read", o.session.seen_count(files), files.len()),
("Findings looked at", judged(&checks), checks.len()),
("Steps tried", judged(&tests), tests.len()),
] {
if total > 0 {
let color = if n == total { c.green } else { c.soft };
f.para(&format!("{label}: {n} of {total}"), color, 0, 0.0);
}
}
let failed: Vec<usize> = (0..o.items.len()).filter(|&i| o.session.state(&o.items[i].id) == State::Done(Verdict::Failed)).collect();
if !failed.is_empty() {
group_heading(f, "FAILED");
for i in failed {
let start = f.y;
let item = &o.items[i];
f.para(&format!("\u{2717} {}", item.text), c.red, 0, 0.0);
if let Some(r) = o.session.record(&item.id).filter(|r| !r.note.is_empty()) {
f.para(&r.note, c.soft, 0, 2.0 * f.cw);
}
let r = Rect::new(f.x, start, f.w, f.y - start);
f.hit(r, Click::Step(i));
}
}
f.gap(0.6);
let open = o.still_open();
if o.session.approved() {
f.callout("You approved this version.", c.green);
} else if open.is_empty() {
f.callout("Everything is done.", c.green);
} else {
f.callout(&format!("Still open: {}.", open.join(", ")), c.yellow);
}
f.gap(0.6);
let mut buttons = Vec::new();
if o.change.pull.is_some() && !o.session.approved() {
let label = if o.confirm_approve { "Really approve?" } else { "Approve" };
buttons.push(button(label, Click::Approve).tone(c.green, o.confirm_approve));
}
if o.change.pull.is_some() {
buttons.extend(merge_buttons(o, c));
}
if o.change.branch.is_some() {
buttons.push(button("Open pull request", Click::Propose).tone(c.accent, false));
}
buttons.push(button("Copy results", Click::CopyResults));
f.buttons(buttons);
}
fn merge_buttons(o: &Opened, colors: Colors) -> Vec<Button> {
if o.merged {
return vec![button("\u{2713} Merged", Click::Merge(Method::Squash)).tone(colors.accent, true)];
}
if o.merging {
return vec![button("Merging\u{2026}", Click::Merge(Method::Squash)).tone(colors.accent, false)];
}
[(Method::Squash, "Squash and merge", "Really squash and merge?"), (Method::Commit, "Merge", "Really merge?")]
.into_iter()
.map(|(how, label, again)| {
let armed = o.confirm_merge == Some(how);
button(if armed { again } else { label }, Click::Merge(how)).tone(colors.accent, armed)
})
.collect()
}
fn file_row(f: &mut Flow, o: &Opened, i: usize, selected: bool) {
let c = f.colors;
let file = &o.change.files[i];
let row_h = (f.ch * 1.55).round();
let r = Rect::new(f.x, f.y, f.w, row_h - (2.0 * f.s).round());
if selected {
f.fill(r, mix(c.panel, c.accent, 0.18), 6.0);
} else if f.hovered(r) {
f.fill(r, c.raised, 6.0);
}
let ty = r.y + (r.h - f.ch) * 0.5;
f.hit(r, Click::ChangedFile(i));
let tick = Rect::new(r.x, r.y, f.cw * 3.0, r.h);
let state = o.session.seen(file);
let (mark, color) = match state {
Seen::Yes => ("\u{2713}", c.green),
Seen::Changed => ("\u{21bb}", c.yellow),
Seen::No => ("\u{25a1}", if f.hovered(tick) { c.fg } else { c.muted }),
};
f.put(r.x + f.cw * 0.75, ty, mark, color, STYLE_BOLD, f.cw * 2.0);
f.hit(tick, Click::Seen(i));
let (letter, tone) = match file.status {
Status::Added => ("A", c.green),
Status::Deleted => ("D", c.red),
Status::Renamed => ("R", c.cyan),
Status::Copied => ("C", c.cyan),
Status::Modified => ("M", c.soft),
};
f.put(r.x + f.cw * 3.0, ty, letter, tone, STYLE_BOLD, f.cw * 1.5);
let found = o.findings_in(&file.path);
if let Some(level) = found.iter().map(|&k| o.change.report.findings[k].level).min() {
let dot = (5.0 * f.s).round();
f.fill(Rect::new(r.x + f.cw * 4.8, r.y + (r.h - dot) * 0.5, dot, dot), c.level(level), 3.0);
}
let counts = if file.binary { "binary".to_string() } else { format!("+{} -{}", file.added_count(), file.removed_count()) };
let counts_w = counts.chars().count() as f32 * f.cw;
let right = r.right() - f.cw * 0.5;
f.put(right - counts_w, ty, &counts, c.muted, 0, counts_w + 1.0);
let path_x = r.x + f.cw * 6.0;
let color = if selected { c.fg } else if state == Seen::Yes { c.muted } else { c.soft };
let room = f.cols(right - counts_w - f.cw - path_x);
let chars: Vec<char> = file.path.chars().collect();
let path: String = if chars.len() > room {
std::iter::once('\u{2026}').chain(chars[chars.len() + 1 - room.max(2)..].iter().copied()).collect()
} else {
file.path.clone()
};
f.put(path_x, ty, &path, color, 0, right - counts_w - f.cw - path_x);
f.y += row_h;
}
fn item_row(f: &mut Flow, o: &Opened, i: usize, selected: bool) {
let c = f.colors;
let item = &o.items[i];
let row_h = (f.ch * 1.55).round();
let r = Rect::new(f.x, f.y, f.w, row_h - (2.0 * f.s).round());
if selected {
f.fill(r, mix(c.panel, c.accent, 0.18), 6.0);
} else if f.hovered(r) {
f.fill(r, c.raised, 6.0);
}
let ty = r.y + (r.h - f.ch) * 0.5;
let state = o.session.state(&item.id);
let (mark, color) = c.state(state);
f.put(r.x + f.cw * 0.75, ty, mark, color, STYLE_BOLD, f.cw * 2.0);
if let Some(level) = item.level {
let dot = (5.0 * f.s).round();
f.fill(Rect::new(r.x + f.cw * 3.0, r.y + (r.h - dot) * 0.5, dot, dot), c.level(level), 3.0);
}
let label: String = item.text.chars().filter(|c| *c != '\u{60}').collect();
let color = if selected { c.fg } else if matches!(state, State::Done(_)) { c.muted } else { c.soft };
f.put(r.x + f.cw * 4.5, ty, &label, color, 0, r.w - f.cw * 5.0);
f.hit(r, Click::Step(i));
f.y += row_h;
}
fn item_detail(f: &mut Flow, o: &Opened, i: usize, focused: bool) {
let c = f.colors;
let item = &o.items[i];
let (x, w) = (f.x, f.w);
f.x += f.cw * 2.0;
f.w -= f.cw * 2.0;
if item.text.chars().filter(|c| *c != '\u{60}').count() > f.cols(w - f.cw * 5.0) {
f.gap(0.3);
f.para(&item.text, c.fg, 0, 0.0);
}
let state = o.session.state(&item.id);
let record = o.session.record(&item.id);
if let State::Stale(verdict) = state {
let was = format!("It {} on an earlier version of this change. Look again.", match verdict {
Verdict::Passed => "passed",
Verdict::Failed => "failed",
Verdict::Skipped => "was skipped",
});
f.gap(0.4);
f.callout(&was, c.yellow);
}
f.gap(0.5);
let is = |v| state == State::Done(v);
let (pass, fail) = if item.check { ("\u{2713} Looks fine", "\u{2717} Problem") } else { ("\u{2713} Pass", "\u{2717} Fail") };
let mut verdicts = vec![
button(pass, Click::Verdict(Verdict::Passed)).tone(c.green, is(Verdict::Passed)),
button(fail, Click::Verdict(Verdict::Failed)).tone(c.red, is(Verdict::Failed)),
button("Skip", Click::Verdict(Verdict::Skipped)).tone(c.soft, is(Verdict::Skipped)),
];
if record.is_some() {
verdicts.push(button("Clear", Click::Clear));
}
f.buttons(verdicts);
if let Some(note) = &o.note {
f.gap(0.5);
f.field(note, "What went wrong? (enter to save)", focused, Some(Click::EditNote));
} else if let Some(r) = record {
f.gap(0.5);
let start = f.y;
if r.note.is_empty() {
f.para("+ add a note", c.muted, 0, 0.0);
} else {
f.para(&format!("Note: {}", r.note), c.soft, 0, 0.0);
}
let r = Rect::new(f.x, start, f.w, f.y - start);
f.hit(r, Click::EditNote);
}
for snippet in session::quoted(&item.text) {
if !snippet.contains(' ') && !session::is_command(&snippet) {
continue;
}
f.gap(0.6);
let code = c.code;
let lines = wrap(&snippet, f.cols(f.w - 2.0 * f.cw)).len() as f32;
let r = Rect::new(f.x, f.y, f.w, (lines * f.line_height() + f.ch * 0.4).round());
f.fill(r, c.raised, 6.0);
f.y += (f.ch * 0.2).round();
let cw = f.cw;
f.para(&snippet, code, 0, cw);
f.y = r.bottom() + (f.ch * 0.3).round();
let mut actions = vec![button("Copy", Click::Copy(snippet.clone()))];
if session::is_command(&snippet) {
actions.push(button("Type in terminal", Click::Type(snippet.clone())));
}
f.buttons(actions);
}
if !item.findings.is_empty() {
f.gap(0.8);
f.put(f.x, f.y, if item.check { "WHERE" } else { "WHY" }, c.muted, STYLE_BOLD, f.w);
f.y += f.line_height();
const SHOWN: usize = 4;
for &k in item.findings.iter().take(SHOWN) {
let finding = &o.change.report.findings[k];
f.gap(0.3);
if !item.check {
let start = f.y;
f.para(&format!("{} {}", finding.code, finding.title), c.level(finding.level), STYLE_BOLD, 0.0);
let r = Rect::new(f.x, start, f.w, f.y - start);
f.hit(r, Click::Finding(k));
}
f.place(finding);
let mut parts: Vec<(&str, &String)> = finding.check.iter().map(|t| ("Look for", t)).collect();
if item.check {
parts.extend(finding.note.iter().map(|t| ("Why", t)));
parts.extend(finding.help.iter().map(|t| ("Fix", t)));
}
for (label, text) in parts {
f.gap(0.2);
f.para(&format!("{label}: {text}"), c.soft, 0, 0.0);
}
}
if item.findings.len() > SHOWN {
f.para(&format!("\u{2026} and {} more on the Findings tab", item.findings.len() - SHOWN), c.muted, 0, 0.0);
}
}
(f.x, f.w) = (x, w);
}
fn file_detail(f: &mut Flow, o: &Opened, file: &FileDiff, i: usize, found: &[usize]) {
let c = f.colors;
let (x, w) = (f.x, f.w);
f.x += f.cw * 2.0;
f.w -= f.cw * 2.0;
f.gap(0.3);
if let Some(old) = &file.old_path {
f.para(&format!("from {old}"), c.muted, 0, 0.0);
}
let state = o.session.seen(file);
if state == Seen::Changed {
f.callout("It changed after you read it. Look at it again.", c.yellow);
f.gap(0.3);
}
let tick = match state {
Seen::Yes => button("\u{2713} Read", Click::Seen(i)).tone(c.green, true),
_ => button("Mark as read", Click::Seen(i)).tone(c.green, false),
};
let line = file.lines().find(|l| l.kind != DiffKind::Context).and_then(|l| l.new_no.or(l.old_no)).unwrap_or(1);
let mut actions = vec![tick];
if file.status != Status::Deleted {
actions.push(button("Open", Click::File(file.path.clone(), line)));
}
f.buttons(actions);
let mut marked: Vec<(u32, Level)> = Vec::new();
for &k in found {
let finding = &o.change.report.findings[k];
if let Some(span) = &finding.span {
marked.push((span.line, finding.level));
}
f.gap(0.3);
let start = f.y;
let at = finding.span.as_ref().map(|s| format!(" line {}", s.line)).unwrap_or_default();
f.para(&format!("{} {}{at}", finding.code, finding.title), c.level(finding.level), 0, 0.0);
let r = Rect::new(f.x, start, f.w, f.y - start);
f.hit(r, Click::Finding(k));
}
f.gap(0.5);
if file.binary {
f.para("A binary file; open it to look.", c.muted, 0, 0.0);
}
const SHOWN: usize = 400;
let lh = f.line_height();
let gutter = f.cw * 6.0;
let total = file.lines().count();
let mut drawn = 0;
'hunks: for (h, hunk) in file.hunks.iter().enumerate() {
if h > 0 {
f.put(f.x + gutter, f.y, "\u{22ef}", c.muted, 0, f.w - gutter);
f.y += lh;
}
for l in &hunk.lines {
if drawn == SHOWN {
break 'hunks;
}
drawn += 1;
if !f.shows(f.y, lh) {
f.y += lh;
continue;
}
let (sign, tint) = match l.kind {
DiffKind::Added => ("+", Some(c.green)),
DiffKind::Removed => ("-", Some(c.red)),
DiffKind::Context => (" ", None),
};
let r = Rect::new(f.x, f.y, f.w, lh);
if let Some(tint) = tint {
f.fill(r, mix(c.panel, tint, 0.13), 0.0);
}
let number = l.new_no.or(l.old_no).unwrap_or(0);
let mark = l.new_no.and_then(|n| marked.iter().filter(|(m, _)| *m == n).map(|(_, lv)| *lv).min());
if let Some(level) = mark {
f.fill(Rect::new(r.x, r.y, (3.0 * f.s).round(), r.h), c.level(level), 0.0);
}
let ty = r.y + (lh - f.ch) * 0.5;
let number = format!("{number:>5}");
f.put(r.x, ty, &number, c.muted, 0, gutter);
let color = match tint {
Some(t) => mix(t, c.fg, 0.45),
None => c.soft,
};
let text = format!("{sign}{}", l.text.replace('\t', " "));
f.put(r.x + gutter, ty, &text, color, 0, r.w - gutter);
f.y += lh;
}
}
if total > drawn {
f.gap(0.3);
f.para(&format!("\u{2026} {} more lines. Open the file to read the rest.", total - drawn), c.muted, 0, 0.0);
}
(f.x, f.w) = (x, w);
}
fn findings_tab(f: &mut Flow, o: &Opened) -> Option<(f32, f32)> {
let c = f.colors;
warnings(f, o);
if o.change.report.findings.is_empty() {
f.para("No findings. That is not proof that the change works; it still wants a run.", c.soft, 0, 0.0);
return None;
}
let mut chosen = None;
for (i, finding) in o.change.report.findings.iter().enumerate() {
let start = f.y;
let selected = i == o.finding;
let color = c.level(finding.level);
let title = format!("{} {}", finding.code, finding.title);
let lines = wrap(&title, f.cols(f.w - 2.0 * f.cw)).len() as f32;
let head = Rect::new(f.x, f.y, f.w, (lines * f.line_height() + f.ch * 0.4).round());
if selected {
f.fill(head, mix(c.panel, c.accent, 0.18), 6.0);
} else if f.hovered(head) {
f.fill(head, c.raised, 6.0);
}
f.fill(Rect::new(head.x, head.y + 3.0 * f.s, (3.0 * f.s).round(), head.h - 6.0 * f.s), color, 1.0);
f.y += (f.ch * 0.2).round();
let cw = f.cw;
f.para(&title, c.fg, 0, 1.5 * cw);
f.y = head.bottom();
f.hit(head, Click::Finding(i));
if selected && o.unfolded {
f.gap(0.3);
f.put(f.x, f.y, level_tag(finding.level), color, STYLE_BOLD, f.w);
f.y += f.line_height();
f.place(finding);
for (label, items) in [("Why", &finding.note), ("Look for", &finding.check), ("Test", &finding.test), ("Fix", &finding.help)] {
for item in items {
f.gap(0.3);
f.para(&format!("{label}: {item}"), c.soft, 0, 0.0);
}
}
f.gap(0.8);
chosen = Some((start, f.y - start));
} else if selected {
chosen = Some((start, head.h));
}
f.gap(0.2);
}
chosen
}
fn description_tab(f: &mut Flow, o: &Opened) {
let c = f.colors;
if let Some(url) = &o.change.url {
f.buttons(vec![button("Open in the browser", Click::Url(url.clone()))]);
f.gap(0.6);
}
if o.change.description.trim().is_empty() {
f.para("There is no description.", c.muted, 0, 0.0);
return;
}
for line in o.change.description.lines().take(600) {
let heading = line.trim_start().starts_with('#');
let shown = if heading { line.trim_start().trim_start_matches('#').trim_start() } else { line };
if shown.trim().is_empty() {
f.gap(0.6);
} else {
let indent = (line.len() - line.trim_start().len()).min(12) as f32 * f.cw;
f.para(shown.trim_start(), if heading { c.fg } else { c.soft }, if heading { STYLE_BOLD } else { 0 }, indent);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn flat(lines: &[Vec<Piece>]) -> Vec<String> {
lines.iter().map(|l| l.iter().map(|(t, code)| if *code { format!("[{t}]") } else { t.clone() }).collect()).collect()
}
#[test]
fn wraps_words_and_marks_code() {
assert_eq!(flat(&wrap("run `php artisan test` now please", 12)), ["run [php]", "[artisan test]", "now please"]);
assert_eq!(flat(&wrap("a lone ` tick", 40)), ["a lone ` tick"]);
assert_eq!(flat(&wrap("abcdefghij kl", 4)), ["abcd", "efgh", "ij", "kl"]);
assert_eq!(flat(&wrap("", 10)), [""]);
assert_eq!(flat(&wrap("a\x1bb\r\nc", 10)), ["ab c"]);
}
#[test]
fn scrolls_only_as_far_as_needed() {
assert_eq!(scrolled_to(100.0, (150.0, 20.0), 200.0, 10.0), 100.0);
assert_eq!(scrolled_to(100.0, (50.0, 20.0), 200.0, 10.0), 40.0);
assert_eq!(scrolled_to(0.0, (300.0, 20.0), 200.0, 10.0), 120.0);
}
}