Debian Codegraph @

helix-vcs/src/diff.rs

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