diff --git a/src/app.rs b/src/app.rs index 1eeaf16..51a5120 100644 --- a/src/app.rs +++ b/src/app.rs @@ -182,6 +182,7 @@ impl App { } else { self.selected = self.selected.min(self.files.len() - 1); } + self.list_state.select(Some(self.selected)); let same_file = previous.as_deref() == self.selected_file().map(|f| f.path.as_str()); @@ -214,6 +215,7 @@ impl App { self.diff_source = None; } } + self.clamp_scroll(); } @@ -252,6 +254,7 @@ impl App { if self.files.is_empty() || index == self.selected && self.diff_source.is_some() { return; } + self.selected = index.min(self.files.len() - 1); self.list_state.select(Some(self.selected)); self.diff_scroll = 0; @@ -290,6 +293,7 @@ impl App { if row < inner_top || row >= self.files_area.bottom().saturating_sub(1) { return; } + let index = self.list_state.offset() + usize::from(row - inner_top); if index < self.files.len() { self.select(index); @@ -303,6 +307,7 @@ impl App { let Some(file) = self.selected_file().cloned() else { return; }; + let result = action(&self.repo, &file); self.report(result); self.refresh(); @@ -369,6 +374,7 @@ impl App { let Mode::Confirm(action) = self.mode else { return; }; + self.mode = Mode::Normal; match action { Confirm::Revert => self.with_selected(|repo, file| repo.revert(file)), @@ -476,6 +482,7 @@ impl App { if self.is_pushing() { return; } + let (tx, rx) = mpsc::channel(); let repo = self.repo.clone(); thread::spawn(move || { @@ -498,6 +505,7 @@ impl App { } Err(e) => self.set_message(MessageKind::Error, e), } + self.refresh(); } } diff --git a/src/diff.rs b/src/diff.rs index 511ac1b..94141fc 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -140,10 +140,12 @@ pub fn build(sections: &[DiffSection], path: &str, theme: &Theme) -> DiffView { if i > 0 { raw.push(raw_row(RowKind::Info, "")); } + if let Some(title) = §ion.title { raw.push(raw_row(RowKind::Section, title)); } } + let before = raw.len(); parse(§ion.text, &mut raw); if raw.len() == before { @@ -177,6 +179,7 @@ pub fn build(sections: &[DiffSection], path: &str, theme: &Theme) -> DiffView { RowKind::Removed => view.removed += 1, _ => {} } + view.max_line_no = view .max_line_no .max(row.old.unwrap_or(0)) @@ -195,9 +198,11 @@ pub fn build(sections: &[DiffSection], path: &str, theme: &Theme) -> DiffView { if let Some(old) = old_hl.as_mut() { let _ = old.highlight_line(&row.text, set); } + new_hl.as_mut() } }; + hl.and_then(|h| h.highlight_line(&row.text, set).ok()) .map(|ranges| { ranges @@ -206,6 +211,7 @@ pub fn build(sections: &[DiffSection], path: &str, theme: &Theme) -> DiffView { .collect::>() }) }; + let pieces = highlighted.unwrap_or_else(|| vec![(Style::default(), row.text.as_str())]); split_emphasis(&pieces, &row.emph) } @@ -328,6 +334,7 @@ fn parse(text: &str, rows: &mut Vec) { if let Some(note) = header_note(line) { rows.push(raw_row(RowKind::Info, ¬e)); } + continue; } @@ -356,9 +363,11 @@ fn parse(text: &str, rows: &mut Vec) { RowKind::Removed => (Some(old), None), _ => (Some(old), Some(new)), }; + if kind != RowKind::Added { old += 1; } + if kind != RowKind::Removed { new += 1; } @@ -418,6 +427,7 @@ fn header_note(line: &str) -> Option { } else { return None; }; + Some(note) } @@ -430,10 +440,12 @@ fn mark_word_changes(rows: &mut [RawRow]) { i += 1; continue; } + let removed_start = i; while i < rows.len() && rows[i].kind == RowKind::Removed { i += 1; } + let added_start = i; while i < rows.len() && rows[i].kind == RowKind::Added { i += 1; @@ -464,13 +476,16 @@ fn tokens(text: &str) -> Vec> { out.push(s..i); start = None; } + out.push(i..i + c.len_utf8()); } } } + if let Some(s) = start { out.push(s..text.len()); } + out } @@ -485,6 +500,7 @@ fn changed_ranges(old: &str, new: &str) -> Option<(Ranges, Ranges)> { if ot.len() > MAX_WORD_DIFF_TOKENS || nt.len() > MAX_WORD_DIFF_TOKENS { return None; } + let same = |i: usize, j: usize| old[ot[i].clone()] == new[nt[j].clone()]; // lcs[i][j] = LCS length of ot[i..] and nt[j..]. @@ -522,6 +538,7 @@ fn changed_ranges(old: &str, new: &str) -> Option<(Ranges, Ranges)> { if total == 0 || (old_changed.is_empty() && new_changed.is_empty()) { return None; } + if (common as f32 / total as f32) < MIN_SIMILARITY { return None; } @@ -546,12 +563,15 @@ fn merge_tokens(text: &str, tokens: &[Range], changed: &[usize]) -> Vec false, }; + match ranges.last_mut() { Some(range) if bridge => range.end = token.end, _ => ranges.push(token), } + last_index = Some(index); } + ranges } @@ -564,12 +584,15 @@ fn convert_style(style: syntect::highlighting::Style, theme: &Theme) -> Style { } else { out = out.fg(Color::Reset); } + if style.font_style.contains(FontStyle::BOLD) { out = out.add_modifier(Modifier::BOLD); } + if style.font_style.contains(FontStyle::ITALIC) { out = out.add_modifier(Modifier::ITALIC); } + out } @@ -580,6 +603,7 @@ fn split_emphasis(pieces: &[(Style, &str)], emph: &[Range]) -> Vec { if text.is_empty() { return; } + let text = sanitize(text); match segs.last_mut() { Some(last) if last.style == style && last.emph == emph => last.text.push_str(&text), @@ -601,6 +625,7 @@ fn split_emphasis(pieces: &[(Style, &str)], emph: &[Range]) -> Vec { } } } + cuts.push(end); cuts.sort_unstable(); @@ -610,6 +635,7 @@ fn split_emphasis(pieces: &[(Style, &str)], emph: &[Range]) -> Vec { push(&text[a - start..b - start], *style, emphasized); } } + segs } diff --git a/src/event_handler.rs b/src/event_handler.rs index 47bc062..de17340 100644 --- a/src/event_handler.rs +++ b/src/event_handler.rs @@ -47,6 +47,7 @@ pub fn handle_mouse(app: &mut App, mouse: MouseEvent) { if app.mode != Mode::Normal { return; } + let pos = Position::new(mouse.column, mouse.row); let over_files = app.files_area.contains(pos); diff --git a/src/git.rs b/src/git.rs index 656355a..d4722d1 100644 --- a/src/git.rs +++ b/src/git.rs @@ -148,11 +148,13 @@ impl Repo { if cached { args.push("--cached"); } + args.push("--"); args.push(&file.path); if cached && let Some(orig) = &file.orig_path { args.push(orig); } + self.run(args) } @@ -184,6 +186,7 @@ impl Repo { if let Some(orig) = &file.orig_path { paths.push(orig); } + self.unstage_paths(&paths) } @@ -239,6 +242,7 @@ impl Repo { if let Some(orig) = &file.orig_path { self.run(["restore", "--", orig.as_str()])?; } + Ok(format!("reverted rename of {}", file.path)) } _ if file.has_staged() => self @@ -268,6 +272,7 @@ impl Repo { self.run(["rm", "-f", "--quiet", "--", &file.path])?; } } + Ok(format!("removed {}", file.path)) } @@ -277,6 +282,7 @@ impl Repo { if message.is_empty() { return Err("commit message is empty".to_string()); } + if !self.has_staged_changes()? { return Err("nothing staged to commit (Space stages a file, a stages all)".to_string()); } @@ -390,6 +396,7 @@ pub fn parse_status(text: &str) -> Status { else { continue; }; + let path = chars.as_str().to_string(); let orig_path = if matches!(index, 'R' | 'C') { @@ -432,6 +439,7 @@ pub fn sanitize(text: &str) -> String { c => out.push(c), } } + out } @@ -540,6 +548,7 @@ pub(crate) mod tests { .success(); assert!(ok, "git {args:?} failed"); }; + git(&["init", "--quiet", "--initial-branch=main"]); git(&["config", "user.name", "gitrat test"]); git(&["config", "user.email", "test@example.com"]); diff --git a/src/main.rs b/src/main.rs index 973f3a5..3b4b99e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -94,6 +94,7 @@ fn event_loop(terminal: &mut terminal::Tui, app: &mut App) -> io::Result<()> { Event::FocusGained => app.refresh(), Event::Resize(..) | Event::FocusLost => {} } + if app.should_quit || !event::poll(Duration::ZERO)? { break; } diff --git a/src/terminal.rs b/src/terminal.rs index 466d7c2..89f00bb 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -58,6 +58,7 @@ fn enter(stdout: &mut Stdout, options: Options) -> io::Result<()> { if options.mouse { execute!(stdout, EnableMouseCapture)?; } + Ok(()) } @@ -67,6 +68,7 @@ pub fn restore(options: Options) -> io::Result<()> { if options.mouse { let _ = execute!(stdout, DisableMouseCapture); } + let _ = execute!( stdout, DisableFocusChange, diff --git a/src/theme.rs b/src/theme.rs index 94675ec..94edc89 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -56,6 +56,7 @@ impl Theme { ThemeChoice::Light => false, ThemeChoice::Auto => detect_dark(), }; + Self::new(dark, detect_truecolor()) } @@ -74,6 +75,7 @@ impl Theme { } else { EmbeddedThemeName::Github }; + let syntax = two_face::theme::extra().get(syntax_name).clone(); if dark { @@ -128,6 +130,7 @@ fn detect_truecolor() -> bool { if std::env::var_os("WT_SESSION").is_some() { return true; } + let program = std::env::var("TERM_PROGRAM").unwrap_or_default(); matches!( program.as_str(), @@ -202,6 +205,7 @@ fn rgb_to_256(r: u8, g: u8, b: u8) -> u8 { _ => usize::from((v - 35) / 40), } }; + let (ri, gi, bi) = (level(r), level(g), level(b)); let cube = (LEVELS[ri], LEVELS[gi], LEVELS[bi]); diff --git a/src/ui.rs b/src/ui.rs index ceec8f2..1ec56ed 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -85,6 +85,7 @@ fn panel(title: Line<'_>, focused: bool) -> Block<'_> { } else { Style::default() }; + Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) @@ -117,6 +118,7 @@ fn render_file_list(frame: &mut Frame, app: &mut App, area: Rect) { Some(orig) => format!("{} → {}", sanitize(orig), sanitize(&file.path)), None => sanitize(&file.path), }; + ListItem::new(Line::from(vec![ Span::styled( format!("{icon} "), @@ -162,6 +164,7 @@ fn render_diff(frame: &mut Frame, app: &App, area: Rect) { } else { String::new() }; + let added = format!("+{}", view.added); let removed = format!(" −{} ", view.removed); let max = width.saturating_sub(pos.width() + added.width() + removed.width() + 4); @@ -230,6 +233,7 @@ fn diff_row( RowKind::Removed => (Some(theme.del_bg), theme.del_emph_bg, "-", theme.del_fg), _ => (None, Color::Reset, " ", theme.gutter_fg), }; + let base = bg.map_or_else(Style::default, |bg| Style::default().bg(bg)); let number = |n: Option| match n { Some(n) => format!("{n:>number_width$}"), @@ -261,21 +265,25 @@ fn diff_row( skip -= w; continue; } + let rest = skip_columns(&seg.text, skip); skip = 0; rest }; + let style = match (bg, seg.emph) { (Some(_), true) => seg.style.bg(emph_bg), (Some(bg), false) => seg.style.bg(bg), (None, _) => seg.style, }; + spans.push(Span::styled(visible, style)); } if bg.is_some() { fill(&mut spans, base); } + Line::from(spans) } RowKind::Hunk => { @@ -292,6 +300,7 @@ fn diff_row( bar.add_modifier(Modifier::ITALIC), )); } + fill(&mut spans, bar); Line::from(spans) } @@ -306,6 +315,7 @@ fn diff_row( if text.is_empty() { return Line::raw(""); } + Line::from(Span::styled( format!(" • {text}"), Style::default() @@ -335,6 +345,7 @@ fn render_commit_bar(frame: &mut Frame, app: &App, area: Rect) { Confirm::Revert => format!("Discard all changes to {path}?"), Confirm::Remove => format!("Delete {path}?"), }; + ( " Confirm ".to_string(), Color::Red, @@ -352,6 +363,7 @@ fn render_commit_bar(frame: &mut Frame, app: &App, area: Rect) { MessageKind::Success => Color::Green, MessageKind::Error => Color::Red, }; + (format!(" {} ", sanitize(&msg.text)), color) } (None, Mode::Input) => ( @@ -360,6 +372,7 @@ fn render_commit_bar(frame: &mut Frame, app: &App, area: Rect) { ), (None, _) => (" Commit message (c to write) ".to_string(), Color::DarkGray), }; + let visible = tail_fitting(&app.commit_input, inner_width.saturating_sub(1)); (title, color, Line::raw(visible)) } @@ -417,9 +430,11 @@ fn render_key_bar(frame: &mut Frame, app: &App, area: Rect) { if used + w > budget { break; } + used += w; push_key(&mut spans, key, desc, app.theme.hunk_fg); } + if app.mode == Mode::Normal { push_key(&mut spans, help.0, help.1, app.theme.hunk_fg); } @@ -475,6 +490,7 @@ fn render_help(frame: &mut Frame, area: Rect, accent: Color) { if i > 0 { lines.push(Line::raw("")); } + lines.push(Line::styled( *title, Style::default() @@ -520,9 +536,11 @@ fn truncate_left(text: &str, max: usize) -> String { if text.width() <= max { return text.to_string(); } + if max == 0 { return String::new(); } + let mut width = 1; let mut start = text.len(); for (i, c) in text.char_indices().rev() { @@ -530,9 +548,11 @@ fn truncate_left(text: &str, max: usize) -> String { if width + w > max { break; } + width += w; start = i; } + format!("…{}", &text[start..]) } @@ -541,6 +561,7 @@ fn truncate_right(text: &str, max: usize) -> String { if text.width() <= max { return text.to_string(); } + let mut out = String::new(); let mut width = 1; for c in text.chars() { @@ -548,9 +569,11 @@ fn truncate_right(text: &str, max: usize) -> String { if width + w > max { break; } + width += w; out.push(c); } + out.push('…'); out } @@ -565,9 +588,11 @@ fn tail_fitting(text: &str, max: usize) -> &str { if width + w > max { break; } + width += w; start = i; } + &text[start..] } @@ -576,6 +601,7 @@ fn skip_columns(text: &str, cols: usize) -> String { if cols == 0 { return text.to_string(); } + let mut skipped = 0; let mut out = String::new(); for c in text.chars() { @@ -585,10 +611,13 @@ fn skip_columns(text: &str, cols: usize) -> String { if skipped > cols { out.push(' '); } + continue; } + out.push(c); } + out }