diff: TUI optimizations

d94444934b8aa540520fe88df57bb094c4ed06a3
Alexis Sellier committed ago 1 parent 8f10de40
crates/diff/src/bin/rustik-diff/session.rs +43 -24
1 1
//! Terminal session loop for the pager binary.
2 2
3 3
use std::io;
4 -
use std::sync::mpsc;
4 +
use std::sync::mpsc::{self, SyncSender, TrySendError};
5 5
use std::thread;
6 6
7 7
use rustik_diff::{
8 8
    BuiltinHighlighter, DiffHighlighter, DiffViewer, HighlightRequest, HighlightResult,
9 9
};
42 42
        highlights_tx,
43 43
    };
44 44
    session.redraw()?;
45 45
46 46
    while let Ok(event) = events_rx.recv() {
47 -
        match event {
48 -
            TerminalEvent::Input(event) => {
49 -
                let event = event?;
50 -
                let area = viewer_area(session.terminal.area());
51 -
                let control = if let Some(repo) = session.repo.as_ref() {
52 -
                    session.viewer.handle_input_with_repo(event, area, repo)?
53 -
                } else {
54 -
                    session.viewer.handle_input(event, area)
55 -
                };
56 -
                match control {
57 -
                    Control::Quit => break,
58 -
                    Control::Redraw => session.redraw()?,
59 -
                    Control::Continue | Control::Wait => {}
60 -
                }
61 -
            }
62 -
            TerminalEvent::Highlights(results) => {
63 -
                if session.viewer.apply_highlights(results) {
64 -
                    session.redraw()?;
65 -
                }
47 +
        let mut redraw = false;
48 +
        if session.update(event, &mut redraw)? == Control::Quit {
49 +
            break;
50 +
        }
51 +
        while let Ok(event) = events_rx.try_recv() {
52 +
            if session.update(event, &mut redraw)? == Control::Quit {
53 +
                return Ok(());
66 54
            }
67 55
        }
56 +
        if redraw {
57 +
            session.redraw()?;
58 +
        }
68 59
    }
69 60
    Ok(())
70 61
}
71 62
72 63
/// Interactive terminal session state.
76 67
    /// Diff viewer state.
77 68
    viewer: &'a mut DiffViewer,
78 69
    /// Git-backed diff repo, present when the input came from Git.
79 70
    repo: Option<GitRepo>,
80 71
    /// Visible-row highlight request channel.
81 -
    highlights_tx: mpsc::Sender<Vec<HighlightRequest>>,
72 +
    highlights_tx: SyncSender<Vec<HighlightRequest>>,
82 73
}
83 74
84 75
impl TerminalSession<'_> {
76 +
    /// Applies one event and records whether the session should redraw.
77 +
    fn update(&mut self, event: TerminalEvent, redraw: &mut bool) -> Result<Control, Error> {
78 +
        match event {
79 +
            TerminalEvent::Input(event) => {
80 +
                let event = event?;
81 +
                let area = viewer_area(self.terminal.area());
82 +
                let control = if let Some(repo) = self.repo.as_ref() {
83 +
                    self.viewer.handle_input_with_repo(event, area, repo)?
84 +
                } else {
85 +
                    self.viewer.handle_input(event, area)
86 +
                };
87 +
                if control == Control::Redraw {
88 +
                    *redraw = true;
89 +
                }
90 +
                Ok(control)
91 +
            }
92 +
            TerminalEvent::Highlights(results) => {
93 +
                *redraw |= self.viewer.apply_highlights(results);
94 +
                Ok(Control::Continue)
95 +
            }
96 +
        }
97 +
    }
98 +
85 99
    /// Draws a frame and requests highlights for visible rows.
