mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
multi_buffer: Sync only changed buffers (#67053)
## Summary A change to any buffer made the multibuffer's next sync read every buffer and diff, and adding a buffer counted as a change. With N buffers, each change cost O(N). Inserting excerpts syncs first, so building a multibuffer one path at a time took O(N²) time on the main thread. Project search, project diagnostics, multi-file git diffs, and find references all build their multibuffers this way. The multibuffer keeps a set of the buffers that changed or were added since the last sync, and a sync reads only those buffers and their diffs. `Buffer::record_changes` takes this set in place of a changed flag, and each buffer adds its ID when it changes. The snapshot stores each buffer's dirty, deleted-file, and conflict flags and counts how many buffers have each one, so `is_dirty`, `has_deleted_file`, and `has_conflict` don't scan every buffer. This also fixes three cases where the multibuffer stayed out of date until another buffer changed: - The `Buffer` methods `did_reload`, `set_capability`, `set_conflict`, and `set_agent_selections` changed dirty, conflict, or selection state without marking the buffer as changed. - Removing a buffer didn't update `is_dirty`, `has_deleted_file`, or `has_conflict`. - `MultiBuffer::clone` dropped changes that the original hadn't synced yet. Benchmark: a test searches an in-memory project of N files, with two matches in each, in a `ProjectSearchView`. Both versions call `MultiBuffer::sync_from_buffer_changes` N + 1 times, and sync time is the total of those calls. Release build, single-threaded GPUI test executor, multibuffer and worktree invariant checks off, Ryzen 7 9800X3D, median of five alternating runs of `main` and this branch: | Files | Sync before | Sync after | Sync speedup | Search before | Search after | Search speedup | |---|---|---|---|---|---|---| | 1,000 | 49.4 ms | 2.4 ms | 21× | 4.21 s | 4.13 s | 1.02× | | 2,000 | 216.3 ms | 5.2 ms | 42× | 10.59 s | 10.24 s | 1.03× | | 4,000 | 928.5 ms | 9.8 ms | 95× | 30.17 s | 28.83 s | 1.05× | ## Testing - `test_dirty_state_across_buffers` checks `MultiBuffer::is_dirty` across three buffers through edits, saves, a reload, a capability change, and an excerpt removal. It fails on `main` at the reload. - `test_deleted_file_and_conflict_state_across_buffers` marks two buffers deleted, then conflicted, without editing them, and clears or removes them one at a time. Each flag stays set until its last buffer is cleared or removed. It fails on `main` at the first conflict check. - `test_clone_with_pending_changes` clones a multibuffer before it syncs a buffer edit and checks that both copies show the edit. It fails on `main`, where the clone misses the edit. - After each mutation, the randomized multibuffer tests check that each buffer's snapshot matches the buffer's version and flags, and that the counts agree with the flags. - `cargo test -p multi_buffer`, `cargo test -p editor -p search -p language`, and `./script/clippy -p multi_buffer -p language` pass, as do the randomized multibuffer tests with `ITERATIONS=300`. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [x] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - Improved performance of multibuffers with many files, such as large project search results
This commit is contained in:
@@ -4909,7 +4909,7 @@ pub mod tests {
|
||||
let buffer = cx.new(|cx| Buffer::local("initial", cx));
|
||||
let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
|
||||
|
||||
// Edit the buffer. This sets buffer_changed_since_sync = true.
|
||||
// Edit the buffer. This adds it to the multibuffer's changed buffers.
|
||||
// Importantly, do NOT call multibuffer.snapshot() yet.
|
||||
buffer.update(cx, |buffer, cx| {
|
||||
buffer.edit([(0..0, "prefix ")], None, cx);
|
||||
|
||||
@@ -27,7 +27,7 @@ use crate::{
|
||||
use anyhow::{Context as _, Result};
|
||||
use clock::Lamport;
|
||||
pub use clock::ReplicaId;
|
||||
use collections::HashMap;
|
||||
use collections::{HashMap, HashSet};
|
||||
use encoding_rs::Encoding;
|
||||
use file_content::{ByteContent, decode_byte_header};
|
||||
use fs::MTime;
|
||||
@@ -45,7 +45,7 @@ use settings::{SettingsStore, WorktreeId};
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
any::Any,
|
||||
cell::Cell,
|
||||
cell::{Cell, RefCell},
|
||||
cmp::{self, Ordering, Reverse},
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fmt::Write as _,
|
||||
@@ -138,7 +138,7 @@ pub struct Buffer {
|
||||
/// Memoize calls to has_changes_since(saved_version).
|
||||
/// The contents of a cell are (self.version, has_changes) at the time of a last call.
|
||||
has_unsaved_edits: Cell<(clock::Global, bool)>,
|
||||
change_bits: Vec<rc::Weak<Cell<bool>>>,
|
||||
changed_buffer_sets: Vec<rc::Weak<RefCell<HashSet<BufferId>>>>,
|
||||
modeline: Option<Arc<ModelineSettings>>,
|
||||
_subscriptions: Vec<gpui::Subscription>,
|
||||
resolved_settings: Option<Arc<LanguageSettings>>,
|
||||
@@ -1193,7 +1193,7 @@ impl Buffer {
|
||||
completion_triggers_timestamp: Lamport::MIN,
|
||||
deferred_ops: OperationQueue::new(),
|
||||
has_conflict: false,
|
||||
change_bits: Default::default(),
|
||||
changed_buffer_sets: Default::default(),
|
||||
modeline: None,
|
||||
_subscriptions: Vec::new(),
|
||||
resolved_settings: None,
|
||||
@@ -1645,6 +1645,7 @@ impl Buffer {
|
||||
pub fn set_capability(&mut self, capability: Capability, cx: &mut Context<Self>) {
|
||||
if self.capability != capability {
|
||||
self.capability = capability;
|
||||
self.was_changed();
|
||||
cx.emit(BufferEvent::CapabilityChanged)
|
||||
}
|
||||
}
|
||||
@@ -1786,6 +1787,7 @@ impl Buffer {
|
||||
.set((self.saved_version.clone(), false));
|
||||
self.text.set_line_ending(line_ending);
|
||||
self.saved_mtime = mtime;
|
||||
self.was_changed();
|
||||
cx.emit(BufferEvent::Reloaded);
|
||||
cx.notify();
|
||||
}
|
||||
@@ -2549,6 +2551,7 @@ impl Buffer {
|
||||
/// Marks the buffer as having a conflict regardless of current buffer state.
|
||||
pub fn set_conflict(&mut self) {
|
||||
self.has_conflict = true;
|
||||
self.was_changed();
|
||||
}
|
||||
|
||||
/// Checks if the buffer and its file have both changed since the buffer
|
||||
@@ -2578,26 +2581,27 @@ impl Buffer {
|
||||
self.text.subscribe()
|
||||
}
|
||||
|
||||
/// Adds a bit to the list of bits that are set when the buffer's text changes.
|
||||
/// Registers a set that receives this buffer's id whenever the buffer changes.
|
||||
///
|
||||
/// This allows downstream code to check if the buffer's text has changed without
|
||||
/// waiting for an effect cycle, which would be required if using eents.
|
||||
pub fn record_changes(&mut self, bit: rc::Weak<Cell<bool>>) {
|
||||
pub fn record_changes(&mut self, changed_buffers: rc::Weak<RefCell<HashSet<BufferId>>>) {
|
||||
if let Err(ix) = self
|
||||
.change_bits
|
||||
.binary_search_by_key(&rc::Weak::as_ptr(&bit), rc::Weak::as_ptr)
|
||||
.changed_buffer_sets
|
||||
.binary_search_by_key(&rc::Weak::as_ptr(&changed_buffers), rc::Weak::as_ptr)
|
||||
{
|
||||
self.change_bits.insert(ix, bit);
|
||||
self.changed_buffer_sets.insert(ix, changed_buffers);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the change bit for all "listeners".
|
||||
/// Inserts this buffer's id into every set registered with [`Buffer::record_changes`].
|
||||
fn was_changed(&mut self) {
|
||||
self.change_bits.retain(|change_bit| {
|
||||
change_bit
|
||||
let buffer_id = self.remote_id();
|
||||
self.changed_buffer_sets.retain(|changed_buffers| {
|
||||
changed_buffers
|
||||
.upgrade()
|
||||
.inspect(|bit| {
|
||||
_ = bit.replace(true);
|
||||
.inspect(|changed_buffers| {
|
||||
changed_buffers.borrow_mut().insert(buffer_id);
|
||||
})
|
||||
.is_some()
|
||||
});
|
||||
@@ -2817,6 +2821,7 @@ impl Buffer {
|
||||
},
|
||||
);
|
||||
self.non_text_state_update_count += 1;
|
||||
self.was_changed();
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ use smallvec::SmallVec;
|
||||
use std::{
|
||||
any::type_name,
|
||||
borrow::Cow,
|
||||
cell::{Cell, OnceCell, Ref, RefCell},
|
||||
cell::{OnceCell, Ref, RefCell},
|
||||
cmp::{self, Ordering},
|
||||
fmt,
|
||||
future::Future,
|
||||
@@ -89,7 +89,9 @@ pub struct MultiBuffer {
|
||||
title: Option<String>,
|
||||
/// The writing capability of the multi-buffer.
|
||||
capability: Capability,
|
||||
buffer_changed_since_sync: Rc<Cell<bool>>,
|
||||
/// Ids of the buffers that changed or were added since the last sync. Buffers add their ids
|
||||
/// through [`Buffer::record_changes`].
|
||||
changed_buffers: Rc<RefCell<HashSet<BufferId>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
@@ -678,6 +680,78 @@ struct BufferStateSnapshot {
|
||||
pub(crate) path_key: PathKey,
|
||||
path_key_index: PathKeyIndex,
|
||||
buffer_snapshot: BufferSnapshot,
|
||||
status: BufferStatus,
|
||||
}
|
||||
|
||||
/// Buffer flags that `MultiBufferSnapshot` aggregates across its buffers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct BufferStatus {
|
||||
is_dirty: bool,
|
||||
has_deleted_file: bool,
|
||||
has_conflict: bool,
|
||||
}
|
||||
|
||||
impl BufferStatus {
|
||||
fn new(buffer: &Buffer) -> Self {
|
||||
Self {
|
||||
is_dirty: buffer.is_dirty(),
|
||||
has_deleted_file: buffer
|
||||
.file()
|
||||
.is_some_and(|file| file.disk_state().is_deleted()),
|
||||
has_conflict: buffer.has_conflict(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
struct BufferStatusCounts {
|
||||
dirty: usize,
|
||||
deleted_file: usize,
|
||||
conflict: usize,
|
||||
}
|
||||
|
||||
impl BufferStatusCounts {
|
||||
fn add(&mut self, status: BufferStatus) {
|
||||
self.dirty += status.is_dirty as usize;
|
||||
self.deleted_file += status.has_deleted_file as usize;
|
||||
self.conflict += status.has_conflict as usize;
|
||||
}
|
||||
|
||||
fn remove(&mut self, status: BufferStatus) {
|
||||
self.dirty -= status.is_dirty as usize;
|
||||
self.deleted_file -= status.has_deleted_file as usize;
|
||||
self.conflict -= status.has_conflict as usize;
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffer state snapshots by buffer id, with counts of the buffers that have each status flag.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct BufferStateSnapshots {
|
||||
snapshots: TreeMap<BufferId, BufferStateSnapshot>,
|
||||
status_counts: BufferStatusCounts,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for BufferStateSnapshots {
|
||||
type Target = TreeMap<BufferId, BufferStateSnapshot>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.snapshots
|
||||
}
|
||||
}
|
||||
|
||||
impl BufferStateSnapshots {
|
||||
fn insert(&mut self, buffer_id: BufferId, buffer_state: BufferStateSnapshot) {
|
||||
self.status_counts.add(buffer_state.status);
|
||||
if let Some(old_buffer_state) = self.snapshots.insert_or_replace(buffer_id, buffer_state) {
|
||||
self.status_counts.remove(old_buffer_state.status);
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, buffer_id: &BufferId) {
|
||||
if let Some(buffer_state) = self.snapshots.remove(buffer_id) {
|
||||
self.status_counts.remove(buffer_state.status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for BufferStateSnapshot {
|
||||
@@ -693,15 +767,12 @@ impl fmt::Debug for BufferStateSnapshot {
|
||||
#[derive(Clone, Default)]
|
||||
pub struct MultiBufferSnapshot {
|
||||
excerpts: SumTree<Excerpt>,
|
||||
buffers: TreeMap<BufferId, BufferStateSnapshot>,
|
||||
buffers: BufferStateSnapshots,
|
||||
path_keys: Arc<IndexSet<PathKey>>,
|
||||
diffs: SumTree<DiffStateSnapshot>,
|
||||
diff_transforms: SumTree<DiffTransform>,
|
||||
non_text_state_update_count: usize,
|
||||
edit_count: usize,
|
||||
is_dirty: bool,
|
||||
has_deleted_file: bool,
|
||||
has_conflict: bool,
|
||||
has_inverted_diff: bool,
|
||||
singleton: bool,
|
||||
trailing_excerpt_update_count: usize,
|
||||
@@ -1286,17 +1357,17 @@ impl MultiBuffer {
|
||||
singleton: false,
|
||||
capability,
|
||||
title: None,
|
||||
buffer_changed_since_sync: Default::default(),
|
||||
changed_buffers: Default::default(),
|
||||
history: History::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clone(&self, new_cx: &mut Context<Self>) -> Self {
|
||||
let mut buffers = BTreeMap::default();
|
||||
let buffer_changed_since_sync = Rc::new(Cell::new(false));
|
||||
let changed_buffers = Rc::new(RefCell::new(self.changed_buffers.borrow().clone()));
|
||||
for (buffer_id, buffer_state) in self.buffers.iter() {
|
||||
buffer_state.buffer.update(new_cx, |buffer, _| {
|
||||
buffer.record_changes(Rc::downgrade(&buffer_changed_since_sync));
|
||||
buffer.record_changes(Rc::downgrade(&changed_buffers));
|
||||
});
|
||||
buffers.insert(
|
||||
*buffer_id,
|
||||
@@ -1322,7 +1393,7 @@ impl MultiBuffer {
|
||||
capability: self.capability,
|
||||
history: self.history.clone(),
|
||||
title: self.title.clone(),
|
||||
buffer_changed_since_sync,
|
||||
changed_buffers,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1868,9 +1939,6 @@ impl MultiBuffer {
|
||||
diff_transforms: _,
|
||||
non_text_state_update_count: _,
|
||||
edit_count: _,
|
||||
is_dirty,
|
||||
has_deleted_file,
|
||||
has_conflict,
|
||||
has_inverted_diff,
|
||||
singleton: _,
|
||||
trailing_excerpt_update_count,
|
||||
@@ -1887,9 +1955,6 @@ impl MultiBuffer {
|
||||
*buffers = Default::default();
|
||||
*diffs = Default::default();
|
||||
*trailing_excerpt_update_count += 1;
|
||||
*is_dirty = false;
|
||||
*has_deleted_file = false;
|
||||
*has_conflict = false;
|
||||
*has_inverted_diff = false;
|
||||
|
||||
let edits = Self::sync_diff_transforms(
|
||||
@@ -2507,14 +2572,15 @@ impl MultiBuffer {
|
||||
|
||||
#[ztracing::instrument(skip_all)]
|
||||
fn sync(&self, cx: &App) {
|
||||
let changed = self.buffer_changed_since_sync.replace(false);
|
||||
if !changed {
|
||||
let changed_buffer_ids = mem::take(&mut *self.changed_buffers.borrow_mut());
|
||||
if changed_buffer_ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let edits = Self::sync_from_buffer_changes(
|
||||
&mut self.snapshot.borrow_mut(),
|
||||
&self.buffers,
|
||||
&self.diffs,
|
||||
&changed_buffer_ids,
|
||||
cx,
|
||||
);
|
||||
if !edits.is_empty() {
|
||||
@@ -2524,11 +2590,17 @@ impl MultiBuffer {
|
||||
|
||||
fn sync_mut(&mut self, cx: &App) -> &mut MultiBufferSnapshot {
|
||||
let snapshot = self.snapshot.get_mut();
|
||||
let changed = self.buffer_changed_since_sync.replace(false);
|
||||
if !changed {
|
||||
let changed_buffer_ids = mem::take(&mut *self.changed_buffers.borrow_mut());
|
||||
if changed_buffer_ids.is_empty() {
|
||||
return snapshot;
|
||||
}
|
||||
let edits = Self::sync_from_buffer_changes(snapshot, &self.buffers, &self.diffs, cx);
|
||||
let edits = Self::sync_from_buffer_changes(
|
||||
snapshot,
|
||||
&self.buffers,
|
||||
&self.diffs,
|
||||
&changed_buffer_ids,
|
||||
cx,
|
||||
);
|
||||
|
||||
if !edits.is_empty() {
|
||||
self.subscriptions.publish(edits);
|
||||
@@ -2541,6 +2613,7 @@ impl MultiBuffer {
|
||||
snapshot: &mut MultiBufferSnapshot,
|
||||
buffers: &BTreeMap<BufferId, BufferState>,
|
||||
diffs: &HashMap<BufferId, DiffState>,
|
||||
changed_buffer_ids: &HashSet<BufferId>,
|
||||
cx: &App,
|
||||
) -> Vec<Edit<MultiBufferOffset>> {
|
||||
let MultiBufferSnapshot {
|
||||
@@ -2551,9 +2624,6 @@ impl MultiBuffer {
|
||||
diff_transforms: _,
|
||||
non_text_state_update_count,
|
||||
edit_count,
|
||||
is_dirty,
|
||||
has_deleted_file,
|
||||
has_conflict,
|
||||
has_inverted_diff: _,
|
||||
singleton: _,
|
||||
trailing_excerpt_update_count: _,
|
||||
@@ -2562,13 +2632,13 @@ impl MultiBuffer {
|
||||
use_extended_diff_range: _,
|
||||
show_headers: _,
|
||||
} = snapshot;
|
||||
*is_dirty = false;
|
||||
*has_deleted_file = false;
|
||||
*has_conflict = false;
|
||||
|
||||
if !diffs.is_empty() {
|
||||
let mut diffs_to_add = Vec::new();
|
||||
for (id, diff) in diffs {
|
||||
for (id, diff) in changed_buffer_ids
|
||||
.iter()
|
||||
.filter_map(|id| diffs.get_key_value(id))
|
||||
{
|
||||
if find_diff_state(buffer_diff, *id).is_none_or(|existing_diff| {
|
||||
if existing_diff.main_buffer.is_none() {
|
||||
return false;
|
||||
@@ -2580,7 +2650,7 @@ impl MultiBuffer {
|
||||
.changed_since(existing_diff.base_text().version())
|
||||
}) {
|
||||
if diffs_to_add.capacity() == 0 {
|
||||
diffs_to_add.reserve(diffs.len());
|
||||
diffs_to_add.reserve(changed_buffer_ids.len());
|
||||
}
|
||||
diffs_to_add.push(sum_tree::Edit::Insert(diff.snapshot(*id, cx)));
|
||||
}
|
||||
@@ -2591,7 +2661,10 @@ impl MultiBuffer {
|
||||
let mut paths_to_edit = Vec::new();
|
||||
let mut non_text_state_updated = false;
|
||||
let mut edited = false;
|
||||
for buffer_state in buffers.values() {
|
||||
for buffer_state in changed_buffer_ids
|
||||
.iter()
|
||||
.filter_map(|buffer_id| buffers.get(buffer_id))
|
||||
{
|
||||
let buffer = buffer_state.buffer.read(cx);
|
||||
let last_snapshot = buffer_snapshots
|
||||
.get(&buffer.remote_id())
|
||||
@@ -2603,7 +2676,10 @@ impl MultiBuffer {
|
||||
current_version.changed_since(last_snapshot.buffer_snapshot.version());
|
||||
let buffer_non_text_state_updated = non_text_state_update_count
|
||||
> last_snapshot.buffer_snapshot.non_text_state_update_count();
|
||||
if buffer_edited || buffer_non_text_state_updated {
|
||||
if buffer_edited
|
||||
|| buffer_non_text_state_updated
|
||||
|| BufferStatus::new(buffer) != last_snapshot.status
|
||||
{
|
||||
paths_to_edit.push((
|
||||
last_snapshot.path_key.clone(),
|
||||
last_snapshot.path_key_index,
|
||||
@@ -2618,11 +2694,6 @@ impl MultiBuffer {
|
||||
|
||||
edited |= buffer_edited;
|
||||
non_text_state_updated |= buffer_non_text_state_updated;
|
||||
*is_dirty |= buffer.is_dirty();
|
||||
*has_deleted_file |= buffer
|
||||
.file()
|
||||
.is_some_and(|file| file.disk_state().is_deleted());
|
||||
*has_conflict |= buffer.has_conflict();
|
||||
}
|
||||
if edited {
|
||||
*edit_count += 1;
|
||||
@@ -2648,6 +2719,7 @@ impl MultiBuffer {
|
||||
path_key: path.clone(),
|
||||
path_key_index,
|
||||
buffer_snapshot: buffer.snapshot(),
|
||||
status: BufferStatus::new(buffer),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3383,7 +3455,29 @@ impl MultiBuffer {
|
||||
}
|
||||
|
||||
fn check_invariants(&self, cx: &App) {
|
||||
self.read(cx).check_invariants();
|
||||
let snapshot = self.read(cx);
|
||||
snapshot.check_invariants();
|
||||
|
||||
let mut status_counts = BufferStatusCounts::default();
|
||||
for (buffer_id, buffer_state) in &self.buffers {
|
||||
let buffer = buffer_state.buffer.read(cx);
|
||||
let buffer_state_snapshot = snapshot
|
||||
.buffers
|
||||
.get(buffer_id)
|
||||
.expect("each buffer should have a snapshot");
|
||||
assert_eq!(
|
||||
buffer_state_snapshot.buffer_snapshot.version(),
|
||||
&buffer.version(),
|
||||
"stale snapshot for buffer {buffer_id:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
buffer_state_snapshot.status,
|
||||
BufferStatus::new(buffer),
|
||||
"stale status for buffer {buffer_id:?}"
|
||||
);
|
||||
status_counts.add(buffer_state_snapshot.status);
|
||||
}
|
||||
assert_eq!(snapshot.buffers.status_counts, status_counts);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6354,15 +6448,15 @@ impl MultiBufferSnapshot {
|
||||
}
|
||||
|
||||
pub fn is_dirty(&self) -> bool {
|
||||
self.is_dirty
|
||||
self.buffers.status_counts.dirty > 0
|
||||
}
|
||||
|
||||
pub fn has_deleted_file(&self) -> bool {
|
||||
self.has_deleted_file
|
||||
self.buffers.status_counts.deleted_file > 0
|
||||
}
|
||||
|
||||
pub fn has_conflict(&self) -> bool {
|
||||
self.has_conflict
|
||||
self.buffers.status_counts.conflict > 0
|
||||
}
|
||||
|
||||
pub fn has_diagnostics(&self) -> bool {
|
||||
|
||||
@@ -2,15 +2,17 @@ use super::*;
|
||||
use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
|
||||
use gpui::{App, Entity, TestAppContext};
|
||||
use indoc::indoc;
|
||||
use language::{Buffer, Rope};
|
||||
use language::{Buffer, DiskState, LocalFile, Rope};
|
||||
use parking_lot::RwLock;
|
||||
use rand::prelude::*;
|
||||
use settings::SettingsStore;
|
||||
use settings::{SettingsStore, WorktreeId};
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use util::RandomCharIter;
|
||||
use util::rel_path::rel_path;
|
||||
use util::paths::PathStyle;
|
||||
use util::rel_path::{RelPath, rel_path};
|
||||
use util::test::sample_text;
|
||||
|
||||
#[gpui::test]
|
||||
@@ -856,6 +858,120 @@ fn test_excerpt_events(cx: &mut App) {
|
||||
assert_eq!(*follower_edit_event_count.read(), 5);
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_dirty_state_across_buffers(cx: &mut App) {
|
||||
let buffers = (0..3)
|
||||
.map(|_| cx.new(|cx| Buffer::local(sample_text(3, 3, 'a'), cx)))
|
||||
.collect::<Vec<_>>();
|
||||
let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
|
||||
multibuffer.update(cx, |multibuffer, cx| {
|
||||
for (ix, buffer) in buffers.iter().enumerate() {
|
||||
multibuffer.set_excerpts_for_path(
|
||||
PathKey::sorted(ix as u64),
|
||||
buffer.clone(),
|
||||
[Point::zero()..Point::new(1, 0)],
|
||||
0,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
});
|
||||
let is_dirty = |cx: &App| multibuffer.read(cx).is_dirty(cx);
|
||||
let edit = |buffer: &Entity<Buffer>, cx: &mut App| {
|
||||
buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "x")], None, cx));
|
||||
};
|
||||
assert!(!is_dirty(cx));
|
||||
|
||||
edit(&buffers[0], cx);
|
||||
edit(&buffers[1], cx);
|
||||
assert!(is_dirty(cx));
|
||||
buffers[0].update(cx, |buffer, cx| buffer.did_save(buffer.version(), None, cx));
|
||||
assert!(is_dirty(cx));
|
||||
buffers[1].update(cx, |buffer, cx| buffer.did_save(buffer.version(), None, cx));
|
||||
assert!(!is_dirty(cx));
|
||||
|
||||
edit(&buffers[2], cx);
|
||||
assert!(is_dirty(cx));
|
||||
buffers[2].update(cx, |buffer, cx| {
|
||||
buffer.did_reload(buffer.version(), buffer.line_ending(), None, cx)
|
||||
});
|
||||
assert!(!is_dirty(cx));
|
||||
|
||||
edit(&buffers[1], cx);
|
||||
assert!(is_dirty(cx));
|
||||
buffers[1].update(cx, |buffer, cx| {
|
||||
buffer.set_capability(Capability::ReadOnly, cx)
|
||||
});
|
||||
assert!(!is_dirty(cx));
|
||||
buffers[1].update(cx, |buffer, cx| {
|
||||
buffer.set_capability(Capability::ReadWrite, cx)
|
||||
});
|
||||
assert!(is_dirty(cx));
|
||||
|
||||
multibuffer.update(cx, |multibuffer, cx| {
|
||||
multibuffer.remove_excerpts(PathKey::sorted(1), cx);
|
||||
});
|
||||
assert!(!is_dirty(cx));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_deleted_file_and_conflict_state_across_buffers(cx: &mut App) {
|
||||
let buffers = (0..2)
|
||||
.map(|_| cx.new(|cx| Buffer::local(sample_text(3, 3, 'a'), cx)))
|
||||
.collect::<Vec<_>>();
|
||||
let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
|
||||
multibuffer.update(cx, |multibuffer, cx| {
|
||||
for (ix, buffer) in buffers.iter().enumerate() {
|
||||
multibuffer.set_excerpts_for_path(
|
||||
PathKey::sorted(ix as u64),
|
||||
buffer.clone(),
|
||||
[Point::zero()..Point::new(1, 0)],
|
||||
0,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
});
|
||||
let has_deleted_file = |cx: &App| multibuffer.read(cx).has_deleted_file(cx);
|
||||
let has_conflict = |cx: &App| multibuffer.read(cx).has_conflict(cx);
|
||||
let set_disk_state = |buffer: &Entity<Buffer>, disk_state: DiskState, cx: &mut App| {
|
||||
let file = Arc::new(TestFile {
|
||||
path: rel_path("file").into_arc(),
|
||||
disk_state,
|
||||
});
|
||||
buffer.update(cx, |buffer, cx| buffer.file_updated(file, cx));
|
||||
};
|
||||
|
||||
set_disk_state(&buffers[0], DiskState::Deleted, cx);
|
||||
set_disk_state(&buffers[1], DiskState::Deleted, cx);
|
||||
assert!(has_deleted_file(cx));
|
||||
set_disk_state(&buffers[0], DiskState::New, cx);
|
||||
assert!(has_deleted_file(cx));
|
||||
set_disk_state(&buffers[1], DiskState::New, cx);
|
||||
assert!(!has_deleted_file(cx));
|
||||
|
||||
buffers[0].update(cx, |buffer, _| buffer.set_conflict());
|
||||
buffers[1].update(cx, |buffer, _| buffer.set_conflict());
|
||||
assert!(has_conflict(cx));
|
||||
buffers[0].update(cx, |buffer, cx| buffer.did_save(buffer.version(), None, cx));
|
||||
assert!(has_conflict(cx));
|
||||
multibuffer.update(cx, |multibuffer, cx| {
|
||||
multibuffer.remove_excerpts(PathKey::sorted(1), cx);
|
||||
});
|
||||
assert!(!has_conflict(cx));
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_clone_with_pending_changes(cx: &mut App) {
|
||||
let buffer = cx.new(|cx| Buffer::local("abc", cx));
|
||||
let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
|
||||
assert_eq!(multibuffer.read(cx).snapshot(cx).text(), "abc");
|
||||
|
||||
buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "x")], None, cx));
|
||||
let cloned_multibuffer =
|
||||
multibuffer.update(cx, |multibuffer, cx| cx.new(|cx| multibuffer.clone(cx)));
|
||||
assert_eq!(cloned_multibuffer.read(cx).snapshot(cx).text(), "xabc");
|
||||
assert_eq!(multibuffer.read(cx).snapshot(cx).text(), "xabc");
|
||||
}
|
||||
|
||||
#[gpui::test]
|
||||
fn test_set_excerpts_for_path_reuses_excerpts_when_only_primary_changes(cx: &mut App) {
|
||||
let buffer = cx.new(|cx| Buffer::local(sample_text(10, 6, 'a'), cx));
|
||||
@@ -7379,3 +7495,46 @@ enum AnchorContractOp {
|
||||
right: bool,
|
||||
},
|
||||
}
|
||||
|
||||
struct TestFile {
|
||||
path: Arc<RelPath>,
|
||||
disk_state: DiskState,
|
||||
}
|
||||
|
||||
impl File for TestFile {
|
||||
fn as_local(&self) -> Option<&dyn LocalFile> {
|
||||
None
|
||||
}
|
||||
|
||||
fn disk_state(&self) -> DiskState {
|
||||
self.disk_state
|
||||
}
|
||||
|
||||
fn path(&self) -> &Arc<RelPath> {
|
||||
&self.path
|
||||
}
|
||||
|
||||
fn full_path(&self, _: &App) -> PathBuf {
|
||||
self.path.as_std_path().to_path_buf()
|
||||
}
|
||||
|
||||
fn path_style(&self, _: &App) -> PathStyle {
|
||||
PathStyle::local()
|
||||
}
|
||||
|
||||
fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
|
||||
self.path.file_name().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn worktree_id(&self, _: &App) -> WorktreeId {
|
||||
WorktreeId::from_usize(0)
|
||||
}
|
||||
|
||||
fn to_proto(&self, _: &App) -> language::proto::File {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn is_private(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ use util::rel_path::RelPath;
|
||||
use ztracing::instrument;
|
||||
|
||||
use crate::{
|
||||
Anchor, BufferState, BufferStateSnapshot, DiffChangeKind, Event, Excerpt, ExcerptOffset,
|
||||
ExcerptRange, ExcerptSummary, ExpandExcerptDirection, MultiBuffer, MultiBufferOffset,
|
||||
PathKeyIndex, build_excerpt_ranges, remove_diff_state,
|
||||
Anchor, BufferState, BufferStateSnapshot, BufferStatus, DiffChangeKind, Event, Excerpt,
|
||||
ExcerptOffset, ExcerptRange, ExcerptSummary, ExpandExcerptDirection, MultiBuffer,
|
||||
MultiBufferOffset, PathKeyIndex, build_excerpt_ranges, remove_diff_state,
|
||||
};
|
||||
|
||||
#[derive(PartialEq, Eq, Ord, PartialOrd, Clone, Hash, Debug)]
|
||||
@@ -622,13 +622,14 @@ impl MultiBuffer {
|
||||
path_key: path_key.clone(),
|
||||
path_key_index,
|
||||
buffer_snapshot: buffer_snapshot.clone(),
|
||||
status: BufferStatus::new(buffer.read(cx)),
|
||||
},
|
||||
);
|
||||
|
||||
self.buffers.entry(buffer_id).or_insert_with(|| {
|
||||
self.buffer_changed_since_sync.replace(true);
|
||||
self.changed_buffers.borrow_mut().insert(buffer_id);
|
||||
buffer.update(cx, |buffer, _| {
|
||||
buffer.record_changes(Rc::downgrade(&self.buffer_changed_since_sync));
|
||||
buffer.record_changes(Rc::downgrade(&self.changed_buffers));
|
||||
});
|
||||
BufferState {
|
||||
_subscriptions: [
|
||||
|
||||
Reference in New Issue
Block a user