Debian Codegraph @

helix-vcs/src/diff/worker.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::sync::Arc;
2
3 use helix_core::{Rope, RopeSlice};
4 use imara_diff::{IndentHeuristic, IndentLevel, InternedInput};
5 use parking_lot::RwLock;
6 use tokio::sync::mpsc::UnboundedReceiver;
7 use tokio::sync::Notify;
8 use tokio::time::{timeout, timeout_at, Duration};
9
10 use crate::diff::{
11 DiffInner, Event, RenderLock, ALGORITHM, DIFF_DEBOUNCE_TIME_ASYNC, DIFF_DEBOUNCE_TIME_SYNC,
12 };
13
14 use super::line_cache::InternedRopeLines;
15
16 #[cfg(test)]
17 mod test;
18
19 pub(super) struct DiffWorker {
20 pub channel: UnboundedReceiver<Event>,
21 pub diff: Arc<RwLock<DiffInner>>,
22 pub diff_finished_notify: Arc<Notify>,
23 pub diff_alloc: imara_diff::Diff,
24 }
25
26 impl DiffWorker {
27 async fn accumulate_events(&mut self, event: Event) -> (Option<Rope>, Option<Rope>) {
28 let mut accumulator = EventAccumulator::new();
29 accumulator.handle_event(event).await;
30 accumulator
31 .accumulate_debounced_events(&mut self.channel, self.diff_finished_notify.clone())
32 .await;
33 (accumulator.doc, accumulator.diff_base)
34 }
35
36 pub async fn run(mut self, diff_base: Rope, doc: Rope) {
37 let mut interner = InternedRopeLines::new(diff_base, doc);
38 if let Some(lines) = interner.interned_lines() {
39 self.perform_diff(lines);
40 }
41 self.apply_hunks(interner.diff_base(), interner.doc());
42 while let Some(event) = self.channel.recv().await {
43 let (doc, diff_base) = self.accumulate_events(event).await;
44
45 let process_accumulated_events = || {
46 if let Some(new_base) = diff_base {
47 interner.update_diff_base(new_base, doc)
48 } else {
49 interner.update_doc(doc.unwrap())
50 }
51
52 if let Some(lines) = interner.interned_lines() {
53 self.perform_diff(lines)
54 }
55 };
56
57 // Calculating diffs is computationally expensive and should
58 // not run inside an async function to avoid blocking other futures.
59 // Note: tokio::task::block_in_place does not work during tests
60 #[cfg(test)]
61 process_accumulated_events();
62 #[cfg(not(test))]
63 tokio::task::block_in_place(process_accumulated_events);
64
65 self.apply_hunks(interner.diff_base(), interner.doc());
66 }
67 }
68
69 /// update the hunks (used by the gutter) by replacing it with `self.new_hunks`.
70 /// `self.new_hunks` is always empty after this function runs.
71 /// To improve performance this function tries to reuse the allocation of the old diff previously stored in `self.line_diffs`
72 fn apply_hunks(&mut self, diff_base: Rope, doc: Rope) {
73 let mut diff = self.diff.write();
74 diff.diff_base = diff_base;
75 diff.doc = doc;
76 diff.hunks.clear();
77 diff.hunks.extend(self.diff_alloc.hunks());
78 drop(diff);
79 self.diff_finished_notify.notify_waiters();
80 }
81
82 fn perform_diff(&mut self, input: &InternedInput<RopeSlice>) {
83 self.diff_alloc.compute_with(
84 ALGORITHM,
85 &input.before,
86 &input.after,
87 input.interner.num_tokens(),
88 );
89 self.diff_alloc.postprocess_with(
90 &input.before,
91 &input.after,
92 IndentHeuristic::new(|token| {
93 IndentLevel::for_ascii_line(input.interner[token].bytes(), 4)
94 }),
95 );
96 }
97 }
98
99 struct EventAccumulator {
100 diff_base: Option<Rope>,
101 doc: Option<Rope>,
102 render_lock: Option<RenderLock>,
103 }
104
105 impl EventAccumulator {
106 fn new() -> EventAccumulator {
107 EventAccumulator {
108 diff_base: None,
109 doc: None,
110 render_lock: None,
111 }
112 }
113
114 async fn handle_event(&mut self, event: Event) {
115 let dst = if event.is_base {
116 &mut self.diff_base
117 } else {
118 &mut self.doc
119 };
120
121 *dst = Some(event.text);
122
123 // always prefer the most synchronous requested render mode
124 if let Some(render_lock) = event.render_lock {
125 match &mut self.render_lock {
126 Some(RenderLock { timeout, .. }) => {
127 // A timeout of `None` means that the render should
128 // always wait for the diff to complete (so no timeout)
129 // remove the existing timeout, otherwise keep the previous timeout
130 // because it will be shorter then the current timeout
131 if render_lock.timeout.is_none() {
132 timeout.take();
133 }
134 }
135 None => self.render_lock = Some(render_lock),
136 }
137 }
138 }
139
140 async fn accumulate_debounced_events(
141 &mut self,
142 channel: &mut UnboundedReceiver<Event>,
143 diff_finished_notify: Arc<Notify>,
144 ) {
145 let async_debounce = Duration::from_millis(DIFF_DEBOUNCE_TIME_ASYNC);
146 let sync_debounce = Duration::from_millis(DIFF_DEBOUNCE_TIME_SYNC);
147 loop {
148 // if we are not blocking rendering use a much longer timeout
149 let debounce = if self.render_lock.is_none() {
150 async_debounce
151 } else {
152 sync_debounce
153 };
154
155 if let Ok(Some(event)) = timeout(debounce, channel.recv()).await {
156 self.handle_event(event).await;
157 } else {
158 break;
159 }
160 }
161
162 // setup task to trigger the rendering
163 match self.render_lock.take() {
164 // diff is performed outside of the rendering loop
165 // request a redraw after the diff is done
166 None => {
167 tokio::spawn(async move {
168 diff_finished_notify.notified().await;
169 helix_event::request_redraw();
170 });
171 }
172 // diff is performed inside the rendering loop
173 // block redraw until the diff is done or the timeout is expired
174 Some(RenderLock {
175 lock,
176 timeout: Some(timeout),
177 }) => {
178 tokio::spawn(async move {
179 let res = {
180 // Acquire a lock on the redraw handle.
181 // The lock will block the rendering from occurring while held.
182 // The rendering waits for the diff if it doesn't time out
183 timeout_at(timeout, diff_finished_notify.notified()).await
184 };
185 // we either reached the timeout or the diff is finished, release the render lock
186 drop(lock);
187 if res.is_ok() {
188 // Diff finished in time we are done.
189 return;
190 }
191 // Diff failed to complete in time log the event
192 // and wait until the diff occurs to trigger an async redraw
193 log::info!("Diff computation timed out, update of diffs might appear delayed");
194 diff_finished_notify.notified().await;
195 helix_event::request_redraw()
196 });
197 }
198 // a blocking diff is performed inside the rendering loop
199 // block redraw until the diff is done
200 Some(RenderLock {
201 lock,
202 timeout: None,
203 }) => {
204 tokio::spawn(async move {
205 diff_finished_notify.notified().await;
206 // diff is done release the lock
207 drop(lock)
208 });
209 }
210 };
211 }
212 }