86 100
    fn redraw(&mut self) -> io::Result<()> {
87 101
        self.draw_frame()?;
88 102
        self.request_visible_highlights();
89 103
        Ok(())
92 106
    /// Requests highlight work for currently visible rows.
93 107
    fn request_visible_highlights(&mut self) {
94 108
        let area = viewer_area(self.terminal.area());
95 109
        let requests = self.viewer.highlight_requests(area);
96 110
        if !requests.is_empty() {
97 -
            let _ = self.highlights_tx.send(requests);
111 +
            match self.highlights_tx.try_send(requests) {
112 +
                Ok(()) => {}
113 +
                Err(TrySendError::Full(requests) | TrySendError::Disconnected(requests)) => {
114 +
                    self.viewer.cancel_highlights(requests);
115 +
                }
116 +
            }
98 117
        }
99 118
    }
100 119
101 120
    /// Draws one terminal frame without scheduling highlight work.
102 121
    fn draw_frame(&mut self) -> io::Result<()> {
130 149
131 150
    /// Spawns the visible-row highlight worker.
132 151
    fn spawn_highlight_worker(
133 152
        tx: mpsc::Sender<Self>,
134 153
        mut highlighter: BuiltinHighlighter,
135 -
    ) -> mpsc::Sender<Vec<HighlightRequest>> {
136 -
        let (requests_tx, requests_rx) = mpsc::channel::<Vec<HighlightRequest>>();
154 +
    ) -> SyncSender<Vec<HighlightRequest>> {
155 +
        let (requests_tx, requests_rx) = mpsc::sync_channel::<Vec<HighlightRequest>>(0);
137 156
        thread::spawn(move || {
138 157
            while let Ok(requests) = requests_rx.recv() {
139 158
                if requests.is_empty() {
140 159
                    continue;
141 160
                }
crates/diff/src/viewer.rs +11 -3
872 872
                    DiffAction::ExtendFileTreeSelection(-1)
873 873
                }
874 874
                _ => return Ok(Control::Continue),
875 875
            },
876 876
        };
877 -
        self.apply(action, area);
878 -
879 -
        Ok(Control::Redraw)
877 +
        match self.apply(action, area) {
878 +
            ViewChange::Changed => Ok(Control::Redraw),
879 +
            ViewChange::Unchanged => Ok(Control::Continue),
880 +
        }
880 881
    }
881 882
882 883
    /// Returns highlight requests for visible source rows plus configured lookahead.
883 884
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
884 885
        let diff = self.layout(area).diff;
907 908
            });
908 909
        }
909 910
        requests
910 911
    }
911 912
913 +
    /// Marks unprocessed highlight requests as requestable again.
914 +
    pub fn cancel_highlights(&mut self, requests: impl IntoIterator<Item = HighlightRequest>) {
915 +
        for request in requests {
916 +
            self.pending_highlights.remove(&request.key);
917 +
        }
918 +
    }
919 +
912 920
    /// Returns the highlight-cache key for one diff row.
913 921
    fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
914 922
        HighlightKey::new(HighlightKeyInput {
915 923
            file: meta.file,
916 924
            side: meta.side,
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/src/viewer/tree.rs +1 -1
193 193
                Label::new("lines removed").fg(FOLDER_FG),
194 194
                Label::from(format!("-{}", stats.deletions)).fg(palette.negative_fg),
195 195
            ]);
196 196
            table.push([
197 197
                Label::new("files changed").fg(FOLDER_FG),
198 -
                Label::from(stats.files_changed.to_string()).fg(Color::White),
198 +
                Label::from(format!(" {}", stats.files_changed)).fg(Color::White),
199 199
            ]);
200 200
            table.render(area, buf);
201 201
        }
202 202
    }
203 203
a.rs +0 -0
b.rs +0 -0
crates/tui-termion/src/backend.rs +73 -7
4 4
5 5
use rustik_tui_core as tui_core;
6 6
use tui_core::backend::Backend;
7 7
use tui_core::buffer::DirtyRun;
8 8
use tui_core::layout::Point;
9 -
use tui_core::{PaintMode, Size};
9 +
use tui_core::{PaintMode, Size, Style};
10 10
11 11
/// Termion-backed terminal output.
12 12
#[derive(Debug)]
13 13
pub struct TermionBackend<W> {
14 14
    writer: W,
52 52
            write!(
53 53
                self.writer,
54 54
                "{}",
55 55
                termion::cursor::Goto(coord(run.x), coord(run.y))
56 56
            )?;
57 -
            for cell in run.cells {
58 -
                if cell.is_continuation() {
59 -
                    continue;
60 -
                }
61 -
                let paint = cell.paint();
62 -
                write!(self.writer, "{}", paint.rendered(self.paint))?;
57 +
            match self.paint {
58 +
                PaintMode::Plain => self.draw_plain_cells(run.cells)?,
59 +
                PaintMode::Styled => self.draw_styled_cells(run.cells)?,
63 60
            }
64 61
        }
65 62
        Ok(())
66 63
    }
