buffer_store.rs

   1use crate::{
   2    ProjectPath,
   3    lsp_store::OpenLspBufferHandle,
   4    worktree_store::{WorktreeStore, WorktreeStoreEvent},
   5};
   6use anyhow::{Context as _, Result, anyhow};
   7use client::Client;
   8use collections::{HashMap, HashSet, hash_map};
   9use futures::{Future, FutureExt as _, channel::oneshot, future::Shared};
  10use gpui::{
  11    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Subscription, Task, WeakEntity,
  12};
  13use language::{
  14    Buffer, BufferEvent, Capability, DiskState, File as _, Language, Operation,
  15    proto::{
  16        deserialize_line_ending, deserialize_version, serialize_line_ending, serialize_version,
  17        split_operations,
  18    },
  19};
  20use rpc::{
  21    AnyProtoClient, ErrorCode, ErrorExt as _, TypedEnvelope,
  22    proto::{self, PeerId},
  23};
  24
  25use settings::Settings;
  26use std::{io, sync::Arc, time::Instant};
  27use text::{BufferId, ReplicaId};
  28use util::{ResultExt as _, TryFutureExt, debug_panic, maybe, rel_path::RelPath};
  29use worktree::{File, PathChange, ProjectEntryId, Worktree, WorktreeId, WorktreeSettings};
  30
  31/// A set of open buffers.
  32pub struct BufferStore {
  33    state: BufferStoreState,
  34    #[allow(clippy::type_complexity)]
  35    loading_buffers: HashMap<ProjectPath, Shared<Task<Result<Entity<Buffer>, Arc<anyhow::Error>>>>>,
  36    worktree_store: Entity<WorktreeStore>,
  37    opened_buffers: HashMap<BufferId, OpenBuffer>,
  38    path_to_buffer_id: HashMap<ProjectPath, BufferId>,
  39    downstream_client: Option<(AnyProtoClient, u64)>,
  40    shared_buffers: HashMap<proto::PeerId, HashMap<BufferId, SharedBuffer>>,
  41    non_searchable_buffers: HashSet<BufferId>,
  42    project_search: RemoteProjectSearchState,
  43}
  44
  45#[derive(Default)]
  46struct RemoteProjectSearchState {
  47    // List of ongoing project search chunks from our remote host. Used by the side issuing a search RPC request.
  48    chunks: HashMap<u64, smol::channel::Sender<BufferId>>,
  49    // Monotonously-increasing handle to hand out to remote host in order to identify the project search result chunk.
  50    next_id: u64,
  51    // Used by the side running the actual search for match candidates to potentially cancel the search prematurely.
  52    searches_in_progress: HashMap<(PeerId, u64), Task<Result<()>>>,
  53}
  54
  55#[derive(Hash, Eq, PartialEq, Clone)]
  56struct SharedBuffer {
  57    buffer: Entity<Buffer>,
  58    lsp_handle: Option<OpenLspBufferHandle>,
  59}
  60
  61enum BufferStoreState {
  62    Local(LocalBufferStore),
  63    Remote(RemoteBufferStore),
  64}
  65
  66struct RemoteBufferStore {
  67    shared_with_me: HashSet<Entity<Buffer>>,
  68    upstream_client: AnyProtoClient,
  69    project_id: u64,
  70    loading_remote_buffers_by_id: HashMap<BufferId, Entity<Buffer>>,
  71    remote_buffer_listeners:
  72        HashMap<BufferId, Vec<oneshot::Sender<anyhow::Result<Entity<Buffer>>>>>,
  73    worktree_store: Entity<WorktreeStore>,
  74}
  75
  76struct LocalBufferStore {
  77    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  78    worktree_store: Entity<WorktreeStore>,
  79    _subscription: Subscription,
  80}
  81
  82enum OpenBuffer {
  83    Complete { buffer: WeakEntity<Buffer> },
  84    Operations(Vec<Operation>),
  85}
  86
  87pub enum BufferStoreEvent {
  88    BufferAdded(Entity<Buffer>),
  89    SharedBufferClosed(proto::PeerId, BufferId),
  90    BufferDropped(BufferId),
  91    BufferChangedFilePath {
  92        buffer: Entity<Buffer>,
  93        old_file: Option<Arc<dyn language::File>>,
  94    },
  95}
  96
  97#[derive(Default, Debug, Clone)]
  98pub struct ProjectTransaction(pub HashMap<Entity<Buffer>, language::Transaction>);
  99
 100impl PartialEq for ProjectTransaction {
 101    fn eq(&self, other: &Self) -> bool {
 102        self.0.len() == other.0.len()
 103            && self.0.iter().all(|(buffer, transaction)| {
 104                other.0.get(buffer).is_some_and(|t| t.id == transaction.id)
 105            })
 106    }
 107}
 108
 109impl EventEmitter<BufferStoreEvent> for BufferStore {}
 110
 111impl RemoteBufferStore {
 112    pub fn wait_for_remote_buffer(
 113        &mut self,
 114        id: BufferId,
 115        cx: &mut Context<BufferStore>,
 116    ) -> Task<Result<Entity<Buffer>>> {
 117        let (tx, rx) = oneshot::channel();
 118        self.remote_buffer_listeners.entry(id).or_default().push(tx);
 119
 120        cx.spawn(async move |this, cx| {
 121            if let Some(buffer) = this
 122                .read_with(cx, |buffer_store, _| buffer_store.get(id))
 123                .ok()
 124                .flatten()
 125            {
 126                return Ok(buffer);
 127            }
 128
 129            cx.background_spawn(async move { rx.await? }).await
 130        })
 131    }
 132
 133    fn save_remote_buffer(
 134        &self,
 135        buffer_handle: Entity<Buffer>,
 136        new_path: Option<proto::ProjectPath>,
 137        cx: &Context<BufferStore>,
 138    ) -> Task<Result<()>> {
 139        let buffer = buffer_handle.read(cx);
 140        let buffer_id = buffer.remote_id().into();
 141        let version = buffer.version();
 142        let rpc = self.upstream_client.clone();
 143        let project_id = self.project_id;
 144        cx.spawn(async move |_, cx| {
 145            let response = rpc
 146                .request(proto::SaveBuffer {
 147                    project_id,
 148                    buffer_id,
 149                    new_path,
 150                    version: serialize_version(&version),
 151                })
 152                .await?;
 153            let version = deserialize_version(&response.version);
 154            let mtime = response.mtime.map(|mtime| mtime.into());
 155
 156            buffer_handle.update(cx, |buffer, cx| {
 157                buffer.did_save(version.clone(), mtime, cx);
 158            });
 159
 160            Ok(())
 161        })
 162    }
 163
 164    pub fn handle_create_buffer_for_peer(
 165        &mut self,
 166        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 167        replica_id: ReplicaId,
 168        capability: Capability,
 169        cx: &mut Context<BufferStore>,
 170    ) -> Result<Option<Entity<Buffer>>> {
 171        match envelope.payload.variant.context("missing variant")? {
 172            proto::create_buffer_for_peer::Variant::State(mut state) => {
 173                let buffer_id = BufferId::new(state.id)?;
 174
 175                let buffer_result = maybe!({
 176                    let mut buffer_file = None;
 177                    if let Some(file) = state.file.take() {
 178                        let worktree_id = worktree::WorktreeId::from_proto(file.worktree_id);
 179                        let worktree = self
 180                            .worktree_store
 181                            .read(cx)
 182                            .worktree_for_id(worktree_id, cx)
 183                            .with_context(|| {
 184                                format!("no worktree found for id {}", file.worktree_id)
 185                            })?;
 186                        buffer_file = Some(Arc::new(File::from_proto(file, worktree, cx)?)
 187                            as Arc<dyn language::File>);
 188                    }
 189                    Buffer::from_proto(replica_id, capability, state, buffer_file)
 190                });
 191
 192                match buffer_result {
 193                    Ok(buffer) => {
 194                        let buffer = cx.new(|_| buffer);
 195                        self.loading_remote_buffers_by_id.insert(buffer_id, buffer);
 196                    }
 197                    Err(error) => {
 198                        if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 199                            for listener in listeners {
 200                                listener.send(Err(anyhow!(error.cloned()))).ok();
 201                            }
 202                        }
 203                    }
 204                }
 205            }
 206            proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 207                let buffer_id = BufferId::new(chunk.buffer_id)?;
 208                let buffer = self
 209                    .loading_remote_buffers_by_id
 210                    .get(&buffer_id)
 211                    .cloned()
 212                    .with_context(|| {
 213                        format!(
 214                            "received chunk for buffer {} without initial state",
 215                            chunk.buffer_id
 216                        )
 217                    })?;
 218
 219                let result = maybe!({
 220                    let operations = chunk
 221                        .operations
 222                        .into_iter()
 223                        .map(language::proto::deserialize_operation)
 224                        .collect::<Result<Vec<_>>>()?;
 225                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx));
 226                    anyhow::Ok(())
 227                });
 228
 229                if let Err(error) = result {
 230                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 231                    if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 232                        for listener in listeners {
 233                            listener.send(Err(error.cloned())).ok();
 234                        }
 235                    }
 236                } else if chunk.is_last {
 237                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 238                    if self.upstream_client.is_via_collab() {
 239                        // retain buffers sent by peers to avoid races.
 240                        self.shared_with_me.insert(buffer.clone());
 241                    }
 242
 243                    if let Some(senders) = self.remote_buffer_listeners.remove(&buffer_id) {
 244                        for sender in senders {
 245                            sender.send(Ok(buffer.clone())).ok();
 246                        }
 247                    }
 248                    return Ok(Some(buffer));
 249                }
 250            }
 251        }
 252        Ok(None)
 253    }
 254
 255    pub fn incomplete_buffer_ids(&self) -> Vec<BufferId> {
 256        self.loading_remote_buffers_by_id
 257            .keys()
 258            .copied()
 259            .collect::<Vec<_>>()
 260    }
 261
 262    pub fn deserialize_project_transaction(
 263        &self,
 264        message: proto::ProjectTransaction,
 265        push_to_history: bool,
 266        cx: &mut Context<BufferStore>,
 267    ) -> Task<Result<ProjectTransaction>> {
 268        cx.spawn(async move |this, cx| {
 269            let mut project_transaction = ProjectTransaction::default();
 270            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 271            {
 272                let buffer_id = BufferId::new(buffer_id)?;
 273                let buffer = this
 274                    .update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 275                    .await?;
 276                let transaction = language::proto::deserialize_transaction(transaction)?;
 277                project_transaction.0.insert(buffer, transaction);
 278            }
 279
 280            for (buffer, transaction) in &project_transaction.0 {
 281                buffer
 282                    .update(cx, |buffer, _| {
 283                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 284                    })
 285                    .await?;
 286
 287                if push_to_history {
 288                    buffer.update(cx, |buffer, _| {
 289                        buffer.push_transaction(transaction.clone(), Instant::now());
 290                        buffer.finalize_last_transaction();
 291                    });
 292                }
 293            }
 294
 295            Ok(project_transaction)
 296        })
 297    }
 298
 299    fn open_buffer(
 300        &self,
 301        path: Arc<RelPath>,
 302        worktree: Entity<Worktree>,
 303        cx: &mut Context<BufferStore>,
 304    ) -> Task<Result<Entity<Buffer>>> {
 305        let worktree_id = worktree.read(cx).id().to_proto();
 306        let project_id = self.project_id;
 307        let client = self.upstream_client.clone();
 308        cx.spawn(async move |this, cx| {
 309            let response = client
 310                .request(proto::OpenBufferByPath {
 311                    project_id,
 312                    worktree_id,
 313                    path: path.to_proto(),
 314                })
 315                .await?;
 316            let buffer_id = BufferId::new(response.buffer_id)?;
 317
 318            let buffer = this
 319                .update(cx, {
 320                    |this, cx| this.wait_for_remote_buffer(buffer_id, cx)
 321                })?
 322                .await?;
 323
 324            Ok(buffer)
 325        })
 326    }
 327
 328    fn create_buffer(
 329        &self,
 330        language: Option<Arc<Language>>,
 331        project_searchable: bool,
 332        cx: &mut Context<BufferStore>,
 333    ) -> Task<Result<Entity<Buffer>>> {
 334        let create = self.upstream_client.request(proto::OpenNewBuffer {
 335            project_id: self.project_id,
 336        });
 337        cx.spawn(async move |this, cx| {
 338            let response = create.await?;
 339            let buffer_id = BufferId::new(response.buffer_id)?;
 340
 341            let buffer = this
 342                .update(cx, |this, cx| {
 343                    if !project_searchable {
 344                        this.non_searchable_buffers.insert(buffer_id);
 345                    }
 346                    this.wait_for_remote_buffer(buffer_id, cx)
 347                })?
 348                .await?;
 349            if let Some(language) = language {
 350                buffer.update(cx, |buffer, cx| {
 351                    buffer.set_language(Some(language), cx);
 352                });
 353            }
 354            Ok(buffer)
 355        })
 356    }
 357
 358    fn reload_buffers(
 359        &self,
 360        buffers: HashSet<Entity<Buffer>>,
 361        push_to_history: bool,
 362        cx: &mut Context<BufferStore>,
 363    ) -> Task<Result<ProjectTransaction>> {
 364        let request = self.upstream_client.request(proto::ReloadBuffers {
 365            project_id: self.project_id,
 366            buffer_ids: buffers
 367                .iter()
 368                .map(|buffer| buffer.read(cx).remote_id().to_proto())
 369                .collect(),
 370        });
 371
 372        cx.spawn(async move |this, cx| {
 373            let response = request.await?.transaction.context("missing transaction")?;
 374            this.update(cx, |this, cx| {
 375                this.deserialize_project_transaction(response, push_to_history, cx)
 376            })?
 377            .await
 378        })
 379    }
 380}
 381
 382impl LocalBufferStore {
 383    fn save_local_buffer(
 384        &self,
 385        buffer_handle: Entity<Buffer>,
 386        worktree: Entity<Worktree>,
 387        path: Arc<RelPath>,
 388        mut has_changed_file: bool,
 389        cx: &mut Context<BufferStore>,
 390    ) -> Task<Result<()>> {
 391        let buffer = buffer_handle.read(cx);
 392
 393        let text = buffer.as_rope().clone();
 394        let line_ending = buffer.line_ending();
 395        let encoding = buffer.encoding();
 396        let has_bom = buffer.has_bom();
 397        let version = buffer.version();
 398        let buffer_id = buffer.remote_id();
 399        let file = buffer.file().cloned();
 400        if file
 401            .as_ref()
 402            .is_some_and(|file| file.disk_state() == DiskState::New)
 403        {
 404            has_changed_file = true;
 405        }
 406
 407        let save = worktree.update(cx, |worktree, cx| {
 408            worktree.write_file(path, text, line_ending, encoding, has_bom, cx)
 409        });
 410
 411        cx.spawn(async move |this, cx| {
 412            let new_file = save.await?;
 413            let mtime = new_file.disk_state().mtime();
 414            this.update(cx, |this, cx| {
 415                if let Some((downstream_client, project_id)) = this.downstream_client.clone() {
 416                    if has_changed_file {
 417                        downstream_client
 418                            .send(proto::UpdateBufferFile {
 419                                project_id,
 420                                buffer_id: buffer_id.to_proto(),
 421                                file: Some(language::File::to_proto(&*new_file, cx)),
 422                            })
 423                            .log_err();
 424                    }
 425                    downstream_client
 426                        .send(proto::BufferSaved {
 427                            project_id,
 428                            buffer_id: buffer_id.to_proto(),
 429                            version: serialize_version(&version),
 430                            mtime: mtime.map(|time| time.into()),
 431                        })
 432                        .log_err();
 433                }
 434            })?;
 435            buffer_handle.update(cx, |buffer, cx| {
 436                if has_changed_file {
 437                    buffer.file_updated(new_file, cx);
 438                }
 439                buffer.did_save(version.clone(), mtime, cx);
 440            });
 441            Ok(())
 442        })
 443    }
 444
 445    fn subscribe_to_worktree(
 446        &mut self,
 447        worktree: &Entity<Worktree>,
 448        cx: &mut Context<BufferStore>,
 449    ) {
 450        cx.subscribe(worktree, |this, worktree, event, cx| {
 451            if worktree.read(cx).is_local()
 452                && let worktree::Event::UpdatedEntries(changes) = event
 453            {
 454                Self::local_worktree_entries_changed(this, &worktree, changes, cx);
 455            }
 456        })
 457        .detach();
 458    }
 459
 460    fn local_worktree_entries_changed(
 461        this: &mut BufferStore,
 462        worktree_handle: &Entity<Worktree>,
 463        changes: &[(Arc<RelPath>, ProjectEntryId, PathChange)],
 464        cx: &mut Context<BufferStore>,
 465    ) {
 466        let snapshot = worktree_handle.read(cx).snapshot();
 467        for (path, entry_id, _) in changes {
 468            Self::local_worktree_entry_changed(
 469                this,
 470                *entry_id,
 471                path,
 472                worktree_handle,
 473                &snapshot,
 474                cx,
 475            );
 476        }
 477    }
 478
 479    fn local_worktree_entry_changed(
 480        this: &mut BufferStore,
 481        entry_id: ProjectEntryId,
 482        path: &Arc<RelPath>,
 483        worktree: &Entity<worktree::Worktree>,
 484        snapshot: &worktree::Snapshot,
 485        cx: &mut Context<BufferStore>,
 486    ) -> Option<()> {
 487        let project_path = ProjectPath {
 488            worktree_id: snapshot.id(),
 489            path: path.clone(),
 490        };
 491
 492        let buffer_id = this
 493            .as_local_mut()
 494            .and_then(|local| local.local_buffer_ids_by_entry_id.get(&entry_id))
 495            .copied()
 496            .or_else(|| this.path_to_buffer_id.get(&project_path).copied())?;
 497
 498        let buffer = if let Some(buffer) = this.get(buffer_id) {
 499            Some(buffer)
 500        } else {
 501            this.opened_buffers.remove(&buffer_id);
 502            this.non_searchable_buffers.remove(&buffer_id);
 503            None
 504        };
 505
 506        let buffer = if let Some(buffer) = buffer {
 507            buffer
 508        } else {
 509            this.path_to_buffer_id.remove(&project_path);
 510            let this = this.as_local_mut()?;
 511            this.local_buffer_ids_by_entry_id.remove(&entry_id);
 512            return None;
 513        };
 514
 515        let events = buffer.update(cx, |buffer, cx| {
 516            let file = buffer.file()?;
 517            let old_file = File::from_dyn(Some(file))?;
 518            if old_file.worktree != *worktree {
 519                return None;
 520            }
 521
 522            let snapshot_entry = old_file
 523                .entry_id
 524                .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 525                .or_else(|| snapshot.entry_for_path(old_file.path.as_ref()));
 526
 527            let new_file = if let Some(entry) = snapshot_entry {
 528                File {
 529                    disk_state: match entry.mtime {
 530                        Some(mtime) => DiskState::Present {
 531                            mtime,
 532                            size: entry.size,
 533                        },
 534                        None => old_file.disk_state,
 535                    },
 536                    is_local: true,
 537                    entry_id: Some(entry.id),
 538                    path: entry.path.clone(),
 539                    worktree: worktree.clone(),
 540                    is_private: entry.is_private,
 541                }
 542            } else {
 543                File {
 544                    disk_state: DiskState::Deleted,
 545                    is_local: true,
 546                    entry_id: old_file.entry_id,
 547                    path: old_file.path.clone(),
 548                    worktree: worktree.clone(),
 549                    is_private: old_file.is_private,
 550                }
 551            };
 552
 553            if new_file == *old_file {
 554                return None;
 555            }
 556
 557            let mut events = Vec::new();
 558            if new_file.path != old_file.path {
 559                this.path_to_buffer_id.remove(&ProjectPath {
 560                    path: old_file.path.clone(),
 561                    worktree_id: old_file.worktree_id(cx),
 562                });
 563                this.path_to_buffer_id.insert(
 564                    ProjectPath {
 565                        worktree_id: new_file.worktree_id(cx),
 566                        path: new_file.path.clone(),
 567                    },
 568                    buffer_id,
 569                );
 570                events.push(BufferStoreEvent::BufferChangedFilePath {
 571                    buffer: cx.entity(),
 572                    old_file: buffer.file().cloned(),
 573                });
 574            }
 575            let local = this.as_local_mut()?;
 576            if new_file.entry_id != old_file.entry_id {
 577                if let Some(entry_id) = old_file.entry_id {
 578                    local.local_buffer_ids_by_entry_id.remove(&entry_id);
 579                }
 580                if let Some(entry_id) = new_file.entry_id {
 581                    local
 582                        .local_buffer_ids_by_entry_id
 583                        .insert(entry_id, buffer_id);
 584                }
 585            }
 586
 587            if let Some((client, project_id)) = &this.downstream_client {
 588                client
 589                    .send(proto::UpdateBufferFile {
 590                        project_id: *project_id,
 591                        buffer_id: buffer_id.to_proto(),
 592                        file: Some(new_file.to_proto(cx)),
 593                    })
 594                    .ok();
 595            }
 596
 597            buffer.file_updated(Arc::new(new_file), cx);
 598            Some(events)
 599        })?;
 600
 601        for event in events {
 602            cx.emit(event);
 603        }
 604
 605        None
 606    }
 607
 608    fn save_buffer(
 609        &self,
 610        buffer: Entity<Buffer>,
 611        cx: &mut Context<BufferStore>,
 612    ) -> Task<Result<()>> {
 613        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 614            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 615        };
 616        let worktree = file.worktree.clone();
 617        self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
 618    }
 619
 620    fn save_buffer_as(
 621        &self,
 622        buffer: Entity<Buffer>,
 623        path: ProjectPath,
 624        cx: &mut Context<BufferStore>,
 625    ) -> Task<Result<()>> {
 626        let Some(worktree) = self
 627            .worktree_store
 628            .read(cx)
 629            .worktree_for_id(path.worktree_id, cx)
 630        else {
 631            return Task::ready(Err(anyhow!("no such worktree")));
 632        };
 633        self.save_local_buffer(buffer, worktree, path.path, true, cx)
 634    }
 635
 636    #[ztracing::instrument(skip_all)]
 637    fn open_buffer(
 638        &self,
 639        path: Arc<RelPath>,
 640        worktree: Entity<Worktree>,
 641        cx: &mut Context<BufferStore>,
 642    ) -> Task<Result<Entity<Buffer>>> {
 643        let load_file = worktree.update(cx, |worktree, cx| worktree.load_file(path.as_ref(), cx));
 644        cx.spawn(async move |this, cx| {
 645            let path = path.clone();
 646            let buffer = match load_file.await {
 647                Ok(loaded) => {
 648                    let reservation = cx.reserve_entity::<Buffer>();
 649                    let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 650                    let text_buffer = cx
 651                        .background_spawn(async move {
 652                            text::Buffer::new(ReplicaId::LOCAL, buffer_id, loaded.text)
 653                        })
 654                        .await;
 655                    cx.insert_entity(reservation, |_| {
 656                        let mut buffer =
 657                            Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite);
 658                        buffer.set_encoding(loaded.encoding);
 659                        buffer.set_has_bom(loaded.has_bom);
 660                        buffer
 661                    })
 662                }
 663                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 664                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 665                    let text_buffer = text::Buffer::new(ReplicaId::LOCAL, buffer_id, "");
 666                    Buffer::build(
 667                        text_buffer,
 668                        Some(Arc::new(File {
 669                            worktree,
 670                            path,
 671                            disk_state: DiskState::New,
 672                            entry_id: None,
 673                            is_local: true,
 674                            is_private: false,
 675                        })),
 676                        Capability::ReadWrite,
 677                    )
 678                }),
 679                Err(e) => return Err(e),
 680            };
 681            this.update(cx, |this, cx| {
 682                this.add_buffer(buffer.clone(), cx)?;
 683                let buffer_id = buffer.read(cx).remote_id();
 684                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 685                    let project_path = ProjectPath {
 686                        worktree_id: file.worktree_id(cx),
 687                        path: file.path.clone(),
 688                    };
 689                    let entry_id = file.entry_id;
 690
 691                    // Check if the file should be read-only based on settings
 692                    let settings = WorktreeSettings::get(Some((&project_path).into()), cx);
 693                    let is_read_only = if project_path.path.is_empty() {
 694                        settings.is_std_path_read_only(&file.full_path(cx))
 695                    } else {
 696                        settings.is_path_read_only(&project_path.path)
 697                    };
 698                    if is_read_only {
 699                        buffer.update(cx, |buffer, cx| {
 700                            buffer.set_capability(Capability::Read, cx);
 701                        });
 702                    }
 703
 704                    this.path_to_buffer_id.insert(project_path, buffer_id);
 705                    let this = this.as_local_mut().unwrap();
 706                    if let Some(entry_id) = entry_id {
 707                        this.local_buffer_ids_by_entry_id
 708                            .insert(entry_id, buffer_id);
 709                    }
 710                }
 711
 712                anyhow::Ok(())
 713            })??;
 714
 715            Ok(buffer)
 716        })
 717    }
 718
 719    fn create_buffer(
 720        &self,
 721        language: Option<Arc<Language>>,
 722        project_searchable: bool,
 723        cx: &mut Context<BufferStore>,
 724    ) -> Task<Result<Entity<Buffer>>> {
 725        cx.spawn(async move |buffer_store, cx| {
 726            let buffer = cx.new(|cx| {
 727                Buffer::local("", cx)
 728                    .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
 729            });
 730            buffer_store.update(cx, |buffer_store, cx| {
 731                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 732                if !project_searchable {
 733                    buffer_store
 734                        .non_searchable_buffers
 735                        .insert(buffer.read(cx).remote_id());
 736                }
 737            })?;
 738            Ok(buffer)
 739        })
 740    }
 741
 742    fn reload_buffers(
 743        &self,
 744        buffers: HashSet<Entity<Buffer>>,
 745        push_to_history: bool,
 746        cx: &mut Context<BufferStore>,
 747    ) -> Task<Result<ProjectTransaction>> {
 748        cx.spawn(async move |_, cx| {
 749            let mut project_transaction = ProjectTransaction::default();
 750            for buffer in buffers {
 751                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx)).await?;
 752                buffer.update(cx, |buffer, cx| {
 753                    if let Some(transaction) = transaction {
 754                        if !push_to_history {
 755                            buffer.forget_transaction(transaction.id);
 756                        }
 757                        project_transaction.0.insert(cx.entity(), transaction);
 758                    }
 759                });
 760            }
 761
 762            Ok(project_transaction)
 763        })
 764    }
 765}
 766
 767impl BufferStore {
 768    pub fn init(client: &AnyProtoClient) {
 769        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 770        client.add_entity_message_handler(Self::handle_buffer_saved);
 771        client.add_entity_message_handler(Self::handle_update_buffer_file);
 772        client.add_entity_request_handler(Self::handle_save_buffer);
 773        client.add_entity_request_handler(Self::handle_reload_buffers);
 774    }
 775
 776    /// Creates a buffer store, optionally retaining its buffers.
 777    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 778        Self {
 779            state: BufferStoreState::Local(LocalBufferStore {
 780                local_buffer_ids_by_entry_id: Default::default(),
 781                worktree_store: worktree_store.clone(),
 782                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 783                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 784                        let this = this.as_local_mut().unwrap();
 785                        this.subscribe_to_worktree(worktree, cx);
 786                    }
 787                }),
 788            }),
 789            downstream_client: None,
 790            opened_buffers: Default::default(),
 791            path_to_buffer_id: Default::default(),
 792            shared_buffers: Default::default(),
 793            loading_buffers: Default::default(),
 794            non_searchable_buffers: Default::default(),
 795            worktree_store,
 796            project_search: Default::default(),
 797        }
 798    }
 799
 800    pub fn remote(
 801        worktree_store: Entity<WorktreeStore>,
 802        upstream_client: AnyProtoClient,
 803        remote_id: u64,
 804        _cx: &mut Context<Self>,
 805    ) -> Self {
 806        Self {
 807            state: BufferStoreState::Remote(RemoteBufferStore {
 808                shared_with_me: Default::default(),
 809                loading_remote_buffers_by_id: Default::default(),
 810                remote_buffer_listeners: Default::default(),
 811                project_id: remote_id,
 812                upstream_client,
 813                worktree_store: worktree_store.clone(),
 814            }),
 815            downstream_client: None,
 816            opened_buffers: Default::default(),
 817            path_to_buffer_id: Default::default(),
 818            loading_buffers: Default::default(),
 819            shared_buffers: Default::default(),
 820            non_searchable_buffers: Default::default(),
 821            worktree_store,
 822            project_search: Default::default(),
 823        }
 824    }
 825
 826    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 827        match &mut self.state {
 828            BufferStoreState::Local(state) => Some(state),
 829            _ => None,
 830        }
 831    }
 832
 833    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 834        match &mut self.state {
 835            BufferStoreState::Remote(state) => Some(state),
 836            _ => None,
 837        }
 838    }
 839
 840    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 841        match &self.state {
 842            BufferStoreState::Remote(state) => Some(state),
 843            _ => None,
 844        }
 845    }
 846
 847    #[ztracing::instrument(skip_all)]
 848    pub fn open_buffer(
 849        &mut self,
 850        project_path: ProjectPath,
 851        cx: &mut Context<Self>,
 852    ) -> Task<Result<Entity<Buffer>>> {
 853        if let Some(buffer) = self.get_by_path(&project_path) {
 854            return Task::ready(Ok(buffer));
 855        }
 856
 857        let task = match self.loading_buffers.entry(project_path.clone()) {
 858            hash_map::Entry::Occupied(e) => e.get().clone(),
 859            hash_map::Entry::Vacant(entry) => {
 860                let path = project_path.path.clone();
 861                let Some(worktree) = self
 862                    .worktree_store
 863                    .read(cx)
 864                    .worktree_for_id(project_path.worktree_id, cx)
 865                else {
 866                    return Task::ready(Err(anyhow!("no such worktree")));
 867                };
 868                let load_buffer = match &self.state {
 869                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 870                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 871                };
 872
 873                entry
 874                    .insert(
 875                        cx.spawn(async move |this, cx| {
 876                            let load_result = load_buffer.await;
 877                            this.update(cx, |this, _cx| {
 878                                // Record the fact that the buffer is no longer loading.
 879                                this.loading_buffers.remove(&project_path);
 880
 881                                let buffer = load_result.map_err(Arc::new)?;
 882                                Ok(buffer)
 883                            })?
 884                        })
 885                        .shared(),
 886                    )
 887                    .clone()
 888            }
 889        };
 890
 891        cx.background_spawn(async move {
 892            task.await.map_err(|e| {
 893                if e.error_code() != ErrorCode::Internal {
 894                    anyhow!(e.error_code())
 895                } else {
 896                    anyhow!("{e}")
 897                }
 898            })
 899        })
 900    }
 901
 902    pub fn create_buffer(
 903        &mut self,
 904        language: Option<Arc<Language>>,
 905        project_searchable: bool,
 906        cx: &mut Context<Self>,
 907    ) -> Task<Result<Entity<Buffer>>> {
 908        match &self.state {
 909            BufferStoreState::Local(this) => this.create_buffer(language, project_searchable, cx),
 910            BufferStoreState::Remote(this) => this.create_buffer(language, project_searchable, cx),
 911        }
 912    }
 913
 914    pub fn save_buffer(
 915        &mut self,
 916        buffer: Entity<Buffer>,
 917        cx: &mut Context<Self>,
 918    ) -> Task<Result<()>> {
 919        match &mut self.state {
 920            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 921            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer, None, cx),
 922        }
 923    }
 924
 925    pub fn save_buffer_as(
 926        &mut self,
 927        buffer: Entity<Buffer>,
 928        path: ProjectPath,
 929        cx: &mut Context<Self>,
 930    ) -> Task<Result<()>> {
 931        let old_file = buffer.read(cx).file().cloned();
 932        let task = match &self.state {
 933            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 934            BufferStoreState::Remote(this) => {
 935                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 936            }
 937        };
 938        cx.spawn(async move |this, cx| {
 939            task.await?;
 940            this.update(cx, |this, cx| {
 941                old_file.clone().and_then(|file| {
 942                    this.path_to_buffer_id.remove(&ProjectPath {
 943                        worktree_id: file.worktree_id(cx),
 944                        path: file.path().clone(),
 945                    })
 946                });
 947
 948                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 949            })
 950        })
 951    }
 952
 953    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 954        let buffer = buffer_entity.read(cx);
 955        let remote_id = buffer.remote_id();
 956        let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
 957            path: file.path.clone(),
 958            worktree_id: file.worktree_id(cx),
 959        });
 960        let is_remote = buffer.replica_id().is_remote();
 961        let open_buffer = OpenBuffer::Complete {
 962            buffer: buffer_entity.downgrade(),
 963        };
 964
 965        let handle = cx.entity().downgrade();
 966        buffer_entity.update(cx, move |_, cx| {
 967            cx.on_release(move |buffer, cx| {
 968                handle
 969                    .update(cx, |_, cx| {
 970                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 971                    })
 972                    .ok();
 973            })
 974            .detach()
 975        });
 976        let _expect_path_to_exist;
 977        match self.opened_buffers.entry(remote_id) {
 978            hash_map::Entry::Vacant(entry) => {
 979                entry.insert(open_buffer);
 980                _expect_path_to_exist = false;
 981            }
 982            hash_map::Entry::Occupied(mut entry) => {
 983                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 984                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 985                } else if entry.get().upgrade().is_some() {
 986                    if is_remote {
 987                        return Ok(());
 988                    } else {
 989                        debug_panic!("buffer {remote_id} was already registered");
 990                        anyhow::bail!("buffer {remote_id} was already registered");
 991                    }
 992                }
 993                entry.insert(open_buffer);
 994                _expect_path_to_exist = true;
 995            }
 996        }
 997
 998        if let Some(path) = path {
 999            self.path_to_buffer_id.insert(path, remote_id);
1000        }
1001
1002        cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
1003        cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
1004        Ok(())
1005    }
1006
1007    pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
1008        self.opened_buffers
1009            .values()
1010            .filter_map(|buffer| buffer.upgrade())
1011    }
1012
1013    pub(crate) fn is_searchable(&self, id: &BufferId) -> bool {
1014        !self.non_searchable_buffers.contains(&id)
1015    }
1016
1017    pub fn loading_buffers(
1018        &self,
1019    ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
1020        self.loading_buffers.iter().map(|(path, task)| {
1021            let task = task.clone();
1022            (path, async move {
1023                task.await.map_err(|e| {
1024                    if e.error_code() != ErrorCode::Internal {
1025                        anyhow!(e.error_code())
1026                    } else {
1027                        anyhow!("{e}")
1028                    }
1029                })
1030            })
1031        })
1032    }
1033
1034    pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
1035        self.path_to_buffer_id.get(project_path)
1036    }
1037
1038    pub fn get_by_path(&self, path: &ProjectPath) -> Option<Entity<Buffer>> {
1039        self.path_to_buffer_id
1040            .get(path)
1041            .and_then(|buffer_id| self.get(*buffer_id))
1042    }
1043
1044    pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1045        self.opened_buffers.get(&buffer_id)?.upgrade()
1046    }
1047
1048    pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
1049        self.get(buffer_id)
1050            .with_context(|| format!("unknown buffer id {buffer_id}"))
1051    }
1052
1053    pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1054        self.get(buffer_id).or_else(|| {
1055            self.as_remote()
1056                .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1057        })
1058    }
1059
1060    pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1061        let buffers = self
1062            .buffers()
1063            .map(|buffer| {
1064                let buffer = buffer.read(cx);
1065                proto::BufferVersion {
1066                    id: buffer.remote_id().into(),
1067                    version: language::proto::serialize_version(&buffer.version),
1068                }
1069            })
1070            .collect();
1071        let incomplete_buffer_ids = self
1072            .as_remote()
1073            .map(|remote| remote.incomplete_buffer_ids())
1074            .unwrap_or_default();
1075        (buffers, incomplete_buffer_ids)
1076    }
1077
1078    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1079        for open_buffer in self.opened_buffers.values_mut() {
1080            if let Some(buffer) = open_buffer.upgrade() {
1081                buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1082            }
1083        }
1084
1085        for buffer in self.buffers() {
1086            buffer.update(cx, |buffer, cx| {
1087                buffer.set_capability(Capability::ReadOnly, cx)
1088            });
1089        }
1090
1091        if let Some(remote) = self.as_remote_mut() {
1092            // Wake up all futures currently waiting on a buffer to get opened,
1093            // to give them a chance to fail now that we've disconnected.
1094            remote.remote_buffer_listeners.clear()
1095        }
1096    }
1097
1098    pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1099        self.downstream_client = Some((downstream_client, remote_id));
1100    }
1101
1102    pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1103        self.downstream_client.take();
1104        self.forget_shared_buffers();
1105    }
1106
1107    pub fn discard_incomplete(&mut self) {
1108        self.opened_buffers
1109            .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1110    }
1111
1112    fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
1113        let file = File::from_dyn(buffer.read(cx).file())?;
1114
1115        let remote_id = buffer.read(cx).remote_id();
1116        if let Some(entry_id) = file.entry_id {
1117            if let Some(local) = self.as_local_mut() {
1118                match local.local_buffer_ids_by_entry_id.get(&entry_id) {
1119                    Some(_) => {
1120                        return None;
1121                    }
1122                    None => {
1123                        local
1124                            .local_buffer_ids_by_entry_id
1125                            .insert(entry_id, remote_id);
1126                    }
1127                }
1128            }
1129            self.path_to_buffer_id.insert(
1130                ProjectPath {
1131                    worktree_id: file.worktree_id(cx),
1132                    path: file.path.clone(),
1133                },
1134                remote_id,
1135            );
1136        };
1137
1138        Some(())
1139    }
1140
1141    fn on_buffer_event(
1142        &mut self,
1143        buffer: Entity<Buffer>,
1144        event: &BufferEvent,
1145        cx: &mut Context<Self>,
1146    ) {
1147        match event {
1148            BufferEvent::FileHandleChanged => {
1149                self.buffer_changed_file(buffer, cx);
1150            }
1151            BufferEvent::Reloaded => {
1152                let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1153                    return;
1154                };
1155                let buffer = buffer.read(cx);
1156                downstream_client
1157                    .send(proto::BufferReloaded {
1158                        project_id: *project_id,
1159                        buffer_id: buffer.remote_id().to_proto(),
1160                        version: serialize_version(&buffer.version()),
1161                        mtime: buffer.saved_mtime().map(|t| t.into()),
1162                        line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1163                    })
1164                    .log_err();
1165            }
1166            BufferEvent::LanguageChanged(_) => {}
1167            _ => {}
1168        }
1169    }
1170
1171    pub async fn handle_update_buffer(
1172        this: Entity<Self>,
1173        envelope: TypedEnvelope<proto::UpdateBuffer>,
1174        mut cx: AsyncApp,
1175    ) -> Result<proto::Ack> {
1176        let payload = envelope.payload;
1177        let buffer_id = BufferId::new(payload.buffer_id)?;
1178        let ops = payload
1179            .operations
1180            .into_iter()
1181            .map(language::proto::deserialize_operation)
1182            .collect::<Result<Vec<_>, _>>()?;
1183        this.update(&mut cx, |this, cx| {
1184            match this.opened_buffers.entry(buffer_id) {
1185                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1186                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1187                    OpenBuffer::Complete { buffer, .. } => {
1188                        if let Some(buffer) = buffer.upgrade() {
1189                            buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1190                        }
1191                    }
1192                },
1193                hash_map::Entry::Vacant(e) => {
1194                    e.insert(OpenBuffer::Operations(ops));
1195                }
1196            }
1197            Ok(proto::Ack {})
1198        })
1199    }
1200
1201    pub fn register_shared_lsp_handle(
1202        &mut self,
1203        peer_id: proto::PeerId,
1204        buffer_id: BufferId,
1205        handle: OpenLspBufferHandle,
1206    ) {
1207        if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id)
1208            && let Some(buffer) = shared_buffers.get_mut(&buffer_id)
1209        {
1210            buffer.lsp_handle = Some(handle);
1211            return;
1212        }
1213        debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1214    }
1215
1216    pub fn handle_synchronize_buffers(
1217        &mut self,
1218        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1219        cx: &mut Context<Self>,
1220        client: Arc<Client>,
1221    ) -> Result<proto::SynchronizeBuffersResponse> {
1222        let project_id = envelope.payload.project_id;
1223        let mut response = proto::SynchronizeBuffersResponse {
1224            buffers: Default::default(),
1225        };
1226        let Some(guest_id) = envelope.original_sender_id else {
1227            anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1228        };
1229
1230        self.shared_buffers.entry(guest_id).or_default().clear();
1231        for buffer in envelope.payload.buffers {
1232            let buffer_id = BufferId::new(buffer.id)?;
1233            let remote_version = language::proto::deserialize_version(&buffer.version);
1234            if let Some(buffer) = self.get(buffer_id) {
1235                self.shared_buffers
1236                    .entry(guest_id)
1237                    .or_default()
1238                    .entry(buffer_id)
1239                    .or_insert_with(|| SharedBuffer {
1240                        buffer: buffer.clone(),
1241                        lsp_handle: None,
1242                    });
1243
1244                let buffer = buffer.read(cx);
1245                response.buffers.push(proto::BufferVersion {
1246                    id: buffer_id.into(),
1247                    version: language::proto::serialize_version(&buffer.version),
1248                });
1249
1250                let operations = buffer.serialize_ops(Some(remote_version), cx);
1251                let client = client.clone();
1252                if let Some(file) = buffer.file() {
1253                    client
1254                        .send(proto::UpdateBufferFile {
1255                            project_id,
1256                            buffer_id: buffer_id.into(),
1257                            file: Some(file.to_proto(cx)),
1258                        })
1259                        .log_err();
1260                }
1261
1262                // TODO(max): do something
1263                // client
1264                //     .send(proto::UpdateStagedText {
1265                //         project_id,
1266                //         buffer_id: buffer_id.into(),
1267                //         diff_base: buffer.diff_base().map(ToString::to_string),
1268                //     })
1269                //     .log_err();
1270
1271                client
1272                    .send(proto::BufferReloaded {
1273                        project_id,
1274                        buffer_id: buffer_id.into(),
1275                        version: language::proto::serialize_version(buffer.saved_version()),
1276                        mtime: buffer.saved_mtime().map(|time| time.into()),
1277                        line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1278                            as i32,
1279                    })
1280                    .log_err();
1281
1282                cx.background_spawn(
1283                    async move {
1284                        let operations = operations.await;
1285                        for chunk in split_operations(operations) {
1286                            client
1287                                .request(proto::UpdateBuffer {
1288                                    project_id,
1289                                    buffer_id: buffer_id.into(),
1290                                    operations: chunk,
1291                                })
1292                                .await?;
1293                        }
1294                        anyhow::Ok(())
1295                    }
1296                    .log_err(),
1297                )
1298                .detach();
1299            }
1300        }
1301        Ok(response)
1302    }
1303
1304    pub fn handle_create_buffer_for_peer(
1305        &mut self,
1306        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1307        replica_id: ReplicaId,
1308        capability: Capability,
1309        cx: &mut Context<Self>,
1310    ) -> Result<()> {
1311        let remote = self
1312            .as_remote_mut()
1313            .context("buffer store is not a remote")?;
1314
1315        if let Some(buffer) =
1316            remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1317        {
1318            self.add_buffer(buffer, cx)?;
1319        }
1320
1321        Ok(())
1322    }
1323
1324    pub async fn handle_update_buffer_file(
1325        this: Entity<Self>,
1326        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1327        mut cx: AsyncApp,
1328    ) -> Result<()> {
1329        let buffer_id = envelope.payload.buffer_id;
1330        let buffer_id = BufferId::new(buffer_id)?;
1331
1332        this.update(&mut cx, |this, cx| {
1333            let payload = envelope.payload.clone();
1334            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1335                let file = payload.file.context("invalid file")?;
1336                let worktree = this
1337                    .worktree_store
1338                    .read(cx)
1339                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1340                    .context("no such worktree")?;
1341                let file = File::from_proto(file, worktree, cx)?;
1342                let old_file = buffer.update(cx, |buffer, cx| {
1343                    let old_file = buffer.file().cloned();
1344                    let new_path = file.path.clone();
1345
1346                    buffer.file_updated(Arc::new(file), cx);
1347                    if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
1348                        Some(old_file)
1349                    } else {
1350                        None
1351                    }
1352                });
1353                if let Some(old_file) = old_file {
1354                    cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1355                }
1356            }
1357            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1358                downstream_client
1359                    .send(proto::UpdateBufferFile {
1360                        project_id: *project_id,
1361                        buffer_id: buffer_id.into(),
1362                        file: envelope.payload.file,
1363                    })
1364                    .log_err();
1365            }
1366            Ok(())
1367        })
1368    }
1369
1370    pub async fn handle_save_buffer(
1371        this: Entity<Self>,
1372        envelope: TypedEnvelope<proto::SaveBuffer>,
1373        mut cx: AsyncApp,
1374    ) -> Result<proto::BufferSaved> {
1375        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1376        let (buffer, project_id) = this.read_with(&cx, |this, _| {
1377            anyhow::Ok((
1378                this.get_existing(buffer_id)?,
1379                this.downstream_client
1380                    .as_ref()
1381                    .map(|(_, project_id)| *project_id)
1382                    .context("project is not shared")?,
1383            ))
1384        })?;
1385        buffer
1386            .update(&mut cx, |buffer, _| {
1387                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1388            })
1389            .await?;
1390        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
1391
1392        if let Some(new_path) = envelope.payload.new_path
1393            && let Some(new_path) = ProjectPath::from_proto(new_path)
1394        {
1395            this.update(&mut cx, |this, cx| {
1396                this.save_buffer_as(buffer.clone(), new_path, cx)
1397            })
1398            .await?;
1399        } else {
1400            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
1401                .await?;
1402        }
1403
1404        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
1405            project_id,
1406            buffer_id: buffer_id.into(),
1407            version: serialize_version(buffer.saved_version()),
1408            mtime: buffer.saved_mtime().map(|time| time.into()),
1409        }))
1410    }
1411
1412    pub async fn handle_close_buffer(
1413        this: Entity<Self>,
1414        envelope: TypedEnvelope<proto::CloseBuffer>,
1415        mut cx: AsyncApp,
1416    ) -> Result<()> {
1417        let peer_id = envelope.sender_id;
1418        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1419        this.update(&mut cx, |this, cx| {
1420            if let Some(shared) = this.shared_buffers.get_mut(&peer_id)
1421                && shared.remove(&buffer_id).is_some()
1422            {
1423                cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1424                if shared.is_empty() {
1425                    this.shared_buffers.remove(&peer_id);
1426                }
1427                return;
1428            }
1429            debug_panic!(
1430                "peer_id {} closed buffer_id {} which was either not open or already closed",
1431                peer_id,
1432                buffer_id
1433            )
1434        });
1435        Ok(())
1436    }
1437
1438    pub async fn handle_buffer_saved(
1439        this: Entity<Self>,
1440        envelope: TypedEnvelope<proto::BufferSaved>,
1441        mut cx: AsyncApp,
1442    ) -> Result<()> {
1443        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1444        let version = deserialize_version(&envelope.payload.version);
1445        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1446        this.update(&mut cx, move |this, cx| {
1447            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1448                buffer.update(cx, |buffer, cx| {
1449                    buffer.did_save(version, mtime, cx);
1450                });
1451            }
1452
1453            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1454                downstream_client
1455                    .send(proto::BufferSaved {
1456                        project_id: *project_id,
1457                        buffer_id: buffer_id.into(),
1458                        mtime: envelope.payload.mtime,
1459                        version: envelope.payload.version,
1460                    })
1461                    .log_err();
1462            }
1463        });
1464        Ok(())
1465    }
1466
1467    pub async fn handle_buffer_reloaded(
1468        this: Entity<Self>,
1469        envelope: TypedEnvelope<proto::BufferReloaded>,
1470        mut cx: AsyncApp,
1471    ) -> Result<()> {
1472        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1473        let version = deserialize_version(&envelope.payload.version);
1474        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1475        let line_ending = deserialize_line_ending(
1476            proto::LineEnding::from_i32(envelope.payload.line_ending)
1477                .context("missing line ending")?,
1478        );
1479        this.update(&mut cx, |this, cx| {
1480            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1481                buffer.update(cx, |buffer, cx| {
1482                    buffer.did_reload(version, line_ending, mtime, cx);
1483                });
1484            }
1485
1486            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1487                downstream_client
1488                    .send(proto::BufferReloaded {
1489                        project_id: *project_id,
1490                        buffer_id: buffer_id.into(),
1491                        mtime: envelope.payload.mtime,
1492                        version: envelope.payload.version,
1493                        line_ending: envelope.payload.line_ending,
1494                    })
1495                    .log_err();
1496            }
1497        });
1498        Ok(())
1499    }
1500
1501    pub fn reload_buffers(
1502        &self,
1503        buffers: HashSet<Entity<Buffer>>,
1504        push_to_history: bool,
1505        cx: &mut Context<Self>,
1506    ) -> Task<Result<ProjectTransaction>> {
1507        if buffers.is_empty() {
1508            return Task::ready(Ok(ProjectTransaction::default()));
1509        }
1510        match &self.state {
1511            BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1512            BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1513        }
1514    }
1515
1516    async fn handle_reload_buffers(
1517        this: Entity<Self>,
1518        envelope: TypedEnvelope<proto::ReloadBuffers>,
1519        mut cx: AsyncApp,
1520    ) -> Result<proto::ReloadBuffersResponse> {
1521        let sender_id = envelope.original_sender_id().unwrap_or_default();
1522        let reload = this.update(&mut cx, |this, cx| {
1523            let mut buffers = HashSet::default();
1524            for buffer_id in &envelope.payload.buffer_ids {
1525                let buffer_id = BufferId::new(*buffer_id)?;
1526                buffers.insert(this.get_existing(buffer_id)?);
1527            }
1528            anyhow::Ok(this.reload_buffers(buffers, false, cx))
1529        })?;
1530
1531        let project_transaction = reload.await?;
1532        let project_transaction = this.update(&mut cx, |this, cx| {
1533            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1534        });
1535        Ok(proto::ReloadBuffersResponse {
1536            transaction: Some(project_transaction),
1537        })
1538    }
1539
1540    pub fn create_buffer_for_peer(
1541        &mut self,
1542        buffer: &Entity<Buffer>,
1543        peer_id: proto::PeerId,
1544        cx: &mut Context<Self>,
1545    ) -> Task<Result<()>> {
1546        let buffer_id = buffer.read(cx).remote_id();
1547        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1548        if shared_buffers.contains_key(&buffer_id) {
1549            return Task::ready(Ok(()));
1550        }
1551        shared_buffers.insert(
1552            buffer_id,
1553            SharedBuffer {
1554                buffer: buffer.clone(),
1555                lsp_handle: None,
1556            },
1557        );
1558
1559        let Some((client, project_id)) = self.downstream_client.clone() else {
1560            return Task::ready(Ok(()));
1561        };
1562
1563        cx.spawn(async move |this, cx| {
1564            let Some(buffer) = this.read_with(cx, |this, _| this.get(buffer_id))? else {
1565                return anyhow::Ok(());
1566            };
1567
1568            let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx));
1569            let operations = operations.await;
1570            let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx));
1571
1572            let initial_state = proto::CreateBufferForPeer {
1573                project_id,
1574                peer_id: Some(peer_id),
1575                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1576            };
1577
1578            if client.send(initial_state).log_err().is_some() {
1579                let client = client.clone();
1580                cx.background_spawn(async move {
1581                    let mut chunks = split_operations(operations).peekable();
1582                    while let Some(chunk) = chunks.next() {
1583                        let is_last = chunks.peek().is_none();
1584                        client.send(proto::CreateBufferForPeer {
1585                            project_id,
1586                            peer_id: Some(peer_id),
1587                            variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1588                                proto::BufferChunk {
1589                                    buffer_id: buffer_id.into(),
1590                                    operations: chunk,
1591                                    is_last,
1592                                },
1593                            )),
1594                        })?;
1595                    }
1596                    anyhow::Ok(())
1597                })
1598                .await
1599                .log_err();
1600            }
1601            Ok(())
1602        })
1603    }
1604
1605    pub fn forget_shared_buffers(&mut self) {
1606        self.shared_buffers.clear();
1607    }
1608
1609    pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1610        self.shared_buffers.remove(peer_id);
1611    }
1612
1613    pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1614        if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1615            self.shared_buffers.insert(new_peer_id, buffers);
1616        }
1617    }
1618
1619    pub fn has_shared_buffers(&self) -> bool {
1620        !self.shared_buffers.is_empty()
1621    }
1622
1623    pub fn create_local_buffer(
1624        &mut self,
1625        text: &str,
1626        language: Option<Arc<Language>>,
1627        project_searchable: bool,
1628        cx: &mut Context<Self>,
1629    ) -> Entity<Buffer> {
1630        let buffer = cx.new(|cx| {
1631            Buffer::local(text, cx)
1632                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1633        });
1634
1635        self.add_buffer(buffer.clone(), cx).log_err();
1636        let buffer_id = buffer.read(cx).remote_id();
1637        if !project_searchable {
1638            self.non_searchable_buffers.insert(buffer_id);
1639        }
1640
1641        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1642            self.path_to_buffer_id.insert(
1643                ProjectPath {
1644                    worktree_id: file.worktree_id(cx),
1645                    path: file.path.clone(),
1646                },
1647                buffer_id,
1648            );
1649            let this = self
1650                .as_local_mut()
1651                .expect("local-only method called in a non-local context");
1652            if let Some(entry_id) = file.entry_id {
1653                this.local_buffer_ids_by_entry_id
1654                    .insert(entry_id, buffer_id);
1655            }
1656        }
1657        buffer
1658    }
1659
1660    pub fn deserialize_project_transaction(
1661        &mut self,
1662        message: proto::ProjectTransaction,
1663        push_to_history: bool,
1664        cx: &mut Context<Self>,
1665    ) -> Task<Result<ProjectTransaction>> {
1666        if let Some(this) = self.as_remote_mut() {
1667            this.deserialize_project_transaction(message, push_to_history, cx)
1668        } else {
1669            debug_panic!("not a remote buffer store");
1670            Task::ready(Err(anyhow!("not a remote buffer store")))
1671        }
1672    }
1673
1674    pub fn wait_for_remote_buffer(
1675        &mut self,
1676        id: BufferId,
1677        cx: &mut Context<BufferStore>,
1678    ) -> Task<Result<Entity<Buffer>>> {
1679        if let Some(this) = self.as_remote_mut() {
1680            this.wait_for_remote_buffer(id, cx)
1681        } else {
1682            debug_panic!("not a remote buffer store");
1683            Task::ready(Err(anyhow!("not a remote buffer store")))
1684        }
1685    }
1686
1687    pub fn serialize_project_transaction_for_peer(
1688        &mut self,
1689        project_transaction: ProjectTransaction,
1690        peer_id: proto::PeerId,
1691        cx: &mut Context<Self>,
1692    ) -> proto::ProjectTransaction {
1693        let mut serialized_transaction = proto::ProjectTransaction {
1694            buffer_ids: Default::default(),
1695            transactions: Default::default(),
1696        };
1697        for (buffer, transaction) in project_transaction.0 {
1698            self.create_buffer_for_peer(&buffer, peer_id, cx)
1699                .detach_and_log_err(cx);
1700            serialized_transaction
1701                .buffer_ids
1702                .push(buffer.read(cx).remote_id().into());
1703            serialized_transaction
1704                .transactions
1705                .push(language::proto::serialize_transaction(&transaction));
1706        }
1707        serialized_transaction
1708    }
1709
1710    pub(crate) fn register_project_search_result_handle(
1711        &mut self,
1712    ) -> (u64, smol::channel::Receiver<BufferId>) {
1713        let (tx, rx) = smol::channel::unbounded();
1714        let handle = util::post_inc(&mut self.project_search.next_id);
1715        let _old_entry = self.project_search.chunks.insert(handle, tx);
1716        debug_assert!(_old_entry.is_none());
1717        (handle, rx)
1718    }
1719
1720    pub fn register_ongoing_project_search(
1721        &mut self,
1722        id: (PeerId, u64),
1723        search: Task<anyhow::Result<()>>,
1724    ) {
1725        let _old = self.project_search.searches_in_progress.insert(id, search);
1726        debug_assert!(_old.is_none());
1727    }
1728
1729    pub async fn handle_find_search_candidates_cancel(
1730        this: Entity<Self>,
1731        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
1732        mut cx: AsyncApp,
1733    ) -> Result<()> {
1734        let id = (
1735            envelope.original_sender_id.unwrap_or(envelope.sender_id),
1736            envelope.payload.handle,
1737        );
1738        let _ = this.update(&mut cx, |this, _| {
1739            this.project_search.searches_in_progress.remove(&id)
1740        });
1741        Ok(())
1742    }
1743
1744    pub(crate) async fn handle_find_search_candidates_chunk(
1745        this: Entity<Self>,
1746        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
1747        mut cx: AsyncApp,
1748    ) -> Result<proto::Ack> {
1749        use proto::find_search_candidates_chunk::Variant;
1750        let handle = envelope.payload.handle;
1751
1752        let buffer_ids = match envelope
1753            .payload
1754            .variant
1755            .context("Expected non-null variant")?
1756        {
1757            Variant::Matches(find_search_candidates_matches) => find_search_candidates_matches
1758                .buffer_ids
1759                .into_iter()
1760                .filter_map(|buffer_id| BufferId::new(buffer_id).ok())
1761                .collect::<Vec<_>>(),
1762            Variant::Done(_) => {
1763                this.update(&mut cx, |this, _| {
1764                    this.project_search.chunks.remove(&handle)
1765                });
1766                return Ok(proto::Ack {});
1767            }
1768        };
1769        let Some(sender) = this.read_with(&mut cx, |this, _| {
1770            this.project_search.chunks.get(&handle).cloned()
1771        }) else {
1772            return Ok(proto::Ack {});
1773        };
1774
1775        for buffer_id in buffer_ids {
1776            let Ok(_) = sender.send(buffer_id).await else {
1777                this.update(&mut cx, |this, _| {
1778                    this.project_search.chunks.remove(&handle)
1779                });
1780                return Ok(proto::Ack {});
1781            };
1782        }
1783        Ok(proto::Ack {})
1784    }
1785}
1786
1787impl OpenBuffer {
1788    fn upgrade(&self) -> Option<Entity<Buffer>> {
1789        match self {
1790            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1791            OpenBuffer::Operations(_) => None,
1792        }
1793    }
1794}
1795
1796fn is_not_found_error(error: &anyhow::Error) -> bool {
1797    error
1798        .root_cause()
1799        .downcast_ref::<io::Error>()
1800        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1801}