Debian Codegraph @

helix-vcs/src/diff.rs

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 use std::iter::Peekable;
2 use std::sync::Arc;
3
4 use helix_core::Rope;
5 use helix_event::RenderLockGuard;
6 use imara_diff::Algorithm;
7 use parking_lot::{RwLock, RwLockReadGuard};
8 use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
9 use tokio::task::JoinHandle;
10 use tokio::time::Instant;
11
12 use crate::diff::worker::DiffWorker;
13
14 pub use imara_diff::Hunk;
15
16 mod line_cache;
17 mod worker;
18
19 /// A rendering lock passed to the differ the prevents redraws from occurring
20 struct RenderLock {
21 pub lock: RenderLockGuard,
22 pub timeout: Option<Instant>,
23 }
24
25 struct Event {
26 text: Rope,
27 is_base: bool,
28 render_lock: Option<RenderLock>,
29 }
30
31 #[derive(Clone, Debug, Default)]
32 struct DiffInner {
33 diff_base: Rope,
34 doc: Rope,
35 hunks: Vec<Hunk>,
36 }
37
38 /// Representation of a diff that can be updated.
39 #[derive(Clone, Debug)]
40 pub struct DiffHandle {
41 channel: UnboundedSender<Event>,
42 diff: Arc<RwLock<DiffInner>>,
43 inverted: bool,
44 }
45
46 impl DiffHandle {
47 pub fn new(diff_base: Rope, doc: Rope) -> DiffHandle {
48 DiffHandle::new_with_handle(diff_base, doc).0
49 }
50
51 fn new_with_handle(diff_base: Rope, doc: Rope) -> (DiffHandle, JoinHandle<()>) {
52 let (sender, receiver) = unbounded_channel();
53 let diff: Arc<RwLock<DiffInner>> = Arc::default();
54 let worker = DiffWorker {
55 channel: receiver,
56 diff: diff.clone(),
57 diff_finished_notify: Arc::default(),
58 diff_alloc: imara_diff::Diff::default(),
59 };
60 let handle = tokio::spawn(worker.run(diff_base, doc));
61 let differ = DiffHandle {
62 channel: sender,
63 diff,
64 inverted: false,
65 };
66 (differ, handle)
67 }
68
69 /// Switch base and modified texts' roles
70 pub fn invert(&mut self) {
71 self.inverted = !self.inverted;
72 }
73
74 /// Load the actual diff
75 pub fn load(&self) -> Diff<'_> {
76 Diff {
77 diff: self.diff.read(),
78 inverted: self.inverted,
79 }
80 }
81
82 /// Updates the document associated with this redraw handle
83 /// This function is only intended to be called from within the rendering loop
84 /// if called from elsewhere it may fail to acquire the render lock and panic
85 pub fn update_document(&self, doc: Rope, block: bool) -> bool {
86 let lock = helix_event::lock_frame();
87 let timeout = if block {
88 None
89 } else {
90 Some(Instant::now() + tokio::time::Duration::from_millis(SYNC_DIFF_TIMEOUT))
91 };
92 self.update_document_impl(doc, self.inverted, Some(RenderLock { lock, timeout }))
93 }
94
95 /// Updates the base text of the diff. Returns if the update was successful.
96 pub fn update_diff_base(&self, diff_base: Rope) -> bool {
97 self.update_document_impl(diff_base, !self.inverted, None)
98 }
99
100 fn update_document_impl(
101 &self,
102 text: Rope,
103 is_base: bool,
104 render_lock: Option<RenderLock>,
105 ) -> bool {
106 let event = Event {
107 text,
108 is_base,
109 render_lock,
110 };
111 self.channel.send(event).is_ok()
112 }
113 }
114
115 /// synchronous debounce value should be low
116 /// so we can update synchronously most of the time
117 const DIFF_DEBOUNCE_TIME_SYNC: u64 = 1;
118 /// maximum time that rendering should be blocked until the diff finishes
119 const SYNC_DIFF_TIMEOUT: u64 = 12;
120 const DIFF_DEBOUNCE_TIME_ASYNC: u64 = 96;
121 const ALGORITHM: Algorithm = Algorithm::Histogram;
122 const MAX_DIFF_LINES: usize = 64 * u16::MAX as usize;
123 // cap average line length to 128 for files with MAX_DIFF_LINES
124 const MAX_DIFF_BYTES: usize = MAX_DIFF_LINES * 128;
125
126 /// A list of changes in a file sorted in ascending
127 /// non-overlapping order
128 #[derive(Debug)]
129 pub struct Diff<'a> {
130 diff: RwLockReadGuard<'a, DiffInner>,
131 inverted: bool,
132 }
133
134 impl Diff<'_> {
135 /// Returns the base [Rope] of the [Diff]
136 pub fn diff_base(&self) -> &Rope {
137 if self.inverted {
138 &self.diff.doc
139 } else {
140 &self.diff.diff_base
141 }
142 }
143
144 /// Returns the [Rope] being compared against
145 pub fn doc(&self) -> &Rope {
146 if self.inverted {
147 &self.diff.diff_base
148 } else {
149 &self.diff.doc
150 }
151 }
152
153 pub fn is_inverted(&self) -> bool {
154 self.inverted
155 }
156
157 /// Returns the `Hunk` for the `n`th change in this file.
158 /// if there is no `n`th change `Hunk::NONE` is returned instead.
159 pub fn nth_hunk(&self, n: u32) -> Hunk {
160 match self.diff.hunks.get(n as usize) {
161 Some(hunk) if self.inverted => hunk.invert(),
162 Some(hunk) => hunk.clone(),
163 None => Hunk::NONE,
164 }
165 }
166
167 pub fn len(&self) -> u32 {
168 self.diff.hunks.len() as u32
169 }
170
171 pub fn is_empty(&self) -> bool {
172 self.len() == 0
173 }
174
175 /// Gives the index of the first hunk after the given line, if one exists.
176 pub fn next_hunk(&self, line: u32) -> Option<u32> {
177 let hunk_range = if self.inverted {
178 |hunk: &Hunk| hunk.before.clone()
179 } else {
180 |hunk: &Hunk| hunk.after.clone()
181 };
182
183 let res = self
184 .diff
185 .hunks
186 .binary_search_by_key(&line, |hunk| hunk_range(hunk).start);
187
188 match res {
189 // Search found a hunk that starts exactly at this line, return the next hunk if it exists.
190 Ok(pos) if pos + 1 == self.diff.hunks.len() => None,
191 Ok(pos) => Some(pos as u32 + 1),
192
193 // No hunk starts exactly at this line, so the search returns
194 // the position where a hunk starting at this line should be inserted.
195 // That position is exactly the position of the next hunk or the end
196 // of the list if no such hunk exists
197 Err(pos) if pos == self.diff.hunks.len() => None,
198 Err(pos) => Some(pos as u32),
199 }
200 }
201
202 /// Gives the index of the first hunk before the given line, if one exists.
203 pub fn prev_hunk(&self, line: u32) -> Option<u32> {
204 let hunk_range = if self.inverted {
205 |hunk: &Hunk| hunk.before.clone()
206 } else {
207 |hunk: &Hunk| hunk.after.clone()
208 };
209 let res = self
210 .diff
211 .hunks
212 .binary_search_by_key(&line, |hunk| hunk_range(hunk).end);
213
214 match res {
215 // Search found a hunk that ends exactly at this line (so it does not include the current line).
216 // We can usually just return that hunk, however a special case for empty hunk is necessary
217 // which represents a pure removal.
218 // Removals are technically empty but are still shown as single line hunks
219 // and as such we must jump to the previous hunk (if it exists) if we are already inside the removal
220 Ok(pos) if !hunk_range(&self.diff.hunks[pos]).is_empty() => Some(pos as u32),
221
222 // No hunk ends exactly at this line, so the search returns
223 // the position where a hunk ending at this line should be inserted.
224 // That position before this one is exactly the position of the previous hunk
225 Err(0) | Ok(0) => None,
226 Err(pos) | Ok(pos) => Some(pos as u32 - 1),
227 }
228 }
229
230 /// Iterates over all hunks that intersect with the given line ranges.
231 ///
232 /// Hunks are returned at most once even when intersecting with multiple of the line
233 /// ranges.
234 pub fn hunks_intersecting_line_ranges<I>(&self, line_ranges: I) -> impl Iterator<Item = &Hunk>
235 where
236 I: Iterator<Item = (usize, usize)>,
237 {
238 HunksInLineRangesIter {
239 hunks: &self.diff.hunks,
240 line_ranges: line_ranges.peekable(),
241 inverted: self.inverted,
242 cursor: 0,
243 }
244 }
245
246 /// Returns the index of the hunk containing the given line if it exists.
247 pub fn hunk_at(&self, line: u32, include_removal: bool) -> Option<u32> {
248 let hunk_range = if self.inverted {
249 |hunk: &Hunk| hunk.before.clone()
250 } else {
251 |hunk: &Hunk| hunk.after.clone()
252 };
253
254 let res = self
255 .diff
256 .hunks
257 .binary_search_by_key(&line, |hunk| hunk_range(hunk).start);
258
259 match res {
260 // Search found a hunk that starts exactly at this line, return it
261 Ok(pos) => Some(pos as u32),
262
263 // No hunk starts exactly at this line, so the search returns
264 // the position where a hunk starting at this line should be inserted.
265 // The previous hunk contains this hunk if it exists and doesn't end before this line
266 Err(0) => None,
267 Err(pos) => {
268 let hunk = hunk_range(&self.diff.hunks[pos - 1]);
269 if hunk.end > line || include_removal && hunk.start == line && hunk.is_empty() {
270 Some(pos as u32 - 1)
271 } else {
272 None
273 }
274 }
275 }
276 }
277 }
278
279 pub struct HunksInLineRangesIter<'a, I: Iterator<Item = (usize, usize)>> {
280 hunks: &'a [Hunk],
281 line_ranges: Peekable<I>,
282 inverted: bool,
283 cursor: usize,
284 }
285
286 impl<'a, I: Iterator<Item = (usize, usize)>> Iterator for HunksInLineRangesIter<'a, I> {
287 type Item = &'a Hunk;
288
289 fn next(&mut self) -> Option<Self::Item> {
290 let hunk_range = if self.inverted {
291 |hunk: &Hunk| hunk.before.clone()
292 } else {
293 |hunk: &Hunk| hunk.after.clone()
294 };
295
296 loop {
297 let (start_line, end_line) = self.line_ranges.peek()?;
298 let hunk = self.hunks.get(self.cursor)?;
299
300 if (hunk_range(hunk).end as usize) < *start_line {
301 // If the hunk under the cursor comes before this range, jump the cursor
302 // ahead to the next hunk that overlaps with the line range.
303 self.cursor += self.hunks[self.cursor..]
304 .partition_point(|hunk| (hunk_range(hunk).end as usize) < *start_line);
305 } else if (hunk_range(hunk).start as usize) <= *end_line {
306 // If the hunk under the cursor overlaps with this line range, emit it
307 // and move the cursor up so that the hunk cannot be emitted twice.
308 self.cursor += 1;
309 return Some(hunk);
310 } else {
311 // Otherwise, go to the next line range.
312 self.line_ranges.next();
313 }
314 }
315 }
316 }