selections_collection.rs

   1use std::{
   2    cmp, fmt, iter, mem,
   3    ops::{AddAssign, Deref, DerefMut, Range, Sub},
   4    sync::Arc,
   5};
   6
   7use collections::HashMap;
   8use gpui::Pixels;
   9use itertools::Itertools as _;
  10use language::{Bias, Point, Selection, SelectionGoal};
  11use multi_buffer::{MultiBufferDimension, MultiBufferOffset};
  12use util::post_inc;
  13
  14use crate::{
  15    Anchor, DisplayPoint, DisplayRow, ExcerptId, MultiBufferSnapshot, SelectMode, ToOffset,
  16    display_map::{DisplaySnapshot, ToDisplayPoint},
  17    movement::TextLayoutDetails,
  18};
  19
  20#[derive(Debug, Clone)]
  21pub struct PendingSelection {
  22    selection: Selection<Anchor>,
  23    mode: SelectMode,
  24}
  25
  26#[derive(Debug, Clone)]
  27pub struct SelectionsCollection {
  28    next_selection_id: usize,
  29    line_mode: bool,
  30    /// The non-pending, non-overlapping selections.
  31    /// The [SelectionsCollection::pending] selection could possibly overlap these
  32    disjoint: Arc<[Selection<Anchor>]>,
  33    /// A pending selection, such as when the mouse is being dragged
  34    pending: Option<PendingSelection>,
  35    select_mode: SelectMode,
  36    is_extending: bool,
  37}
  38
  39impl SelectionsCollection {
  40    pub fn new() -> Self {
  41        Self {
  42            next_selection_id: 1,
  43            line_mode: false,
  44            disjoint: Arc::default(),
  45            pending: Some(PendingSelection {
  46                selection: Selection {
  47                    id: 0,
  48                    start: Anchor::min(),
  49                    end: Anchor::min(),
  50                    reversed: false,
  51                    goal: SelectionGoal::None,
  52                },
  53                mode: SelectMode::Character,
  54            }),
  55            select_mode: SelectMode::Character,
  56            is_extending: false,
  57        }
  58    }
  59
  60    pub fn clone_state(&mut self, other: &SelectionsCollection) {
  61        self.next_selection_id = other.next_selection_id;
  62        self.line_mode = other.line_mode;
  63        self.disjoint = other.disjoint.clone();
  64        self.pending.clone_from(&other.pending);
  65    }
  66
  67    pub fn count(&self) -> usize {
  68        let mut count = self.disjoint.len();
  69        if self.pending.is_some() {
  70            count += 1;
  71        }
  72        count
  73    }
  74
  75    /// The non-pending, non-overlapping selections. There could be a pending selection that
  76    /// overlaps these if the mouse is being dragged, etc. This could also be empty if there is a
  77    /// pending selection. Returned as selections over Anchors.
  78    pub fn disjoint_anchors_arc(&self) -> Arc<[Selection<Anchor>]> {
  79        self.disjoint.clone()
  80    }
  81
  82    /// The non-pending, non-overlapping selections. There could be a pending selection that
  83    /// overlaps these if the mouse is being dragged, etc. This could also be empty if there is a
  84    /// pending selection. Returned as selections over Anchors.
  85    pub fn disjoint_anchors(&self) -> &[Selection<Anchor>] {
  86        &self.disjoint
  87    }
  88
  89    pub fn disjoint_anchor_ranges(&self) -> impl Iterator<Item = Range<Anchor>> {
  90        // Mapping the Arc slice would borrow it, whereas indexing captures it.
  91        let disjoint = self.disjoint_anchors_arc();
  92        (0..disjoint.len()).map(move |ix| disjoint[ix].range())
  93    }
  94
  95    /// Non-overlapping selections using anchors, including the pending selection.
  96    pub fn all_anchors(&self, snapshot: &DisplaySnapshot) -> Arc<[Selection<Anchor>]> {
  97        if self.pending.is_none() {
  98            self.disjoint_anchors_arc()
  99        } else {
 100            let all_offset_selections = self.all::<MultiBufferOffset>(snapshot);
 101            all_offset_selections
 102                .into_iter()
 103                .map(|selection| selection_to_anchor_selection(selection, snapshot))
 104                .collect()
 105        }
 106    }
 107
 108    pub fn pending_anchor(&self) -> Option<&Selection<Anchor>> {
 109        self.pending.as_ref().map(|pending| &pending.selection)
 110    }
 111
 112    pub fn pending_anchor_mut(&mut self) -> Option<&mut Selection<Anchor>> {
 113        self.pending.as_mut().map(|pending| &mut pending.selection)
 114    }
 115
 116    pub fn pending<D>(&self, snapshot: &DisplaySnapshot) -> Option<Selection<D>>
 117    where
 118        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 119    {
 120        resolve_selections_wrapping_blocks(self.pending_anchor(), &snapshot).next()
 121    }
 122
 123    pub(crate) fn pending_mode(&self) -> Option<SelectMode> {
 124        self.pending.as_ref().map(|pending| pending.mode.clone())
 125    }
 126
 127    pub fn all<D>(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<D>>
 128    where
 129        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 130    {
 131        let disjoint_anchors = &self.disjoint;
 132        let mut disjoint =
 133            resolve_selections_wrapping_blocks::<D, _>(disjoint_anchors.iter(), &snapshot)
 134                .peekable();
 135        let mut pending_opt = self.pending::<D>(&snapshot);
 136        iter::from_fn(move || {
 137            if let Some(pending) = pending_opt.as_mut() {
 138                while let Some(next_selection) = disjoint.peek() {
 139                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
 140                        let next_selection = disjoint.next().unwrap();
 141                        if next_selection.start < pending.start {
 142                            pending.start = next_selection.start;
 143                        }
 144                        if next_selection.end > pending.end {
 145                            pending.end = next_selection.end;
 146                        }
 147                    } else if next_selection.end < pending.start {
 148                        return disjoint.next();
 149                    } else {
 150                        break;
 151                    }
 152                }
 153
 154                pending_opt.take()
 155            } else {
 156                disjoint.next()
 157            }
 158        })
 159        .collect()
 160    }
 161
 162    /// Returns all of the selections, adjusted to take into account the selection line_mode
 163    pub fn all_adjusted(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<Point>> {
 164        let mut selections = self.all::<Point>(&snapshot);
 165        if self.line_mode {
 166            for selection in &mut selections {
 167                let new_range = snapshot.expand_to_line(selection.range());
 168                selection.start = new_range.start;
 169                selection.end = new_range.end;
 170            }
 171        }
 172        selections
 173    }
 174
 175    /// Returns the newest selection, adjusted to take into account the selection line_mode
 176    pub fn newest_adjusted(&self, snapshot: &DisplaySnapshot) -> Selection<Point> {
 177        let mut selection = self.newest::<Point>(&snapshot);
 178        if self.line_mode {
 179            let new_range = snapshot.expand_to_line(selection.range());
 180            selection.start = new_range.start;
 181            selection.end = new_range.end;
 182        }
 183        selection
 184    }
 185
 186    pub fn all_adjusted_display(
 187        &self,
 188        display_map: &DisplaySnapshot,
 189    ) -> Vec<Selection<DisplayPoint>> {
 190        if self.line_mode {
 191            let selections = self.all::<Point>(&display_map);
 192            let result = selections
 193                .into_iter()
 194                .map(|mut selection| {
 195                    let new_range = display_map.expand_to_line(selection.range());
 196                    selection.start = new_range.start;
 197                    selection.end = new_range.end;
 198                    selection.map(|point| point.to_display_point(&display_map))
 199                })
 200                .collect();
 201            result
 202        } else {
 203            self.all_display(display_map)
 204        }
 205    }
 206
 207    pub fn disjoint_in_range<D>(
 208        &self,
 209        range: Range<Anchor>,
 210        snapshot: &DisplaySnapshot,
 211    ) -> Vec<Selection<D>>
 212    where
 213        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord + std::fmt::Debug,
 214    {
 215        let start_ix = match self
 216            .disjoint
 217            .binary_search_by(|probe| probe.end.cmp(&range.start, snapshot.buffer_snapshot()))
 218        {
 219            Ok(ix) | Err(ix) => ix,
 220        };
 221        let end_ix = match self
 222            .disjoint
 223            .binary_search_by(|probe| probe.start.cmp(&range.end, snapshot.buffer_snapshot()))
 224        {
 225            Ok(ix) => ix + 1,
 226            Err(ix) => ix,
 227        };
 228        resolve_selections_wrapping_blocks(&self.disjoint[start_ix..end_ix], snapshot).collect()
 229    }
 230
 231    pub fn all_display(&self, snapshot: &DisplaySnapshot) -> Vec<Selection<DisplayPoint>> {
 232        let disjoint_anchors = &self.disjoint;
 233        let mut disjoint =
 234            resolve_selections_display(disjoint_anchors.iter(), &snapshot).peekable();
 235        let mut pending_opt = resolve_selections_display(self.pending_anchor(), &snapshot).next();
 236        iter::from_fn(move || {
 237            if let Some(pending) = pending_opt.as_mut() {
 238                while let Some(next_selection) = disjoint.peek() {
 239                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
 240                        let next_selection = disjoint.next().unwrap();
 241                        if next_selection.start < pending.start {
 242                            pending.start = next_selection.start;
 243                        }
 244                        if next_selection.end > pending.end {
 245                            pending.end = next_selection.end;
 246                        }
 247                    } else if next_selection.end < pending.start {
 248                        return disjoint.next();
 249                    } else {
 250                        break;
 251                    }
 252                }
 253
 254                pending_opt.take()
 255            } else {
 256                disjoint.next()
 257            }
 258        })
 259        .collect()
 260    }
 261
 262    pub fn newest_anchor(&self) -> &Selection<Anchor> {
 263        self.pending
 264            .as_ref()
 265            .map(|s| &s.selection)
 266            .or_else(|| self.disjoint.iter().max_by_key(|s| s.id))
 267            .unwrap()
 268    }
 269
 270    pub fn newest<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 271    where
 272        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 273    {
 274        resolve_selections_wrapping_blocks([self.newest_anchor()], &snapshot)
 275            .next()
 276            .unwrap()
 277    }
 278
 279    pub fn newest_display(&self, snapshot: &DisplaySnapshot) -> Selection<DisplayPoint> {
 280        resolve_selections_display([self.newest_anchor()], &snapshot)
 281            .next()
 282            .unwrap()
 283    }
 284
 285    pub fn oldest_anchor(&self) -> &Selection<Anchor> {
 286        self.disjoint
 287            .iter()
 288            .min_by_key(|s| s.id)
 289            .or_else(|| self.pending.as_ref().map(|p| &p.selection))
 290            .unwrap()
 291    }
 292
 293    pub fn oldest<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 294    where
 295        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 296    {
 297        resolve_selections_wrapping_blocks([self.oldest_anchor()], &snapshot)
 298            .next()
 299            .unwrap()
 300    }
 301
 302    pub fn first_anchor(&self) -> Selection<Anchor> {
 303        self.pending
 304            .as_ref()
 305            .map(|pending| pending.selection.clone())
 306            .unwrap_or_else(|| self.disjoint.first().cloned().unwrap())
 307    }
 308
 309    pub fn first<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 310    where
 311        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 312    {
 313        self.all(snapshot).first().unwrap().clone()
 314    }
 315
 316    pub fn last<D>(&self, snapshot: &DisplaySnapshot) -> Selection<D>
 317    where
 318        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 319    {
 320        self.all(snapshot).last().unwrap().clone()
 321    }
 322
 323    /// Returns a list of (potentially backwards!) ranges representing the selections.
 324    /// Useful for test assertions, but prefer `.all()` instead.
 325    #[cfg(any(test, feature = "test-support"))]
 326    pub fn ranges<D>(&self, snapshot: &DisplaySnapshot) -> Vec<Range<D>>
 327    where
 328        D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
 329    {
 330        self.all::<D>(snapshot)
 331            .iter()
 332            .map(|s| {
 333                if s.reversed {
 334                    s.end..s.start
 335                } else {
 336                    s.start..s.end
 337                }
 338            })
 339            .collect()
 340    }
 341
 342    #[cfg(any(test, feature = "test-support"))]
 343    pub fn display_ranges(&self, display_snapshot: &DisplaySnapshot) -> Vec<Range<DisplayPoint>> {
 344        self.disjoint_anchors_arc()
 345            .iter()
 346            .chain(self.pending_anchor())
 347            .map(|s| {
 348                if s.reversed {
 349                    s.end.to_display_point(display_snapshot)
 350                        ..s.start.to_display_point(display_snapshot)
 351                } else {
 352                    s.start.to_display_point(display_snapshot)
 353                        ..s.end.to_display_point(display_snapshot)
 354                }
 355            })
 356            .collect()
 357    }
 358
 359    /// Attempts to build a selection in the provided `DisplayRow` within the
 360    /// same range as the provided range of `Pixels`.
 361    /// Returns `None` if the range is not empty but it starts past the line's
 362    /// length, meaning that the line isn't long enough to be contained within
 363    /// part of the provided range.
 364    pub fn build_columnar_selection(
 365        &mut self,
 366        display_map: &DisplaySnapshot,
 367        row: DisplayRow,
 368        positions: &Range<Pixels>,
 369        reversed: bool,
 370        text_layout_details: &TextLayoutDetails,
 371    ) -> Option<Selection<Point>> {
 372        let is_empty = positions.start == positions.end;
 373        let line_len = display_map.line_len(row);
 374        let line = display_map.layout_row(row, text_layout_details);
 375        let start_col = line.closest_index_for_x(positions.start) as u32;
 376
 377        let (start, end) = if is_empty {
 378            let point = DisplayPoint::new(row, std::cmp::min(start_col, line_len));
 379            (point, point)
 380        } else {
 381            if start_col >= line_len {
 382                return None;
 383            }
 384            let start = DisplayPoint::new(row, start_col);
 385            let end_col = line.closest_index_for_x(positions.end) as u32;
 386            let end = DisplayPoint::new(row, end_col);
 387            (start, end)
 388        };
 389
 390        Some(Selection {
 391            id: post_inc(&mut self.next_selection_id),
 392            start: start.to_point(display_map),
 393            end: end.to_point(display_map),
 394            reversed,
 395            goal: SelectionGoal::HorizontalRange {
 396                start: positions.start.into(),
 397                end: positions.end.into(),
 398            },
 399        })
 400    }
 401
 402    pub fn change_with<R>(
 403        &mut self,
 404        snapshot: &DisplaySnapshot,
 405        change: impl FnOnce(&mut MutableSelectionsCollection<'_, '_>) -> R,
 406    ) -> (bool, R) {
 407        let mut mutable_collection = MutableSelectionsCollection {
 408            snapshot,
 409            collection: self,
 410            selections_changed: false,
 411        };
 412
 413        let result = change(&mut mutable_collection);
 414        assert!(
 415            !mutable_collection.disjoint.is_empty() || mutable_collection.pending.is_some(),
 416            "There must be at least one selection"
 417        );
 418        if cfg!(debug_assertions) {
 419            mutable_collection.disjoint.iter().for_each(|selection| {
 420                assert!(
 421                    snapshot.can_resolve(&selection.start),
 422                    "disjoint selection start is not resolvable for the given snapshot:\n{selection:?}, {excerpt:?}",
 423                    excerpt = snapshot.buffer_for_excerpt(selection.start.excerpt_id).map(|snapshot| snapshot.remote_id()),
 424                );
 425                assert!(
 426                    snapshot.can_resolve(&selection.end),
 427                    "disjoint selection end is not resolvable for the given snapshot: {selection:?}, {excerpt:?}",
 428                    excerpt = snapshot.buffer_for_excerpt(selection.end.excerpt_id).map(|snapshot| snapshot.remote_id()),
 429                );
 430            });
 431            if let Some(pending) = &mutable_collection.pending {
 432                let selection = &pending.selection;
 433                assert!(
 434                    snapshot.can_resolve(&selection.start),
 435                    "pending selection start is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
 436                    excerpt = snapshot
 437                        .buffer_for_excerpt(selection.start.excerpt_id)
 438                        .map(|snapshot| snapshot.remote_id()),
 439                );
 440                assert!(
 441                    snapshot.can_resolve(&selection.end),
 442                    "pending selection end is not resolvable for the given snapshot: {pending:?}, {excerpt:?}",
 443                    excerpt = snapshot
 444                        .buffer_for_excerpt(selection.end.excerpt_id)
 445                        .map(|snapshot| snapshot.remote_id()),
 446                );
 447            }
 448        }
 449        (mutable_collection.selections_changed, result)
 450    }
 451
 452    pub fn next_selection_id(&self) -> usize {
 453        self.next_selection_id
 454    }
 455
 456    pub fn line_mode(&self) -> bool {
 457        self.line_mode
 458    }
 459
 460    pub fn set_line_mode(&mut self, line_mode: bool) {
 461        self.line_mode = line_mode;
 462    }
 463
 464    pub fn select_mode(&self) -> &SelectMode {
 465        &self.select_mode
 466    }
 467
 468    pub fn set_select_mode(&mut self, select_mode: SelectMode) {
 469        self.select_mode = select_mode;
 470    }
 471
 472    pub fn is_extending(&self) -> bool {
 473        self.is_extending
 474    }
 475
 476    pub fn set_is_extending(&mut self, is_extending: bool) {
 477        self.is_extending = is_extending;
 478    }
 479}
 480
 481pub struct MutableSelectionsCollection<'snap, 'a> {
 482    collection: &'a mut SelectionsCollection,
 483    snapshot: &'snap DisplaySnapshot,
 484    selections_changed: bool,
 485}
 486
 487impl<'snap, 'a> fmt::Debug for MutableSelectionsCollection<'snap, 'a> {
 488    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 489        f.debug_struct("MutableSelectionsCollection")
 490            .field("collection", &self.collection)
 491            .field("selections_changed", &self.selections_changed)
 492            .finish()
 493    }
 494}
 495
 496impl<'snap, 'a> MutableSelectionsCollection<'snap, 'a> {
 497    pub fn display_snapshot(&self) -> DisplaySnapshot {
 498        self.snapshot.clone()
 499    }
 500
 501    pub fn clear_disjoint(&mut self) {
 502        self.collection.disjoint = Arc::default();
 503    }
 504
 505    pub fn delete(&mut self, selection_id: usize) {
 506        let mut changed = false;
 507        self.collection.disjoint = self
 508            .disjoint
 509            .iter()
 510            .filter(|selection| {
 511                let found = selection.id == selection_id;
 512                changed |= found;
 513                !found
 514            })
 515            .cloned()
 516            .collect();
 517
 518        self.selections_changed |= changed;
 519    }
 520
 521    pub fn remove_selections_from_buffer(&mut self, buffer_id: language::BufferId) {
 522        let mut changed = false;
 523
 524        let filtered_selections: Arc<[Selection<Anchor>]> = {
 525            self.disjoint
 526                .iter()
 527                .filter(|selection| {
 528                    if let Some(selection_buffer_id) =
 529                        self.snapshot.buffer_id_for_anchor(selection.start)
 530                    {
 531                        let should_remove = selection_buffer_id == buffer_id;
 532                        changed |= should_remove;
 533                        !should_remove
 534                    } else {
 535                        true
 536                    }
 537                })
 538                .cloned()
 539                .collect()
 540        };
 541
 542        if filtered_selections.is_empty() {
 543            let default_anchor = self.snapshot.anchor_before(MultiBufferOffset(0));
 544            self.collection.disjoint = Arc::from([Selection {
 545                id: post_inc(&mut self.collection.next_selection_id),
 546                start: default_anchor,
 547                end: default_anchor,
 548                reversed: false,
 549                goal: SelectionGoal::None,
 550            }]);
 551        } else {
 552            self.collection.disjoint = filtered_selections;
 553        }
 554
 555        self.selections_changed |= changed;
 556    }
 557
 558    pub fn clear_pending(&mut self) {
 559        if self.collection.pending.is_some() {
 560            self.collection.pending = None;
 561            self.selections_changed = true;
 562        }
 563    }
 564
 565    pub(crate) fn set_pending_anchor_range(&mut self, range: Range<Anchor>, mode: SelectMode) {
 566        self.collection.pending = Some(PendingSelection {
 567            selection: {
 568                let mut start = range.start;
 569                let mut end = range.end;
 570                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 571                    mem::swap(&mut start, &mut end);
 572                    true
 573                } else {
 574                    false
 575                };
 576                Selection {
 577                    id: post_inc(&mut self.collection.next_selection_id),
 578                    start,
 579                    end,
 580                    reversed,
 581                    goal: SelectionGoal::None,
 582                }
 583            },
 584            mode,
 585        });
 586        self.selections_changed = true;
 587    }
 588
 589    pub(crate) fn set_pending(&mut self, selection: Selection<Anchor>, mode: SelectMode) {
 590        self.collection.pending = Some(PendingSelection { selection, mode });
 591        self.selections_changed = true;
 592    }
 593
 594    pub fn try_cancel(&mut self) -> bool {
 595        if let Some(pending) = self.collection.pending.take() {
 596            if self.disjoint.is_empty() {
 597                self.collection.disjoint = Arc::from([pending.selection]);
 598            }
 599            self.selections_changed = true;
 600            return true;
 601        }
 602
 603        let mut oldest = self.oldest_anchor().clone();
 604        if self.count() > 1 {
 605            self.collection.disjoint = Arc::from([oldest]);
 606            self.selections_changed = true;
 607            return true;
 608        }
 609
 610        if !oldest.start.cmp(&oldest.end, self.snapshot).is_eq() {
 611            let head = oldest.head();
 612            oldest.start = head;
 613            oldest.end = head;
 614            self.collection.disjoint = Arc::from([oldest]);
 615            self.selections_changed = true;
 616            return true;
 617        }
 618
 619        false
 620    }
 621
 622    pub fn insert_range<T>(&mut self, range: Range<T>)
 623    where
 624        T: ToOffset,
 625    {
 626        let display_map = self.display_snapshot();
 627        let mut selections = self.collection.all(&display_map);
 628        let mut start = range.start.to_offset(self.snapshot);
 629        let mut end = range.end.to_offset(self.snapshot);
 630        let reversed = if start > end {
 631            mem::swap(&mut start, &mut end);
 632            true
 633        } else {
 634            false
 635        };
 636        selections.push(Selection {
 637            id: post_inc(&mut self.collection.next_selection_id),
 638            start,
 639            end,
 640            reversed,
 641            goal: SelectionGoal::None,
 642        });
 643        self.select(selections);
 644    }
 645
 646    pub fn select<T>(&mut self, selections: Vec<Selection<T>>)
 647    where
 648        T: ToOffset + std::marker::Copy + std::fmt::Debug,
 649    {
 650        let mut selections = selections
 651            .into_iter()
 652            .map(|selection| selection.map(|it| it.to_offset(self.snapshot)))
 653            .map(|mut selection| {
 654                if selection.start > selection.end {
 655                    mem::swap(&mut selection.start, &mut selection.end);
 656                    selection.reversed = true
 657                }
 658                selection
 659            })
 660            .collect::<Vec<_>>();
 661        selections.sort_unstable_by_key(|s| s.start);
 662        // Merge overlapping selections.
 663        let mut i = 1;
 664        while i < selections.len() {
 665            if selections[i].start <= selections[i - 1].end {
 666                let removed = selections.remove(i);
 667                if removed.start < selections[i - 1].start {
 668                    selections[i - 1].start = removed.start;
 669                }
 670                if selections[i - 1].end < removed.end {
 671                    selections[i - 1].end = removed.end;
 672                }
 673            } else {
 674                i += 1;
 675            }
 676        }
 677
 678        self.collection.disjoint = Arc::from_iter(
 679            selections
 680                .into_iter()
 681                .map(|selection| selection_to_anchor_selection(selection, self.snapshot)),
 682        );
 683        self.collection.pending = None;
 684        self.selections_changed = true;
 685    }
 686
 687    pub fn select_anchors(&mut self, selections: Vec<Selection<Anchor>>) {
 688        let map = self.display_snapshot();
 689        let resolved_selections =
 690            resolve_selections_wrapping_blocks::<MultiBufferOffset, _>(&selections, &map)
 691                .collect::<Vec<_>>();
 692        self.select(resolved_selections);
 693    }
 694
 695    pub fn select_ranges<I, T>(&mut self, ranges: I)
 696    where
 697        I: IntoIterator<Item = Range<T>>,
 698        T: ToOffset,
 699    {
 700        let ranges = ranges
 701            .into_iter()
 702            .map(|range| range.start.to_offset(self.snapshot)..range.end.to_offset(self.snapshot));
 703        self.select_offset_ranges(ranges);
 704    }
 705
 706    fn select_offset_ranges<I>(&mut self, ranges: I)
 707    where
 708        I: IntoIterator<Item = Range<MultiBufferOffset>>,
 709    {
 710        let selections = ranges
 711            .into_iter()
 712            .map(|range| {
 713                let mut start = range.start;
 714                let mut end = range.end;
 715                let reversed = if start > end {
 716                    mem::swap(&mut start, &mut end);
 717                    true
 718                } else {
 719                    false
 720                };
 721                Selection {
 722                    id: post_inc(&mut self.collection.next_selection_id),
 723                    start,
 724                    end,
 725                    reversed,
 726                    goal: SelectionGoal::None,
 727                }
 728            })
 729            .collect::<Vec<_>>();
 730
 731        self.select(selections)
 732    }
 733
 734    pub fn select_anchor_ranges<I>(&mut self, ranges: I)
 735    where
 736        I: IntoIterator<Item = Range<Anchor>>,
 737    {
 738        let selections = ranges
 739            .into_iter()
 740            .map(|range| {
 741                let mut start = range.start;
 742                let mut end = range.end;
 743                let reversed = if start.cmp(&end, self.snapshot).is_gt() {
 744                    mem::swap(&mut start, &mut end);
 745                    true
 746                } else {
 747                    false
 748                };
 749                Selection {
 750                    id: post_inc(&mut self.collection.next_selection_id),
 751                    start,
 752                    end,
 753                    reversed,
 754                    goal: SelectionGoal::None,
 755                }
 756            })
 757            .collect::<Vec<_>>();
 758        self.select_anchors(selections)
 759    }
 760
 761    pub fn new_selection_id(&mut self) -> usize {
 762        post_inc(&mut self.next_selection_id)
 763    }
 764
 765    pub fn select_display_ranges<T>(&mut self, ranges: T)
 766    where
 767        T: IntoIterator<Item = Range<DisplayPoint>>,
 768    {
 769        let selections = ranges
 770            .into_iter()
 771            .map(|range| {
 772                let mut start = range.start;
 773                let mut end = range.end;
 774                let reversed = if start > end {
 775                    mem::swap(&mut start, &mut end);
 776                    true
 777                } else {
 778                    false
 779                };
 780                Selection {
 781                    id: post_inc(&mut self.collection.next_selection_id),
 782                    start: start.to_point(self.snapshot),
 783                    end: end.to_point(self.snapshot),
 784                    reversed,
 785                    goal: SelectionGoal::None,
 786                }
 787            })
 788            .collect();
 789        self.select(selections);
 790    }
 791
 792    pub fn reverse_selections(&mut self) {
 793        let mut new_selections: Vec<Selection<Point>> = Vec::new();
 794        let disjoint = self.disjoint.clone();
 795        for selection in disjoint
 796            .iter()
 797            .sorted_by(|first, second| Ord::cmp(&second.id, &first.id))
 798            .collect::<Vec<&Selection<Anchor>>>()
 799        {
 800            new_selections.push(Selection {
 801                id: self.new_selection_id(),
 802                start: selection
 803                    .start
 804                    .to_display_point(self.snapshot)
 805                    .to_point(self.snapshot),
 806                end: selection
 807                    .end
 808                    .to_display_point(self.snapshot)
 809                    .to_point(self.snapshot),
 810                reversed: selection.reversed,
 811                goal: selection.goal,
 812            });
 813        }
 814        self.select(new_selections);
 815    }
 816
 817    pub fn move_with(
 818        &mut self,
 819        mut move_selection: impl FnMut(&DisplaySnapshot, &mut Selection<DisplayPoint>),
 820    ) {
 821        let mut changed = false;
 822        let display_map = self.display_snapshot();
 823        let selections = self.collection.all_display(&display_map);
 824        let selections = selections
 825            .into_iter()
 826            .map(|selection| {
 827                let mut moved_selection = selection.clone();
 828                move_selection(&display_map, &mut moved_selection);
 829                if selection != moved_selection {
 830                    changed = true;
 831                }
 832                moved_selection.map(|display_point| display_point.to_point(&display_map))
 833            })
 834            .collect();
 835
 836        if changed {
 837            self.select(selections)
 838        }
 839    }
 840
 841    pub fn move_offsets_with(
 842        &mut self,
 843        mut move_selection: impl FnMut(&MultiBufferSnapshot, &mut Selection<MultiBufferOffset>),
 844    ) {
 845        let mut changed = false;
 846        let display_map = self.display_snapshot();
 847        let selections = self
 848            .collection
 849            .all::<MultiBufferOffset>(&display_map)
 850            .into_iter()
 851            .map(|selection| {
 852                let mut moved_selection = selection.clone();
 853                move_selection(self.snapshot, &mut moved_selection);
 854                if selection != moved_selection {
 855                    changed = true;
 856                }
 857                moved_selection
 858            })
 859            .collect();
 860
 861        if changed {
 862            self.select(selections)
 863        }
 864    }
 865
 866    pub fn move_heads_with(
 867        &mut self,
 868        mut update_head: impl FnMut(
 869            &DisplaySnapshot,
 870            DisplayPoint,
 871            SelectionGoal,
 872        ) -> (DisplayPoint, SelectionGoal),
 873    ) {
 874        self.move_with(|map, selection| {
 875            let (new_head, new_goal) = update_head(map, selection.head(), selection.goal);
 876            selection.set_head(new_head, new_goal);
 877        });
 878    }
 879
 880    pub fn move_cursors_with(
 881        &mut self,
 882        mut update_cursor_position: impl FnMut(
 883            &DisplaySnapshot,
 884            DisplayPoint,
 885            SelectionGoal,
 886        ) -> (DisplayPoint, SelectionGoal),
 887    ) {
 888        self.move_with(|map, selection| {
 889            let (cursor, new_goal) = update_cursor_position(map, selection.head(), selection.goal);
 890            selection.collapse_to(cursor, new_goal)
 891        });
 892    }
 893
 894    pub fn maybe_move_cursors_with(
 895        &mut self,
 896        mut update_cursor_position: impl FnMut(
 897            &DisplaySnapshot,
 898            DisplayPoint,
 899            SelectionGoal,
 900        ) -> Option<(DisplayPoint, SelectionGoal)>,
 901    ) {
 902        self.move_cursors_with(|map, point, goal| {
 903            update_cursor_position(map, point, goal).unwrap_or((point, goal))
 904        })
 905    }
 906
 907    pub fn replace_cursors_with(
 908        &mut self,
 909        find_replacement_cursors: impl FnOnce(&DisplaySnapshot) -> Vec<DisplayPoint>,
 910    ) {
 911        let new_selections = find_replacement_cursors(self.snapshot)
 912            .into_iter()
 913            .map(|cursor| {
 914                let cursor_point = cursor.to_point(self.snapshot);
 915                Selection {
 916                    id: post_inc(&mut self.collection.next_selection_id),
 917                    start: cursor_point,
 918                    end: cursor_point,
 919                    reversed: false,
 920                    goal: SelectionGoal::None,
 921                }
 922            })
 923            .collect();
 924        self.select(new_selections);
 925    }
 926
 927    /// Compute new ranges for any selections that were located in excerpts that have
 928    /// since been removed.
 929    ///
 930    /// Returns a `HashMap` indicating which selections whose former head position
 931    /// was no longer present. The keys of the map are selection ids. The values are
 932    /// the id of the new excerpt where the head of the selection has been moved.
 933    pub fn refresh(&mut self) -> HashMap<usize, ExcerptId> {
 934        let mut pending = self.collection.pending.take();
 935        let mut selections_with_lost_position = HashMap::default();
 936
 937        let anchors_with_status = {
 938            let disjoint_anchors = self
 939                .disjoint
 940                .iter()
 941                .flat_map(|selection| [&selection.start, &selection.end]);
 942            self.snapshot.refresh_anchors(disjoint_anchors)
 943        };
 944        let adjusted_disjoint: Vec<_> = anchors_with_status
 945            .chunks(2)
 946            .map(|selection_anchors| {
 947                let (anchor_ix, start, kept_start) = selection_anchors[0];
 948                let (_, end, kept_end) = selection_anchors[1];
 949                let selection = &self.disjoint[anchor_ix / 2];
 950                let kept_head = if selection.reversed {
 951                    kept_start
 952                } else {
 953                    kept_end
 954                };
 955                if !kept_head {
 956                    selections_with_lost_position.insert(selection.id, selection.head().excerpt_id);
 957                }
 958
 959                Selection {
 960                    id: selection.id,
 961                    start,
 962                    end,
 963                    reversed: selection.reversed,
 964                    goal: selection.goal,
 965                }
 966            })
 967            .collect();
 968
 969        if !adjusted_disjoint.is_empty() {
 970            let map = self.display_snapshot();
 971            let resolved_selections =
 972                resolve_selections_wrapping_blocks(adjusted_disjoint.iter(), &map).collect();
 973            self.select::<MultiBufferOffset>(resolved_selections);
 974        }
 975
 976        if let Some(pending) = pending.as_mut() {
 977            let anchors = self
 978                .snapshot
 979                .refresh_anchors([&pending.selection.start, &pending.selection.end]);
 980            let (_, start, kept_start) = anchors[0];
 981            let (_, end, kept_end) = anchors[1];
 982            let kept_head = if pending.selection.reversed {
 983                kept_start
 984            } else {
 985                kept_end
 986            };
 987            if !kept_head {
 988                selections_with_lost_position
 989                    .insert(pending.selection.id, pending.selection.head().excerpt_id);
 990            }
 991
 992            pending.selection.start = start;
 993            pending.selection.end = end;
 994        }
 995        self.collection.pending = pending;
 996        self.selections_changed = true;
 997
 998        selections_with_lost_position
 999    }
