diff --git a/CHANGELOG.md b/CHANGELOG.md index 068a997..82bc178 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in ## 0.1.1 - unreleased - docs: new README, docs moved under docs/. +- `Options.chrome`: set it to `false` and the engine draws no label row, footer or help + overlay, so the host owns those rows. Adding this field breaks hosts that build `Options` + without `..Options::default()`. +- `Engine::set_markers` draws host markers in the gutter for ranges of source lines. +- `Engine::reveal` moves the cursor to a source line, and `Engine::select_range` selects a + range of source lines as the user would. ## 0.1.0 - 2026-10-27 diff --git a/docs/embedding.md b/docs/embedding.md index 95611d5..c10a4e5 100644 --- a/docs/embedding.md +++ b/docs/embedding.md @@ -63,6 +63,20 @@ The draw rectangle is intersected with the frame. Engine drawing does not change The supplied rectangle controls reflow. Terminal resize events request a redraw but do not replace the pane dimensions with the full terminal dimensions. Supply the current rectangle on every draw, including when a pane moves without changing size. +### Without chrome + +By default the engine draws a label row at the top of its rectangle, a footer with status and key hints at the bottom, and a help overlay on `?`. +Set `Options { chrome: false, .. }` when the host owns those rows: + +- The diff, its file headers and the Files sidebar fill the whole rectangle. The rectangle needs at least 40 columns × 8 rows instead of 40 × 10. +- `Command::Help` and the `?` key are ignored, so the help overlay never opens. +- `draw_with_controls` ignores its `ReadingControls`; the host shows its own hints and notices. +- The loading, failure and too-small placeholders name no keys. + +Read the state the footer would have shown from `status()`: `loading`, `coloring`, `preparing_source`, `source_failed` and `error`, and `files` for the count. +The review label, layout and theme are the host's own inputs and `options()`. +`chrome` is fixed for the engine's lifetime, and `replace()` keeps it. + ## Commands and selection `handle_event(event, focused)` applies the viewer's default bindings. @@ -92,6 +106,42 @@ The default mouse route supports Shift-click within the same file and side. The The standalone maps `V` and Escape to these commands. `handle_event` alone does not add those keyboard bindings. Headers and padding never become endpoints. Ranges can span unavailable patch-only gaps; `source_read` rejects those gaps during streaming. +### Host-driven position and selection + +`reveal(file, side, line)` scrolls an original source line into view and puts the cursor on it, on that side. +`select_range(range)` makes a fixed selection over `range.first..=range.last`, as if the user had selected it and finished. +The cursor ends on `range.last`; `selection()`, `selected_source()` and `source_read()` then report it as they would a user selection, and `selection_extending()` is false. +Both give the diff keyboard focus and close the help overlay. + +Both return an error, and change nothing, when the line is not displayed: the file is not in the review, the line is outside the file or on the other side only, or it sits in a gap that the patch does not supply and nobody has revealed. +Checked context counts once it is revealed. For `select_range` only the two endpoints must be displayed. As with a user selection, the lines between them can cross a gap, and `source_read` then rejects the range. +`select_range` also rejects a range from another review or with `first` of 0 or greater than `last`. +Moving the cursor to another file or side clears the selection, as it does for a user selection. + +### Gutter markers + +`set_markers(&[Marker])` replaces every marker with a new set; an empty slice clears them. +A `Marker` is a `SourceRange` plus a Ratatui `Style`: + +```rust +use diffs_rs::{engine::{Marker, Side}, reading::SourceRange}; +use ratatui::style::{Color, Style}; + +engine.set_markers(&[Marker { + range: SourceRange { review: engine.review_id(), file: 0, side: Side::New, first: 12, last: 14 }, + style: Style::new().fg(Color::Yellow), +}])?; +``` + +Each visible row whose source line on `range.side` falls in the range shows `▌` in the first gutter cell, patched with `style`. Continuation rows of a wrapped line show it too. +In the split layout a marker shows on its own side's half. A unified row shows both line numbers, so a marker on either side applies. +The cursor `▎` and selection `┃` indicators take precedence in that cell. Where markers overlap, the later one in the slice wins. +The set is indexed per file and side when it is replaced, so each drawn row costs one lookup however many markers exist. + +Markers for lines that are not displayed, or for files that have not arrived yet, draw nothing until they are. Markers can be set before the first file arrives. +`set_markers` rejects the whole set, keeping the previous one, if any range belongs to another review or has `first` of 0 or greater than `last`. It also fails after `close()`. +`replace()` and `close()` drop the markers. Set them again for the new review with its `review_id()`. + ### Source reading and search `source_read(SourceRange)` prepares an original-side range with inclusive source-line coordinates. @@ -165,6 +215,8 @@ cargo run --release --locked --example embedded_viewer -- fixtures/review.patch Use full commit IDs to keep Git inputs fixed across repeated opens. A symbolic revision resolves again on each open. File pairs capture fresh bytes on each open; editing the live files does not change an already captured review. Arguments are validated before acquiring the terminal. The left pane belongs to the host. Tab switches outer focus; `r` opens the next review, `c` closes the review without exiting, `o` reopens it, and `q` exits the host. +`m` marks the selection (Shift-click to make one) or the cursor line with a gutter marker, and `'` selects the last mark again with `select_range`. +`--no-chrome` turns off the viewer's label row, footer and help; the host then draws its own status row from `status()` below the viewer. These are example-host controls, not additional viewer bindings. The example uses the current terminal and does not open windows or change preferences. `State: source unavailable` distinguishes degraded full-source preparation from a ready review. Published patch content remains readable, and the host can replace the review. Unexpected worker/storage errors and failed cleanup terminate the example with an error; they are not treated as recoverable input errors. diff --git a/examples/embedded_viewer.rs b/examples/embedded_viewer.rs index cc9f8f1..bb8ba97 100644 --- a/examples/embedded_viewer.rs +++ b/examples/embedded_viewer.rs @@ -16,12 +16,14 @@ use crossterm::{ LeaveAlternateScreen, }, }; -use diffs_rs::engine::{Engine, Input, Layout, Options, SidebarPreference}; +use diffs_rs::engine::{Engine, Input, Layout, Marker, Options, Side, SidebarPreference}; use diffs_rs::input::LocalInput; +use diffs_rs::reading::SourceRange; use ratatui::{ Terminal, backend::CrosstermBackend, layout::Rect, + style::{Color, Style}, widgets::{Block, Borders, Paragraph}, }; @@ -45,7 +47,12 @@ impl ReviewInput { } } -fn review_inputs() -> Result> { +struct Arguments { + inputs: Vec, + chrome: bool, +} + +fn review_inputs() -> Result { let matches = clap::Command::new("embedded_viewer") .about("Open local reviews in one terminal host, in argument order") .arg_required_else_help(true) @@ -73,6 +80,12 @@ fn review_inputs() -> Result> { .value_parser(OsStringValueParser::new()) .help("Compare Git commits; use full commit IDs to pin repeated opens"), ) + .arg( + Arg::new("no-chrome") + .long("no-chrome") + .action(ArgAction::SetTrue) + .help("Hide the viewer's label row, footer and help; the host draws a status row"), + ) .get_matches(); let mut inputs = Vec::new(); if let Some(paths) = matches.get_many::("patch") { @@ -114,7 +127,10 @@ fn review_inputs() -> Result> { } } inputs.sort_unstable_by_key(|(index, _)| *index); - Ok(inputs.into_iter().map(|(_, input)| input).collect()) + Ok(Arguments { + inputs: inputs.into_iter().map(|(_, input)| input).collect(), + chrome: !matches.get_flag("no-chrome"), + }) } struct HostTerminal { @@ -174,14 +190,65 @@ fn host_text(engine: &Engine, review: usize, focus: bool) -> Result { let focus = if focus { "viewer" } else { "host" }; Ok(format!( "Host pane\nFocus: {focus}\nReview: {}\nState: {state}\n\n{location}\n\n\ - Tab switch focus\nr next review\no reopen review\nc close review\nq exit host\n\n\ + Tab switch focus\nr next review\no reopen review\nc close review\n\ + m mark selection\n' select last mark\nq exit host\n\n\ Viewer keys stay local.", review + 1 )) } +/// The host's own status row, used when the viewer draws no footer. +fn status_text(engine: &Engine, marks: usize) -> String { + let status = engine.status(); + let state = if status.closed { + "Review closed" + } else if let Some(error) = status.error { + error + } else if status.loading { + "Loading patch…" + } else if status.coloring || status.preparing_source { + "Coloring visible code…" + } else if status.source_failed { + "Source unavailable · patch view retained" + } else { + "Ready" + }; + format!(" {state} · {} files · {marks} marks", status.files) +} + +/// Marks the selection, or the cursor line when nothing is selected. +fn mark(engine: &mut Engine, marks: &mut Vec) -> Result<()> { + let range = match engine.selection() { + Some(range) => range, + None => { + let Some(source) = engine.selected_source()? else { + return Ok(()); + }; + let line = match source.side { + Side::Old => source.old_line, + Side::New => source.new_line, + }; + let Some(line) = line else { + return Ok(()); + }; + SourceRange { + review: source.review, + file: source.file, + side: source.side, + first: line, + last: line, + } + } + }; + marks.push(Marker { + range, + style: Style::new().fg(Color::Yellow), + }); + engine.set_markers(marks) +} + fn run() -> Result<()> { - let inputs = review_inputs()?; + let Arguments { inputs, chrome } = review_inputs()?; let (wake, ready) = mpsc::sync_channel(1); let events = TerminalInput::start(wake.clone())?; terminal::enable_raw_mode()?; @@ -198,10 +265,12 @@ fn run() -> Result<()> { Options { layout: Layout::Split, sidebar: SidebarPreference::Hide, + chrome, ..Options::default() }, wake, )?; + let mut marks = Vec::new(); let mut focus = true; let mut dirty = true; let mut resized = false; @@ -225,6 +294,15 @@ fn run() -> Result<()> { let width = area.width.min(28); let beside = Rect::new(area.x, area.y, width, area.height); viewer = Rect::new(area.x + width, area.y, area.width - width, area.height); + if !chrome { + // Without viewer chrome, the host owns a status row below the diff. + viewer.height = viewer.height.saturating_sub(1); + frame.render_widget( + Paragraph::new(status_text(&engine, marks.len())), + Rect::new(viewer.x, viewer.bottom(), viewer.width, 1) + .intersection(area), + ); + } rendered = engine.draw(frame, viewer).and_then(|()| { let text = host_text(&engine, review, focus)?; frame.render_widget( @@ -264,6 +342,7 @@ fn run() -> Result<()> { } KeyCode::Char('c') => { engine.close()?; + marks.clear(); dirty = true; continue; } @@ -272,6 +351,24 @@ fn run() -> Result<()> { review = (review + 1) % inputs.len(); } engine.replace(inputs[review].open())?; + marks.clear(); + dirty = true; + continue; + } + KeyCode::Char('m') if !engine.status().closed => { + mark(&mut engine, &mut marks)?; + dirty = true; + continue; + } + KeyCode::Char('\'') => { + // A mark on revealed context leaves the diff if its source is + // withdrawn; the error is recoverable, so drop that mark. + if let Some(last) = marks.last() + && engine.select_range(last.range).is_err() + { + marks.pop(); + engine.set_markers(&marks)?; + } dirty = true; continue; } diff --git a/src/app.rs b/src/app.rs index e2a57f0..19e5273 100644 --- a/src/app.rs +++ b/src/app.rs @@ -54,6 +54,8 @@ pub struct App { pub horizontal: usize, pub wrap: bool, pub numbers: bool, + /// Draws the label row, footer and help overlay. Hosts that own those rows turn it off. + pub chrome: bool, pub help: bool, pub cache: Cache, pub geometry: crate::geometry::Cache, @@ -65,6 +67,7 @@ pub struct App { pub worker: Worker, pub(crate) search_match: Option, pub(crate) selection: Option, + pub(crate) markers: crate::engine::markers::Markers, reading_anchor: Option, } @@ -92,12 +95,14 @@ impl App { worker, search_match: None, selection: None, + markers: Default::default(), top: Position::default(), cursor: Position::default(), old_side: false, horizontal: 0, wrap: false, numbers: true, + chrome: true, help: false, cache: Cache::default(), geometry: crate::geometry::Cache::default(), diff --git a/src/app/controls.rs b/src/app/controls.rs index 04de687..72da60a 100644 --- a/src/app/controls.rs +++ b/src/app/controls.rs @@ -138,6 +138,7 @@ impl App { self.sidebar.notice = None; let mut highlight = true; match command { + Command::Help if !self.chrome => return Ok(InputEffect::Ignored), Command::Help => { self.help = !self.help; highlight = false; diff --git a/src/app/sidebar.rs b/src/app/sidebar.rs index 723b2dd..ce69465 100644 --- a/src/app/sidebar.rs +++ b/src/app/sidebar.rs @@ -117,6 +117,16 @@ impl App { self.sidebar.preference = preference; } + /// The pane height that view movement reasons about. It always counts the label and + /// footer rows, so without chrome the diff rows fill the whole supplied rectangle. + pub(crate) fn layout_height(&self, screen: u16) -> u16 { + if self.chrome { + screen + } else { + screen.saturating_add(2) + } + } + pub(crate) fn prepare_view(&mut self, screen: Rect) -> anyhow::Result<()> { for file in &self.doc.files[self.sidebar.tree.len()..] { self.sidebar.tree.append(file)?; @@ -140,24 +150,21 @@ impl App { SidebarPreference::Show => true, SidebarPreference::Hide => false, }; - let shown = wants_tree && screen.width >= MIN_WIDTH && screen.height >= 10; + let height = self.layout_height(screen.height); + let top = screen.y + u16::from(self.chrome); + let shown = wants_tree && screen.width >= MIN_WIDTH && height >= 10; if shown { self.sidebar.notice = None; } self.sidebar.screen = screen; self.sidebar.area = if shown { - Rect::new(screen.x, screen.y + 1, TREE_WIDTH, screen.height - 2) + Rect::new(screen.x, top, TREE_WIDTH, height - 2) } else { Rect::default() }; let inset = if shown { TREE_WIDTH + 1 } else { 0 }; - self.sidebar.diff = if screen.width >= 40 && screen.height >= 10 { - Rect::new( - screen.x + inset, - screen.y + 1, - screen.width - inset, - screen.height - 2, - ) + self.sidebar.diff = if screen.width >= 40 && height >= 10 { + Rect::new(screen.x + inset, top, screen.width - inset, height - 2) } else { Rect::default() }; @@ -169,20 +176,28 @@ impl App { self.visible.clear(); return Ok(()); } - let changed = self.width != self.sidebar.diff.width || self.height != screen.height; + let changed = self.width != self.sidebar.diff.width || self.height != height; if changed { - self.reflow(self.layout, self.sidebar.diff.width, screen.height)?; + self.reflow(self.layout, self.sidebar.diff.width, height)?; } Ok(()) } + /// Gives the diff keyboard focus and closes help, as a host-requested move expects. + pub(crate) fn focus_diff(&mut self) { + self.sidebar.focus = Focus::Diff; + self.help = false; + } + pub(crate) fn files_command(&mut self) -> anyhow::Result<()> { if self.sidebar.focused() { self.sidebar.preference = SidebarPreference::Hide; self.sidebar.focus = Focus::Diff; } else { self.sidebar.preference = SidebarPreference::Show; - if self.sidebar.screen.width < MIN_WIDTH || self.sidebar.screen.height < 10 { + if self.sidebar.screen.width < MIN_WIDTH + || self.layout_height(self.sidebar.screen.height) < 10 + { self.sidebar.notice = Some("Files need at least 97 columns × 10 rows"); } else { self.sidebar.focus = Focus::Files; diff --git a/src/app/source.rs b/src/app/source.rs index 7b6e6bb..f622895 100644 --- a/src/app/source.rs +++ b/src/app/source.rs @@ -42,6 +42,19 @@ impl App { Ok(Some((id, old))) } + /// The displayed record of an original line on one side: a patch record, or revealed + /// checked context. Lines in unrevealed gaps, or outside the file, have none. + pub(crate) fn displayed_source(&self, file: usize, old: bool, line: u32) -> Option { + let index = self.doc.files.get(file)?; + let id = index + .source_for_line(old, line) + .map(LineId::Patch) + .or_else(|| self.view.context_line(file, old, line))?; + self.view + .source_row(&self.doc, id, self.split()) + .map(|_| id) + } + pub(crate) fn line_file(&self, id: LineId) -> &Arc { match id { LineId::Patch(id) => self.doc.file_for_source(id), diff --git a/src/engine.rs b/src/engine.rs index 621660e..e2d2330 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1,5 +1,6 @@ //! A review owns its workers and view state, but never the host terminal. +pub(crate) mod markers; mod reading; mod selection; @@ -28,6 +29,7 @@ use crate::{ text::{safe_label, safe_text}, theme::Appearance, }; +pub use markers::Marker; pub enum Input { Patch(PathBuf), @@ -46,6 +48,9 @@ pub struct Options { pub sidebar: SidebarPreference, pub wrap: bool, pub line_numbers: bool, + /// Draw the label row, the footer and the help overlay. With `false` the diff fills the + /// whole draw rectangle, `Command::Help` is ignored, and the host shows `status()` itself. + pub chrome: bool, } impl Default for Options { @@ -56,6 +61,7 @@ impl Default for Options { sidebar: SidebarPreference::Auto, wrap: false, line_numbers: true, + chrome: true, } } } @@ -115,6 +121,8 @@ pub struct Engine { last_draw: Instant, draw_pending: bool, area: Rect, + /// Markers set before the first file arrived; the viewer state takes them when created. + markers: markers::Markers, } impl Engine { @@ -157,6 +165,7 @@ impl Engine { last_draw: Instant::now(), draw_pending: false, area: Rect::default(), + markers: markers::Markers::default(), }) } @@ -171,6 +180,7 @@ impl Engine { sidebar: app.sidebar.preference, wrap: app.wrap, line_numbers: app.numbers, + chrome: app.chrome, }) } @@ -305,6 +315,8 @@ impl Engine { app.set_sidebar_preference(self.options.sidebar); app.wrap = self.options.wrap; app.numbers = self.options.line_numbers; + app.chrome = self.options.chrome; + app.markers = std::mem::take(&mut self.markers); if self.full_sources { app.sources = Some(Vec::new()); } @@ -425,13 +437,24 @@ impl Engine { render::draw_with_controls(frame, app, area, self.error.as_deref(), controls)?; self.request |= previous_size != (app.width, app.height); } else { + // Without chrome the host owns the keys, so these placeholders name none. + let keys = self.options.chrome; let text = self .error .as_ref() - .map(|error| format!("Cannot open patch\n\n{error}\n\nq quit")) + .map(|error| { + format!( + "Cannot open patch\n\n{error}{}", + if keys { "\n\nq quit" } else { "" } + ) + }) .unwrap_or_else(|| { if self.input.is_some() { - "Loading patch…\n\nq quit · Ctrl-C cancel".into() + if keys { + "Loading patch…\n\nq quit · Ctrl-C cancel".into() + } else { + "Loading patch…".into() + } } else { "Review closed".into() } @@ -588,6 +611,7 @@ impl Engine { .transpose(); let colors = self.app.as_mut().map(|app| app.worker.close()).transpose(); self.app = None; + self.markers = markers::Markers::default(); self.loading = false; self.error = None; self.source_failed = false; diff --git a/src/engine/markers.rs b/src/engine/markers.rs new file mode 100644 index 0000000..70bd49b --- /dev/null +++ b/src/engine/markers.rs @@ -0,0 +1,227 @@ +use std::collections::{BinaryHeap, HashMap}; + +use anyhow::{Result, ensure}; +use ratatui::style::Style; + +use super::{Engine, InputEffect, ReviewId, Side}; +use crate::reading::SourceRange; + +/// A host-owned gutter mark over original source lines `range.first..=range.last` on one side. +/// +/// The engine draws `▌` in the first gutter cell of each visible row whose source line on +/// `range.side` falls in the range, patched with `style`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Marker { + pub range: SourceRange, + pub style: Style, +} + +/// The gutter glyph of a marked row. +pub(crate) const SYMBOL: &str = "▌"; + +/// Non-overlapping, ordered line spans for one side of one file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Span { + first: u32, + last: u32, + style: Style, +} + +/// Markers indexed by file and side. Overlaps are resolved when the set is replaced, so a +/// drawn row costs one map lookup and one binary search, whatever the number of markers. +#[derive(Default)] +pub(crate) struct Markers { + files: HashMap; 2]>, +} + +impl Markers { + /// Later markers in `markers` win where ranges overlap. + fn new(markers: &[Marker]) -> Self { + let mut grouped: HashMap<(usize, usize), Vec> = HashMap::new(); + for (index, marker) in markers.iter().enumerate() { + grouped + .entry((marker.range.file, side_index(marker.range.side))) + .or_default() + .push(index); + } + let mut files: HashMap; 2]> = HashMap::new(); + for ((file, side), indices) in grouped { + files.entry(file).or_default()[side] = flatten(markers, indices); + } + Self { files } + } + + pub(crate) fn style(&self, file: usize, side: Side, line: Option) -> Option