1use std::{mem, ops::Range, sync::Arc};
2
3use collections::HashSet;
4use gpui::{App, AppContext, Context, Entity};
5use itertools::Itertools;
6use language::{Buffer, BufferSnapshot};
7use rope::Point;
8use text::{Bias, BufferId, OffsetRangeExt, locator::Locator};
9use util::{post_inc, rel_path::RelPath};
10
11use crate::{
12 Anchor, ExcerptId, ExcerptRange, ExpandExcerptDirection, MultiBuffer, build_excerpt_ranges,
13};
14
15#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]
16pub struct PathKey {
17 // Used by the derived PartialOrd & Ord
18 pub sort_prefix: Option<u64>,
19 pub path: Arc<RelPath>,
20}
21
22impl PathKey {
23 pub fn with_sort_prefix(sort_prefix: u64, path: Arc<RelPath>) -> Self {
24 Self {
25 sort_prefix: Some(sort_prefix),
26 path,
27 }
28 }
29
30 pub fn for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Self {
31 if let Some(file) = buffer.read(cx).file() {
32 Self::with_sort_prefix(file.worktree_id(cx).to_proto(), file.path().clone())
33 } else {
34 Self {
35 sort_prefix: None,
36 path: RelPath::unix(&buffer.entity_id().to_string())
37 .unwrap()
38 .into_arc(),
39 }
40 }
41 }
42}
43
44impl MultiBuffer {
45 pub fn paths(&self) -> impl Iterator<Item = PathKey> + '_ {
46 self.excerpts_by_path.keys().cloned()
47 }
48
49 pub fn remove_excerpts_for_path(&mut self, path: PathKey, cx: &mut Context<Self>) {
50 if let Some(to_remove) = self.excerpts_by_path.remove(&path) {
51 self.remove_excerpts(to_remove, cx)
52 }
53 }
54
55 pub fn location_for_path(&self, path: &PathKey, cx: &App) -> Option<Anchor> {
56 let excerpt_id = self.excerpts_by_path.get(path)?.first()?;
57 let snapshot = self.read(cx);
58 let excerpt = snapshot.excerpt(*excerpt_id)?;
59 Some(Anchor::in_buffer(
60 *excerpt_id,
61 excerpt.buffer_id,
62 excerpt.range.context.start,
63 ))
64 }
65
66 pub fn excerpt_paths(&self) -> impl Iterator<Item = &PathKey> {
67 self.excerpts_by_path.keys()
68 }
69
70 /// Sets excerpts, returns `true` if at least one new excerpt was added.
71 pub fn set_excerpts_for_path(
72 &mut self,
73 path: PathKey,
74 buffer: Entity<Buffer>,
75 ranges: impl IntoIterator<Item = Range<Point>>,
76 context_line_count: u32,
77 cx: &mut Context<Self>,
78 ) -> (Vec<Range<Anchor>>, bool) {
79 let buffer_snapshot = buffer.read(cx).snapshot();
80 let excerpt_ranges = build_excerpt_ranges(ranges, context_line_count, &buffer_snapshot);
81
82 let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
83 self.set_merged_excerpt_ranges_for_path(
84 path,
85 buffer,
86 excerpt_ranges,
87 &buffer_snapshot,
88 new,
89 counts,
90 cx,
91 )
92 }
93
94 pub fn set_excerpt_ranges_for_path(
95 &mut self,
96 path: PathKey,
97 buffer: Entity<Buffer>,
98 buffer_snapshot: &BufferSnapshot,
99 excerpt_ranges: Vec<ExcerptRange<Point>>,
100 cx: &mut Context<Self>,
101 ) -> (Vec<Range<Anchor>>, bool) {
102 let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
103 self.set_merged_excerpt_ranges_for_path(
104 path,
105 buffer,
106 excerpt_ranges,
107 buffer_snapshot,
108 new,
109 counts,
110 cx,
111 )
112 }
113
114 pub fn set_anchored_excerpts_for_path(
115 &self,
116 path_key: PathKey,
117 buffer: Entity<Buffer>,
118 ranges: Vec<Range<text::Anchor>>,
119 context_line_count: u32,
120 cx: &Context<Self>,
121 ) -> impl Future<Output = Vec<Range<Anchor>>> + use<> {
122 let buffer_snapshot = buffer.read(cx).snapshot();
123 let multi_buffer = cx.weak_entity();
124 let mut app = cx.to_async();
125 async move {
126 let snapshot = buffer_snapshot.clone();
127 let (excerpt_ranges, new, counts) = app
128 .background_spawn(async move {
129 let ranges = ranges.into_iter().map(|range| range.to_point(&snapshot));
130 let excerpt_ranges =
131 build_excerpt_ranges(ranges, context_line_count, &snapshot);
132 let (new, counts) = Self::merge_excerpt_ranges(&excerpt_ranges);
133 (excerpt_ranges, new, counts)
134 })
135 .await;
136
137 multi_buffer
138 .update(&mut app, move |multi_buffer, cx| {
139 let (ranges, _) = multi_buffer.set_merged_excerpt_ranges_for_path(
140 path_key,
141 buffer,
142 excerpt_ranges,
143 &buffer_snapshot,
144 new,
145 counts,
146 cx,
147 );
148 ranges
149 })
150 .ok()
151 .unwrap_or_default()
152 }
153 }
154
155 pub fn remove_excerpts_for_buffer(&mut self, buffer: BufferId, cx: &mut Context<Self>) {
156 self.remove_excerpts(
157 self.excerpts_for_buffer(buffer, cx)
158 .into_iter()
159 .map(|(excerpt, _)| excerpt),
160 cx,
161 );
162 }
163
164 pub(super) fn expand_excerpts_with_paths(
165 &mut self,
166 ids: impl IntoIterator<Item = ExcerptId>,
167 line_count: u32,
168 direction: ExpandExcerptDirection,
169 cx: &mut Context<Self>,
170 ) {
171 let grouped = ids
172 .into_iter()
173 .chunk_by(|id| self.paths_by_excerpt.get(id).cloned())
174 .into_iter()
175 .flat_map(|(k, v)| Some((k?, v.into_iter().collect::<Vec<_>>())))
176 .collect::<Vec<_>>();
177 let snapshot = self.snapshot(cx);
178
179 for (path, ids) in grouped.into_iter() {
180 let Some(excerpt_ids) = self.excerpts_by_path.get(&path) else {
181 continue;
182 };
183
184 let ids_to_expand = HashSet::from_iter(ids);
185 let expanded_ranges = excerpt_ids.iter().filter_map(|excerpt_id| {
186 let excerpt = snapshot.excerpt(*excerpt_id)?;
187
188 let mut context = excerpt.range.context.to_point(&excerpt.buffer);
189 if ids_to_expand.contains(excerpt_id) {
190 match direction {
191 ExpandExcerptDirection::Up => {
192 context.start.row = context.start.row.saturating_sub(line_count);
193 context.start.column = 0;
194 }
195 ExpandExcerptDirection::Down => {
196 context.end.row =
197 (context.end.row + line_count).min(excerpt.buffer.max_point().row);
198 context.end.column = excerpt.buffer.line_len(context.end.row);
199 }
200 ExpandExcerptDirection::UpAndDown => {
201 context.start.row = context.start.row.saturating_sub(line_count);
202 context.start.column = 0;
203 context.end.row =
204 (context.end.row + line_count).min(excerpt.buffer.max_point().row);
205 context.end.column = excerpt.buffer.line_len(context.end.row);
206 }
207 }
208 }
209
210 Some(ExcerptRange {
211 context,
212 primary: excerpt.range.primary.to_point(&excerpt.buffer),
213 })
214 });
215 let mut merged_ranges: Vec<ExcerptRange<Point>> = Vec::new();
216 for range in expanded_ranges {
217 if let Some(last_range) = merged_ranges.last_mut()
218 && last_range.context.end >= range.context.start
219 {
220 last_range.context.end = range.context.end;
221 continue;
222 }
223 merged_ranges.push(range)
224 }
225 let Some(excerpt_id) = excerpt_ids.first() else {
226 continue;
227 };
228 let Some(buffer_id) = &snapshot.buffer_id_for_excerpt(*excerpt_id) else {
229 continue;
230 };
231
232 let Some(buffer) = self.buffers.get(buffer_id).map(|b| b.buffer.clone()) else {
233 continue;
234 };
235
236 let buffer_snapshot = buffer.read(cx).snapshot();
237 self.update_path_excerpts(path.clone(), buffer, &buffer_snapshot, merged_ranges, cx);
238 }
239 }
240
241 /// Sets excerpts, returns `true` if at least one new excerpt was added.
242 fn set_merged_excerpt_ranges_for_path(
243 &mut self,
244 path: PathKey,
245 buffer: Entity<Buffer>,
246 ranges: Vec<ExcerptRange<Point>>,
247 buffer_snapshot: &BufferSnapshot,
248 new: Vec<ExcerptRange<Point>>,
249 counts: Vec<usize>,
250 cx: &mut Context<Self>,
251 ) -> (Vec<Range<Anchor>>, bool) {
252 let (excerpt_ids, added_a_new_excerpt) =
253 self.update_path_excerpts(path, buffer, buffer_snapshot, new, cx);
254
255 let mut result = Vec::new();
256 let mut ranges = ranges.into_iter();
257 for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(counts.into_iter()) {
258 for range in ranges.by_ref().take(range_count) {
259 let range = Anchor::range_in_buffer(
260 excerpt_id,
261 buffer_snapshot.remote_id(),
262 buffer_snapshot.anchor_before(&range.primary.start)
263 ..buffer_snapshot.anchor_after(&range.primary.end),
264 );
265 result.push(range)
266 }
267 }
268 (result, added_a_new_excerpt)
269 }
270
271 fn update_path_excerpts(
272 &mut self,
273 path: PathKey,
274 buffer: Entity<Buffer>,
275 buffer_snapshot: &BufferSnapshot,
276 new: Vec<ExcerptRange<Point>>,
277 cx: &mut Context<Self>,
278 ) -> (Vec<ExcerptId>, bool) {
279 let mut insert_after = self
280 .excerpts_by_path
281 .range(..path.clone())
282 .next_back()
283 .map(|(_, value)| *value.last().unwrap())
284 .unwrap_or(ExcerptId::min());
285
286 let existing = self
287 .excerpts_by_path
288 .get(&path)
289 .cloned()
290 .unwrap_or_default();
291
292 let mut new_iter = new.into_iter().peekable();
293 let mut existing_iter = existing.into_iter().peekable();
294
295 let mut excerpt_ids = Vec::new();
296 let mut to_remove = Vec::new();
297 let mut to_insert: Vec<(ExcerptId, ExcerptRange<Point>)> = Vec::new();
298 let mut added_a_new_excerpt = false;
299 let snapshot = self.snapshot(cx);
300
301 let mut next_excerpt_id =
302 if let Some(last_entry) = self.snapshot.borrow().excerpt_ids.last() {
303 last_entry.id.0 + 1
304 } else {
305 1
306 };
307
308 let mut next_excerpt_id = move || ExcerptId(post_inc(&mut next_excerpt_id));
309
310 let mut excerpts_cursor = snapshot.excerpts.cursor::<Option<&Locator>>(());
311 excerpts_cursor.next();
312
313 loop {
314 let new = new_iter.peek();
315 let existing = if let Some(existing_id) = existing_iter.peek() {
316 let locator = snapshot.excerpt_locator_for_id(*existing_id);
317 excerpts_cursor.seek_forward(&Some(locator), Bias::Left);
318 if let Some(excerpt) = excerpts_cursor.item() {
319 if excerpt.buffer_id != buffer_snapshot.remote_id() {
320 to_remove.push(*existing_id);
321 existing_iter.next();
322 continue;
323 }
324 Some((
325 *existing_id,
326 excerpt.range.context.to_point(buffer_snapshot),
327 ))
328 } else {
329 None
330 }
331 } else {
332 None
333 };
334
335 if let Some((last_id, last)) = to_insert.last_mut() {
336 if let Some(new) = new
337 && last.context.end >= new.context.start
338 {
339 last.context.end = last.context.end.max(new.context.end);
340 excerpt_ids.push(*last_id);
341 new_iter.next();
342 continue;
343 }
344 if let Some((existing_id, existing_range)) = &existing
345 && last.context.end >= existing_range.start
346 {
347 last.context.end = last.context.end.max(existing_range.end);
348 to_remove.push(*existing_id);
349 self.snapshot
350 .get_mut()
351 .replaced_excerpts
352 .insert(*existing_id, *last_id);
353 existing_iter.next();
354 continue;
355 }
356 }
357
358 match (new, existing) {
359 (None, None) => break,
360 (None, Some((existing_id, _))) => {
361 existing_iter.next();
362 to_remove.push(existing_id);
363 continue;
364 }
365 (Some(_), None) => {
366 added_a_new_excerpt = true;
367 let new_id = next_excerpt_id();
368 excerpt_ids.push(new_id);
369 to_insert.push((new_id, new_iter.next().unwrap()));
370 continue;
371 }
372 (Some(new), Some((_, existing_range))) => {
373 if existing_range.end < new.context.start {
374 let existing_id = existing_iter.next().unwrap();
375 to_remove.push(existing_id);
376 continue;
377 } else if existing_range.start > new.context.end {
378 let new_id = next_excerpt_id();
379 excerpt_ids.push(new_id);
380 to_insert.push((new_id, new_iter.next().unwrap()));
381 continue;
382 }
383
384 if existing_range.start == new.context.start
385 && existing_range.end == new.context.end
386 {
387 self.insert_excerpts_with_ids_after(
388 insert_after,
389 buffer.clone(),
390 mem::take(&mut to_insert),
391 cx,
392 );
393 insert_after = existing_iter.next().unwrap();
394 excerpt_ids.push(insert_after);
395 new_iter.next();
396 } else {
397 let existing_id = existing_iter.next().unwrap();
398 let new_id = next_excerpt_id();
399 self.snapshot
400 .get_mut()
401 .replaced_excerpts
402 .insert(existing_id, new_id);
403 to_remove.push(existing_id);
404 let mut range = new_iter.next().unwrap();
405 range.context.start = range.context.start.min(existing_range.start);
406 range.context.end = range.context.end.max(existing_range.end);
407 excerpt_ids.push(new_id);
408 to_insert.push((new_id, range));
409 }
410 }
411 };
412 }
413
414 self.insert_excerpts_with_ids_after(insert_after, buffer, to_insert, cx);
415 self.remove_excerpts(to_remove, cx);
416 if excerpt_ids.is_empty() {
417 self.excerpts_by_path.remove(&path);
418 } else {
419 for excerpt_id in &excerpt_ids {
420 self.paths_by_excerpt.insert(*excerpt_id, path.clone());
421 }
422 self.excerpts_by_path
423 .insert(path, excerpt_ids.iter().dedup().cloned().collect());
424 }
425
426 (excerpt_ids, added_a_new_excerpt)
427 }
428}