//! Read-only diff viewer state and buffer rendering. mod tree; use std::borrow::Cow; use std::collections::btree_map::Entry; use std::collections::{BTreeMap, BTreeSet}; use std::convert::Infallible; use std::io::Read as _; use std::ops::Range; use std::path::{Component, Path, PathBuf}; use std::sync::Arc; use rustik_highlight as syntax; use rustik_tui as tui; use tui::{ Badge, Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton, Paint, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text, VStack, View, Viewport, Widget, colors, }; use crate::context::{self, ContextChange, ContextState}; use crate::decorate::{DiffDecorator, FileDecoration, HunkDecoration, ReviewProgress}; use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult}; use crate::word; use crate::{ CommitHeader, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, FileKind, FileMode, FileStats, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, Oid, RowId, }; pub use tree::{FileTree, FileTreeMode, FileTreeTarget}; /// Visible and lookahead row ranges that should be highlighted. #[derive(Clone, Debug, Eq, PartialEq)] struct HighlightWindow { /// First row that can produce a visible highlight. start: usize, /// End of the currently visible row range. visible_end: usize, /// End of the lookahead row range. lookahead_end: usize, } /// Minimum width before the viewer attempts table-style diff rows. const MIN_RENDER_COLS: usize = 12; /// Width of old and new line number cells. const LINE_NUMBER_WIDTH: usize = 5; /// Width of the review-state gutter before the line numbers. const REVIEW_GUTTER_WIDTH: usize = 1; /// Foreground color used by old and new line number cells. const LINE_NUMBER_FG: Color = colors::fixed::DIM; /// Foreground color used by line number cells in the focused hunk. const SELECTED_LINE_NUMBER_FG: Color = colors::fixed::MUTED; /// Width of the hunk marker cell. const MARKER_WIDTH: usize = 3; /// Scrollbar track glyph (distinct from box-drawing borders so the column reads as a track). const SCROLLBAR_TRACK: char = '🮘'; /// Scrollbar thumb glyph. const SCROLLBAR_THUMB: char = '▐'; /// File-card divider glyph (used between header/hunks and between hunks). const DIVIDER: char = '─'; /// Foreground color for neutral file-kind badges such as moved and copied. const FILE_KIND_BADGE_FG: Color = colors::rgb::PURPLE; /// Dim background for neutral file-kind badges. const FILE_KIND_BADGE_BG: Color = Color::RGB(32, 22, 42); /// Shared border style for all file cards. const FILE_BORDER: tui::Border = tui::Border::new(colors::FAINT); /// Sticky file-header divider glyph. const STICKY_DIVIDER: char = '╴'; /// Rename arrow. const RENAME_ARROW: &str = "→"; /// Missing trailing newline marker. const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file"; /// Rendered source text replacement for a single source tab. const SOURCE_TAB_MARKER: &str = "· "; /// Marker cell shown between hunks in the diff marker column. const HUNK_GAP_MARKER_CELL: &str = " ⋮ "; /// Separator shown between file header metadata segments: ·. const FILE_HEADER_SEGMENT_SEPARATOR: &str = " · "; /// Width of the file review progress bar in file headers. const FILE_PROGRESS_BAR_WIDTH: usize = 10; /// Glyph text used by file review progress bars: ━. const FILE_PROGRESS_BAR_GLYPH: &str = "━"; /// Columns reserved for file-header review status, matching "+9999 -9999". const FILE_REVIEW_STATUS_COLS: usize = 11; /// Default syntax theme selection stored in highlight keys. const DEFAULT_THEME: &str = "auto"; /// Number of rows in a sticky file header. const STICKY_HEADER_ROWS: usize = 3; /// Number of body rows moved by keyboard line-scroll inputs. const LINE_SCROLL_ROWS: isize = 1; /// Number of source columns moved by horizontal-scroll inputs. const HORIZONTAL_SCROLL_COLS: usize = 8; /// Number of body rows moved by mouse-wheel inputs. const WHEEL_SCROLL_ROWS: isize = 3; /// Central viewport percentage where hunk navigation preserves the scroll offset. const HUNK_SCROLL_COMFORT_PERCENT: usize = 60; /// Local row of a file card's top border. const FILE_TOP_ROW: usize = 0; /// Local row of a file card's header. const FILE_HEADER_ROW: usize = 1; /// Local row of the divider between a file header and its hunk body. const FILE_DIVIDER_ROW: usize = 2; /// Local row of the first hunk body line after the fixed file-card chrome. const HUNK_BODY_START: usize = FILE_DIVIDER_ROW + 1; /// Total card height when the file has no visible body. const EMPTY_CARD_ROWS: usize = FILE_DIVIDER_ROW + 1; /// Escapes path control characters while preserving printable Unicode. fn escape_path(input: &str) -> Cow<'_, str> { if !input.chars().any(char::is_control) { return Cow::Borrowed(input); } let mut escaped = String::with_capacity(input.len()); for ch in input.chars() { if ch.is_control() { escaped.extend(ch.escape_default()); } else { escaped.push(ch); } } Cow::Owned(escaped) } /// Mutable read-only diff viewport state. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct DiffState { /// Vertical viewport over the rendered document. pub scroll: Viewport, /// Horizontal source-text offset in terminal columns. pub horizontal: usize, /// Currently focused commit, file, or hunk. pub focus: Option, } /// Focus target inside a diff document. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum DiffFocus { /// Focus the commit header. Commit, /// Focus a file header. File(FileId), /// Focus a hunk header. Hunk(HunkId), } /// Viewer action accepted by [`DiffViewer::apply`]. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DiffAction { /// Scroll the viewport. Scroll(Scroll), /// Scroll source text horizontally by signed steps. ScrollHorizontal(isize), /// Clamp scroll after a terminal resize. Resize, /// Focus the next file or hunk target. FocusNext, /// Focus the previous file or hunk target. FocusPrevious, /// Focus the next hunk target. NextHunk, /// Focus the previous hunk target. PreviousHunk, /// Toggle the file tree between automatic visibility and hidden. ToggleFileTree, /// Move the file-tree cursor by visible rows, jumping to files as they are selected. MoveFileTree(isize), /// Show the current file-tree target without changing folder expansion. ShowFileTreeTarget, /// Activate the current file-tree target. ActivateFileTreeTarget, /// Collapse the focused file-tree folder. CollapseFileTreeFolder, /// Expand the focused file-tree folder. ExpandFileTreeFolder, } /// Result of applying a viewer action. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ViewChange { /// The action changed viewer state. Changed, /// The action left viewer state unchanged. Unchanged, } /// Diff viewer options. #[derive(Clone, Debug)] pub struct DiffOptions { /// Optional syntax override stored in highlight requests. pub syntax: Option, /// Theme name stored in highlight requests. pub theme: String, /// Positive and negative colors used for diff chrome. pub diff_palette: DiffPalette, /// Whether the file tree may be rendered beside the diff. pub file_tree: FileTreeMode, /// Folder name shown as the file tree root. pub file_tree_root: String, /// Visual treatment for hunk focus. pub hunk_focus: HunkFocus, } /// Visual treatment for hunk focus. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum HunkFocus { /// Render focused and unfocused hunks normally. #[default] Plain, /// Force all non-focused hunk body rows to the dim foreground. DimUnfocused, } /// Positive and negative colors used for diff chrome. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct DiffPalette { /// Background color for removed source rows. pub negative_row_bg: Color, /// Background color for added source rows. pub positive_row_bg: Color, /// Background color for changed word spans inside removed rows. pub negative_word_bg: Color, /// Background color for changed word spans inside added rows. pub positive_word_bg: Color, /// Foreground color for removed stats, markers, and labels. pub negative_fg: Color, /// Foreground color for added stats, markers, and labels. pub positive_fg: Color, } /// Repo refetch request prepared by the viewer for asynchronous context updates. #[derive(Clone, Debug)] pub struct ContextRequest { /// Context state to install when the request completes. next_context: ContextState, /// Paths and original file ids to replace. files: Vec<(PathBuf, FileId)>, /// Currently rendered hunks whose identities should survive the refetch. originals: Vec, /// Git context width to request. context_lines: usize, /// Next hunk and row ids used to remap fetched files. next_ids: (usize, usize), } /// Decoded replacement files for an asynchronous context update. #[derive(Clone, Debug)] pub struct ContextUpdate { /// Context state prepared when the request was started. next_context: ContextState, /// Replacement file diffs with ids remapped to this viewer. files: Vec, /// Unchanged rows added outside the original bounded review hunks. expanded_context: BTreeSet, } /// Pure diff viewer that renders into a caller-owned buffer. #[derive(Clone, Debug)] pub struct DiffViewer { /// Diff document being viewed. document: DiffDocument, /// File metadata that does not change with hunk visibility or context. summaries: BTreeMap, /// Unchanged full-file rows outside the bounded review hunks. expanded_context: BTreeSet, /// Viewer options. options: DiffOptions, /// Mutable viewport state. state: DiffState, /// Last focused visible hunk for each file. hunk_focus: BTreeMap, /// Highlighted row cache. highlights: BTreeMap, /// Requests already handed to a worker. pending_highlights: BTreeSet, /// Per-hunk source context reused across highlight-request batches. hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>, /// Whole-file source text used as highlighting context, keyed by blob. /// /// A syntax tokenizer's state at a line is the fold of every line before it, /// so a hunk highlighted in isolation starts from a default state and loses /// any enclosing block, comment, or string. Highlighting against the whole /// blob restores that context; sides with no blob (added or deleted files) /// are absent and fall back to the hunk-only source. /// /// Keying by object id rather than by file means hiding hunks or widening /// context cannot invalidate an entry: those rewrite a file's hunks but /// leave it pointing at the same blobs. blob_sources: BTreeMap, /// Whole-file source text for worktree files, which have no new-side blob. worktree_sources: BTreeMap, /// Total bytes held across both source maps. source_bytes: usize, /// Cached intra-line word diffs, keyed by hunk. word_diffs: BTreeMap, /// Rendered commit-preamble rows for the most recent body width. preamble: Vec, /// File-tree state and model. file_tree: tree::FileTree, /// Interactive override for file-tree visibility. file_tree_visibility: FileTreeVisibility, /// Cached rendered row positions for visible files. index: RowIndex, /// Hunk-context expansion bookkeeping. context: ContextState, /// Optional host-supplied source of file and hunk decorations. /// /// Shared rather than boxed so the viewer keeps deriving `Clone`. `None` /// renders the plain diff with no decorations. decorator: Option>, } /// Cached rendered row positions for the current document visibility state. /// /// Visible files tile the content region contiguously, so each file is stored /// by its first rendered row only; its last row is the next file's start (or /// [`RowIndex::rows`] for the final file). #[derive(Clone, Debug, Default)] struct RowIndex { /// Visible files in rendered order, each at its first rendered row. files: Vec, /// Total number of rendered rows. rows: usize, } /// Largest blob kept as syntax-highlighting context, in bytes. /// /// Tokenizing the lines before a hunk is linear in the prefix and cached per /// file, so the cap only guards against pathological inputs such as minified /// bundles or generated data. const MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024; /// Total bytes of highlight context a viewer keeps across all files. /// /// A per-blob cap alone bounds nothing in aggregate: a review touching /// thousands of files would otherwise hold every one of their sides resident. /// Files past the budget keep using hunk-only sources. const MAX_TOTAL_SOURCE_BYTES: usize = 64 * 1024 * 1024; /// One source blob read for LOC metadata and highlight context. #[derive(Clone, Debug)] struct LoadedBlob { /// Nonblank line count. loc: usize, /// Blob source, absent when the blob is binary or above [`MAX_SOURCE_BYTES`]. source: Option, } impl LoadedBlob { /// Counts lines and keeps the text when it is usable as highlight context. fn read(bytes: Vec) -> Self { let loc = bytes .split(|byte| *byte == b'\n') .filter(|line| line.iter().any(|byte| !byte.is_ascii_whitespace())) .count(); let source = (bytes.len() <= MAX_SOURCE_BYTES) .then(|| String::from_utf8(bytes).ok()) .flatten() .map(|text| HighlightSource::new(text, 1)); Self { loc, source } } /// Reads a bounded source from one safe worktree path. /// /// `root` must be canonical so containment checks use one path form. fn read_worktree(root: &Path, path: &Path, mode: FileMode) -> Option { if path.as_os_str().is_empty() || !path .components() .all(|component| matches!(component, Component::Normal(_))) { return None; } let full_path = root.join(path); let bytes = if mode == FileMode::Link { let parent = full_path.parent()?.canonicalize().ok()?; if !parent.starts_with(root) || !std::fs::symlink_metadata(&full_path) .ok()? .file_type() .is_symlink() { return None; } std::fs::read_link(full_path) .ok()? .into_os_string() .into_encoded_bytes() } else { if !std::fs::symlink_metadata(&full_path) .ok()? .file_type() .is_file() { return None; } let path = full_path.canonicalize().ok()?; if !path.starts_with(root) { return None; } let mut file = std::fs::File::open(path).ok()?; if file.metadata().ok()?.len() > MAX_SOURCE_BYTES as u64 { return None; } let mut bytes = Vec::new(); file.by_ref() .take(MAX_SOURCE_BYTES as u64 + 1) .read_to_end(&mut bytes) .ok()?; if bytes.len() > MAX_SOURCE_BYTES { return None; } bytes }; Some(Self::read(bytes)) } } /// Stable metadata shown in a file header. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] struct FileSummary { /// Nonblank displayed-side lines, upgraded from the full blob when available. loc: Option, /// Addition and deletion counts in the original file diff. stats: FileStats, } /// Whether separate review hunks render a synthetic gap row between them. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum HunkGaps { /// Show a vertical ellipsis where bounded diff context is omitted. Visible, /// Join contiguous full-file context without a synthetic gap. Hidden, } impl From<&FileDiff> for FileSummary { fn from(file: &FileDiff) -> Self { let stats = file.stats(); Self { loc: (!file.header.is_binary()).then(|| file.loc()), stats, } } } /// The rendered position of one visible file. #[derive(Clone, Copy, Debug)] struct IndexedFileRows { /// Index into the document file list. file_index: usize, /// First rendered row occupied by the file. start: usize, } /// One rendered row before viewport projection. #[derive(Clone, Debug)] struct RenderRow { /// Renderable line. line: Line, /// Source-row metadata when this is a diff source row. diff: Option, } /// Hunk decoration resolved for one rendered body row. #[derive(Clone, Copy, Debug, Default)] struct HunkRowDecoration { /// Optional marker drawn before a changed row. gutter: Option>, /// Style composed onto the row body. style: Option