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 { mtime },
 531                        None => old_file.disk_state,
 532                    },
 533                    is_local: true,
 534                    entry_id: Some(entry.id),
 535                    path: entry.path.clone(),
 536                    worktree: worktree.clone(),
 537                    is_private: entry.is_private,
 538                }
 539            } else {
 540                File {
 541                    disk_state: DiskState::Deleted,
 542                    is_local: true,
 543                    entry_id: old_file.entry_id,
 544                    path: old_file.path.clone(),
 545                    worktree: worktree.clone(),
 546                    is_private: old_file.is_private,
 547                }
 548            };
 549
 550            if new_file == *old_file {
 551                return None;
 552            }
 553
 554            let mut events = Vec::new();
 555            if new_file.path != old_file.path {
 556                this.path_to_buffer_id.remove(&ProjectPath {
 557                    path: old_file.path.clone(),
 558                    worktree_id: old_file.worktree_id(cx),
 559                });
 560                this.path_to_buffer_id.insert(
 561                    ProjectPath {
 562                        worktree_id: new_file.worktree_id(cx),
 563                        path: new_file.path.clone(),
 564                    },
 565                    buffer_id,
 566                );
 567                events.push(BufferStoreEvent::BufferChangedFilePath {
 568                    buffer: cx.entity(),
 569                    old_file: buffer.file().cloned(),
 570                });
 571            }
 572            let local = this.as_local_mut()?;
 573            if new_file.entry_id != old_file.entry_id {
 574                if let Some(entry_id) = old_file.entry_id {
 575                    local.local_buffer_ids_by_entry_id.remove(&entry_id);
 576                }
 577                if let Some(entry_id) = new_file.entry_id {
 578                    local
 579                        .local_buffer_ids_by_entry_id
 580                        .insert(entry_id, buffer_id);
 581                }
 582            }
 583
 584            if let Some((client, project_id)) = &this.downstream_client {
 585                client
 586                    .send(proto::UpdateBufferFile {
 587                        project_id: *project_id,
 588                        buffer_id: buffer_id.to_proto(),
 589                        file: Some(new_file.to_proto(cx)),
 590                    })
 591                    .ok();
 592            }
 593
 594            buffer.file_updated(Arc::new(new_file), cx);
 595            Some(events)
 596        })?;
 597
 598        for event in events {
 599            cx.emit(event);
 600        }
 601
 602        None
 603    }
 604
 605    fn save_buffer(
 606        &self,
 607        buffer: Entity<Buffer>,
 608        cx: &mut Context<BufferStore>,
 609    ) -> Task<Result<()>> {
 610        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 611            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 612        };
 613        let worktree = file.worktree.clone();
 614        self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
 615    }
 616
 617    fn save_buffer_as(
 618        &self,
 619        buffer: Entity<Buffer>,
 620        path: ProjectPath,
 621        cx: &mut Context<BufferStore>,
 622    ) -> Task<Result<()>> {
 623        let Some(worktree) = self
 624            .worktree_store
 625            .read(cx)
 626            .worktree_for_id(path.worktree_id, cx)
 627        else {
 628            return Task::ready(Err(anyhow!("no such worktree")));
 629        };
 630        self.save_local_buffer(buffer, worktree, path.path, true, cx)
 631    }
 632
 633    #[ztracing::instrument(skip_all)]
 634    fn open_buffer(
 635        &self,
 636        path: Arc<RelPath>,
 637        worktree: Entity<Worktree>,
 638        cx: &mut Context<BufferStore>,
 639    ) -> Task<Result<Entity<Buffer>>> {
 640        let load_file = worktree.update(cx, |worktree, cx| worktree.load_file(path.as_ref(), cx));
 641        cx.spawn(async move |this, cx| {
 642            let path = path.clone();
 643            let buffer = match load_file.await {
 644                Ok(loaded) => {
 645                    let reservation = cx.reserve_entity::<Buffer>();
 646                    let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 647                    let text_buffer = cx
 648                        .background_spawn(async move {
 649                            text::Buffer::new(ReplicaId::LOCAL, buffer_id, loaded.text)
 650                        })
 651                        .await;
 652                    cx.insert_entity(reservation, |_| {
 653                        let mut buffer =
 654                            Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite);
 655                        buffer.set_encoding(loaded.encoding);
 656                        buffer.set_has_bom(loaded.has_bom);
 657                        buffer
 658                    })
 659                }
 660                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 661                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 662                    let text_buffer = text::Buffer::new(ReplicaId::LOCAL, buffer_id, "");
 663                    Buffer::build(
 664                        text_buffer,
 665                        Some(Arc::new(File {
 666                            worktree,
 667                            path,
 668                            disk_state: DiskState::New,
 669                            entry_id: None,
 670                            is_local: true,
 671                            is_private: false,
 672                        })),
 673                        Capability::ReadWrite,
 674                    )
 675                }),
 676                Err(e) => return Err(e),
 677            };
 678            this.update(cx, |this, cx| {
 679                this.add_buffer(buffer.clone(), cx)?;
 680                let buffer_id = buffer.read(cx).remote_id();
 681                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 682                    let project_path = ProjectPath {
 683                        worktree_id: file.worktree_id(cx),
 684                        path: file.path.clone(),
 685                    };
 686                    let entry_id = file.entry_id;
 687
 688                    // Check if the file should be read-only based on settings
 689                    let settings = WorktreeSettings::get(Some((&project_path).into()), cx);
 690                    let is_read_only = if project_path.path.is_empty() {
 691                        settings.is_std_path_read_only(&file.full_path(cx))
 692                    } else {
 693                        settings.is_path_read_only(&project_path.path)
 694                    };
 695                    if is_read_only {
 696                        buffer.update(cx, |buffer, cx| {
 697                            buffer.set_capability(Capability::Read, cx);
 698                        });
 699                    }
 700
 701                    this.path_to_buffer_id.insert(project_path, buffer_id);
 702                    let this = this.as_local_mut().unwrap();
 703                    if let Some(entry_id) = entry_id {
 704                        this.local_buffer_ids_by_entry_id
 705                            .insert(entry_id, buffer_id);
 706                    }
 707                }
 708
 709                anyhow::Ok(())
 710            })??;
 711
 712            Ok(buffer)
 713        })
 714    }
 715
 716    fn create_buffer(
 717        &self,
 718        language: Option<Arc<Language>>,
 719        project_searchable: bool,
 720        cx: &mut Context<BufferStore>,
 721    ) -> Task<Result<Entity<Buffer>>> {
 722        cx.spawn(async move |buffer_store, cx| {
 723            let buffer = cx.new(|cx| {
 724                Buffer::local("", cx)
 725                    .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
 726            });
 727            buffer_store.update(cx, |buffer_store, cx| {
 728                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 729                if !project_searchable {
 730                    buffer_store
 731                        .non_searchable_buffers
 732                        .insert(buffer.read(cx).remote_id());
 733                }
 734            })?;
 735            Ok(buffer)
 736        })
 737    }
 738
 739    fn reload_buffers(
 740        &self,
 741        buffers: HashSet<Entity<Buffer>>,
 742        push_to_history: bool,
 743        cx: &mut Context<BufferStore>,
 744    ) -> Task<Result<ProjectTransaction>> {
 745        cx.spawn(async move |_, cx| {
 746            let mut project_transaction = ProjectTransaction::default();
 747            for buffer in buffers {
 748                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx)).await?;
 749                buffer.update(cx, |buffer, cx| {
 750                    if let Some(transaction) = transaction {
 751                        if !push_to_history {
 752                            buffer.forget_transaction(transaction.id);
 753                        }
 754                        project_transaction.0.insert(cx.entity(), transaction);
 755                    }
 756                });
 757            }
 758
 759            Ok(project_transaction)
 760        })
 761    }
 762}
 763
 764impl BufferStore {
 765    pub fn init(client: &AnyProtoClient) {
 766        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 767        client.add_entity_message_handler(Self::handle_buffer_saved);
 768        client.add_entity_message_handler(Self::handle_update_buffer_file);
 769        client.add_entity_request_handler(Self::handle_save_buffer);
 770        client.add_entity_request_handler(Self::handle_reload_buffers);
 771    }
 772
 773    /// Creates a buffer store, optionally retaining its buffers.
 774    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 775        Self {
 776            state: BufferStoreState::Local(LocalBufferStore {
 777                local_buffer_ids_by_entry_id: Default::default(),
 778                worktree_store: worktree_store.clone(),
 779                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 780                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 781                        let this = this.as_local_mut().unwrap();
 782                        this.subscribe_to_worktree(worktree, cx);
 783                    }
 784                }),
 785            }),
 786            downstream_client: None,
 787            opened_buffers: Default::default(),
 788            path_to_buffer_id: Default::default(),
 789            shared_buffers: Default::default(),
 790            loading_buffers: Default::default(),
 791            non_searchable_buffers: Default::default(),
 792            worktree_store,
 793            project_search: Default::default(),
 794        }
 795    }
 796
 797    pub fn remote(
 798        worktree_store: Entity<WorktreeStore>,
 799        upstream_client: AnyProtoClient,
 800        remote_id: u64,
 801        _cx: &mut Context<Self>,
 802    ) -> Self {
 803        Self {
 804            state: BufferStoreState::Remote(RemoteBufferStore {
 805                shared_with_me: Default::default(),
 806                loading_remote_buffers_by_id: Default::default(),
 807                remote_buffer_listeners: Default::default(),
 808                project_id: remote_id,
 809                upstream_client,
 810                worktree_store: worktree_store.clone(),
 811            }),
 812            downstream_client: None,
 813            opened_buffers: Default::default(),
 814            path_to_buffer_id: Default::default(),
 815            loading_buffers: Default::default(),
 816            shared_buffers: Default::default(),
 817            non_searchable_buffers: Default::default(),
 818            worktree_store,
 819            project_search: Default::default(),
 820        }
 821    }
 822
 823    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 824        match &mut self.state {
 825            BufferStoreState::Local(state) => Some(state),
 826            _ => None,
 827        }
 828    }
 829
 830    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 831        match &mut self.state {
 832            BufferStoreState::Remote(state) => Some(state),
 833            _ => None,
 834        }
 835    }
 836
 837    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 838        match &self.state {
 839            BufferStoreState::Remote(state) => Some(state),
 840            _ => None,
 841        }
 842    }
 843
 844    #[ztracing::instrument(skip_all)]
 845    pub fn open_buffer(
 846        &mut self,
 847        project_path: ProjectPath,
 848        cx: &mut Context<Self>,
 849    ) -> Task<Result<Entity<Buffer>>> {
 850        if let Some(buffer) = self.get_by_path(&project_path) {
 851            return Task::ready(Ok(buffer));
 852        }
 853
 854        let task = match self.loading_buffers.entry(project_path.clone()) {
 855            hash_map::Entry::Occupied(e) => e.get().clone(),
 856            hash_map::Entry::Vacant(entry) => {
 857                let path = project_path.path.clone();
 858                let Some(worktree) = self
 859                    .worktree_store
 860                    .read(cx)
 861                    .worktree_for_id(project_path.worktree_id, cx)
 862                else {
 863                    return Task::ready(Err(anyhow!("no such worktree")));
 864                };
 865                let load_buffer = match &self.state {
 866                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 867                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 868                };
 869
 870                entry
 871                    .insert(
 872                        // todo(lw): hot foreground spawn
 873                        cx.spawn(async move |this, cx| {
 874                            let load_result = load_buffer.await;
 875                            this.update(cx, |this, _cx| {
 876                                // Record the fact that the buffer is no longer loading.
 877                                this.loading_buffers.remove(&project_path);
 878
 879                                let buffer = load_result.map_err(Arc::new)?;
 880                                Ok(buffer)
 881                            })?
 882                        })
 883                        .shared(),
 884                    )
 885                    .clone()
 886            }
 887        };
 888
 889        cx.background_spawn(async move {
 890            task.await.map_err(|e| {
 891                if e.error_code() != ErrorCode::Internal {
 892                    anyhow!(e.error_code())
 893                } else {
 894                    anyhow!("{e}")
 895                }
 896            })
 897        })
 898    }
 899
 900    pub fn create_buffer(
 901        &mut self,
 902        language: Option<Arc<Language>>,
 903        project_searchable: bool,
 904        cx: &mut Context<Self>,
 905    ) -> Task<Result<Entity<Buffer>>> {
 906        match &self.state {
 907            BufferStoreState::Local(this) => this.create_buffer(language, project_searchable, cx),
 908            BufferStoreState::Remote(this) => this.create_buffer(language, project_searchable, cx),
 909        }
 910    }
 911
 912    pub fn save_buffer(
 913        &mut self,
 914        buffer: Entity<Buffer>,
 915        cx: &mut Context<Self>,
 916    ) -> Task<Result<()>> {
 917        match &mut self.state {
 918            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 919            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer, None, cx),
 920        }
 921    }
 922
 923    pub fn save_buffer_as(
 924        &mut self,
 925        buffer: Entity<Buffer>,
 926        path: ProjectPath,
 927        cx: &mut Context<Self>,
 928    ) -> Task<Result<()>> {
 929        let old_file = buffer.read(cx).file().cloned();
 930        let task = match &self.state {
 931            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 932            BufferStoreState::Remote(this) => {
 933                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 934            }
 935        };
 936        cx.spawn(async move |this, cx| {
 937            task.await?;
 938            this.update(cx, |this, cx| {
 939                old_file.clone().and_then(|file| {
 940                    this.path_to_buffer_id.remove(&ProjectPath {
 941                        worktree_id: file.worktree_id(cx),
 942                        path: file.path().clone(),
 943                    })
 944                });
 945
 946                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 947            })
 948        })
 949    }
 950
 951    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 952        let buffer = buffer_entity.read(cx);
 953        let remote_id = buffer.remote_id();
 954        let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
 955            path: file.path.clone(),
 956            worktree_id: file.worktree_id(cx),
 957        });
 958        let is_remote = buffer.replica_id().is_remote();
 959        let open_buffer = OpenBuffer::Complete {
 960            buffer: buffer_entity.downgrade(),
 961        };
 962
 963        let handle = cx.entity().downgrade();
 964        buffer_entity.update(cx, move |_, cx| {
 965            cx.on_release(move |buffer, cx| {
 966                handle
 967                    .update(cx, |_, cx| {
 968                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 969                    })
 970                    .ok();
 971            })
 972            .detach()
 973        });
 974        let _expect_path_to_exist;
 975        match self.opened_buffers.entry(remote_id) {
 976            hash_map::Entry::Vacant(entry) => {
 977                entry.insert(open_buffer);
 978                _expect_path_to_exist = false;
 979            }
 980            hash_map::Entry::Occupied(mut entry) => {
 981                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 982                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 983                } else if entry.get().upgrade().is_some() {
 984                    if is_remote {
 985                        return Ok(());
 986                    } else {
 987                        debug_panic!("buffer {remote_id} was already registered");
 988                        anyhow::bail!("buffer {remote_id} was already registered");
 989                    }
 990                }
 991                entry.insert(open_buffer);
 992                _expect_path_to_exist = true;
 993            }
 994        }
 995
 996        if let Some(path) = path {
 997            self.path_to_buffer_id.insert(path, remote_id);
 998        }
 999