1000}
1001
1002impl Deref for MutableSelectionsCollection<'_, '_> {
1003    type Target = SelectionsCollection;
1004    fn deref(&self) -> &Self::Target {
1005        self.collection
1006    }
1007}
1008
1009impl DerefMut for MutableSelectionsCollection<'_, '_> {
1010    fn deref_mut(&mut self) -> &mut Self::Target {
1011        self.collection
1012    }
1013}
1014
1015fn selection_to_anchor_selection(
1016    selection: Selection<MultiBufferOffset>,
1017    buffer: &MultiBufferSnapshot,
1018) -> Selection<Anchor> {
1019    let end_bias = if selection.start == selection.end {
1020        Bias::Right
1021    } else {
1022        Bias::Left
1023    };
1024    Selection {
1025        id: selection.id,
1026        start: buffer.anchor_after(selection.start),
1027        end: buffer.anchor_at(selection.end, end_bias),
1028        reversed: selection.reversed,
1029        goal: selection.goal,
1030    }
1031}
1032
1033fn resolve_selections_point<'a>(
1034    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1035    map: &'a DisplaySnapshot,
1036) -> impl 'a + Iterator<Item = Selection<Point>> {
1037    let (to_summarize, selections) = selections.into_iter().tee();
1038    let mut summaries = map
1039        .buffer_snapshot()
1040        .summaries_for_anchors::<Point, _>(to_summarize.flat_map(|s| [&s.start, &s.end]))
1041        .into_iter();
1042    selections.map(move |s| {
1043        let start = summaries.next().unwrap();
1044        let end = summaries.next().unwrap();
1045        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1046        Selection {
1047            id: s.id,
1048            start,
1049            end,
1050            reversed: s.reversed,
1051            goal: s.goal,
1052        }
1053    })
1054}
1055
1056/// Panics if passed selections are not in order
1057/// Resolves the anchors to display positions
1058fn resolve_selections_display<'a>(
1059    selections: impl 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1060    map: &'a DisplaySnapshot,
1061) -> impl 'a + Iterator<Item = Selection<DisplayPoint>> {
1062    let selections = resolve_selections_point(selections, map).map(move |s| {
1063        let display_start = map.point_to_display_point(s.start, Bias::Left);
1064        let display_end = map.point_to_display_point(
1065            s.end,
1066            if s.start == s.end {
1067                Bias::Right
1068            } else {
1069                Bias::Left
1070            },
1071        );
1072        assert!(
1073            display_start <= display_end,
1074            "display_start: {:?}, display_end: {:?}",
1075            display_start,
1076            display_end
1077        );
1078        Selection {
1079            id: s.id,
1080            start: display_start,
1081            end: display_end,
1082            reversed: s.reversed,
1083            goal: s.goal,
1084        }
1085    });
1086    coalesce_selections(selections)
1087}
1088
1089/// Resolves the passed in anchors to [`MultiBufferDimension`]s `D`
1090/// wrapping around blocks inbetween.
1091///
1092/// # Panics
1093///
1094/// Panics if passed selections are not in order
1095pub(crate) fn resolve_selections_wrapping_blocks<'a, D, I>(
1096    selections: I,
1097    map: &'a DisplaySnapshot,
1098) -> impl 'a + Iterator<Item = Selection<D>>
1099where
1100    D: MultiBufferDimension + Sub + AddAssign<<D as Sub>::Output> + Ord,
1101    I: 'a + IntoIterator<Item = &'a Selection<Anchor>>,
1102{
1103    // Transforms `Anchor -> DisplayPoint -> Point -> DisplayPoint -> D`
1104    // todo(lw): We should be able to short circuit the `Anchor -> DisplayPoint -> Point` to `Anchor -> Point`
1105    let (to_convert, selections) = resolve_selections_display(selections, map).tee();
1106    let mut converted_endpoints =
1107        map.buffer_snapshot()
1108            .dimensions_from_points::<D>(to_convert.flat_map(|s| {
1109                let start = map.display_point_to_point(s.start, Bias::Left);
1110                let end = map.display_point_to_point(s.end, Bias::Right);
1111                assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1112                [start, end]
1113            }));
1114    selections.map(move |s| {
1115        let start = converted_endpoints.next().unwrap();
1116        let end = converted_endpoints.next().unwrap();
1117        assert!(start <= end, "start: {:?}, end: {:?}", start, end);
1118        Selection {
1119            id: s.id,
1120            start,
1121            end,
1122            reversed: s.reversed,
1123            goal: s.goal,
1124        }
1125    })
1126}
1127
1128fn coalesce_selections<D: Ord + fmt::Debug + Copy>(
1129    selections: impl Iterator<Item = Selection<D>>,
1130) -> impl Iterator<Item = Selection<D>> {
1131    let mut selections = selections.peekable();
1132    iter::from_fn(move || {
1133        let mut selection = selections.next()?;
1134        while let Some(next_selection) = selections.peek() {
1135            if selection.end >= next_selection.start {
1136                if selection.reversed == next_selection.reversed {
1137                    selection.end = cmp::max(selection.end, next_selection.end);
1138                    selections.next();
1139                } else {
1140                    selection.end = cmp::max(selection.start, next_selection.start);
1141                    break;
1142                }
1143            } else {
1144                break;
1145            }
1146        }
1147        assert!(
1148            selection.start <= selection.end,
1149            "selection.start: {:?}, selection.end: {:?}, selection.reversed: {:?}",
1150            selection.start,
1151            selection.end,
1152            selection.reversed
1153        );
1154        Some(selection)
1155    })
1156}