path_key.rs

  1use std::{ops::Range, rc::Rc, sync::Arc};
  2
  3use gpui::{App, AppContext, Context, Entity};
  4use itertools::Itertools;
  5use language::{Buffer, BufferSnapshot};
  6use rope::Point;
  7use sum_tree::{Dimensions, SumTree};
  8use text::{Bias, BufferId, Edit, OffsetRangeExt, Patch};
  9use util::rel_path::RelPath;
 10use ztracing::instrument;
 11
 12use crate::{
 13    Anchor, BufferState, BufferStateSnapshot, DiffChangeKind, Event, Excerpt, ExcerptOffset,
 14    ExcerptRange, ExcerptSummary, ExpandExcerptDirection, MultiBuffer, MultiBufferDimension,
 15    PathKeyIndex, ToOffset, build_excerpt_ranges,
 16};
 17
 18#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]
 19pub struct PathKey {
 20    // Used by the derived PartialOrd & Ord
 21    pub sort_prefix: Option<u64>,
 22    pub path: Arc<RelPath>,
 23}
 24
 25impl PathKey {
 26    pub fn min() -> Self {
 27        Self {
 28            sort_prefix: None,
 29            path: RelPath::empty().into_arc(),
 30        }
 31    }
 32
 33    pub fn sorted(sort_prefix: u64) -> Self {
 34        Self {
 35            sort_prefix: Some(sort_prefix),
 36            path: RelPath::empty().into_arc(),
 37        }
 38    }
 39    pub fn with_sort_prefix(sort_prefix: u64, path: Arc<RelPath>) -> Self {
 40        Self {
 41            sort_prefix: Some(sort_prefix),
 42            path,
 43        }
 44    }
 45
 46    pub fn for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Self {
 47        if let Some(file) = buffer.read(cx).file() {
 48            Self::with_sort_prefix(file.worktree_id(cx).to_proto(), file.path().clone())
 49        } else {
 50            Self {
 51                sort_prefix: None,
 52                path: RelPath::unix(&buffer.entity_id().to_string())
 53                    .unwrap()
 54                    .into_arc(),
 55            }
 56        }
 57    }
 58}
 59
 60impl MultiBuffer {
 61    pub fn buffer_for_path(&self, path: &PathKey, cx: &App) -> Option<Entity<Buffer>> {
 62        let snapshot = self.snapshot(cx);
 63        let excerpt = snapshot.excerpts_for_path(path).next()?;
 64        self.buffer(excerpt.buffer_id)
 65    }
 66
 67    pub fn location_for_path(&self, path: &PathKey, cx: &App) -> Option<Anchor> {
 68        let snapshot = self.snapshot(cx);
 69        let excerpt = snapshot.excerpts_for_path(path).next()?;
 70        Some(Anchor::in_buffer(
 71            excerpt.path_key_index,
 72            excerpt.range.start,
 73        ))
 74    }
 75
 76    pub fn set_excerpts_for_buffer(
 77        &mut self,
 78        buffer: Entity<Buffer>,
 79        ranges: impl IntoIterator<Item = Range<Point>>,
 80        context_line_count: u32,
 81        cx: &mut Context<Self>,
 82    ) -> (Vec<Range<Anchor>>, bool) {
 83        let path = PathKey::for_buffer(&buffer, cx);
 84        self.set_excerpts_for_path(path, buffer, ranges, context_line_count, cx)
 85    }
 86
 87    /// Sets excerpts, returns `true` if at least one new excerpt was added.
 88    #[instrument(skip_all)]
 89    pub fn set_excerpts_for_path(
 90        &mut self,
 91        path: PathKey,
 92        buffer: Entity<Buffer>,
 93        ranges: impl IntoIterator<Item = Range<Point>>,
 94        context_line_count: u32,
 95        cx: &mut Context<Self>,
 96    ) -> (Vec<Range<Anchor>>, bool) {
 97        let buffer_snapshot = buffer.read(cx).snapshot();
 98        let ranges: Vec<_> = ranges.into_iter().collect();
 99        let excerpt_ranges =
100            build_excerpt_ranges(ranges.clone(), context_line_count, &buffer_snapshot);
101
102        let merged = Self::merge_excerpt_ranges(&excerpt_ranges);
103        let (inserted, path_key_index) =
104            self.set_merged_excerpt_ranges_for_path(path, buffer, &buffer_snapshot, merged, cx);
105        // todo!() move this into the callers that care
106        let anchors = ranges
107            .into_iter()
108            .map(|range| {
109                Anchor::range_in_buffer(path_key_index, buffer_snapshot.anchor_range_around(range))
110            })
111            .collect::<Vec<_>>();
112        (anchors, inserted)
113    }
114
115    pub fn set_excerpt_ranges_for_path(
116        &mut self,
117        path: PathKey,
118        buffer: Entity<Buffer>,
119        buffer_snapshot: &BufferSnapshot,
120        excerpt_ranges: Vec<ExcerptRange<Point>>,
121        cx: &mut Context<Self>,
122    ) -> (Vec<Range<Anchor>>, PathKeyIndex, bool) {
123        let merged = Self::merge_excerpt_ranges(&excerpt_ranges);
124        let (inserted, path_key_index) =
125            self.set_merged_excerpt_ranges_for_path(path, buffer, buffer_snapshot, merged, cx);
126        // todo!() move this into the callers that care
127        let anchors = excerpt_ranges
128            .into_iter()
129            .map(|range| {
130                Anchor::range_in_buffer(
131                    path_key_index,
132                    buffer_snapshot.anchor_range_around(range.primary),
133                )
134            })
135            .collect::<Vec<_>>();
136        (anchors, path_key_index, inserted)
137    }
138
139    pub fn set_anchored_excerpts_for_path(
140        &self,
141        path_key: PathKey,
142        buffer: Entity<Buffer>,
143        ranges: Vec<Range<text::Anchor>>,
144        context_line_count: u32,
145        cx: &Context<Self>,
146    ) -> impl Future<Output = Vec<Range<Anchor>>> + use<> {
147        let buffer_snapshot = buffer.read(cx).snapshot();
148        let multi_buffer = cx.weak_entity();
149        let mut app = cx.to_async();
150        async move {
151            let snapshot = buffer_snapshot.clone();
152            let (ranges, merged_excerpt_ranges) = app
153                .background_spawn(async move {
154                    let point_ranges = ranges.iter().map(|range| range.to_point(&snapshot));
155                    let excerpt_ranges =
156                        build_excerpt_ranges(point_ranges, context_line_count, &snapshot);
157                    let merged = Self::merge_excerpt_ranges(&excerpt_ranges);
158                    (ranges, merged)
159                })
160                .await;
161
162            multi_buffer
163                .update(&mut app, move |multi_buffer, cx| {
164                    let (_, path_key_index) = multi_buffer.set_merged_excerpt_ranges_for_path(
165                        path_key,
166                        buffer,
167                        &buffer_snapshot,
168                        merged_excerpt_ranges,
169                        cx,
170                    );
171                    ranges
172                        .into_iter()
173                        .map(|range| Anchor::range_in_buffer(path_key_index, range))
174                        .collect()
175                })
176                .ok()
177                .unwrap_or_default()
178        }
179    }
180
181    pub fn expand_excerpts(
182        &mut self,
183        anchors: impl IntoIterator<Item = Anchor>,
184        line_count: u32,
185        direction: ExpandExcerptDirection,
186        cx: &mut Context<Self>,
187    ) {
188        let snapshot = self.snapshot(cx);
189        let mut sorted_anchors = anchors
190            .into_iter()
191            .filter_map(|anchor| anchor.excerpt_anchor())
192            .collect::<Vec<_>>();
193        sorted_anchors.sort_by(|a, b| a.cmp(b, &snapshot));
194        let buffers = sorted_anchors.into_iter().chunk_by(|anchor| anchor.path);
195        let mut cursor = snapshot.excerpts.cursor::<ExcerptSummary>(());
196
197        for (path_index, excerpt_anchors) in &buffers {
198            let path = snapshot
199                .path_keys_by_index
200                .get(&path_index)
201                .expect("anchor from wrong multibuffer");
202
203            let mut excerpt_anchors = excerpt_anchors.peekable();
204            let mut ranges = Vec::new();
205
206            cursor.seek_forward(path, Bias::Left);
207            let Some((buffer, buffer_snapshot)) = cursor
208                .item()
209                .map(|excerpt| (excerpt.buffer(&self), excerpt.buffer_snapshot(&snapshot)))
210            else {
211                continue;
212            };
213
214            while let Some(excerpt) = cursor.item()
215                && &excerpt.path_key == path
216            {
217                let mut range = ExcerptRange {
218                    context: excerpt.range.context.to_point(buffer_snapshot),
219                    primary: excerpt.range.primary.to_point(buffer_snapshot),
220                };
221
222                let mut needs_expand = false;
223                while excerpt_anchors.peek().is_some_and(|anchor| {
224                    excerpt
225                        .range
226                        .contains(&anchor.text_anchor(), buffer_snapshot)
227                }) {
228                    needs_expand = true;
229                    excerpt_anchors.next();
230                }
231
232                if needs_expand {
233                    match direction {
234                        ExpandExcerptDirection::Up => {
235                            range.context.start.row =
236                                range.context.start.row.saturating_sub(line_count);
237                            range.context.start.column = 0;
238                        }
239                        ExpandExcerptDirection::Down => {
240                            range.context.end.row = (range.context.end.row + line_count)
241                                .min(excerpt.buffer_snapshot(&snapshot).max_point().row);
242                            range.context.end.column = excerpt
243                                .buffer_snapshot(&snapshot)
244                                .line_len(range.context.end.row);
245                        }
246                        ExpandExcerptDirection::UpAndDown => {
247                            range.context.start.row =
248                                range.context.start.row.saturating_sub(line_count);
249                            range.context.start.column = 0;
250                            range.context.end.row = (range.context.end.row + line_count)
251                                .min(excerpt.buffer_snapshot(&snapshot).max_point().row);
252                            range.context.end.column = excerpt
253                                .buffer_snapshot(&snapshot)
254                                .line_len(range.context.end.row);
255                        }
256                    }
257                }
258
259                ranges.push(range);
260                cursor.next();
261            }
262
263            self.set_excerpt_ranges_for_path(path.clone(), buffer, buffer_snapshot, ranges, cx);
264        }
265    }
266
267    /// Sets excerpts, returns `true` if at least one new excerpt was added.
268    pub(crate) fn set_merged_excerpt_ranges_for_path<T>(
269        &mut self,
270        path: PathKey,
271        buffer: Entity<Buffer>,
272        buffer_snapshot: &BufferSnapshot,
273        new: Vec<ExcerptRange<T>>,
274        cx: &mut Context<Self>,
275    ) -> (bool, PathKeyIndex)
276    where
277        T: language::ToOffset,
278    {
279        let anchor_ranges = new
280            .into_iter()
281            .map(|r| ExcerptRange {
282                context: buffer_snapshot.anchor_before(r.context.start)
283                    ..buffer_snapshot.anchor_after(r.context.end),
284                primary: buffer_snapshot.anchor_before(r.primary.start)
285                    ..buffer_snapshot.anchor_after(r.primary.end),
286            })
287            .collect::<Vec<_>>();
288        self.update_path_excerpts(path, buffer, buffer_snapshot, &anchor_ranges, cx)
289    }
290
291    fn get_or_create_path_key_index(&mut self, path_key: &PathKey) -> PathKeyIndex {
292        let mut snapshot = self.snapshot.borrow_mut();
293        let existing = snapshot
294            .path_keys_by_index
295            .iter()
296            // todo!() perf? (but ExcerptIdMapping was doing this)
297            .find(|(_, existing_path)| existing_path == &path_key)
298            .map(|(index, _)| *index);
299
300        if let Some(existing) = existing {
301            return existing;
302        }
303
304        let index = snapshot
305            .path_keys_by_index
306            .last()
307            .map(|(index, _)| PathKeyIndex(index.0 + 1))
308            .unwrap_or(PathKeyIndex(0));
309        snapshot.path_keys_by_index.insert(index, path_key.clone());
310        index
311    }
312
313    // todo!() re-instate nonshrinking version for project diff / diagnostics
314    pub fn update_path_excerpts<'a>(
315        &mut self,
316        path_key: PathKey,
317        buffer: Entity<Buffer>,
318        buffer_snapshot: &BufferSnapshot,
319        to_insert: &Vec<ExcerptRange<text::Anchor>>,
320        cx: &mut Context<Self>,
321    ) -> (bool, PathKeyIndex) {
322        let path_key_index = self.get_or_create_path_key_index(&path_key);
323        if let Some(old_path_key) = self
324            .snapshot(cx)
325            .path_for_buffer(buffer_snapshot.remote_id())
326            && old_path_key != &path_key
327        {
328            self.remove_excerpts(old_path_key.clone(), cx);
329        }
330
331        if to_insert.len() == 0 {
332            self.remove_excerpts(path_key.clone(), cx);
333
334            return (false, path_key_index);
335        }
336        assert_eq!(self.history.transaction_depth(), 0);
337        self.sync_mut(cx);
338
339        let buffer_id = buffer_snapshot.remote_id();
340
341        let mut snapshot = self.snapshot.get_mut();
342        let mut cursor = snapshot
343            .excerpts
344            .cursor::<Dimensions<PathKey, ExcerptOffset>>(());
345        let mut new_excerpts = SumTree::new(());
346
347        let new_ranges = to_insert.clone();
348        let mut to_insert = to_insert.iter().peekable();
349        let mut patch = Patch::empty();
350        let mut added_new_excerpt = false;
351
352        new_excerpts.append(cursor.slice(&path_key, Bias::Left), ());
353
354        // handle the case where the path key used to be associated
355        // with a different buffer by removing its excerpts.
356        if let Some(excerpt) = cursor.item()
357            && excerpt.path_key == path_key
358            && excerpt.buffer_id != buffer_id
359        {
360            let before = cursor.position.1;
361            cursor.seek_forward(&path_key, Bias::Right);
362            let after = cursor.position.1;
363            patch.push(Edit {
364                old: before..after,
365                new: new_excerpts.summary().len()..new_excerpts.summary().len(),
366            });
367        }
368
369        while let Some(excerpt) = cursor.item()
370            && excerpt.path_key == path_key
371        {
372            assert_eq!(excerpt.buffer_id, buffer_id);
373            let Some(next_excerpt) = to_insert.peek() else {
374                break;
375            };
376            if &excerpt.range == *next_excerpt {
377                new_excerpts.push(excerpt.clone(), ());
378                to_insert.next();
379                cursor.next();
380                continue;
381            }
382
383            if excerpt
384                .range
385                .context
386                .start
387                .cmp(&next_excerpt.context.start, &buffer_snapshot)
388                .is_le()
389            {
390                // remove old excerpt
391                let before = cursor.position.1;
392                cursor.next();
393                let after = cursor.position.1;
394                patch.push(Edit {
395                    old: before..after,
396                    new: new_excerpts.summary().len()..new_excerpts.summary().len(),
397                });
398            } else {
399                // insert new excerpt
400                let next_excerpt = to_insert.next().unwrap();
401                added_new_excerpt = true;
402                let before = new_excerpts.summary().len();
403                new_excerpts.update_last(|excerpt| excerpt.has_trailing_newline = true, ());
404                new_excerpts.push(
405                    Excerpt::new(
406                        path_key.clone(),
407                        path_key_index,
408                        &buffer_snapshot,
409                        next_excerpt.clone(),
410                        to_insert.peek().is_some()
411                            || cursor
412                                .next_item()
413                                .is_some_and(|item| item.path_key_index != path_key_index),
414                    ),
415                    (),
416                );
417                let after = new_excerpts.summary().len();
418                patch.push_maybe_empty(Edit {
419                    old: cursor.position.1..cursor.position.1,
420                    new: before..after,
421                });
422            }
423        }
424
425        // remove any further trailing excerpts
426        let mut before = cursor.position.1;
427        cursor.seek_forward(&path_key, Bias::Right);
428        let after = cursor.position.1;
429        // if we removed the previous last excerpt, remove the trailing newline from the new last excerpt
430        if cursor.item().is_none() && to_insert.peek().is_none() {
431            new_excerpts.update_last(
432                |excerpt| {
433                    if excerpt.has_trailing_newline {
434                        before.0.0 = before
435                            .0
436                            .0
437                            .checked_sub(1)
438                            .expect("should have preceding excerpt");
439                        excerpt.has_trailing_newline = false;
440                    }
441                },
442                (),
443            );
444        }
445        patch.push(Edit {
446            old: before..after,
447            new: new_excerpts.summary().len()..new_excerpts.summary().len(),
448        });
449
450        while let Some(next_excerpt) = to_insert.next() {
451            added_new_excerpt = true;
452            let before = new_excerpts.summary().len();
453            new_excerpts.update_last(|excerpt| excerpt.has_trailing_newline = true, ());
454            new_excerpts.push(
455                Excerpt::new(
456                    path_key.clone(),
457                    path_key_index,
458                    &buffer_snapshot,
459                    next_excerpt.clone(),
460                    to_insert.peek().is_some()
461                        || cursor
462                            .item()
463                            .is_some_and(|item| item.path_key_index != path_key_index),
464                ),
465                (),
466            );
467            let after = new_excerpts.summary().len();
468            patch.push_maybe_empty(Edit {
469                old: cursor.position.1..cursor.position.1,
470                new: before..after,
471            });
472        }
473
474        let suffix = cursor.suffix();
475        let changed_trailing_excerpt = suffix.is_empty();
476        new_excerpts.append(suffix, ());
477        drop(cursor);
478
479        snapshot.excerpts = new_excerpts;
480        snapshot.buffers.insert(
481            buffer_id,
482            BufferStateSnapshot {
483                path_key: path_key.clone(),
484                buffer_snapshot: buffer_snapshot.clone(),
485            },
486        );
487
488        self.buffers.entry(buffer_id).or_insert_with(|| {
489            self.buffer_changed_since_sync.replace(true);
490            buffer.update(cx, |buffer, _| {
491                buffer.record_changes(Rc::downgrade(&self.buffer_changed_since_sync));
492            });
493            BufferState {
494                _subscriptions: [
495                    cx.observe(&buffer, |_, _, cx| cx.notify()),
496                    cx.subscribe(&buffer, Self::on_buffer_event),
497                ],
498                buffer: buffer.clone(),
499            }
500        });
501
502        if changed_trailing_excerpt {
503            snapshot.trailing_excerpt_update_count += 1;
504        }
505
506        let edits = Self::sync_diff_transforms(
507            &mut snapshot,
508            patch.into_inner(),
509            DiffChangeKind::BufferEdited,
510        );
511        if !edits.is_empty() {
512            self.subscriptions.publish(edits);
513        }
514
515        cx.emit(Event::Edited {
516            edited_buffer: None,
517        });
518        cx.emit(Event::BufferUpdated {
519            buffer,
520            path_key: path_key.clone(),
521            ranges: new_ranges,
522        });
523        cx.notify();
524
525        (added_new_excerpt, path_key_index)
526    }
527
528    pub fn remove_excerpts_for_buffer(&mut self, buffer: BufferId, cx: &mut Context<Self>) {
529        let snapshot = self.sync_mut(cx);
530        let Some(path) = snapshot.path_for_buffer(buffer).cloned() else {
531            return;
532        };
533        self.remove_excerpts(path, cx);
534    }
535
536    pub fn remove_excerpts(&mut self, path: PathKey, cx: &mut Context<Self>) {
537        assert_eq!(self.history.transaction_depth(), 0);
538        self.sync_mut(cx);
539
540        let mut snapshot = self.snapshot.get_mut();
541        let mut cursor = snapshot
542            .excerpts
543            .cursor::<Dimensions<PathKey, ExcerptOffset>>(());
544        let mut new_excerpts = SumTree::new(());
545        new_excerpts.append(cursor.slice(&path, Bias::Left), ());
546        let mut edit_start = cursor.position.1;
547        let mut buffer_id = None;
548        if let Some(excerpt) = cursor.item()
549            && excerpt.path_key == path
550        {
551            buffer_id = Some(excerpt.buffer_id);
552        }
553        cursor.seek(&path, Bias::Right);
554        let edit_end = cursor.position.1;
555        let suffix = cursor.suffix();
556        let changed_trailing_excerpt = suffix.is_empty();
557        new_excerpts.append(suffix, ());
558
559        if let Some(buffer_id) = buffer_id {
560            snapshot.buffers.remove(&buffer_id);
561            self.buffers.remove(&buffer_id);
562            cx.emit(Event::BuffersRemoved {
563                removed_buffer_ids: vec![buffer_id],
564            })
565        }
566        drop(cursor);
567        if changed_trailing_excerpt {
568            snapshot.trailing_excerpt_update_count += 1;
569            new_excerpts.update_last(
570                |excerpt| {
571                    if excerpt.has_trailing_newline {
572                        excerpt.has_trailing_newline = false;
573                        edit_start.0.0 = edit_start
574                            .0
575                            .0
576                            .checked_sub(1)
577                            .expect("should have at least one excerpt");
578                    }
579                },
580                (),
581            )
582        }
583
584        let edit = Edit {
585            old: edit_start..edit_end,
586            new: edit_start..edit_start,
587        };
588        snapshot.excerpts = new_excerpts;
589
590        let edits =
591            Self::sync_diff_transforms(&mut snapshot, vec![edit], DiffChangeKind::BufferEdited);
592        if !edits.is_empty() {
593            self.subscriptions.publish(edits);
594        }
595
596        cx.emit(Event::Edited {
597            edited_buffer: None,
598        });
599        cx.notify();
600    }
601}