text.rs

   1mod anchor;
   2mod locator;
   3pub mod operation_queue;
   4mod patch;
   5mod point;
   6mod point_utf16;
   7#[cfg(any(test, feature = "test-support"))]
   8pub mod random_char_iter;
   9pub mod rope;
  10mod selection;
  11pub mod subscription;
  12#[cfg(test)]
  13mod tests;
  14
  15pub use anchor::*;
  16use anyhow::{anyhow, Result};
  17use clock::ReplicaId;
  18use collections::{HashMap, HashSet};
  19use locator::Locator;
  20use operation_queue::OperationQueue;
  21pub use patch::Patch;
  22pub use point::*;
  23pub use point_utf16::*;
  24#[cfg(any(test, feature = "test-support"))]
  25pub use random_char_iter::*;
  26use rope::TextDimension;
  27pub use rope::{Chunks, Rope, TextSummary};
  28pub use selection::*;
  29use std::{
  30    cmp::{self, Ordering},
  31    iter::Iterator,
  32    ops::{self, Deref, Range, Sub},
  33    str,
  34    sync::Arc,
  35    time::{Duration, Instant},
  36};
  37pub use subscription::*;
  38pub use sum_tree::Bias;
  39use sum_tree::{FilterCursor, SumTree};
  40
  41pub struct Buffer {
  42    snapshot: BufferSnapshot,
  43    last_edit: clock::Local,
  44    history: History,
  45    selection_sets: HashMap<SelectionSetId, SelectionSet>,
  46    deferred_ops: OperationQueue<Operation>,
  47    deferred_replicas: HashSet<ReplicaId>,
  48    replica_id: ReplicaId,
  49    remote_id: u64,
  50    local_clock: clock::Local,
  51    lamport_clock: clock::Lamport,
  52    subscriptions: Topic,
  53}
  54
  55#[derive(Clone, Debug)]
  56pub struct BufferSnapshot {
  57    visible_text: Rope,
  58    deleted_text: Rope,
  59    undo_map: UndoMap,
  60    fragments: SumTree<Fragment>,
  61    insertions: SumTree<InsertionFragment>,
  62    pub version: clock::Global,
  63}
  64
  65#[derive(Clone, Debug)]
  66pub struct Transaction {
  67    start: clock::Global,
  68    end: clock::Global,
  69    edits: Vec<clock::Local>,
  70    ranges: Vec<Range<FullOffset>>,
  71    selections_before: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
  72    selections_after: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
  73    first_edit_at: Instant,
  74    last_edit_at: Instant,
  75}
  76
  77impl Transaction {
  78    pub fn starting_selection_set_ids<'a>(&'a self) -> impl Iterator<Item = SelectionSetId> + 'a {
  79        self.selections_before.keys().copied()
  80    }
  81
  82    fn push_edit(&mut self, edit: &EditOperation) {
  83        self.edits.push(edit.timestamp.local());
  84        self.end.observe(edit.timestamp.local());
  85
  86        let mut other_ranges = edit.ranges.iter().peekable();
  87        let mut new_ranges = Vec::new();
  88        let insertion_len = edit.new_text.as_ref().map_or(0, |t| t.len());
  89        let mut delta = 0;
  90
  91        for mut self_range in self.ranges.iter().cloned() {
  92            self_range.start += delta;
  93            self_range.end += delta;
  94
  95            while let Some(other_range) = other_ranges.peek() {
  96                let mut other_range = (*other_range).clone();
  97                other_range.start += delta;
  98                other_range.end += delta;
  99
 100                if other_range.start <= self_range.end {
 101                    other_ranges.next().unwrap();
 102                    delta += insertion_len;
 103
 104                    if other_range.end < self_range.start {
 105                        new_ranges.push(other_range.start..other_range.end + insertion_len);
 106                        self_range.start += insertion_len;
 107                        self_range.end += insertion_len;
 108                    } else {
 109                        self_range.start = cmp::min(self_range.start, other_range.start);
 110                        self_range.end = cmp::max(self_range.end, other_range.end) + insertion_len;
 111                    }
 112                } else {
 113                    break;
 114                }
 115            }
 116
 117            new_ranges.push(self_range);
 118        }
 119
 120        for other_range in other_ranges {
 121            new_ranges.push(other_range.start + delta..other_range.end + delta + insertion_len);
 122            delta += insertion_len;
 123        }
 124
 125        self.ranges = new_ranges;
 126    }
 127}
 128
 129#[derive(Clone)]
 130pub struct History {
 131    // TODO: Turn this into a String or Rope, maybe.
 132    pub base_text: Arc<str>,
 133    ops: HashMap<clock::Local, EditOperation>,
 134    undo_stack: Vec<Transaction>,
 135    redo_stack: Vec<Transaction>,
 136    transaction_depth: usize,
 137    group_interval: Duration,
 138}
 139
 140impl History {
 141    pub fn new(base_text: Arc<str>) -> Self {
 142        Self {
 143            base_text,
 144            ops: Default::default(),
 145            undo_stack: Vec::new(),
 146            redo_stack: Vec::new(),
 147            transaction_depth: 0,
 148            group_interval: Duration::from_millis(300),
 149        }
 150    }
 151
 152    fn push(&mut self, op: EditOperation) {
 153        self.ops.insert(op.timestamp.local(), op);
 154    }
 155
 156    fn start_transaction(
 157        &mut self,
 158        start: clock::Global,
 159        selections_before: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
 160        now: Instant,
 161    ) {
 162        self.transaction_depth += 1;
 163        if self.transaction_depth == 1 {
 164            self.undo_stack.push(Transaction {
 165                start: start.clone(),
 166                end: start,
 167                edits: Vec::new(),
 168                ranges: Vec::new(),
 169                selections_before,
 170                selections_after: Default::default(),
 171                first_edit_at: now,
 172                last_edit_at: now,
 173            });
 174        }
 175    }
 176
 177    fn end_transaction(
 178        &mut self,
 179        selections_after: HashMap<SelectionSetId, Arc<[Selection<Anchor>]>>,
 180        now: Instant,
 181    ) -> Option<&Transaction> {
 182        assert_ne!(self.transaction_depth, 0);
 183        self.transaction_depth -= 1;
 184        if self.transaction_depth == 0 {
 185            if self.undo_stack.last().unwrap().ranges.is_empty() {
 186                self.undo_stack.pop();
 187                None
 188            } else {
 189                let transaction = self.undo_stack.last_mut().unwrap();
 190                transaction.selections_after = selections_after;
 191                transaction.last_edit_at = now;
 192                Some(transaction)
 193            }
 194        } else {
 195            None
 196        }
 197    }
 198
 199    fn group(&mut self) {
 200        let mut new_len = self.undo_stack.len();
 201        let mut transactions = self.undo_stack.iter_mut();
 202
 203        if let Some(mut transaction) = transactions.next_back() {
 204            while let Some(prev_transaction) = transactions.next_back() {
 205                if transaction.first_edit_at - prev_transaction.last_edit_at <= self.group_interval
 206                    && transaction.start == prev_transaction.end
 207                {
 208                    transaction = prev_transaction;
 209                    new_len -= 1;
 210                } else {
 211                    break;
 212                }
 213            }
 214        }
 215
 216        let (transactions_to_keep, transactions_to_merge) = self.undo_stack.split_at_mut(new_len);
 217        if let Some(last_transaction) = transactions_to_keep.last_mut() {
 218            for transaction in &*transactions_to_merge {
 219                for edit_id in &transaction.edits {
 220                    last_transaction.push_edit(&self.ops[edit_id]);
 221                }
 222            }
 223
 224            if let Some(transaction) = transactions_to_merge.last_mut() {
 225                last_transaction.last_edit_at = transaction.last_edit_at;
 226                last_transaction
 227                    .selections_after
 228                    .extend(transaction.selections_after.drain());
 229                last_transaction.end = transaction.end.clone();
 230            }
 231        }
 232
 233        self.undo_stack.truncate(new_len);
 234    }
 235
 236    fn push_undo(&mut self, edit_id: clock::Local) {
 237        assert_ne!(self.transaction_depth, 0);
 238        let last_transaction = self.undo_stack.last_mut().unwrap();
 239        last_transaction.push_edit(&self.ops[&edit_id]);
 240    }
 241
 242    fn pop_undo(&mut self) -> Option<&Transaction> {
 243        assert_eq!(self.transaction_depth, 0);
 244        if let Some(transaction) = self.undo_stack.pop() {
 245            self.redo_stack.push(transaction);
 246            self.redo_stack.last()
 247        } else {
 248            None
 249        }
 250    }
 251
 252    fn pop_redo(&mut self) -> Option<&Transaction> {
 253        assert_eq!(self.transaction_depth, 0);
 254        if let Some(transaction) = self.redo_stack.pop() {
 255            self.undo_stack.push(transaction);
 256            self.undo_stack.last()
 257        } else {
 258            None
 259        }
 260    }
 261}
 262
 263#[derive(Clone, Default, Debug)]
 264struct UndoMap(HashMap<clock::Local, Vec<(clock::Local, u32)>>);
 265
 266impl UndoMap {
 267    fn insert(&mut self, undo: &UndoOperation) {
 268        for (edit_id, count) in &undo.counts {
 269            self.0.entry(*edit_id).or_default().push((undo.id, *count));
 270        }
 271    }
 272
 273    fn is_undone(&self, edit_id: clock::Local) -> bool {
 274        self.undo_count(edit_id) % 2 == 1
 275    }
 276
 277    fn was_undone(&self, edit_id: clock::Local, version: &clock::Global) -> bool {
 278        let undo_count = self
 279            .0
 280            .get(&edit_id)
 281            .unwrap_or(&Vec::new())
 282            .iter()
 283            .filter(|(undo_id, _)| version.observed(*undo_id))
 284            .map(|(_, undo_count)| *undo_count)
 285            .max()
 286            .unwrap_or(0);
 287        undo_count % 2 == 1
 288    }
 289
 290    fn undo_count(&self, edit_id: clock::Local) -> u32 {
 291        self.0
 292            .get(&edit_id)
 293            .unwrap_or(&Vec::new())
 294            .iter()
 295            .map(|(_, undo_count)| *undo_count)
 296            .max()
 297            .unwrap_or(0)
 298    }
 299}
 300
 301struct Edits<'a, D: TextDimension, F: FnMut(&FragmentSummary) -> bool> {
 302    visible_cursor: rope::Cursor<'a>,
 303    deleted_cursor: rope::Cursor<'a>,
 304    fragments_cursor: Option<FilterCursor<'a, F, Fragment, FragmentTextSummary>>,
 305    undos: &'a UndoMap,
 306    since: &'a clock::Global,
 307    old_end: D,
 308    new_end: D,
 309    range: Range<FullOffset>,
 310}
 311
 312#[derive(Clone, Debug, Default, Eq, PartialEq)]
 313pub struct Edit<D> {
 314    pub old: Range<D>,
 315    pub new: Range<D>,
 316}
 317
 318impl<D> Edit<D>
 319where
 320    D: Sub<D, Output = D> + PartialEq + Copy,
 321{
 322    pub fn old_len(&self) -> D {
 323        self.old.end - self.old.start
 324    }
 325
 326    pub fn new_len(&self) -> D {
 327        self.new.end - self.new.start
 328    }
 329
 330    pub fn is_empty(&self) -> bool {
 331        self.old.start == self.old.end && self.new.start == self.new.end
 332    }
 333}
 334
 335impl<D1, D2> Edit<(D1, D2)> {
 336    pub fn flatten(self) -> (Edit<D1>, Edit<D2>) {
 337        (
 338            Edit {
 339                old: self.old.start.0..self.old.end.0,
 340                new: self.new.start.0..self.new.end.0,
 341            },
 342            Edit {
 343                old: self.old.start.1..self.old.end.1,
 344                new: self.new.start.1..self.new.end.1,
 345            },
 346        )
 347    }
 348}
 349
 350#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
 351pub struct InsertionTimestamp {
 352    pub replica_id: ReplicaId,
 353    pub local: clock::Seq,
 354    pub lamport: clock::Seq,
 355}
 356
 357impl InsertionTimestamp {
 358    fn local(&self) -> clock::Local {
 359        clock::Local {
 360            replica_id: self.replica_id,
 361            value: self.local,
 362        }
 363    }
 364
 365    fn lamport(&self) -> clock::Lamport {
 366        clock::Lamport {
 367            replica_id: self.replica_id,
 368            value: self.lamport,
 369        }
 370    }
 371}
 372
 373#[derive(Eq, PartialEq, Clone, Debug)]
 374struct Fragment {
 375    id: Locator,
 376    insertion_timestamp: InsertionTimestamp,
 377    insertion_offset: usize,
 378    len: usize,
 379    visible: bool,
 380    deletions: HashSet<clock::Local>,
 381    max_undos: clock::Global,
 382}
 383
 384#[derive(Eq, PartialEq, Clone, Debug)]
 385pub struct FragmentSummary {
 386    text: FragmentTextSummary,
 387    max_id: Locator,
 388    max_version: clock::Global,
 389    min_insertion_version: clock::Global,
 390    max_insertion_version: clock::Global,
 391}
 392
 393#[derive(Copy, Default, Clone, Debug, PartialEq, Eq)]
 394struct FragmentTextSummary {
 395    visible: usize,
 396    deleted: usize,
 397}
 398
 399impl FragmentTextSummary {
 400    pub fn full_offset(&self) -> FullOffset {
 401        FullOffset(self.visible + self.deleted)
 402    }
 403}
 404
 405impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FragmentTextSummary {
 406    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
 407        self.visible += summary.text.visible;
 408        self.deleted += summary.text.deleted;
 409    }
 410}
 411
 412#[derive(Eq, PartialEq, Clone, Debug)]
 413struct InsertionFragment {
 414    timestamp: clock::Local,
 415    split_offset: usize,
 416    fragment_id: Locator,
 417}
 418
 419#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
 420struct InsertionFragmentKey {
 421    timestamp: clock::Local,
 422    split_offset: usize,
 423}
 424
 425#[derive(Clone, Debug, Eq, PartialEq)]
 426pub enum Operation {
 427    Edit(EditOperation),
 428    Undo {
 429        undo: UndoOperation,
 430        lamport_timestamp: clock::Lamport,
 431    },
 432    UpdateSelections {
 433        set_id: SelectionSetId,
 434        selections: Arc<[Selection<Anchor>]>,
 435        lamport_timestamp: clock::Lamport,
 436    },
 437    RemoveSelections {
 438        set_id: SelectionSetId,
 439        lamport_timestamp: clock::Lamport,
 440    },
 441    SetActiveSelections {
 442        set_id: Option<SelectionSetId>,
 443        lamport_timestamp: clock::Lamport,
 444    },
 445}
 446
 447#[derive(Clone, Debug, Eq, PartialEq)]
 448pub struct EditOperation {
 449    pub timestamp: InsertionTimestamp,
 450    pub version: clock::Global,
 451    pub ranges: Vec<Range<FullOffset>>,
 452    pub new_text: Option<String>,
 453}
 454
 455#[derive(Clone, Debug, Eq, PartialEq)]
 456pub struct UndoOperation {
 457    pub id: clock::Local,
 458    pub counts: HashMap<clock::Local, u32>,
 459    pub ranges: Vec<Range<FullOffset>>,
 460    pub version: clock::Global,
 461}
 462
 463impl Buffer {
 464    pub fn new(replica_id: u16, remote_id: u64, history: History) -> Buffer {
 465        let mut fragments = SumTree::new();
 466        let mut insertions = SumTree::new();
 467
 468        let mut local_clock = clock::Local::new(replica_id);
 469        let mut lamport_clock = clock::Lamport::new(replica_id);
 470        let mut version = clock::Global::new();
 471        let visible_text = Rope::from(history.base_text.as_ref());
 472        if visible_text.len() > 0 {
 473            let insertion_timestamp = InsertionTimestamp {
 474                replica_id: 0,
 475                local: 1,
 476                lamport: 1,
 477            };
 478            local_clock.observe(insertion_timestamp.local());
 479            lamport_clock.observe(insertion_timestamp.lamport());
 480            version.observe(insertion_timestamp.local());
 481            let fragment_id = Locator::between(&Locator::min(), &Locator::max());
 482            let fragment = Fragment {
 483                id: fragment_id,
 484                insertion_timestamp,
 485                insertion_offset: 0,
 486                len: visible_text.len(),
 487                visible: true,
 488                deletions: Default::default(),
 489                max_undos: Default::default(),
 490            };
 491            insertions.push(InsertionFragment::new(&fragment), &());
 492            fragments.push(fragment, &None);
 493        }
 494
 495        Buffer {
 496            snapshot: BufferSnapshot {
 497                visible_text,
 498                deleted_text: Rope::new(),
 499                fragments,
 500                insertions,
 501                version,
 502                undo_map: Default::default(),
 503            },
 504            last_edit: clock::Local::default(),
 505            history,
 506            selection_sets: Default::default(),
 507            deferred_ops: OperationQueue::new(),
 508            deferred_replicas: HashSet::default(),
 509            replica_id,
 510            remote_id,
 511            local_clock,
 512            lamport_clock,
 513            subscriptions: Default::default(),
 514        }
 515    }
 516
 517    pub fn version(&self) -> clock::Global {
 518        self.version.clone()
 519    }
 520
 521    pub fn snapshot(&self) -> BufferSnapshot {
 522        self.snapshot.clone()
 523    }
 524
 525    pub fn replica_id(&self) -> ReplicaId {
 526        self.local_clock.replica_id
 527    }
 528
 529    pub fn lamport_timestamp(&self) -> clock::Lamport {
 530        self.lamport_clock
 531    }
 532
 533    pub fn remote_id(&self) -> u64 {
 534        self.remote_id
 535    }
 536
 537    pub fn deferred_ops_len(&self) -> usize {
 538        self.deferred_ops.len()
 539    }
 540
 541    pub fn edit<R, I, S, T>(&mut self, ranges: R, new_text: T) -> EditOperation
 542    where
 543        R: IntoIterator<IntoIter = I>,
 544        I: ExactSizeIterator<Item = Range<S>>,
 545        S: ToOffset,
 546        T: Into<String>,
 547    {
 548        let new_text = new_text.into();
 549        let new_text_len = new_text.len();
 550        let new_text = if new_text_len > 0 {
 551            Some(new_text)
 552        } else {
 553            None
 554        };
 555
 556        self.start_transaction(None).unwrap();
 557        let timestamp = InsertionTimestamp {
 558            replica_id: self.replica_id,
 559            local: self.local_clock.tick().value,
 560            lamport: self.lamport_clock.tick().value,
 561        };
 562        let edit = self.apply_local_edit(ranges.into_iter(), new_text, timestamp);
 563
 564        self.history.push(edit.clone());
 565        self.history.push_undo(edit.timestamp.local());
 566        self.last_edit = edit.timestamp.local();
 567        self.snapshot.version.observe(edit.timestamp.local());
 568        self.end_transaction(None);
 569        edit
 570    }
 571
 572    fn apply_local_edit<S: ToOffset>(
 573        &mut self,
 574        ranges: impl ExactSizeIterator<Item = Range<S>>,
 575        new_text: Option<String>,
 576        timestamp: InsertionTimestamp,
 577    ) -> EditOperation {
 578        let mut edits = Patch::default();
 579        let mut edit_op = EditOperation {
 580            timestamp,
 581            version: self.version(),
 582            ranges: Vec::with_capacity(ranges.len()),
 583            new_text: None,
 584        };
 585        let mut new_insertions = Vec::new();
 586        let mut insertion_offset = 0;
 587
 588        let mut ranges = ranges
 589            .map(|range| range.start.to_offset(&*self)..range.end.to_offset(&*self))
 590            .peekable();
 591
 592        let mut new_ropes =
 593            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
 594        let mut old_fragments = self.fragments.cursor::<FragmentTextSummary>();
 595        let mut new_fragments =
 596            old_fragments.slice(&ranges.peek().unwrap().start, Bias::Right, &None);
 597        new_ropes.push_tree(new_fragments.summary().text);
 598
 599        let mut fragment_start = old_fragments.start().visible;
 600        for range in ranges {
 601            let fragment_end = old_fragments.end(&None).visible;
 602
 603            // If the current fragment ends before this range, then jump ahead to the first fragment
 604            // that extends past the start of this range, reusing any intervening fragments.
 605            if fragment_end < range.start {
 606                // If the current fragment has been partially consumed, then consume the rest of it
 607                // and advance to the next fragment before slicing.
 608                if fragment_start > old_fragments.start().visible {
 609                    if fragment_end > fragment_start {
 610                        let mut suffix = old_fragments.item().unwrap().clone();
 611                        suffix.len = fragment_end - fragment_start;
 612                        suffix.insertion_offset += fragment_start - old_fragments.start().visible;
 613                        new_insertions.push(InsertionFragment::insert_new(&suffix));
 614                        new_ropes.push_fragment(&suffix, suffix.visible);
 615                        new_fragments.push(suffix, &None);
 616                    }
 617                    old_fragments.next(&None);
 618                }
 619
 620                let slice = old_fragments.slice(&range.start, Bias::Right, &None);
 621                new_ropes.push_tree(slice.summary().text);
 622                new_fragments.push_tree(slice, &None);
 623                fragment_start = old_fragments.start().visible;
 624            }
 625
 626            let full_range_start = FullOffset(range.start + old_fragments.start().deleted);
 627
 628            // Preserve any portion of the current fragment that precedes this range.
 629            if fragment_start < range.start {
 630                let mut prefix = old_fragments.item().unwrap().clone();
 631                prefix.len = range.start - fragment_start;
 632                prefix.insertion_offset += fragment_start - old_fragments.start().visible;
 633                prefix.id = Locator::between(&new_fragments.summary().max_id, &prefix.id);
 634                new_insertions.push(InsertionFragment::insert_new(&prefix));
 635                new_ropes.push_fragment(&prefix, prefix.visible);
 636                new_fragments.push(prefix, &None);
 637                fragment_start = range.start;
 638            }
 639
 640            // Insert the new text before any existing fragments within the range.
 641            if let Some(new_text) = new_text.as_deref() {
 642                let new_start = new_fragments.summary().text.visible;
 643                edits.push(Edit {
 644                    old: fragment_start..fragment_start,
 645                    new: new_start..new_start + new_text.len(),
 646                });
 647                let fragment = Fragment {
 648                    id: Locator::between(
 649                        &new_fragments.summary().max_id,
 650                        old_fragments
 651                            .item()
 652                            .map_or(&Locator::max(), |old_fragment| &old_fragment.id),
 653                    ),
 654                    insertion_timestamp: timestamp,
 655                    insertion_offset,
 656                    len: new_text.len(),
 657                    deletions: Default::default(),
 658                    max_undos: Default::default(),
 659                    visible: true,
 660                };
 661                new_insertions.push(InsertionFragment::insert_new(&fragment));
 662                new_ropes.push_str(new_text);
 663                new_fragments.push(fragment, &None);
 664                insertion_offset += new_text.len();
 665            }
 666
 667            // Advance through every fragment that intersects this range, marking the intersecting
 668            // portions as deleted.
 669            while fragment_start < range.end {
 670                let fragment = old_fragments.item().unwrap();
 671                let fragment_end = old_fragments.end(&None).visible;
 672                let mut intersection = fragment.clone();
 673                let intersection_end = cmp::min(range.end, fragment_end);
 674                if fragment.visible {
 675                    intersection.len = intersection_end - fragment_start;
 676                    intersection.insertion_offset += fragment_start - old_fragments.start().visible;
 677                    intersection.id =
 678                        Locator::between(&new_fragments.summary().max_id, &intersection.id);
 679                    intersection.deletions.insert(timestamp.local());
 680                    intersection.visible = false;
 681                }
 682                if intersection.len > 0 {
 683                    if fragment.visible && !intersection.visible {
 684                        let new_start = new_fragments.summary().text.visible;
 685                        edits.push(Edit {
 686                            old: fragment_start..intersection_end,
 687                            new: new_start..new_start,
 688                        });
 689                    }
 690                    new_insertions.push(InsertionFragment::insert_new(&intersection));
 691                    new_ropes.push_fragment(&intersection, fragment.visible);
 692                    new_fragments.push(intersection, &None);
 693                    fragment_start = intersection_end;
 694                }
 695                if fragment_end <= range.end {
 696                    old_fragments.next(&None);
 697                }
 698            }
 699
 700            let full_range_end = FullOffset(range.end + old_fragments.start().deleted);
 701            edit_op.ranges.push(full_range_start..full_range_end);
 702        }
 703
 704        // If the current fragment has been partially consumed, then consume the rest of it
 705        // and advance to the next fragment before slicing.
 706        if fragment_start > old_fragments.start().visible {
 707            let fragment_end = old_fragments.end(&None).visible;
 708            if fragment_end > fragment_start {
 709                let mut suffix = old_fragments.item().unwrap().clone();
 710                suffix.len = fragment_end - fragment_start;
 711                suffix.insertion_offset += fragment_start - old_fragments.start().visible;
 712                new_insertions.push(InsertionFragment::insert_new(&suffix));
 713                new_ropes.push_fragment(&suffix, suffix.visible);
 714                new_fragments.push(suffix, &None);
 715            }
 716            old_fragments.next(&None);
 717        }
 718
 719        let suffix = old_fragments.suffix(&None);
 720        new_ropes.push_tree(suffix.summary().text);
 721        new_fragments.push_tree(suffix, &None);
 722        let (visible_text, deleted_text) = new_ropes.finish();
 723        drop(old_fragments);
 724
 725        self.snapshot.fragments = new_fragments;
 726        self.snapshot.insertions.edit(new_insertions, &());
 727        self.snapshot.visible_text = visible_text;
 728        self.snapshot.deleted_text = deleted_text;
 729        self.subscriptions.publish_mut(&edits);
 730        edit_op.new_text = new_text;
 731        edit_op
 732    }
 733
 734    pub fn apply_ops<I: IntoIterator<Item = Operation>>(&mut self, ops: I) -> Result<()> {
 735        let mut deferred_ops = Vec::new();
 736        for op in ops {
 737            if self.can_apply_op(&op) {
 738                self.apply_op(op)?;
 739            } else {
 740                self.deferred_replicas.insert(op.replica_id());
 741                deferred_ops.push(op);
 742            }
 743        }
 744        self.deferred_ops.insert(deferred_ops);
 745        self.flush_deferred_ops()?;
 746        Ok(())
 747    }
 748
 749    fn apply_op(&mut self, op: Operation) -> Result<()> {
 750        match op {
 751            Operation::Edit(edit) => {
 752                if !self.version.observed(edit.timestamp.local()) {
 753                    self.apply_remote_edit(
 754                        &edit.version,
 755                        &edit.ranges,
 756                        edit.new_text.as_deref(),
 757                        edit.timestamp,
 758                    );
 759                    self.snapshot.version.observe(edit.timestamp.local());
 760                    self.history.push(edit);
 761                }
 762            }
 763            Operation::Undo {
 764                undo,
 765                lamport_timestamp,
 766            } => {
 767                if !self.version.observed(undo.id) {
 768                    self.apply_undo(&undo)?;
 769                    self.snapshot.version.observe(undo.id);
 770                    self.lamport_clock.observe(lamport_timestamp);
 771                }
 772            }
 773            Operation::UpdateSelections {
 774                set_id,
 775                selections,
 776                lamport_timestamp,
 777            } => {
 778                if let Some(set) = self.selection_sets.get_mut(&set_id) {
 779                    set.selections = selections;
 780                } else {
 781                    self.selection_sets.insert(
 782                        set_id,
 783                        SelectionSet {
 784                            id: set_id,
 785                            selections,
 786                            active: false,
 787                        },
 788                    );
 789                }
 790                self.lamport_clock.observe(lamport_timestamp);
 791            }
 792            Operation::RemoveSelections {
 793                set_id,
 794                lamport_timestamp,
 795            } => {
 796                self.selection_sets.remove(&set_id);
 797                self.lamport_clock.observe(lamport_timestamp);
 798            }
 799            Operation::SetActiveSelections {
 800                set_id,
 801                lamport_timestamp,
 802            } => {
 803                for (id, set) in &mut self.selection_sets {
 804                    if id.replica_id == lamport_timestamp.replica_id {
 805                        if Some(*id) == set_id {
 806                            set.active = true;
 807                        } else {
 808                            set.active = false;
 809                        }
 810                    }
 811                }
 812                self.lamport_clock.observe(lamport_timestamp);
 813            }
 814        }
 815        Ok(())
 816    }
 817
 818    fn apply_remote_edit(
 819        &mut self,
 820        version: &clock::Global,
 821        ranges: &[Range<FullOffset>],
 822        new_text: Option<&str>,
 823        timestamp: InsertionTimestamp,
 824    ) {
 825        if ranges.is_empty() {
 826            return;
 827        }
 828
 829        let mut edits = Patch::default();
 830        let cx = Some(version.clone());
 831        let mut new_insertions = Vec::new();
 832        let mut insertion_offset = 0;
 833        let mut new_ropes =
 834            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
 835        let mut old_fragments = self.fragments.cursor::<(VersionedFullOffset, usize)>();
 836        let mut new_fragments = old_fragments.slice(
 837            &VersionedFullOffset::Offset(ranges[0].start),
 838            Bias::Left,
 839            &cx,
 840        );
 841        new_ropes.push_tree(new_fragments.summary().text);
 842
 843        let mut fragment_start = old_fragments.start().0.full_offset();
 844        for range in ranges {
 845            let fragment_end = old_fragments.end(&cx).0.full_offset();
 846
 847            // If the current fragment ends before this range, then jump ahead to the first fragment
 848            // that extends past the start of this range, reusing any intervening fragments.
 849            if fragment_end < range.start {
 850                // If the current fragment has been partially consumed, then consume the rest of it
 851                // and advance to the next fragment before slicing.
 852                if fragment_start > old_fragments.start().0.full_offset() {
 853                    if fragment_end > fragment_start {
 854                        let mut suffix = old_fragments.item().unwrap().clone();
 855                        suffix.len = fragment_end.0 - fragment_start.0;
 856                        suffix.insertion_offset +=
 857                            fragment_start - old_fragments.start().0.full_offset();
 858                        new_insertions.push(InsertionFragment::insert_new(&suffix));
 859                        new_ropes.push_fragment(&suffix, suffix.visible);
 860                        new_fragments.push(suffix, &None);
 861                    }
 862                    old_fragments.next(&cx);
 863                }
 864
 865                let slice =
 866                    old_fragments.slice(&VersionedFullOffset::Offset(range.start), Bias::Left, &cx);
 867                new_ropes.push_tree(slice.summary().text);
 868                new_fragments.push_tree(slice, &None);
 869                fragment_start = old_fragments.start().0.full_offset();
 870            }
 871
 872            // If we are at the end of a non-concurrent fragment, advance to the next one.
 873            let fragment_end = old_fragments.end(&cx).0.full_offset();
 874            if fragment_end == range.start && fragment_end > fragment_start {
 875                let mut fragment = old_fragments.item().unwrap().clone();
 876                fragment.len = fragment_end.0 - fragment_start.0;
 877                fragment.insertion_offset += fragment_start - old_fragments.start().0.full_offset();
 878                new_insertions.push(InsertionFragment::insert_new(&fragment));
 879                new_ropes.push_fragment(&fragment, fragment.visible);
 880                new_fragments.push(fragment, &None);
 881                old_fragments.next(&cx);
 882                fragment_start = old_fragments.start().0.full_offset();
 883            }
 884
 885            // Skip over insertions that are concurrent to this edit, but have a lower lamport
 886            // timestamp.
 887            while let Some(fragment) = old_fragments.item() {
 888                if fragment_start == range.start
 889                    && fragment.insertion_timestamp.lamport() > timestamp.lamport()
 890                {
 891                    new_ropes.push_fragment(fragment, fragment.visible);
 892                    new_fragments.push(fragment.clone(), &None);
 893                    old_fragments.next(&cx);
 894                    debug_assert_eq!(fragment_start, range.start);
 895                } else {
 896                    break;
 897                }
 898            }
 899            debug_assert!(fragment_start <= range.start);
 900
 901            // Preserve any portion of the current fragment that precedes this range.
 902            if fragment_start < range.start {
 903                let mut prefix = old_fragments.item().unwrap().clone();
 904                prefix.len = range.start.0 - fragment_start.0;
 905                prefix.insertion_offset += fragment_start - old_fragments.start().0.full_offset();
 906                prefix.id = Locator::between(&new_fragments.summary().max_id, &prefix.id);
 907                new_insertions.push(InsertionFragment::insert_new(&prefix));
 908                fragment_start = range.start;
 909                new_ropes.push_fragment(&prefix, prefix.visible);
 910                new_fragments.push(prefix, &None);
 911            }
 912
 913            // Insert the new text before any existing fragments within the range.
 914            if let Some(new_text) = new_text {
 915                let mut old_start = old_fragments.start().1;
 916                if old_fragments.item().map_or(false, |f| f.visible) {
 917                    old_start += fragment_start.0 - old_fragments.start().0.full_offset().0;
 918                }
 919                let new_start = new_fragments.summary().text.visible;
 920                edits.push(Edit {
 921                    old: old_start..old_start,
 922                    new: new_start..new_start + new_text.len(),
 923                });
 924                let fragment = Fragment {
 925                    id: Locator::between(
 926                        &new_fragments.summary().max_id,
 927                        old_fragments
 928                            .item()
 929                            .map_or(&Locator::max(), |old_fragment| &old_fragment.id),
 930                    ),
 931                    insertion_timestamp: timestamp,
 932                    insertion_offset,
 933                    len: new_text.len(),
 934                    deletions: Default::default(),
 935                    max_undos: Default::default(),
 936                    visible: true,
 937                };
 938                new_insertions.push(InsertionFragment::insert_new(&fragment));
 939                new_ropes.push_str(new_text);
 940                new_fragments.push(fragment, &None);
 941                insertion_offset += new_text.len();
 942            }
 943
 944            // Advance through every fragment that intersects this range, marking the intersecting
 945            // portions as deleted.
 946            while fragment_start < range.end {
 947                let fragment = old_fragments.item().unwrap();
 948                let fragment_end = old_fragments.end(&cx).0.full_offset();
 949                let mut intersection = fragment.clone();
 950                let intersection_end = cmp::min(range.end, fragment_end);
 951                if fragment.was_visible(version, &self.undo_map) {
 952                    intersection.len = intersection_end.0 - fragment_start.0;
 953                    intersection.insertion_offset +=
 954                        fragment_start - old_fragments.start().0.full_offset();
 955                    intersection.id =
 956                        Locator::between(&new_fragments.summary().max_id, &intersection.id);
 957                    intersection.deletions.insert(timestamp.local());
 958                    intersection.visible = false;
 959                }
 960                if intersection.len > 0 {
 961                    if fragment.visible && !intersection.visible {
 962                        let old_start = old_fragments.start().1
 963                            + (fragment_start.0 - old_fragments.start().0.full_offset().0);
 964                        let new_start = new_fragments.summary().text.visible;
 965                        edits.push(Edit {
 966                            old: old_start..old_start + intersection.len,
 967                            new: new_start..new_start,
 968                        });
 969                    }
 970                    new_insertions.push(InsertionFragment::insert_new(&intersection));
 971                    new_ropes.push_fragment(&intersection, fragment.visible);
 972                    new_fragments.push(intersection, &None);
 973                    fragment_start = intersection_end;
 974                }
 975                if fragment_end <= range.end {
 976                    old_fragments.next(&cx);
 977                }
 978            }
 979        }
 980
 981        // If the current fragment has been partially consumed, then consume the rest of it
 982        // and advance to the next fragment before slicing.
 983        if fragment_start > old_fragments.start().0.full_offset() {
 984            let fragment_end = old_fragments.end(&cx).0.full_offset();
 985            if fragment_end > fragment_start {
 986                let mut suffix = old_fragments.item().unwrap().clone();
 987                suffix.len = fragment_end.0 - fragment_start.0;
 988                suffix.insertion_offset += fragment_start - old_fragments.start().0.full_offset();
 989                new_insertions.push(InsertionFragment::insert_new(&suffix));
 990                new_ropes.push_fragment(&suffix, suffix.visible);
 991                new_fragments.push(suffix, &None);
 992            }
 993            old_fragments.next(&cx);
 994        }
 995
 996        let suffix = old_fragments.suffix(&cx);
 997        new_ropes.push_tree(suffix.summary().text);
 998        new_fragments.push_tree(suffix, &None);
 999        let (visible_text, deleted_text) = new_ropes.finish();
1000        drop(old_fragments);
1001
1002        self.snapshot.fragments = new_fragments;
1003        self.snapshot.visible_text = visible_text;
1004        self.snapshot.deleted_text = deleted_text;
1005        self.snapshot.insertions.edit(new_insertions, &());
1006        self.local_clock.observe(timestamp.local());
1007        self.lamport_clock.observe(timestamp.lamport());
1008        self.subscriptions.publish_mut(&edits);
1009    }
1010
1011    fn apply_undo(&mut self, undo: &UndoOperation) -> Result<()> {
1012        let mut edits = Patch::default();
1013        self.snapshot.undo_map.insert(undo);
1014
1015        let mut cx = undo.version.clone();
1016        for edit_id in undo.counts.keys().copied() {
1017            cx.observe(edit_id);
1018        }
1019        let cx = Some(cx);
1020
1021        let mut old_fragments = self.fragments.cursor::<(VersionedFullOffset, usize)>();
1022        let mut new_fragments = old_fragments.slice(
1023            &VersionedFullOffset::Offset(undo.ranges[0].start),
1024            Bias::Right,
1025            &cx,
1026        );
1027        let mut new_ropes =
1028            RopeBuilder::new(self.visible_text.cursor(0), self.deleted_text.cursor(0));
1029        new_ropes.push_tree(new_fragments.summary().text);
1030
1031        for range in &undo.ranges {
1032            let mut end_offset = old_fragments.end(&cx).0.full_offset();
1033
1034            if end_offset < range.start {
1035                let preceding_fragments = old_fragments.slice(
1036                    &VersionedFullOffset::Offset(range.start),
1037                    Bias::Right,
1038                    &cx,
1039                );
1040                new_ropes.push_tree(preceding_fragments.summary().text);
1041                new_fragments.push_tree(preceding_fragments, &None);
1042            }
1043
1044            while end_offset <= range.end {
1045                if let Some(fragment) = old_fragments.item() {
1046                    let mut fragment = fragment.clone();
1047                    let fragment_was_visible = fragment.visible;
1048
1049                    if fragment.was_visible(&undo.version, &self.undo_map)
1050                        || undo
1051                            .counts
1052                            .contains_key(&fragment.insertion_timestamp.local())
1053                    {
1054                        fragment.visible = fragment.is_visible(&self.undo_map);
1055                        fragment.max_undos.observe(undo.id);
1056                    }
1057
1058                    let old_start = old_fragments.start().1;
1059                    let new_start = new_fragments.summary().text.visible;
1060                    if fragment_was_visible && !fragment.visible {
1061                        edits.push(Edit {
1062                            old: old_start..old_start + fragment.len,
1063                            new: new_start..new_start,
1064                        });
1065                    } else if !fragment_was_visible && fragment.visible {
1066                        edits.push(Edit {
1067                            old: old_start..old_start,
1068                            new: new_start..new_start + fragment.len,
1069                        });
1070                    }
1071                    new_ropes.push_fragment(&fragment, fragment_was_visible);
1072                    new_fragments.push(fragment, &None);
1073
1074                    old_fragments.next(&cx);
1075                    if end_offset == old_fragments.end(&cx).0.full_offset() {
1076                        let unseen_fragments = old_fragments.slice(
1077                            &VersionedFullOffset::Offset(end_offset),
1078                            Bias::Right,
1079                            &cx,
1080                        );
1081                        new_ropes.push_tree(unseen_fragments.summary().text);
1082                        new_fragments.push_tree(unseen_fragments, &None);
1083                    }
1084                    end_offset = old_fragments.end(&cx).0.full_offset();
1085                } else {
1086                    break;
1087                }
1088            }
1089        }
1090
1091        let suffix = old_fragments.suffix(&cx);
1092        new_ropes.push_tree(suffix.summary().text);
1093        new_fragments.push_tree(suffix, &None);
1094
1095        drop(old_fragments);
1096        let (visible_text, deleted_text) = new_ropes.finish();
1097        self.snapshot.fragments = new_fragments;
1098        self.snapshot.visible_text = visible_text;
1099        self.snapshot.deleted_text = deleted_text;
1100        self.subscriptions.publish_mut(&edits);
1101        Ok(())
1102    }
1103
1104    fn flush_deferred_ops(&mut self) -> Result<()> {
1105        self.deferred_replicas.clear();
1106        let mut deferred_ops = Vec::new();
1107        for op in self.deferred_ops.drain().iter().cloned() {
1108            if self.can_apply_op(&op) {
1109                self.apply_op(op)?;
1110            } else {
1111                self.deferred_replicas.insert(op.replica_id());
1112                deferred_ops.push(op);
1113            }
1114        }
1115        self.deferred_ops.insert(deferred_ops);
1116        Ok(())
1117    }
1118
1119    fn can_apply_op(&self, op: &Operation) -> bool {
1120        if self.deferred_replicas.contains(&op.replica_id()) {
1121            false
1122        } else {
1123            match op {
1124                Operation::Edit(edit) => self.version.ge(&edit.version),
1125                Operation::Undo { undo, .. } => self.version.ge(&undo.version),
1126                Operation::UpdateSelections { selections, .. } => selections
1127                    .iter()
1128                    .all(|s| self.can_resolve(&s.start) && self.can_resolve(&s.end)),
1129                Operation::RemoveSelections { .. } => true,
1130                Operation::SetActiveSelections { set_id, .. } => {
1131                    set_id.map_or(true, |set_id| self.selection_sets.contains_key(&set_id))
1132                }
1133            }
1134        }
1135    }
1136
1137    pub fn can_resolve(&self, anchor: &Anchor) -> bool {
1138        *anchor == Anchor::min()
1139            || *anchor == Anchor::max()
1140            || self.version.observed(anchor.timestamp)
1141    }
1142
1143    pub fn peek_undo_stack(&self) -> Option<&Transaction> {
1144        self.history.undo_stack.last()
1145    }
1146
1147    pub fn start_transaction(
1148        &mut self,
1149        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1150    ) -> Result<()> {
1151        self.start_transaction_at(selection_set_ids, Instant::now())
1152    }
1153
1154    pub fn start_transaction_at(
1155        &mut self,
1156        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1157        now: Instant,
1158    ) -> Result<()> {
1159        let selections = selection_set_ids
1160            .into_iter()
1161            .map(|set_id| {
1162                let set = self
1163                    .selection_sets
1164                    .get(&set_id)
1165                    .expect("invalid selection set id");
1166                (set_id, set.selections.clone())
1167            })
1168            .collect();
1169        self.history
1170            .start_transaction(self.version.clone(), selections, now);
1171        Ok(())
1172    }
1173
1174    pub fn end_transaction(&mut self, selection_set_ids: impl IntoIterator<Item = SelectionSetId>) {
1175        self.end_transaction_at(selection_set_ids, Instant::now());
1176    }
1177
1178    pub fn end_transaction_at(
1179        &mut self,
1180        selection_set_ids: impl IntoIterator<Item = SelectionSetId>,
1181        now: Instant,
1182    ) -> Option<clock::Global> {
1183        let selections = selection_set_ids
1184            .into_iter()
1185            .map(|set_id| {
1186                let set = self
1187                    .selection_sets
1188                    .get(&set_id)
1189                    .expect("invalid selection set id");
1190                (set_id, set.selections.clone())
1191            })
1192            .collect();
1193
1194        if let Some(transaction) = self.history.end_transaction(selections, now) {
1195            let since = transaction.start.clone();
1196            self.history.group();
1197            Some(since)
1198        } else {
1199            None
1200        }
1201    }
1202
1203    pub fn remove_peer(&mut self, replica_id: ReplicaId) {
1204        self.selection_sets
1205            .retain(|set_id, _| set_id.replica_id != replica_id)
1206    }
1207
1208    pub fn base_text(&self) -> &Arc<str> {
1209        &self.history.base_text
1210    }
1211
1212    pub fn history(&self) -> impl Iterator<Item = &EditOperation> {
1213        self.history.ops.values()
1214    }
1215
1216    pub fn undo(&mut self) -> Vec<Operation> {
1217        let mut ops = Vec::new();
1218        if let Some(transaction) = self.history.pop_undo().cloned() {
1219            let selections = transaction.selections_before.clone();
1220            ops.push(self.undo_or_redo(transaction).unwrap());
1221            for (set_id, selections) in selections {
1222                ops.extend(self.restore_selection_set(set_id, selections));
1223            }
1224        }
1225        ops
1226    }
1227
1228    pub fn redo(&mut self) -> Vec<Operation> {
1229        let mut ops = Vec::new();
1230        if let Some(transaction) = self.history.pop_redo().cloned() {
1231            let selections = transaction.selections_after.clone();
1232            ops.push(self.undo_or_redo(transaction).unwrap());
1233            for (set_id, selections) in selections {
1234                ops.extend(self.restore_selection_set(set_id, selections));
1235            }
1236        }
1237        ops
1238    }
1239
1240    fn undo_or_redo(&mut self, transaction: Transaction) -> Result<Operation> {
1241        let mut counts = HashMap::default();
1242        for edit_id in transaction.edits {
1243            counts.insert(edit_id, self.undo_map.undo_count(edit_id) + 1);
1244        }
1245
1246        let undo = UndoOperation {
1247            id: self.local_clock.tick(),
1248            counts,
1249            ranges: transaction.ranges,
1250            version: transaction.start.clone(),
1251        };
1252        self.apply_undo(&undo)?;
1253        self.snapshot.version.observe(undo.id);
1254
1255        Ok(Operation::Undo {
1256            undo,
1257            lamport_timestamp: self.lamport_clock.tick(),
1258        })
1259    }
1260
1261    pub fn subscribe(&mut self) -> Subscription {
1262        self.subscriptions.subscribe()
1263    }
1264
1265    pub fn selection_set(&self, set_id: SelectionSetId) -> Result<&SelectionSet> {
1266        self.selection_sets
1267            .get(&set_id)
1268            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))
1269    }
1270
1271    pub fn selection_sets(&self) -> impl Iterator<Item = (&SelectionSetId, &SelectionSet)> {
1272        self.selection_sets.iter()
1273    }
1274
1275    fn build_anchor_selection_set<T: ToOffset>(
1276        &self,
1277        selections: &[Selection<T>],
1278    ) -> Arc<[Selection<Anchor>]> {
1279        Arc::from(
1280            selections
1281                .iter()
1282                .map(|selection| Selection {
1283                    id: selection.id,
1284                    start: self.anchor_before(&selection.start),
1285                    end: self.anchor_before(&selection.end),
1286                    reversed: selection.reversed,
1287                    goal: selection.goal,
1288                })
1289                .collect::<Vec<_>>(),
1290        )
1291    }
1292
1293    pub fn update_selection_set<T: ToOffset>(
1294        &mut self,
1295        set_id: SelectionSetId,
1296        selections: &[Selection<T>],
1297    ) -> Result<Operation> {
1298        let selections = self.build_anchor_selection_set(selections);
1299        let set = self
1300            .selection_sets
1301            .get_mut(&set_id)
1302            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1303        set.selections = selections.clone();
1304        Ok(Operation::UpdateSelections {
1305            set_id,
1306            selections,
1307            lamport_timestamp: self.lamport_clock.tick(),
1308        })
1309    }
1310
1311    pub fn restore_selection_set(
1312        &mut self,
1313        set_id: SelectionSetId,
1314        selections: Arc<[Selection<Anchor>]>,
1315    ) -> Result<Operation> {
1316        let set = self
1317            .selection_sets
1318            .get_mut(&set_id)
1319            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1320        set.selections = selections.clone();
1321        Ok(Operation::UpdateSelections {
1322            set_id,
1323            selections,
1324            lamport_timestamp: self.lamport_clock.tick(),
1325        })
1326    }
1327
1328    pub fn add_selection_set<T: ToOffset>(&mut self, selections: &[Selection<T>]) -> Operation {
1329        let selections = self.build_anchor_selection_set(selections);
1330        let set_id = self.lamport_clock.tick();
1331        self.selection_sets.insert(
1332            set_id,
1333            SelectionSet {
1334                id: set_id,
1335                selections: selections.clone(),
1336                active: false,
1337            },
1338        );
1339        Operation::UpdateSelections {
1340            set_id,
1341            selections,
1342            lamport_timestamp: set_id,
1343        }
1344    }
1345
1346    pub fn add_raw_selection_set(&mut self, id: SelectionSetId, selections: SelectionSet) {
1347        self.selection_sets.insert(id, selections);
1348    }
1349
1350    pub fn set_active_selection_set(
1351        &mut self,
1352        set_id: Option<SelectionSetId>,
1353    ) -> Result<Operation> {
1354        if let Some(set_id) = set_id {
1355            assert_eq!(set_id.replica_id, self.replica_id());
1356        }
1357
1358        for (id, set) in &mut self.selection_sets {
1359            if id.replica_id == self.local_clock.replica_id {
1360                if Some(*id) == set_id {
1361                    set.active = true;
1362                } else {
1363                    set.active = false;
1364                }
1365            }
1366        }
1367
1368        Ok(Operation::SetActiveSelections {
1369            set_id,
1370            lamport_timestamp: self.lamport_clock.tick(),
1371        })
1372    }
1373
1374    pub fn remove_selection_set(&mut self, set_id: SelectionSetId) -> Result<Operation> {
1375        self.selection_sets
1376            .remove(&set_id)
1377            .ok_or_else(|| anyhow!("invalid selection set id {:?}", set_id))?;
1378        Ok(Operation::RemoveSelections {
1379            set_id,
1380            lamport_timestamp: self.lamport_clock.tick(),
1381        })
1382    }
1383}
1384
1385#[cfg(any(test, feature = "test-support"))]
1386impl Buffer {
1387    fn random_byte_range(&mut self, start_offset: usize, rng: &mut impl rand::Rng) -> Range<usize> {
1388        let end = self.clip_offset(rng.gen_range(start_offset..=self.len()), Bias::Right);
1389        let start = self.clip_offset(rng.gen_range(start_offset..=end), Bias::Right);
1390        start..end
1391    }
1392
1393    pub fn randomly_edit<T>(
1394        &mut self,
1395        rng: &mut T,
1396        old_range_count: usize,
1397    ) -> (Vec<Range<usize>>, String, Operation)
1398    where
1399        T: rand::Rng,
1400    {
1401        let mut old_ranges: Vec<Range<usize>> = Vec::new();
1402        for _ in 0..old_range_count {
1403            let last_end = old_ranges.last().map_or(0, |last_range| last_range.end + 1);
1404            if last_end > self.len() {
1405                break;
1406            }
1407            old_ranges.push(self.random_byte_range(last_end, rng));
1408        }
1409        let new_text_len = rng.gen_range(0..10);
1410        let new_text: String = crate::random_char_iter::RandomCharIter::new(&mut *rng)
1411            .take(new_text_len)
1412            .collect();
1413        log::info!(
1414            "mutating buffer {} at {:?}: {:?}",
1415            self.replica_id,
1416            old_ranges,
1417            new_text
1418        );
1419        let op = self.edit(old_ranges.iter().cloned(), new_text.as_str());
1420        (old_ranges, new_text, Operation::Edit(op))
1421    }
1422
1423    pub fn randomly_mutate<T>(&mut self, rng: &mut T) -> Vec<Operation>
1424    where
1425        T: rand::Rng,
1426    {
1427        use rand::prelude::*;
1428
1429        let mut ops = vec![self.randomly_edit(rng, 5).2];
1430
1431        // Randomly add, remove or mutate selection sets.
1432        let replica_selection_sets = &self
1433            .selection_sets()
1434            .map(|(set_id, _)| *set_id)
1435            .filter(|set_id| self.replica_id == set_id.replica_id)
1436            .collect::<Vec<_>>();
1437        let set_id = replica_selection_sets.choose(rng);
1438        if set_id.is_some() && rng.gen_bool(1.0 / 6.0) {
1439            ops.push(self.remove_selection_set(*set_id.unwrap()).unwrap());
1440        } else {
1441            let mut ranges = Vec::new();
1442            for _ in 0..5 {
1443                ranges.push(self.random_byte_range(0, rng));
1444            }
1445            let new_selections = self.selections_from_ranges(ranges).unwrap();
1446
1447            let op = if set_id.is_none() || rng.gen_bool(1.0 / 5.0) {
1448                self.add_selection_set(&new_selections)
1449            } else {
1450                self.update_selection_set(*set_id.unwrap(), &new_selections)
1451                    .unwrap()
1452            };
1453            ops.push(op);
1454        }
1455
1456        ops
1457    }
1458
1459    pub fn randomly_undo_redo(&mut self, rng: &mut impl rand::Rng) -> Vec<Operation> {
1460        use rand::prelude::*;
1461
1462        let mut ops = Vec::new();
1463        for _ in 0..rng.gen_range(1..=5) {
1464            if let Some(transaction) = self.history.undo_stack.choose(rng).cloned() {
1465                log::info!(
1466                    "undoing buffer {} transaction {:?}",
1467                    self.replica_id,
1468                    transaction
1469                );
1470                ops.push(self.undo_or_redo(transaction).unwrap());
1471            }
1472        }
1473        ops
1474    }
1475
1476    fn selections_from_ranges<I>(&self, ranges: I) -> Result<Vec<Selection<usize>>>
1477    where
1478        I: IntoIterator<Item = Range<usize>>,
1479    {
1480        use std::sync::atomic::{self, AtomicUsize};
1481
1482        static NEXT_SELECTION_ID: AtomicUsize = AtomicUsize::new(0);
1483
1484        let mut ranges = ranges.into_iter().collect::<Vec<_>>();
1485        ranges.sort_unstable_by_key(|range| range.start);
1486
1487        let mut selections = Vec::<Selection<usize>>::with_capacity(ranges.len());
1488        for mut range in ranges {
1489            let mut reversed = false;
1490            if range.start > range.end {
1491                reversed = true;
1492                std::mem::swap(&mut range.start, &mut range.end);
1493            }
1494
1495            if let Some(selection) = selections.last_mut() {
1496                if selection.end >= range.start {
1497                    selection.end = range.end;
1498                    continue;
1499                }
1500            }
1501
1502            selections.push(Selection {
1503                id: NEXT_SELECTION_ID.fetch_add(1, atomic::Ordering::SeqCst),
1504                start: range.start,
1505                end: range.end,
1506                reversed,
1507                goal: SelectionGoal::None,
1508            });
1509        }
1510        Ok(selections)
1511    }
1512
1513    #[cfg(test)]
1514    pub fn selection_ranges<'a, D>(&'a self, set_id: SelectionSetId) -> Result<Vec<Range<D>>>
1515    where
1516        D: TextDimension,
1517    {
1518        Ok(self
1519            .selection_set(set_id)?
1520            .selections(self)
1521            .map(move |selection| {
1522                if selection.reversed {
1523                    selection.end..selection.start
1524                } else {
1525                    selection.start..selection.end
1526                }
1527            })
1528            .collect())
1529    }
1530
1531    #[cfg(test)]
1532    pub fn all_selection_ranges<'a, D>(
1533        &'a self,
1534    ) -> impl 'a + Iterator<Item = (SelectionSetId, Vec<Range<usize>>)>
1535    where
1536        D: TextDimension,
1537    {
1538        self.selection_sets
1539            .keys()
1540            .map(move |set_id| (*set_id, self.selection_ranges(*set_id).unwrap()))
1541    }
1542}
1543
1544impl Deref for Buffer {
1545    type Target = BufferSnapshot;
1546
1547    fn deref(&self) -> &Self::Target {
1548        &self.snapshot
1549    }
1550}
1551
1552impl BufferSnapshot {
1553    pub fn as_rope(&self) -> &Rope {
1554        &self.visible_text
1555    }
1556
1557    pub fn row_count(&self) -> u32 {
1558        self.max_point().row + 1
1559    }
1560
1561    pub fn len(&self) -> usize {
1562        self.visible_text.len()
1563    }
1564
1565    pub fn chars(&self) -> impl Iterator<Item = char> + '_ {
1566        self.chars_at(0)
1567    }
1568
1569    pub fn chars_for_range<T: ToOffset>(&self, range: Range<T>) -> impl Iterator<Item = char> + '_ {
1570        self.text_for_range(range).flat_map(str::chars)
1571    }
1572
1573    pub fn contains_str_at<T>(&self, position: T, needle: &str) -> bool
1574    where
1575        T: ToOffset,
1576    {
1577        let position = position.to_offset(self);
1578        position == self.clip_offset(position, Bias::Left)
1579            && self
1580                .bytes_in_range(position..self.len())
1581                .flatten()
1582                .copied()
1583                .take(needle.len())
1584                .eq(needle.bytes())
1585    }
1586
1587    pub fn text(&self) -> String {
1588        self.text_for_range(0..self.len()).collect()
1589    }
1590
1591    pub fn text_summary(&self) -> TextSummary {
1592        self.visible_text.summary()
1593    }
1594
1595    pub fn max_point(&self) -> Point {
1596        self.visible_text.max_point()
1597    }
1598
1599    pub fn point_to_offset(&self, point: Point) -> usize {
1600        self.visible_text.point_to_offset(point)
1601    }
1602
1603    pub fn point_utf16_to_offset(&self, point: PointUtf16) -> usize {
1604        self.visible_text.point_utf16_to_offset(point)
1605    }
1606
1607    pub fn offset_to_point(&self, offset: usize) -> Point {
1608        self.visible_text.offset_to_point(offset)
1609    }
1610
1611    pub fn offset_to_point_utf16(&self, offset: usize) -> PointUtf16 {
1612        self.visible_text.offset_to_point_utf16(offset)
1613    }
1614
1615    pub fn version(&self) -> &clock::Global {
1616        &self.version
1617    }
1618
1619    pub fn chars_at<'a, T: ToOffset>(&'a self, position: T) -> impl Iterator<Item = char> + 'a {
1620        let offset = position.to_offset(self);
1621        self.visible_text.chars_at(offset)
1622    }
1623
1624    pub fn reversed_chars_at<'a, T: ToOffset>(
1625        &'a self,
1626        position: T,
1627    ) -> impl Iterator<Item = char> + 'a {
1628        let offset = position.to_offset(self);
1629        self.visible_text.reversed_chars_at(offset)
1630    }
1631
1632    pub fn bytes_in_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> rope::Bytes<'a> {
1633        let start = range.start.to_offset(self);
1634        let end = range.end.to_offset(self);
1635        self.visible_text.bytes_in_range(start..end)
1636    }
1637
1638    pub fn text_for_range<'a, T: ToOffset>(&'a self, range: Range<T>) -> Chunks<'a> {
1639        let start = range.start.to_offset(self);
1640        let end = range.end.to_offset(self);
1641        self.visible_text.chunks_in_range(start..end)
1642    }
1643
1644    pub fn line_len(&self, row: u32) -> u32 {
1645        let row_start_offset = Point::new(row, 0).to_offset(self);
1646        let row_end_offset = if row >= self.max_point().row {
1647            self.len()
1648        } else {
1649            Point::new(row + 1, 0).to_offset(self) - 1
1650        };
1651        (row_end_offset - row_start_offset) as u32
1652    }
1653
1654    pub fn is_line_blank(&self, row: u32) -> bool {
1655        self.text_for_range(Point::new(row, 0)..Point::new(row, self.line_len(row)))
1656            .all(|chunk| chunk.matches(|c: char| !c.is_whitespace()).next().is_none())
1657    }
1658
1659    pub fn indent_column_for_line(&self, row: u32) -> u32 {
1660        let mut result = 0;
1661        for c in self.chars_at(Point::new(row, 0)) {
1662            if c == ' ' {
1663                result += 1;
1664            } else {
1665                break;
1666            }
1667        }
1668        result
1669    }
1670
1671    pub fn text_summary_for_range<'a, D, O: ToOffset>(&'a self, range: Range<O>) -> D
1672    where
1673        D: TextDimension,
1674    {
1675        self.visible_text
1676            .cursor(range.start.to_offset(self))
1677            .summary(range.end.to_offset(self))
1678    }
1679
1680    pub fn summaries_for_anchors<'a, D, A>(&'a self, anchors: A) -> impl 'a + Iterator<Item = D>
1681    where
1682        D: 'a + TextDimension,
1683        A: 'a + IntoIterator<Item = &'a Anchor>,
1684    {
1685        let anchors = anchors.into_iter();
1686        let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1687        let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1688        let mut text_cursor = self.visible_text.cursor(0);
1689        let mut position = D::default();
1690
1691        anchors.map(move |anchor| {
1692            if *anchor == Anchor::min() {
1693                return D::default();
1694            } else if *anchor == Anchor::max() {
1695                return D::from_text_summary(&self.visible_text.summary());
1696            }
1697
1698            let anchor_key = InsertionFragmentKey {
1699                timestamp: anchor.timestamp,
1700                split_offset: anchor.offset,
1701            };
1702            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1703            if let Some(insertion) = insertion_cursor.item() {
1704                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1705                if comparison == Ordering::Greater
1706                    || (anchor.bias == Bias::Left
1707                        && comparison == Ordering::Equal
1708                        && anchor.offset > 0)
1709                {
1710                    insertion_cursor.prev(&());
1711                }
1712            } else {
1713                insertion_cursor.prev(&());
1714            }
1715            let insertion = insertion_cursor.item().expect("invalid insertion");
1716            debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1717
1718            fragment_cursor.seek_forward(&Some(&insertion.fragment_id), Bias::Left, &None);
1719            let fragment = fragment_cursor.item().unwrap();
1720            let mut fragment_offset = fragment_cursor.start().1;
1721            if fragment.visible {
1722                fragment_offset += anchor.offset - insertion.split_offset;
1723            }
1724
1725            position.add_assign(&text_cursor.summary(fragment_offset));
1726            position.clone()
1727        })
1728    }
1729
1730    fn summary_for_anchor<'a, D>(&'a self, anchor: &Anchor) -> D
1731    where
1732        D: TextDimension,
1733    {
1734        if *anchor == Anchor::min() {
1735            D::default()
1736        } else if *anchor == Anchor::max() {
1737            D::from_text_summary(&self.visible_text.summary())
1738        } else {
1739            let anchor_key = InsertionFragmentKey {
1740                timestamp: anchor.timestamp,
1741                split_offset: anchor.offset,
1742            };
1743            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1744            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1745            if let Some(insertion) = insertion_cursor.item() {
1746                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1747                if comparison == Ordering::Greater
1748                    || (anchor.bias == Bias::Left
1749                        && comparison == Ordering::Equal
1750                        && anchor.offset > 0)
1751                {
1752                    insertion_cursor.prev(&());
1753                }
1754            } else {
1755                insertion_cursor.prev(&());
1756            }
1757            let insertion = insertion_cursor.item().expect("invalid insertion");
1758            debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1759
1760            let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, usize)>();
1761            fragment_cursor.seek(&Some(&insertion.fragment_id), Bias::Left, &None);
1762            let fragment = fragment_cursor.item().unwrap();
1763            let mut fragment_offset = fragment_cursor.start().1;
1764            if fragment.visible {
1765                fragment_offset += anchor.offset - insertion.split_offset;
1766            }
1767            self.text_summary_for_range(0..fragment_offset)
1768        }
1769    }
1770
1771    fn full_offset_for_anchor(&self, anchor: &Anchor) -> FullOffset {
1772        if *anchor == Anchor::min() {
1773            Default::default()
1774        } else if *anchor == Anchor::max() {
1775            let text = self.fragments.summary().text;
1776            FullOffset(text.visible + text.deleted)
1777        } else {
1778            let anchor_key = InsertionFragmentKey {
1779                timestamp: anchor.timestamp,
1780                split_offset: anchor.offset,
1781            };
1782            let mut insertion_cursor = self.insertions.cursor::<InsertionFragmentKey>();
1783            insertion_cursor.seek(&anchor_key, anchor.bias, &());
1784            if let Some(insertion) = insertion_cursor.item() {
1785                let comparison = sum_tree::KeyedItem::key(insertion).cmp(&anchor_key);
1786                if comparison == Ordering::Greater
1787                    || (anchor.bias == Bias::Left
1788                        && comparison == Ordering::Equal
1789                        && anchor.offset > 0)
1790                {
1791                    insertion_cursor.prev(&());
1792                }
1793            } else {
1794                insertion_cursor.prev(&());
1795            }
1796            let insertion = insertion_cursor.item().expect("invalid insertion");
1797            debug_assert_eq!(insertion.timestamp, anchor.timestamp, "invalid insertion");
1798
1799            let mut fragment_cursor = self.fragments.cursor::<(Option<&Locator>, FullOffset)>();
1800            fragment_cursor.seek(&Some(&insertion.fragment_id), Bias::Left, &None);
1801            fragment_cursor.start().1 + (anchor.offset - insertion.split_offset)
1802        }
1803    }
1804
1805    pub fn anchor_before<T: ToOffset>(&self, position: T) -> Anchor {
1806        self.anchor_at(position, Bias::Left)
1807    }
1808
1809    pub fn anchor_after<T: ToOffset>(&self, position: T) -> Anchor {
1810        self.anchor_at(position, Bias::Right)
1811    }
1812
1813    pub fn anchor_at<T: ToOffset>(&self, position: T, bias: Bias) -> Anchor {
1814        let offset = position.to_offset(self);
1815        if bias == Bias::Left && offset == 0 {
1816            Anchor::min()
1817        } else if bias == Bias::Right && offset == self.len() {
1818            Anchor::max()
1819        } else {
1820            let mut fragment_cursor = self.fragments.cursor::<usize>();
1821            fragment_cursor.seek(&offset, bias, &None);
1822            let fragment = fragment_cursor.item().unwrap();
1823            let overshoot = offset - *fragment_cursor.start();
1824            Anchor {
1825                timestamp: fragment.insertion_timestamp.local(),
1826                offset: fragment.insertion_offset + overshoot,
1827                bias,
1828            }
1829        }
1830    }
1831
1832    pub fn clip_offset(&self, offset: usize, bias: Bias) -> usize {
1833        self.visible_text.clip_offset(offset, bias)
1834    }
1835
1836    pub fn clip_point(&self, point: Point, bias: Bias) -> Point {
1837        self.visible_text.clip_point(point, bias)
1838    }
1839
1840    pub fn clip_point_utf16(&self, point: PointUtf16, bias: Bias) -> PointUtf16 {
1841        self.visible_text.clip_point_utf16(point, bias)
1842    }
1843
1844    // pub fn point_for_offset(&self, offset: usize) -> Result<Point> {
1845    //     if offset <= self.len() {
1846    //         Ok(self.text_summary_for_range(0..offset))
1847    //     } else {
1848    //         Err(anyhow!("offset out of bounds"))
1849    //     }
1850    // }
1851
1852    pub fn edits_since<'a, D>(
1853        &'a self,
1854        since: &'a clock::Global,
1855    ) -> impl 'a + Iterator<Item = Edit<D>>
1856    where
1857        D: TextDimension + Ord,
1858    {
1859        self.edits_since_in_range(since, Anchor::min()..Anchor::max())
1860    }
1861
1862    pub fn edits_since_in_range<'a, D>(
1863        &'a self,
1864        since: &'a clock::Global,
1865        range: Range<Anchor>,
1866    ) -> impl 'a + Iterator<Item = Edit<D>>
1867    where
1868        D: TextDimension + Ord,
1869    {
1870        let fragments_cursor = if *since == self.version {
1871            None
1872        } else {
1873            Some(
1874                self.fragments
1875                    .filter(move |summary| !since.ge(&summary.max_version), &None),
1876            )
1877        };
1878
1879        let mut cursor = self
1880            .fragments
1881            .cursor::<(VersionedFullOffset, FragmentTextSummary)>();
1882        cursor.seek(
1883            &VersionedFullOffset::Offset(range.start.full_offset),
1884            range.start.bias,
1885            &Some(range.start.version),
1886        );
1887        let mut visible_start = cursor.start().1.visible;
1888        let mut deleted_start = cursor.start().1.deleted;
1889        if let Some(fragment) = cursor.item() {
1890            let overshoot = range.start.full_offset.0 - cursor.start().0.full_offset().0;
1891            if fragment.visible {
1892                visible_start += overshoot;
1893            } else {
1894                deleted_start += overshoot;
1895            }
1896        }
1897
1898        let full_offset_start = FullOffset(visible_start + deleted_start);
1899        let full_offset_end = range.end.to_full_offset(self, range.end.bias);
1900        Edits {
1901            visible_cursor: self.visible_text.cursor(visible_start),
1902            deleted_cursor: self.deleted_text.cursor(deleted_start),
1903            fragments_cursor,
1904            undos: &self.undo_map,
1905            since,
1906            old_end: Default::default(),
1907            new_end: Default::default(),
1908            range: full_offset_start..full_offset_end,
1909        }
1910    }
1911}
1912
1913struct RopeBuilder<'a> {
1914    old_visible_cursor: rope::Cursor<'a>,
1915    old_deleted_cursor: rope::Cursor<'a>,
1916    new_visible: Rope,
1917    new_deleted: Rope,
1918}
1919
1920impl<'a> RopeBuilder<'a> {
1921    fn new(old_visible_cursor: rope::Cursor<'a>, old_deleted_cursor: rope::Cursor<'a>) -> Self {
1922        Self {
1923            old_visible_cursor,
1924            old_deleted_cursor,
1925            new_visible: Rope::new(),
1926            new_deleted: Rope::new(),
1927        }
1928    }
1929
1930    fn push_tree(&mut self, len: FragmentTextSummary) {
1931        self.push(len.visible, true, true);
1932        self.push(len.deleted, false, false);
1933    }
1934
1935    fn push_fragment(&mut self, fragment: &Fragment, was_visible: bool) {
1936        debug_assert!(fragment.len > 0);
1937        self.push(fragment.len, was_visible, fragment.visible)
1938    }
1939
1940    fn push(&mut self, len: usize, was_visible: bool, is_visible: bool) {
1941        let text = if was_visible {
1942            self.old_visible_cursor
1943                .slice(self.old_visible_cursor.offset() + len)
1944        } else {
1945            self.old_deleted_cursor
1946                .slice(self.old_deleted_cursor.offset() + len)
1947        };
1948        if is_visible {
1949            self.new_visible.append(text);
1950        } else {
1951            self.new_deleted.append(text);
1952        }
1953    }
1954
1955    fn push_str(&mut self, text: &str) {
1956        self.new_visible.push(text);
1957    }
1958
1959    fn finish(mut self) -> (Rope, Rope) {
1960        self.new_visible.append(self.old_visible_cursor.suffix());
1961        self.new_deleted.append(self.old_deleted_cursor.suffix());
1962        (self.new_visible, self.new_deleted)
1963    }
1964}
1965
1966impl<'a, D: TextDimension + Ord, F: FnMut(&FragmentSummary) -> bool> Iterator for Edits<'a, D, F> {
1967    type Item = Edit<D>;
1968
1969    fn next(&mut self) -> Option<Self::Item> {
1970        let mut pending_edit: Option<Edit<D>> = None;
1971        let cursor = self.fragments_cursor.as_mut()?;
1972
1973        while let Some(fragment) = cursor.item() {
1974            if cursor.end(&None).full_offset() < self.range.start {
1975                cursor.next(&None);
1976                continue;
1977            } else if cursor.start().full_offset() >= self.range.end {
1978                break;
1979            }
1980
1981            if cursor.start().visible > self.visible_cursor.offset() {
1982                let summary = self.visible_cursor.summary(cursor.start().visible);
1983                self.old_end.add_assign(&summary);
1984                self.new_end.add_assign(&summary);
1985            }
1986
1987            if pending_edit
1988                .as_ref()
1989                .map_or(false, |change| change.new.end < self.new_end)
1990            {
1991                break;
1992            }
1993
1994            if !fragment.was_visible(&self.since, &self.undos) && fragment.visible {
1995                let visible_end = cmp::min(
1996                    cursor.end(&None).visible,
1997                    cursor.start().visible + (self.range.end - cursor.start().full_offset()),
1998                );
1999
2000                let fragment_summary = self.visible_cursor.summary(visible_end);
2001                let mut new_end = self.new_end.clone();
2002                new_end.add_assign(&fragment_summary);
2003                if let Some(pending_edit) = pending_edit.as_mut() {
2004                    pending_edit.new.end = new_end.clone();
2005                } else {
2006                    pending_edit = Some(Edit {
2007                        old: self.old_end.clone()..self.old_end.clone(),
2008                        new: self.new_end.clone()..new_end.clone(),
2009                    });
2010                }
2011
2012                self.new_end = new_end;
2013            } else if fragment.was_visible(&self.since, &self.undos) && !fragment.visible {
2014                let deleted_end = cmp::min(
2015                    cursor.end(&None).deleted,
2016                    cursor.start().deleted + (self.range.end - cursor.start().full_offset()),
2017                );
2018
2019                if cursor.start().deleted > self.deleted_cursor.offset() {
2020                    self.deleted_cursor.seek_forward(cursor.start().deleted);
2021                }
2022                let fragment_summary = self.deleted_cursor.summary(deleted_end);
2023                let mut old_end = self.old_end.clone();
2024                old_end.add_assign(&fragment_summary);
2025                if let Some(pending_edit) = pending_edit.as_mut() {
2026                    pending_edit.old.end = old_end.clone();
2027                } else {
2028                    pending_edit = Some(Edit {
2029                        old: self.old_end.clone()..old_end.clone(),
2030                        new: self.new_end.clone()..self.new_end.clone(),
2031                    });
2032                }
2033
2034                self.old_end = old_end;
2035            }
2036
2037            cursor.next(&None);
2038        }
2039
2040        pending_edit
2041    }
2042}
2043
2044impl Fragment {
2045    fn is_visible(&self, undos: &UndoMap) -> bool {
2046        !undos.is_undone(self.insertion_timestamp.local())
2047            && self.deletions.iter().all(|d| undos.is_undone(*d))
2048    }
2049
2050    fn was_visible(&self, version: &clock::Global, undos: &UndoMap) -> bool {
2051        (version.observed(self.insertion_timestamp.local())
2052            && !undos.was_undone(self.insertion_timestamp.local(), version))
2053            && self
2054                .deletions
2055                .iter()
2056                .all(|d| !version.observed(*d) || undos.was_undone(*d, version))
2057    }
2058}
2059
2060impl sum_tree::Item for Fragment {
2061    type Summary = FragmentSummary;
2062
2063    fn summary(&self) -> Self::Summary {
2064        let mut max_version = clock::Global::new();
2065        max_version.observe(self.insertion_timestamp.local());
2066        for deletion in &self.deletions {
2067            max_version.observe(*deletion);
2068        }
2069        max_version.join(&self.max_undos);
2070
2071        let mut min_insertion_version = clock::Global::new();
2072        min_insertion_version.observe(self.insertion_timestamp.local());
2073        let max_insertion_version = min_insertion_version.clone();
2074        if self.visible {
2075            FragmentSummary {
2076                max_id: self.id.clone(),
2077                text: FragmentTextSummary {
2078                    visible: self.len,
2079                    deleted: 0,
2080                },
2081                max_version,
2082                min_insertion_version,
2083                max_insertion_version,
2084            }
2085        } else {
2086            FragmentSummary {
2087                max_id: self.id.clone(),
2088                text: FragmentTextSummary {
2089                    visible: 0,
2090                    deleted: self.len,
2091                },
2092                max_version,
2093                min_insertion_version,
2094                max_insertion_version,
2095            }
2096        }
2097    }
2098}
2099
2100impl sum_tree::Summary for FragmentSummary {
2101    type Context = Option<clock::Global>;
2102
2103    fn add_summary(&mut self, other: &Self, _: &Self::Context) {
2104        self.max_id.assign(&other.max_id);
2105        self.text.visible += &other.text.visible;
2106        self.text.deleted += &other.text.deleted;
2107        self.max_version.join(&other.max_version);
2108        self.min_insertion_version
2109            .meet(&other.min_insertion_version);
2110        self.max_insertion_version
2111            .join(&other.max_insertion_version);
2112    }
2113}
2114
2115impl Default for FragmentSummary {
2116    fn default() -> Self {
2117        FragmentSummary {
2118            max_id: Locator::min(),
2119            text: FragmentTextSummary::default(),
2120            max_version: clock::Global::new(),
2121            min_insertion_version: clock::Global::new(),
2122            max_insertion_version: clock::Global::new(),
2123        }
2124    }
2125}
2126
2127impl sum_tree::Item for InsertionFragment {
2128    type Summary = InsertionFragmentKey;
2129
2130    fn summary(&self) -> Self::Summary {
2131        InsertionFragmentKey {
2132            timestamp: self.timestamp,
2133            split_offset: self.split_offset,
2134        }
2135    }
2136}
2137
2138impl sum_tree::KeyedItem for InsertionFragment {
2139    type Key = InsertionFragmentKey;
2140
2141    fn key(&self) -> Self::Key {
2142        sum_tree::Item::summary(self)
2143    }
2144}
2145
2146impl InsertionFragment {
2147    fn new(fragment: &Fragment) -> Self {
2148        Self {
2149            timestamp: fragment.insertion_timestamp.local(),
2150            split_offset: fragment.insertion_offset,
2151            fragment_id: fragment.id.clone(),
2152        }
2153    }
2154
2155    fn insert_new(fragment: &Fragment) -> sum_tree::Edit<Self> {
2156        sum_tree::Edit::Insert(Self::new(fragment))
2157    }
2158}
2159
2160impl sum_tree::Summary for InsertionFragmentKey {
2161    type Context = ();
2162
2163    fn add_summary(&mut self, summary: &Self, _: &()) {
2164        *self = *summary;
2165    }
2166}
2167
2168#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
2169pub struct FullOffset(pub usize);
2170
2171impl ops::AddAssign<usize> for FullOffset {
2172    fn add_assign(&mut self, rhs: usize) {
2173        self.0 += rhs;
2174    }
2175}
2176
2177impl ops::Add<usize> for FullOffset {
2178    type Output = Self;
2179
2180    fn add(mut self, rhs: usize) -> Self::Output {
2181        self += rhs;
2182        self
2183    }
2184}
2185
2186impl ops::Sub for FullOffset {
2187    type Output = usize;
2188
2189    fn sub(self, rhs: Self) -> Self::Output {
2190        self.0 - rhs.0
2191    }
2192}
2193
2194impl<'a> sum_tree::Dimension<'a, FragmentSummary> for usize {
2195    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2196        *self += summary.text.visible;
2197    }
2198}
2199
2200impl<'a> sum_tree::Dimension<'a, FragmentSummary> for FullOffset {
2201    fn add_summary(&mut self, summary: &FragmentSummary, _: &Option<clock::Global>) {
2202        self.0 += summary.text.visible + summary.text.deleted;
2203    }
2204}
2205
2206impl<'a> sum_tree::Dimension<'a, FragmentSummary> for Option<&'a Locator> {
2207    fn add_summary(&mut self, summary: &'a FragmentSummary, _: &Option<clock::Global>) {
2208        *self = Some(&summary.max_id);
2209    }
2210}
2211
2212impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, FragmentTextSummary> for usize {
2213    fn cmp(
2214        &self,
2215        cursor_location: &FragmentTextSummary,
2216        _: &Option<clock::Global>,
2217    ) -> cmp::Ordering {
2218        Ord::cmp(self, &cursor_location.visible)
2219    }
2220}
2221
2222#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2223enum VersionedFullOffset {
2224    Offset(FullOffset),
2225    Invalid,
2226}
2227
2228impl VersionedFullOffset {
2229    fn full_offset(&self) -> FullOffset {
2230        if let Self::Offset(position) = self {
2231            *position
2232        } else {
2233            panic!("invalid version")
2234        }
2235    }
2236}
2237
2238impl Default for VersionedFullOffset {
2239    fn default() -> Self {
2240        Self::Offset(Default::default())
2241    }
2242}
2243
2244impl<'a> sum_tree::Dimension<'a, FragmentSummary> for VersionedFullOffset {
2245    fn add_summary(&mut self, summary: &'a FragmentSummary, cx: &Option<clock::Global>) {
2246        if let Self::Offset(offset) = self {
2247            let version = cx.as_ref().unwrap();
2248            if version.ge(&summary.max_insertion_version) {
2249                *offset += summary.text.visible + summary.text.deleted;
2250            } else if version.observed_any(&summary.min_insertion_version) {
2251                *self = Self::Invalid;
2252            }
2253        }
2254    }
2255}
2256
2257impl<'a> sum_tree::SeekTarget<'a, FragmentSummary, Self> for VersionedFullOffset {
2258    fn cmp(&self, cursor_position: &Self, _: &Option<clock::Global>) -> cmp::Ordering {
2259        match (self, cursor_position) {
2260            (Self::Offset(a), Self::Offset(b)) => Ord::cmp(a, b),
2261            (Self::Offset(_), Self::Invalid) => cmp::Ordering::Less,
2262            (Self::Invalid, _) => unreachable!(),
2263        }
2264    }
2265}
2266
2267impl Operation {
2268    fn replica_id(&self) -> ReplicaId {
2269        operation_queue::Operation::lamport_timestamp(self).replica_id
2270    }
2271
2272    pub fn is_edit(&self) -> bool {
2273        match self {
2274            Operation::Edit { .. } => true,
2275            _ => false,
2276        }
2277    }
2278}
2279
2280impl operation_queue::Operation for Operation {
2281    fn lamport_timestamp(&self) -> clock::Lamport {
2282        match self {
2283            Operation::Edit(edit) => edit.timestamp.lamport(),
2284            Operation::Undo {
2285                lamport_timestamp, ..
2286            } => *lamport_timestamp,
2287            Operation::UpdateSelections {
2288                lamport_timestamp, ..
2289            } => *lamport_timestamp,
2290            Operation::RemoveSelections {
2291                lamport_timestamp, ..
2292            } => *lamport_timestamp,
2293            Operation::SetActiveSelections {
2294                lamport_timestamp, ..
2295            } => *lamport_timestamp,
2296        }
2297    }
2298}
2299
2300pub trait ToOffset {
2301    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize;
2302
2303    fn to_full_offset<'a>(&self, snapshot: &BufferSnapshot, bias: Bias) -> FullOffset {
2304        let offset = self.to_offset(&snapshot);
2305        let mut cursor = snapshot.fragments.cursor::<FragmentTextSummary>();
2306        cursor.seek(&offset, bias, &None);
2307        FullOffset(offset + cursor.start().deleted)
2308    }
2309}
2310
2311impl ToOffset for Point {
2312    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2313        snapshot.point_to_offset(*self)
2314    }
2315}
2316
2317impl ToOffset for PointUtf16 {
2318    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2319        snapshot.point_utf16_to_offset(*self)
2320    }
2321}
2322
2323impl ToOffset for usize {
2324    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2325        assert!(*self <= snapshot.len(), "offset is out of range");
2326        *self
2327    }
2328}
2329
2330impl ToOffset for Anchor {
2331    fn to_offset<'a>(&self, snapshot: &BufferSnapshot) -> usize {
2332        snapshot.summary_for_anchor(self)
2333    }
2334}
2335
2336impl<'a, T: ToOffset> ToOffset for &'a T {
2337    fn to_offset(&self, content: &BufferSnapshot) -> usize {
2338        (*self).to_offset(content)
2339    }
2340}
2341
2342pub trait ToPoint {
2343    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point;
2344}
2345
2346impl ToPoint for Anchor {
2347    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point {
2348        snapshot.summary_for_anchor(self)
2349    }
2350}
2351
2352impl ToPoint for usize {
2353    fn to_point<'a>(&self, snapshot: &BufferSnapshot) -> Point {
2354        snapshot.offset_to_point(*self)
2355    }
2356}
2357
2358impl ToPoint for Point {
2359    fn to_point<'a>(&self, _: &BufferSnapshot) -> Point {
2360        *self
2361    }
2362}
2363
2364pub trait FromAnchor {
2365    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self;
2366}
2367
2368impl FromAnchor for Point {
2369    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2370        anchor.to_point(snapshot)
2371    }
2372}
2373
2374impl FromAnchor for usize {
2375    fn from_anchor(anchor: &Anchor, snapshot: &BufferSnapshot) -> Self {
2376        anchor.to_offset(snapshot)
2377    }
2378}