1use std::{
2 cell::Ref,
3 cmp, iter, mem,
4 ops::{Deref, Range, Sub},
5 sync::Arc,
6};
7
8use collections::HashMap;
9use gpui::{AppContext, ModelHandle, MutableAppContext};
10use itertools::Itertools;
11use language::{rope::TextDimension, Bias, Point, Selection, SelectionGoal, ToPoint};
12use util::post_inc;
13
14use crate::{
15 display_map::{DisplayMap, DisplaySnapshot, ToDisplayPoint},
16 Anchor, DisplayPoint, ExcerptId, MultiBuffer, MultiBufferSnapshot, SelectMode, ToOffset,
17};
18
19#[derive(Clone)]
20pub struct PendingSelection {
21 pub selection: Selection<Anchor>,
22 pub mode: SelectMode,
23}
24
25#[derive(Clone)]
26pub struct SelectionsCollection {
27 display_map: ModelHandle<DisplayMap>,
28 buffer: ModelHandle<MultiBuffer>,
29 pub next_selection_id: usize,
30 pub line_mode: bool,
31 disjoint: Arc<[Selection<Anchor>]>,
32 pending: Option<PendingSelection>,
33}
34
35impl SelectionsCollection {
36 pub fn new(display_map: ModelHandle<DisplayMap>, buffer: ModelHandle<MultiBuffer>) -> Self {
37 Self {
38 display_map,
39 buffer,
40 next_selection_id: 1,
41 line_mode: false,
42 disjoint: Arc::from([]),
43 pending: Some(PendingSelection {
44 selection: Selection {
45 id: 0,
46 start: Anchor::min(),
47 end: Anchor::min(),
48 reversed: false,
49 goal: SelectionGoal::None,
50 },
51 mode: SelectMode::Character,
52 }),
53 }
54 }
55
56 fn display_map(&self, cx: &mut MutableAppContext) -> DisplaySnapshot {
57 self.display_map.update(cx, |map, cx| map.snapshot(cx))
58 }
59
60 fn buffer<'a>(&self, cx: &'a AppContext) -> Ref<'a, MultiBufferSnapshot> {
61 self.buffer.read(cx).read(cx)
62 }
63
64 pub fn set_state(&mut self, other: &SelectionsCollection) {
65 self.next_selection_id = other.next_selection_id;
66 self.line_mode = other.line_mode;
67 self.disjoint = other.disjoint.clone();
68 self.pending = other.pending.clone();
69 }
70
71 pub fn count<'a>(&self) -> usize {
72 let mut count = self.disjoint.len();
73 if self.pending.is_some() {
74 count += 1;
75 }
76 count
77 }
78
79 pub fn disjoint_anchors(&self) -> Arc<[Selection<Anchor>]> {
80 self.disjoint.clone()
81 }
82
83 pub fn pending_anchor(&self) -> Option<Selection<Anchor>> {
84 self.pending
85 .as_ref()
86 .map(|pending| pending.selection.clone())
87 }
88
89 pub fn pending<D: TextDimension + Ord + Sub<D, Output = D>>(
90 &self,
91 cx: &AppContext,
92 ) -> Option<Selection<D>> {
93 self.pending_anchor()
94 .as_ref()
95 .map(|pending| pending.map(|p| p.summary::<D>(&self.buffer(cx))))
96 }
97
98 pub fn pending_mode(&self) -> Option<SelectMode> {
99 self.pending.as_ref().map(|pending| pending.mode.clone())
100 }
101
102 pub fn all<'a, D>(&self, cx: &AppContext) -> Vec<Selection<D>>
103 where
104 D: 'a + TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
105 {
106 let disjoint_anchors = &self.disjoint;
107 let mut disjoint =
108 resolve_multiple::<D, _>(disjoint_anchors.iter(), &self.buffer(cx)).peekable();
109
110 let mut pending_opt = self.pending::<D>(cx);
111
112 iter::from_fn(move || {
113 if let Some(pending) = pending_opt.as_mut() {
114 while let Some(next_selection) = disjoint.peek() {
115 if pending.start <= next_selection.end && pending.end >= next_selection.start {
116 let next_selection = disjoint.next().unwrap();
117 if next_selection.start < pending.start {
118 pending.start = next_selection.start;
119 }
120 if next_selection.end > pending.end {
121 pending.end = next_selection.end;
122 }
123 } else if next_selection.end < pending.start {
124 return disjoint.next();
125 } else {
126 break;
127 }
128 }
129
130 pending_opt.take()
131 } else {
132 disjoint.next()
133 }
134 })
135 .collect()
136 }
137
138 // Returns all of the selections, adjusted to take into account the selection line_mode
139 pub fn all_adjusted(&self, cx: &mut MutableAppContext) -> Vec<Selection<Point>> {
140 let mut selections = self.all::<Point>(cx);
141 if self.line_mode {
142 let map = self.display_map(cx);
143 for selection in &mut selections {
144 let new_range = map.expand_to_line(selection.range());
145 selection.start = new_range.start;
146 selection.end = new_range.end;
147 }
148 }
149 selections
150 }
151
152 pub fn all_adjusted_display(
153 &self,
154 cx: &mut MutableAppContext,
155 ) -> (DisplaySnapshot, Vec<Selection<DisplayPoint>>) {
156 if self.line_mode {
157 let selections = self.all::<Point>(cx);
158 let map = self.display_map(cx);
159 let result = selections
160 .into_iter()
161 .map(|mut selection| {
162 let new_range = map.expand_to_line(selection.range());
163 selection.start = new_range.start;
164 selection.end = new_range.end;
165 selection.map(|point| point.to_display_point(&map))
166 })
167 .collect();
168 (map, result)
169 } else {
170 self.all_display(cx)
171 }
172 }
173
174 pub fn disjoint_in_range<'a, D>(
175 &self,
176 range: Range<Anchor>,
177 cx: &AppContext,
178 ) -> Vec<Selection<D>>
179 where
180 D: 'a + TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
181 {
182 let buffer = self.buffer(cx);
183 let start_ix = match self
184 .disjoint
185 .binary_search_by(|probe| probe.end.cmp(&range.start, &buffer))
186 {
187 Ok(ix) | Err(ix) => ix,
188 };
189 let end_ix = match self
190 .disjoint
191 .binary_search_by(|probe| probe.start.cmp(&range.end, &buffer))
192 {
193 Ok(ix) => ix + 1,
194 Err(ix) => ix,
195 };
196 resolve_multiple(&self.disjoint[start_ix..end_ix], &buffer).collect()
197 }
198
199 pub fn all_display(
200 &self,
201 cx: &mut MutableAppContext,
202 ) -> (DisplaySnapshot, Vec<Selection<DisplayPoint>>) {
203 let display_map = self.display_map(cx);
204 let selections = self
205 .all::<Point>(cx)
206 .into_iter()
207 .map(|selection| selection.map(|point| point.to_display_point(&display_map)))
208 .collect();
209 (display_map, selections)
210 }
211
212 pub fn newest_anchor(&self) -> &Selection<Anchor> {
213 self.pending
214 .as_ref()
215 .map(|s| &s.selection)
216 .or_else(|| self.disjoint.iter().max_by_key(|s| s.id))
217 .unwrap()
218 }
219
220 pub fn newest<D: TextDimension + Ord + Sub<D, Output = D>>(
221 &self,
222 cx: &AppContext,
223 ) -> Selection<D> {
224 resolve(self.newest_anchor(), &self.buffer(cx))
225 }
226
227 pub fn newest_display(&self, cx: &mut MutableAppContext) -> Selection<DisplayPoint> {
228 let display_map = self.display_map(cx);
229 let selection = self
230 .newest_anchor()
231 .map(|point| point.to_display_point(&display_map));
232 selection
233 }
234
235 pub fn oldest_anchor(&self) -> &Selection<Anchor> {
236 self.disjoint
237 .iter()
238 .min_by_key(|s| s.id)
239 .or_else(|| self.pending.as_ref().map(|p| &p.selection))
240 .unwrap()
241 }
242
243 pub fn oldest<D: TextDimension + Ord + Sub<D, Output = D>>(
244 &self,
245 cx: &AppContext,
246 ) -> Selection<D> {
247 resolve(self.oldest_anchor(), &self.buffer(cx))
248 }
249
250 pub fn first<D: TextDimension + Ord + Sub<D, Output = D>>(
251 &self,
252 cx: &AppContext,
253 ) -> Selection<D> {
254 self.all(cx).first().unwrap().clone()
255 }
256
257 pub fn last<D: TextDimension + Ord + Sub<D, Output = D>>(
258 &self,
259 cx: &AppContext,
260 ) -> Selection<D> {
261 self.all(cx).last().unwrap().clone()
262 }
263
264 #[cfg(any(test, feature = "test-support"))]
265 pub fn ranges<D: TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug>(
266 &self,
267 cx: &AppContext,
268 ) -> Vec<Range<D>> {
269 self.all::<D>(cx)
270 .iter()
271 .map(|s| {
272 if s.reversed {
273 s.end.clone()..s.start.clone()
274 } else {
275 s.start.clone()..s.end.clone()
276 }
277 })
278 .collect()
279 }
280
281 #[cfg(any(test, feature = "test-support"))]
282 pub fn display_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
283 let display_map = self.display_map(cx);
284 self.disjoint_anchors()
285 .iter()
286 .chain(self.pending_anchor().as_ref())
287 .map(|s| {
288 if s.reversed {
289 s.end.to_display_point(&display_map)..s.start.to_display_point(&display_map)
290 } else {
291 s.start.to_display_point(&display_map)..s.end.to_display_point(&display_map)
292 }
293 })
294 .collect()
295 }
296
297 pub fn build_columnar_selection(
298 &mut self,
299 display_map: &DisplaySnapshot,
300 row: u32,
301 columns: &Range<u32>,
302 reversed: bool,
303 ) -> Option<Selection<Point>> {
304 let is_empty = columns.start == columns.end;
305 let line_len = display_map.line_len(row);
306 if columns.start < line_len || (is_empty && columns.start == line_len) {
307 let start = DisplayPoint::new(row, columns.start);
308 let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
309
310 Some(Selection {
311 id: post_inc(&mut self.next_selection_id),
312 start: start.to_point(display_map),
313 end: end.to_point(display_map),
314 reversed,
315 goal: SelectionGoal::ColumnRange {
316 start: columns.start,
317 end: columns.end,
318 },
319 })
320 } else {
321 None
322 }
323 }
324
325 pub(crate) fn change_with<R>(
326 &mut self,
327 cx: &mut MutableAppContext,
328 change: impl FnOnce(&mut MutableSelectionsCollection) -> R,
329 ) -> (bool, R) {
330 let mut mutable_collection = MutableSelectionsCollection {
331 collection: self,
332 selections_changed: false,
333 cx,
334 };
335
336 let result = change(&mut mutable_collection);
337 assert!(
338 !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
339 "There must be at least one selection"
340 );
341 (mutable_collection.selections_changed, result)
342 }
343}
344
345pub struct MutableSelectionsCollection<'a> {
346 collection: &'a mut SelectionsCollection,
347 selections_changed: bool,
348 cx: &'a mut MutableAppContext,
349}
350
351impl<'a> MutableSelectionsCollection<'a> {
352 fn display_map(&mut self) -> DisplaySnapshot {
353 self.collection.display_map(self.cx)
354 }
355
356 fn buffer(&self) -> Ref<MultiBufferSnapshot> {
357 self.collection.buffer(self.cx)
358 }
359
360 pub fn clear_disjoint(&mut self) {
361 self.collection.disjoint = Arc::from([]);
362 }
363
364 pub fn delete(&mut self, selection_id: usize) {
365 let mut changed = false;
366 self.collection.disjoint = self
367 .disjoint
368 .into_iter()
369 .filter(|selection| {
370 let found = selection.id == selection_id;
371 changed |= found;
372 !found
373 })
374 .cloned()
375 .collect();
376
377 self.selections_changed |= changed;
378 }
379
380 pub fn clear_pending(&mut self) {
381 if self.collection.pending.is_some() {
382 self.collection.pending = None;
383 self.selections_changed = true;
384 }
385 }
386
387 pub fn set_pending_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
388 self.collection.pending = Some(PendingSelection {
389 selection: Selection {
390 id: post_inc(&mut self.collection.next_selection_id),
391 start: range.start,
392 end: range.end,
393 reversed: false,
394 goal: SelectionGoal::None,
395 },
396 mode,
397 });
398 self.selections_changed = true;
399 }
400
401 pub fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
402 self.collection.pending = Some(PendingSelection { selection, mode });
403 self.selections_changed = true;
404 }
405
406 pub fn try_cancel(&mut self) -> bool {
407 if let Some(pending) = self.collection.pending.take() {
408 if self.disjoint.is_empty() {
409 self.collection.disjoint = Arc::from([pending.selection]);
410 }
411 self.selections_changed = true;
412 return true;
413 }
414
415 let mut oldest = self.oldest_anchor().clone();
416 if self.count() > 1 {
417 self.collection.disjoint = Arc::from([oldest]);
418 self.selections_changed = true;
419 return true;
420 }
421
422 if !oldest.start.cmp(&oldest.end, &self.buffer()).is_eq() {
423 let head = oldest.head();
424 oldest.start = head.clone();
425 oldest.end = head;
426 self.collection.disjoint = Arc::from([oldest]);
427 self.selections_changed = true;
428 return true;
429 }
430
431 return false;
432 }
433
434 pub fn insert_range<T>(&mut self, range: Range<T>)
435 where
436 T: 'a + ToOffset + ToPoint + TextDimension + Ord + Sub<T, Output = T> + std::marker::Copy,
437 {
438 let mut selections = self.all(self.cx);
439 let mut start = range.start.to_offset(&self.buffer());
440 let mut end = range.end.to_offset(&self.buffer());
441 let reversed = if start > end {
442 mem::swap(&mut start, &mut end);
443 true
444 } else {
445 false
446 };
447 selections.push(Selection {
448 id: post_inc(&mut self.collection.next_selection_id),
449 start,
450 end,
451 reversed,
452 goal: SelectionGoal::None,
453 });
454 self.select(selections);
455 }
456
457 pub fn select<T>(&mut self, mut selections: Vec<Selection<T>>)
458 where
459 T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
460 {
461 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
462 selections.sort_unstable_by_key(|s| s.start);
463 // Merge overlapping selections.
464 let mut i = 1;
465 while i < selections.len() {
466 if selections[i - 1].end >= selections[i].start {
467 let removed = selections.remove(i);
468 if removed.start < selections[i - 1].start {
469 selections[i - 1].start = removed.start;
470 }
471 if removed.end > selections[i - 1].end {
472 selections[i - 1].end = removed.end;
473 }
474 } else {
475 i += 1;
476 }
477 }
478
479 self.collection.disjoint = Arc::from_iter(selections.into_iter().map(|selection| {
480 let end_bias = if selection.end > selection.start {
481 Bias::Left
482 } else {
483 Bias::Right
484 };
485 Selection {
486 id: selection.id,
487 start: buffer.anchor_after(selection.start),
488 end: buffer.anchor_at(selection.end, end_bias),
489 reversed: selection.reversed,
490 goal: selection.goal,
491 }
492 }));
493
494 self.collection.pending = None;
495 self.selections_changed = true;
496 }
497
498 pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
499 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
500 let resolved_selections =
501 resolve_multiple::<usize, _>(&selections, &buffer).collect::<Vec<_>>();
502 self.select(resolved_selections);
503 }
504
505 pub fn select_ranges<I, T>(&mut self, ranges: I)
506 where
507 I: IntoIterator<Item = Range<T>>,
508 T: ToOffset,
509 {
510 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
511 let selections = ranges
512 .into_iter()
513 .map(|range| {
514 let mut start = range.start.to_offset(&buffer);
515 let mut end = range.end.to_offset(&buffer);
516 let reversed = if start > end {
517 mem::swap(&mut start, &mut end);
518 true
519 } else {
520 false
521 };
522 Selection {
523 id: post_inc(&mut self.collection.next_selection_id),
524 start,
525 end,
526 reversed,
527 goal: SelectionGoal::None,
528 }
529 })
530 .collect::<Vec<_>>();
531
532 self.select(selections)
533 }
534
535 pub fn select_anchor_ranges<I: IntoIterator<Item = Range<Anchor>>>(&mut self, ranges: I) {
536 let buffer = self.buffer.read(self.cx).snapshot(self.cx);
537 let selections = ranges
538 .into_iter()
539 .map(|range| {
540 let mut start = range.start;
541 let mut end = range.end;
542 let reversed = if start.cmp(&end, &buffer).is_gt() {
543 mem::swap(&mut start, &mut end);
544 true
545 } else {
546 false
547 };
548 Selection {
549 id: post_inc(&mut self.collection.next_selection_id),
550 start,
551 end,
552 reversed,
553 goal: SelectionGoal::None,
554 }
555 })
556 .collect::<Vec<_>>();
557
558 self.select_anchors(selections)
559 }
560
561 #[cfg(any(test, feature = "test-support"))]
562 pub fn select_display_ranges<T>(&mut self, ranges: T)
563 where
564 T: IntoIterator<Item = Range<DisplayPoint>>,
565 {
566 let display_map = self.display_map();
567 let selections = ranges
568 .into_iter()
569 .map(|range| {
570 let mut start = range.start;
571 let mut end = range.end;
572 let reversed = if start > end {
573 mem::swap(&mut start, &mut end);
574 true
575 } else {
576 false
577 };
578 Selection {
579 id: post_inc(&mut self.collection.next_selection_id),
580 start: start.to_point(&display_map),
581 end: end.to_point(&display_map),
582 reversed,
583 goal: SelectionGoal::None,
584 }
585 })
586 .collect();
587 self.select(selections);
588 }
589
590 pub fn move_with(
591 &mut self,
592 mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
593 ) {
594 let mut changed = false;
595 let display_map = self.display_map();
596 let selections = self
597 .all::<Point>(self.cx)
598 .into_iter()
599 .map(|selection| {
600 let mut moved_selection =
601 selection.map(|point| point.to_display_point(&display_map));
602 move_selection(&display_map, &mut moved_selection);
603 let moved_selection =
604 moved_selection.map(|display_point| display_point.to_point(&display_map));
605 if selection != moved_selection {
606 changed = true;
607 }
608 moved_selection
609 })
610 .collect();
611
612 if changed {
613 self.select(selections)
614 }
615 }
616
617 pub fn move_heads_with(
618 &mut self,
619 mut update_head: impl FnMut(
620 &DisplaySnapshot,
621 DisplayPoint,
622 SelectionGoal,
623 ) -> (DisplayPoint, SelectionGoal),
624 ) {
625 self.move_with(|map, selection| {
626 let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
627 selection.set_head(new_head, new_goal);
628 });
629 }
630
631 pub fn move_cursors_with(
632 &mut self,
633 mut update_cursor_position: impl FnMut(
634 &DisplaySnapshot,
635 DisplayPoint,
636 SelectionGoal,
637 ) -> (DisplayPoint, SelectionGoal),
638 ) {
639 self.move_with(|map, selection| {
640 let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
641 selection.collapse_to(cursor, new_goal)
642 });
643 }
644
645 pub fn replace_cursors_with(
646 &mut self,
647 mut find_replacement_cursors: impl FnMut(&DisplaySnapshot) -> Vec<DisplayPoint>,
648 ) {
649 let display_map = self.display_map();
650 let new_selections = find_replacement_cursors(&display_map)
651 .into_iter()
652 .map(|cursor| {
653 let cursor_point = cursor.to_point(&display_map);
654 Selection {
655 id: post_inc(&mut self.collection.next_selection_id),
656 start: cursor_point,
657 end: cursor_point,
658 reversed: false,
659 goal: SelectionGoal::None,
660 }
661 })
662 .collect();
663 self.select(new_selections);
664 }
665
666 /// Compute new ranges for any selections that were located in excerpts that have
667 /// since been removed.
668 ///
669 /// Returns a `HashMap` indicating which selections whose former head position
670 /// was no longer present. The keys of the map are selection ids. The values are
671 /// the id of the new excerpt where the head of the selection has been moved.
672 pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
673 let mut pending = self.collection.pending.take();
674 let mut selections_with_lost_position = HashMap::default();
675
676 let anchors_with_status = {
677 let buffer = self.buffer();
678 let disjoint_anchors = self
679 .disjoint
680 .iter()
681 .flat_map(|selection| [&selection.start, &selection.end]);
682 buffer.refresh_anchors(disjoint_anchors)
683 };
684 let adjusted_disjoint: Vec<_> = anchors_with_status
685 .chunks(2)
686 .map(|selection_anchors| {
687 let (anchor_ix, start, kept_start) = selection_anchors[0].clone();
688 let (_, end, kept_end) = selection_anchors[1].clone();
689 let selection = &self.disjoint[anchor_ix / 2];
690 let kept_head = if selection.reversed {
691 kept_start
692 } else {
693 kept_end
694 };
695 if !kept_head {
696 selections_with_lost_position
697 .insert(selection.id, selection.head().excerpt_id.clone());
698 }
699
700 Selection {
701 id: selection.id,
702 start,
703 end,
704 reversed: selection.reversed,
705 goal: selection.goal,
706 }
707 })
708 .collect();
709
710 if !adjusted_disjoint.is_empty() {
711 let resolved_selections =
712 resolve_multiple(adjusted_disjoint.iter(), &self.buffer()).collect();
713 self.select::<usize>(resolved_selections);
714 }
715
716 if let Some(pending) = pending.as_mut() {
717 let buffer = self.buffer();
718 let anchors =
719 buffer.refresh_anchors([&pending.selection.start, &pending.selection.end]);
720 let (_, start, kept_start) = anchors[0].clone();
721 let (_, end, kept_end) = anchors[1].clone();
722 let kept_head = if pending.selection.reversed {
723 kept_start
724 } else {
725 kept_end
726 };
727 if !kept_head {
728 selections_with_lost_position.insert(
729 pending.selection.id,
730 pending.selection.head().excerpt_id.clone(),
731 );
732 }
733
734 pending.selection.start = start;
735 pending.selection.end = end;
736 }
737 self.collection.pending = pending;
738 self.selections_changed = true;
739
740 selections_with_lost_position
741 }
742}
743
744impl<'a> Deref for MutableSelectionsCollection<'a> {
745 type Target = SelectionsCollection;
746 fn deref(&self) -> &Self::Target {
747 self.collection
748 }
749}
750
751// Panics if passed selections are not in order
752pub fn resolve_multiple<'a, D, I>(
753 selections: I,
754 snapshot: &MultiBufferSnapshot,
755) -> impl 'a + Iterator<Item = Selection<D>>
756where
757 D: TextDimension + Ord + Sub<D, Output = D> + std::fmt::Debug,
758 I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
759{
760 let (to_summarize, selections) = selections.into_iter().tee();
761 let mut summaries = snapshot
762 .summaries_for_anchors::<D, _>(
763 to_summarize
764 .flat_map(|s| [&s.start, &s.end])
765 .collect::<Vec<_>>(),
766 )
767 .into_iter();
768 selections.map(move |s| Selection {
769 id: s.id,
770 start: summaries.next().unwrap(),
771 end: summaries.next().unwrap(),
772 reversed: s.reversed,
773 goal: s.goal,
774 })
775}
776
777fn resolve<D: TextDimension + Ord + Sub<D, Output = D>>(
778 selection: &Selection<Anchor>,
779 buffer: &MultiBufferSnapshot,
780) -> Selection<D> {
781 selection.map(|p| p.summary::<D>(&buffer))
782}