Debian Codegraph @

helix-vcs/src/diff/worker.rs

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