67 64
88 85
            write!(self.writer, "{}", termion::cursor::Hide)
89 86
        }
90 87
    }
91 88
}
92 89
90 +
impl<W: Write> TermionBackend<W> {
91 +
    /// Writes cells without ANSI styling.
92 +
    fn draw_plain_cells(&mut self, cells: &[tui_core::buffer::Cell]) -> io::Result<()> {
93 +
        for cell in cells {
94 +
            if cell.is_continuation() {
95 +
                continue;
96 +
            }
97 +
            self.writer.write_all(cell.glyph().as_bytes())?;
98 +
        }
99 +
        Ok(())
100 +
    }
101 +
102 +
    /// Writes cells while keeping one ANSI style active across matching cells.
103 +
    fn draw_styled_cells(&mut self, cells: &[tui_core::buffer::Cell]) -> io::Result<()> {
104 +
        let mut style = Style::default();
105 +
106 +
        for cell in cells {
107 +
            if cell.is_continuation() {
108 +
                continue;
109 +
            }
110 +
            let next = cell.style();
111 +
            if next != style {
112 +
                self.write_style_suffix(style)?;
113 +
                self.write_style_prefix(next)?;
114 +
                style = next;
115 +
            }
116 +
            self.writer.write_all(cell.glyph().as_bytes())?;
117 +
        }
118 +
        self.write_style_suffix(style)
119 +
    }
120 +
121 +
    /// Writes the ANSI prefix for `style`.
122 +
    fn write_style_prefix(&mut self, style: Style) -> io::Result<()> {
123 +
        let mut text = String::new();
124 +
        style
125 +
            .fmt_prefix(&mut text)
126 +
            .map_err(|_| io::Error::other("write_style_prefix: failed to format style prefix"))?;
127 +
        self.writer.write_all(text.as_bytes())
128 +
    }
129 +
130 +
    /// Writes the ANSI suffix for `style`.
131 +
    fn write_style_suffix(&mut self, style: Style) -> io::Result<()> {
132 +
        let mut text = String::new();
133 +
        style
134 +
            .fmt_suffix(&mut text)
135 +
            .map_err(|_| io::Error::other("write_style_suffix: failed to format style suffix"))?;
136 +
        self.writer.write_all(text.as_bytes())
137 +
    }
138 +
}
139 +
93 140
/// Converts a zero-based coordinate into a terminal coordinate.
94 141
fn coord(value: usize) -> u16 {
95 142
    u16::try_from(value.saturating_add(1)).unwrap_or(u16::MAX)
96 143
}
97 144
141 188
        let out = String::from_utf8(plain.into_inner()).unwrap();
142 189
143 190
        assert_eq!(out, "\x1B[1;1Hx");
144 191
    }
145 192
193 +
    #[test]
194 +
    fn termion_backend_keeps_matching_cell_styles_active() {
195 +
        let cells = [
196 +
            tui_core::buffer::Cell::new('x', Color::Red.style()),
197 +
            tui_core::buffer::Cell::new('y', Color::Red.style()),
198 +
        ];
199 +
        let run = DirtyRun {
200 +
            x: 0,
201 +
            y: 0,
202 +
            cells: &cells,
203 +
        };
204 +
        let mut backend = TermionBackend::new(Vec::new());
205 +
206 +
        backend.draw(&[run]).unwrap();
207 +
        let out = String::from_utf8(backend.into_inner()).unwrap();
208 +
209 +
        assert_eq!(out, "\x1B[1;1H\x1B[31mxy\x1B[0m");
210 +
    }
211 +
146 212
    #[test]
147 213
    fn termion_backend_does_not_write_wide_continuation_cells() {
148 214
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
149 215
        buffer.reset_dirty();
150 216
        buffer.set_str(0, 0, "🍍a", Style::default());