1000        cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
1001        cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
1002        Ok(())
1003    }
1004
1005    pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
1006        self.opened_buffers
1007            .values()
1008            .filter_map(|buffer| buffer.upgrade())
1009    }
1010
1011    pub(crate) fn is_searchable(&self, id: &BufferId) -> bool {
1012        !self.non_searchable_buffers.contains(&id)
1013    }
1014
1015    pub fn loading_buffers(
1016        &self,
1017    ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
1018        self.loading_buffers.iter().map(|(path, task)| {
1019            let task = task.clone();
1020            (path, async move {
1021                task.await.map_err(|e| {
1022                    if e.error_code() != ErrorCode::Internal {
1023                        anyhow!(e.error_code())
1024                    } else {
1025                        anyhow!("{e}")
1026                    }
1027                })
1028            })
1029        })
1030    }
1031
1032    pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
1033        self.path_to_buffer_id.get(project_path)
1034    }
1035
1036    pub fn get_by_path(&self, path: &ProjectPath) -> Option<Entity<Buffer>> {
1037        self.path_to_buffer_id
1038            .get(path)
1039            .and_then(|buffer_id| self.get(*buffer_id))
1040    }
1041
1042    pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1043        self.opened_buffers.get(&buffer_id)?.upgrade()
1044    }
1045
1046    pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
1047        self.get(buffer_id)
1048            .with_context(|| format!("unknown buffer id {buffer_id}"))
1049    }
1050
1051    pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1052        self.get(buffer_id).or_else(|| {
1053            self.as_remote()
1054                .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1055        })
1056    }
1057
1058    pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1059        let buffers = self
1060            .buffers()
1061            .map(|buffer| {
1062                let buffer = buffer.read(cx);
1063                proto::BufferVersion {
1064                    id: buffer.remote_id().into(),
1065                    version: language::proto::serialize_version(&buffer.version),
1066                }
1067            })
1068            .collect();
1069        let incomplete_buffer_ids = self
1070            .as_remote()
1071            .map(|remote| remote.incomplete_buffer_ids())
1072            .unwrap_or_default();
1073        (buffers, incomplete_buffer_ids)
1074    }
1075
1076    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1077        for open_buffer in self.opened_buffers.values_mut() {
1078            if let Some(buffer) = open_buffer.upgrade() {
1079                buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1080            }
1081        }
1082
1083        for buffer in self.buffers() {
1084            buffer.update(cx, |buffer, cx| {
1085                buffer.set_capability(Capability::ReadOnly, cx)
1086            });
1087        }
1088
1089        if let Some(remote) = self.as_remote_mut() {
1090            // Wake up all futures currently waiting on a buffer to get opened,
1091            // to give them a chance to fail now that we've disconnected.
1092            remote.remote_buffer_listeners.clear()
1093        }
1094    }
1095
1096    pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1097        self.downstream_client = Some((downstream_client, remote_id));
1098    }
1099
1100    pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1101        self.downstream_client.take();
1102        self.forget_shared_buffers();
1103    }
1104
1105    pub fn discard_incomplete(&mut self) {
1106        self.opened_buffers
1107            .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1108    }
1109
1110    fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
1111        let file = File::from_dyn(buffer.read(cx).file())?;
1112
1113        let remote_id = buffer.read(cx).remote_id();
1114        if let Some(entry_id) = file.entry_id {
1115            if let Some(local) = self.as_local_mut() {
1116                match local.local_buffer_ids_by_entry_id.get(&entry_id) {
1117                    Some(_) => {
1118                        return None;
1119                    }
1120                    None => {
1121                        local
1122                            .local_buffer_ids_by_entry_id
1123                            .insert(entry_id, remote_id);
1124                    }
1125                }
1126            }
1127            self.path_to_buffer_id.insert(
1128                ProjectPath {
1129                    worktree_id: file.worktree_id(cx),
1130                    path: file.path.clone(),
1131                },
1132                remote_id,
1133            );
1134        };
1135
1136        Some(())
1137    }
1138
1139    fn on_buffer_event(
1140        &mut self,
1141        buffer: Entity<Buffer>,
1142        event: &BufferEvent,
1143        cx: &mut Context<Self>,
1144    ) {
1145        match event {
1146            BufferEvent::FileHandleChanged => {
1147                self.buffer_changed_file(buffer, cx);
1148            }
1149            BufferEvent::Reloaded => {
1150                let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1151                    return;
1152                };
1153                let buffer = buffer.read(cx);
1154                downstream_client
1155                    .send(proto::BufferReloaded {
1156                        project_id: *project_id,
1157                        buffer_id: buffer.remote_id().to_proto(),
1158                        version: serialize_version(&buffer.version()),
1159                        mtime: buffer.saved_mtime().map(|t| t.into()),
1160                        line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1161                    })
1162                    .log_err();
1163            }
1164            BufferEvent::LanguageChanged(_) => {}
1165            _ => {}
1166        }
1167    }
1168
1169    pub async fn handle_update_buffer(
1170        this: Entity<Self>,
1171        envelope: TypedEnvelope<proto::UpdateBuffer>,
1172        mut cx: AsyncApp,
1173    ) -> Result<proto::Ack> {
1174        let payload = envelope.payload;
1175        let buffer_id = BufferId::new(payload.buffer_id)?;
1176        let ops = payload
1177            .operations
1178            .into_iter()
1179            .map(language::proto::deserialize_operation)
1180            .collect::<Result<Vec<_>, _>>()?;
1181        this.update(&mut cx, |this, cx| {
1182            match this.opened_buffers.entry(buffer_id) {
1183                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1184                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1185                    OpenBuffer::Complete { buffer, .. } => {
1186                        if let Some(buffer) = buffer.upgrade() {
1187                            buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1188                        }
1189                    }
1190                },
1191                hash_map::Entry::Vacant(e) => {
1192                    e.insert(OpenBuffer::Operations(ops));
1193                }
1194            }
1195            Ok(proto::Ack {})
1196        })
1197    }
1198
1199    pub fn register_shared_lsp_handle(
1200        &mut self,
1201        peer_id: proto::PeerId,
1202        buffer_id: BufferId,
1203        handle: OpenLspBufferHandle,
1204    ) {
1205        if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id)
1206            && let Some(buffer) = shared_buffers.get_mut(&buffer_id)
1207        {
1208            buffer.lsp_handle = Some(handle);
1209            return;
1210        }
1211        debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1212    }
1213
1214    pub fn handle_synchronize_buffers(
1215        &mut self,
1216        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1217        cx: &mut Context<Self>,
1218        client: Arc<Client>,
1219    ) -> Result<proto::SynchronizeBuffersResponse> {
1220        let project_id = envelope.payload.project_id;
1221        let mut response = proto::SynchronizeBuffersResponse {
1222            buffers: Default::default(),
1223        };
1224        let Some(guest_id) = envelope.original_sender_id else {
1225            anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1226        };
1227
1228        self.shared_buffers.entry(guest_id).or_default().clear();
1229        for buffer in envelope.payload.buffers {
1230            let buffer_id = BufferId::new(buffer.id)?;
1231            let remote_version = language::proto::deserialize_version(&buffer.version);
1232            if let Some(buffer) = self.get(buffer_id) {
1233                self.shared_buffers
1234                    .entry(guest_id)
1235                    .or_default()
1236                    .entry(buffer_id)
1237                    .or_insert_with(|| SharedBuffer {
1238                        buffer: buffer.clone(),
1239                        lsp_handle: None,
1240                    });
1241
1242                let buffer = buffer.read(cx);
1243                response.buffers.push(proto::BufferVersion {
1244                    id: buffer_id.into(),
1245                    version: language::proto::serialize_version(&buffer.version),
1246                });
1247
1248                let operations = buffer.serialize_ops(Some(remote_version), cx);
1249                let client = client.clone();
1250                if let Some(file) = buffer.file() {
1251                    client
1252                        .send(proto::UpdateBufferFile {
1253                            project_id,
1254                            buffer_id: buffer_id.into(),
1255                            file: Some(file.to_proto(cx)),
1256                        })
1257                        .log_err();
1258                }
1259
1260                // TODO(max): do something
1261                // client
1262                //     .send(proto::UpdateStagedText {
1263                //         project_id,
1264                //         buffer_id: buffer_id.into(),
1265                //         diff_base: buffer.diff_base().map(ToString::to_string),
1266                //     })
1267                //     .log_err();
1268
1269                client
1270                    .send(proto::BufferReloaded {
1271                        project_id,
1272                        buffer_id: buffer_id.into(),
1273                        version: language::proto::serialize_version(buffer.saved_version()),
1274                        mtime: buffer.saved_mtime().map(|time| time.into()),
1275                        line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1276                            as i32,
1277                    })
1278                    .log_err();
1279
1280                cx.background_spawn(
1281                    async move {
1282                        let operations = operations.await;
1283                        for chunk in split_operations(operations) {
1284                            client
1285                                .request(proto::UpdateBuffer {
1286                                    project_id,
1287                                    buffer_id: buffer_id.into(),
1288                                    operations: chunk,
1289                                })
1290                                .await?;
1291                        }
1292                        anyhow::Ok(())
1293                    }
1294                    .log_err(),
1295                )
1296                .detach();
1297            }
1298        }
1299        Ok(response)
1300    }
1301
1302    pub fn handle_create_buffer_for_peer(
1303        &mut self,
1304        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1305        replica_id: ReplicaId,
1306        capability: Capability,
1307        cx: &mut Context<Self>,
1308    ) -> Result<()> {
1309        let remote = self
1310            .as_remote_mut()
1311            .context("buffer store is not a remote")?;
1312
1313        if let Some(buffer) =
1314            remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1315        {
1316            self.add_buffer(buffer, cx)?;
1317        }
1318
1319        Ok(())
1320    }
1321
1322    pub async fn handle_update_buffer_file(
1323        this: Entity<Self>,
1324        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1325        mut cx: AsyncApp,
1326    ) -> Result<()> {
1327        let buffer_id = envelope.payload.buffer_id;
1328        let buffer_id = BufferId::new(buffer_id)?;
1329
1330        this.update(&mut cx, |this, cx| {
1331            let payload = envelope.payload.clone();
1332            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1333                let file = payload.file.context("invalid file")?;
1334                let worktree = this
1335                    .worktree_store
1336                    .read(cx)
1337                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1338                    .context("no such worktree")?;
1339                let file = File::from_proto(file, worktree, cx)?;
1340                let old_file = buffer.update(cx, |buffer, cx| {
1341                    let old_file = buffer.file().cloned();
1342                    let new_path = file.path.clone();
1343
1344                    buffer.file_updated(Arc::new(file), cx);
1345                    if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
1346                        Some(old_file)
1347                    } else {
1348                        None
1349                    }
1350                });
1351                if let Some(old_file) = old_file {
1352                    cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1353                }
1354            }
1355            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1356                downstream_client
1357                    .send(proto::UpdateBufferFile {
1358                        project_id: *project_id,
1359                        buffer_id: buffer_id.into(),
1360                        file: envelope.payload.file,
1361                    })
1362                    .log_err();
1363            }
1364            Ok(())
1365        })
1366    }
1367
1368    pub async fn handle_save_buffer(
1369        this: Entity<Self>,
1370        envelope: TypedEnvelope<proto::SaveBuffer>,
1371        mut cx: AsyncApp,
1372    ) -> Result<proto::BufferSaved> {
1373        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1374        let (buffer, project_id) = this.read_with(&cx, |this, _| {
1375            anyhow::Ok((
1376                this.get_existing(buffer_id)?,
1377                this.downstream_client
1378                    .as_ref()
1379                    .map(|(_, project_id)| *project_id)
1380                    .context("project is not shared")?,
1381            ))
1382        })?;
1383        buffer
1384            .update(&mut cx, |buffer, _| {
1385                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1386            })
1387            .await?;
1388        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
1389
1390        if let Some(new_path) = envelope.payload.new_path
1391            && let Some(new_path) = ProjectPath::from_proto(new_path)
1392        {
1393            this.update(&mut cx, |this, cx| {
1394                this.save_buffer_as(buffer.clone(), new_path, cx)
1395            })
1396            .await?;
1397        } else {
1398            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
1399                .await?;
1400        }
1401
1402        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
1403            project_id,
1404            buffer_id: buffer_id.into(),
1405            version: serialize_version(buffer.saved_version()),
1406            mtime: buffer.saved_mtime().map(|time| time.into()),
1407        }))
1408    }
1409
1410    pub async fn handle_close_buffer(
1411        this: Entity<Self>,
1412        envelope: TypedEnvelope<proto::CloseBuffer>,
1413        mut cx: AsyncApp,
1414    ) -> Result<()> {
1415        let peer_id = envelope.sender_id;
1416        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1417        this.update(&mut cx, |this, cx| {
1418            if let Some(shared) = this.shared_buffers.get_mut(&peer_id)
1419                && shared.remove(&buffer_id).is_some()
1420            {
1421                cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1422                if shared.is_empty() {
1423                    this.shared_buffers.remove(&peer_id);
1424                }
1425                return;
1426            }
1427            debug_panic!(
1428                "peer_id {} closed buffer_id {} which was either not open or already closed",
1429                peer_id,
1430                buffer_id
1431            )
1432        });
1433        Ok(())
1434    }
1435
1436    pub async fn handle_buffer_saved(
1437        this: Entity<Self>,
1438        envelope: TypedEnvelope<proto::BufferSaved>,
1439        mut cx: AsyncApp,
1440    ) -> Result<()> {
1441        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1442        let version = deserialize_version(&envelope.payload.version);
1443        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1444        this.update(&mut cx, move |this, cx| {
1445            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1446                buffer.update(cx, |buffer, cx| {
1447                    buffer.did_save(version, mtime, cx);
1448                });
1449            }
1450
1451            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1452                downstream_client
1453                    .send(proto::BufferSaved {
1454                        project_id: *project_id,
1455                        buffer_id: buffer_id.into(),
1456                        mtime: envelope.payload.mtime,
1457                        version: envelope.payload.version,
1458                    })
1459                    .log_err();
1460            }
1461        });
1462        Ok(())
1463    }
1464
1465    pub async fn handle_buffer_reloaded(
1466        this: Entity<Self>,
1467        envelope: TypedEnvelope<proto::BufferReloaded>,
1468        mut cx: AsyncApp,
1469    ) -> Result<()> {
1470        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1471        let version = deserialize_version(&envelope.payload.version);
1472        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1473        let line_ending = deserialize_line_ending(
1474            proto::LineEnding::from_i32(envelope.payload.line_ending)
1475                .context("missing line ending")?,
1476        );
1477        this.update(&mut cx, |this, cx| {
1478            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1479                buffer.update(cx, |buffer, cx| {
1480                    buffer.did_reload(version, line_ending, mtime, cx);
1481                });
1482            }
1483
1484            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1485                downstream_client
1486                    .send(proto::BufferReloaded {
1487                        project_id: *project_id,
1488                        buffer_id: buffer_id.into(),
1489                        mtime: envelope.payload.mtime,
1490                        version: envelope.payload.version,
1491                        line_ending: envelope.payload.line_ending,
1492                    })
1493                    .log_err();
1494            }
1495        });
1496        Ok(())
1497    }
1498
1499    pub fn reload_buffers(
1500        &self,
1501        buffers: HashSet<Entity<Buffer>>,
1502        push_to_history: bool,
1503        cx: &mut Context<Self>,
1504    ) -> Task<Result<ProjectTransaction>> {
1505        if buffers.is_empty() {
1506            return Task::ready(Ok(ProjectTransaction::default()));
1507        }
1508        match &self.state {
1509            BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1510            BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1511        }
1512    }
1513
1514    async fn handle_reload_buffers(
1515        this: Entity<Self>,
1516        envelope: TypedEnvelope<proto::ReloadBuffers>,
1517        mut cx: AsyncApp,
1518    ) -> Result<proto::ReloadBuffersResponse> {
1519        let sender_id = envelope.original_sender_id().unwrap_or_default();
1520        let reload = this.update(&mut cx, |this, cx| {
1521            let mut buffers = HashSet::default();
1522            for buffer_id in &envelope.payload.buffer_ids {
1523                let buffer_id = BufferId::new(*buffer_id)?;
1524                buffers.insert(this.get_existing(buffer_id)?);
1525            }
1526            anyhow::Ok(this.reload_buffers(buffers, false, cx))
1527        })?;
1528
1529        let project_transaction = reload.await?;
1530        let project_transaction = this.update(&mut cx, |this, cx| {
1531            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1532        });
1533        Ok(proto::ReloadBuffersResponse {
1534            transaction: Some(project_transaction),
1535        })
1536    }
1537
1538    pub fn create_buffer_for_peer(
1539        &mut self,
1540        buffer: &Entity<Buffer>,
1541        peer_id: proto::PeerId,
1542        cx: &mut Context<Self>,
1543    ) -> Task<Result<()>> {
1544        let buffer_id = buffer.read(cx).remote_id();
1545        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1546        if shared_buffers.contains_key(&buffer_id) {
1547            return Task::ready(Ok(()));
1548        }
1549        shared_buffers.insert(
1550            buffer_id,
1551            SharedBuffer {
1552                buffer: buffer.clone(),
1553                lsp_handle: None,
1554            },
1555        );
1556
1557        let Some((client, project_id)) = self.downstream_client.clone() else {
1558            return Task::ready(Ok(()));
1559        };
1560
1561        cx.spawn(async move |this, cx| {
1562            let Some(buffer) = this.read_with(cx, |this, _| this.get(buffer_id))? else {
1563                return anyhow::Ok(());
1564            };
1565
1566            let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx));
1567            let operations = operations.await;
1568            let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx));
1569
1570            let initial_state = proto::CreateBufferForPeer {
1571                project_id,
1572                peer_id: Some(peer_id),
1573                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1574            };
1575
1576            if client.send(initial_state).log_err().is_some() {
1577                let client = client.clone();
1578                cx.background_spawn(async move {
1579                    let mut chunks = split_operations(operations).peekable();
1580                    while let Some(chunk) = chunks.next() {
1581                        let is_last = chunks.peek().is_none();
1582                        client.send(proto::CreateBufferForPeer {
1583                            project_id,
1584                            peer_id: Some(peer_id),
1585                            variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1586                                proto::BufferChunk {
1587                                    buffer_id: buffer_id.into(),
1588                                    operations: chunk,
1589                                    is_last,
1590                                },
1591                            )),
1592                        })?;
1593                    }
1594                    anyhow::Ok(())
1595                })
1596                .await
1597                .log_err();
1598            }
1599            Ok(())
1600        })
1601    }
1602
1603    pub fn forget_shared_buffers(&mut self) {
1604        self.shared_buffers.clear();
1605    }
1606
1607    pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1608        self.shared_buffers.remove(peer_id);
1609    }
1610
1611    pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1612        if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1613            self.shared_buffers.insert(new_peer_id, buffers);
1614        }
1615    }
1616
1617    pub fn has_shared_buffers(&self) -> bool {
1618        !self.shared_buffers.is_empty()
1619    }
1620
1621    pub fn create_local_buffer(
1622        &mut self,
1623        text: &str,
1624        language: Option<Arc<Language>>,
1625        project_searchable: bool,
1626        cx: &mut Context<Self>,
1627    ) -> Entity<Buffer> {
1628        let buffer = cx.new(|cx| {
1629            Buffer::local(text, cx)
1630                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1631        });
1632
1633        self.add_buffer(buffer.clone(), cx).log_err();
1634        let buffer_id = buffer.read(cx).remote_id();
1635        if !project_searchable {
1636            self.non_searchable_buffers.insert(buffer_id);
1637        }
1638
1639        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1640            self.path_to_buffer_id.insert(
1641                ProjectPath {
1642                    worktree_id: file.worktree_id(cx),
1643                    path: file.path.clone(),
1644                },
1645                buffer_id,
1646            );
1647            let this = self
1648                .as_local_mut()
1649                .expect("local-only method called in a non-local context");
1650            if let Some(entry_id) = file.entry_id {
1651                this.local_buffer_ids_by_entry_id
1652                    .insert(entry_id, buffer_id);
1653            }
1654        }
1655        buffer
1656    }
1657
1658    pub fn deserialize_project_transaction(
1659        &mut self,
1660        message: proto::ProjectTransaction,
1661        push_to_history: bool,
1662        cx: &mut Context<Self>,
1663    ) -> Task<Result<ProjectTransaction>> {
1664        if let Some(this) = self.as_remote_mut() {
1665            this.deserialize_project_transaction(message, push_to_history, cx)
1666        } else {
1667            debug_panic!("not a remote buffer store");
1668            Task::ready(Err(anyhow!("not a remote buffer store")))
1669        }
1670    }
1671
1672    pub fn wait_for_remote_buffer(
1673        &mut self,
1674        id: BufferId,
1675        cx: &mut Context<BufferStore>,
1676    ) -> Task<Result<Entity<Buffer>>> {
1677        if let Some(this) = self.as_remote_mut() {
1678            this.wait_for_remote_buffer(id, cx)
1679        } else {
1680            debug_panic!("not a remote buffer store");
1681            Task::ready(Err(anyhow!("not a remote buffer store")))
1682        }
1683    }
1684
1685    pub fn serialize_project_transaction_for_peer(
1686        &mut self,
1687        project_transaction: ProjectTransaction,
1688        peer_id: proto::PeerId,
1689        cx: &mut Context<Self>,
1690    ) -> proto::ProjectTransaction {
1691        let mut serialized_transaction = proto::ProjectTransaction {
1692            buffer_ids: Default::default(),
1693            transactions: Default::default(),
1694        };
1695        for (buffer, transaction) in project_transaction.0 {
1696            self.create_buffer_for_peer(&buffer, peer_id, cx)
1697                .detach_and_log_err(cx);
1698            serialized_transaction
1699                .buffer_ids
1700                .push(buffer.read(cx).remote_id().into());
1701            serialized_transaction
1702                .transactions
1703                .push(language::proto::serialize_transaction(&transaction));
1704        }
1705        serialized_transaction
1706    }
1707
1708    pub(crate) fn register_project_search_result_handle(
1709        &mut self,
1710    ) -> (u64, smol::channel::Receiver<BufferId>) {
1711        let (tx, rx) = smol::channel::unbounded();
1712        let handle = util::post_inc(&mut self.project_search.next_id);
1713        let _old_entry = self.project_search.chunks.insert(handle, tx);
1714        debug_assert!(_old_entry.is_none());
1715        (handle, rx)
1716    }
1717
1718    pub fn register_ongoing_project_search(
1719        &mut self,
1720        id: (PeerId, u64),
1721        search: Task<anyhow::Result<()>>,
1722    ) {
1723        let _old = self.project_search.searches_in_progress.insert(id, search);
1724        debug_assert!(_old.is_none());
1725    }
1726
1727    pub async fn handle_find_search_candidates_cancel(
1728        this: Entity<Self>,
1729        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
1730        mut cx: AsyncApp,
1731    ) -> Result<()> {
1732        let id = (
1733            envelope.original_sender_id.unwrap_or(envelope.sender_id),
1734            envelope.payload.handle,
1735        );
1736        let _ = this.update(&mut cx, |this, _| {
1737            this.project_search.searches_in_progress.remove(&id)
1738        });
1739        Ok(())
1740    }
1741
1742    pub(crate) async fn handle_find_search_candidates_chunk(
1743        this: Entity<Self>,
1744        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
1745        mut cx: AsyncApp,
1746    ) -> Result<proto::Ack> {
1747        use proto::find_search_candidates_chunk::Variant;
1748        let handle = envelope.payload.handle;
1749
1750        let buffer_ids = match envelope
1751            .payload
1752            .variant
1753            .context("Expected non-null variant")?
1754        {
1755            Variant::Matches(find_search_candidates_matches) => find_search_candidates_matches
1756                .buffer_ids
1757                .into_iter()
1758                .filter_map(|buffer_id| BufferId::new(buffer_id).ok())
1759                .collect::<Vec<_>>(),
1760            Variant::Done(_) => {
1761                this.update(&mut cx, |this, _| {
1762                    this.project_search.chunks.remove(&handle)
1763                });
1764                return Ok(proto::Ack {});
1765            }
1766        };
1767        let Some(sender) = this.read_with(&mut cx, |this, _| {
1768            this.project_search.chunks.get(&handle).cloned()
1769        }) else {
1770            return Ok(proto::Ack {});
1771        };
1772
1773        for buffer_id in buffer_ids {
1774            let Ok(_) = sender.send(buffer_id).await else {
1775                this.update(&mut cx, |this, _| {
1776                    this.project_search.chunks.remove(&handle)
1777                });
1778                return Ok(proto::Ack {});
1779            };
1780        }
1781        Ok(proto::Ack {})
1782    }
1783}
1784
1785impl OpenBuffer {
1786    fn upgrade(&self) -> Option<Entity<Buffer>> {
1787        match self {
1788            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1789            OpenBuffer::Operations(_) => None,
1790        }
1791    }
1792}
1793
1794fn is_not_found_error(error: &anyhow::Error) -> bool {
1795    error
1796        .root_cause()
1797        .downcast_ref::<io::Error>()
1798        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1799}