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                        cx.spawn(async move |this, cx| {
 873                            let load_result = load_buffer.await;
 874                            this.update(cx, |this, _cx| {
 875                                // Record the fact that the buffer is no longer loading.
 876                                this.loading_buffers.remove(&project_path);
 877
 878                                let buffer = load_result.map_err(Arc::new)?;
 879                                Ok(buffer)
 880                            })?
 881                        })
 882                        .shared(),
 883                    )
 884                    .clone()
 885            }
 886        };
 887
 888        cx.background_spawn(async move {
 889            task.await.map_err(|e| {
 890                if e.error_code() != ErrorCode::Internal {
 891                    anyhow!(e.error_code())
 892                } else {
 893                    anyhow!("{e}")
 894                }
 895            })
 896        })
 897    }
 898
 899    pub fn create_buffer(
 900        &mut self,
 901        language: Option<Arc<Language>>,
 902        project_searchable: bool,
 903        cx: &mut Context<Self>,
 904    ) -> Task<Result<Entity<Buffer>>> {
 905        match &self.state {
 906            BufferStoreState::Local(this) => this.create_buffer(language, project_searchable, cx),
 907            BufferStoreState::Remote(this) => this.create_buffer(language, project_searchable, cx),
 908        }
 909    }
 910
 911    pub fn save_buffer(
 912        &mut self,
 913        buffer: Entity<Buffer>,
 914        cx: &mut Context<Self>,
 915    ) -> Task<Result<()>> {
 916        match &mut self.state {
 917            BufferStoreState::Local(this) => this.save_buffer(buffer, cx),
 918            BufferStoreState::Remote(this) => this.save_remote_buffer(buffer, None, cx),
 919        }
 920    }
 921
 922    pub fn save_buffer_as(
 923        &mut self,
 924        buffer: Entity<Buffer>,
 925        path: ProjectPath,
 926        cx: &mut Context<Self>,
 927    ) -> Task<Result<()>> {
 928        let old_file = buffer.read(cx).file().cloned();
 929        let task = match &self.state {
 930            BufferStoreState::Local(this) => this.save_buffer_as(buffer.clone(), path, cx),
 931            BufferStoreState::Remote(this) => {
 932                this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 933            }
 934        };
 935        cx.spawn(async move |this, cx| {
 936            task.await?;
 937            this.update(cx, |this, cx| {
 938                old_file.clone().and_then(|file| {
 939                    this.path_to_buffer_id.remove(&ProjectPath {
 940                        worktree_id: file.worktree_id(cx),
 941                        path: file.path().clone(),
 942                    })
 943                });
 944
 945                cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
 946            })
 947        })
 948    }
 949
 950    fn add_buffer(&mut self, buffer_entity: Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
 951        let buffer = buffer_entity.read(cx);
 952        let remote_id = buffer.remote_id();
 953        let path = File::from_dyn(buffer.file()).map(|file| ProjectPath {
 954            path: file.path.clone(),
 955            worktree_id: file.worktree_id(cx),
 956        });
 957        let is_remote = buffer.replica_id().is_remote();
 958        let open_buffer = OpenBuffer::Complete {
 959            buffer: buffer_entity.downgrade(),
 960        };
 961
 962        let handle = cx.entity().downgrade();
 963        buffer_entity.update(cx, move |_, cx| {
 964            cx.on_release(move |buffer, cx| {
 965                handle
 966                    .update(cx, |_, cx| {
 967                        cx.emit(BufferStoreEvent::BufferDropped(buffer.remote_id()))
 968                    })
 969                    .ok();
 970            })
 971            .detach()
 972        });
 973        let _expect_path_to_exist;
 974        match self.opened_buffers.entry(remote_id) {
 975            hash_map::Entry::Vacant(entry) => {
 976                entry.insert(open_buffer);
 977                _expect_path_to_exist = false;
 978            }
 979            hash_map::Entry::Occupied(mut entry) => {
 980                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 981                    buffer_entity.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx));
 982                } else if entry.get().upgrade().is_some() {
 983                    if is_remote {
 984                        return Ok(());
 985                    } else {
 986                        debug_panic!("buffer {remote_id} was already registered");
 987                        anyhow::bail!("buffer {remote_id} was already registered");
 988                    }
 989                }
 990                entry.insert(open_buffer);
 991                _expect_path_to_exist = true;
 992            }
 993        }
 994
 995        if let Some(path) = path {
 996            self.path_to_buffer_id.insert(path, remote_id);
 997        }
 998
 999        cx.subscribe(&buffer_entity, Self::on_buffer_event).detach();
1000        cx.emit(BufferStoreEvent::BufferAdded(buffer_entity));
1001        Ok(())
1002    }
1003
1004    pub fn buffers(&self) -> impl '_ + Iterator<Item = Entity<Buffer>> {
1005        self.opened_buffers
1006            .values()
1007            .filter_map(|buffer| buffer.upgrade())
1008    }
1009
1010    pub(crate) fn is_searchable(&self, id: &BufferId) -> bool {
1011        !self.non_searchable_buffers.contains(&id)
1012    }
1013
1014    pub fn loading_buffers(
1015        &self,
1016    ) -> impl Iterator<Item = (&ProjectPath, impl Future<Output = Result<Entity<Buffer>>>)> {
1017        self.loading_buffers.iter().map(|(path, task)| {
1018            let task = task.clone();
1019            (path, async move {
1020                task.await.map_err(|e| {
1021                    if e.error_code() != ErrorCode::Internal {
1022                        anyhow!(e.error_code())
1023                    } else {
1024                        anyhow!("{e}")
1025                    }
1026                })
1027            })
1028        })
1029    }
1030
1031    pub fn buffer_id_for_project_path(&self, project_path: &ProjectPath) -> Option<&BufferId> {
1032        self.path_to_buffer_id.get(project_path)
1033    }
1034
1035    pub fn get_by_path(&self, path: &ProjectPath) -> Option<Entity<Buffer>> {
1036        self.path_to_buffer_id
1037            .get(path)
1038            .and_then(|buffer_id| self.get(*buffer_id))
1039    }
1040
1041    pub fn get(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1042        self.opened_buffers.get(&buffer_id)?.upgrade()
1043    }
1044
1045    pub fn get_existing(&self, buffer_id: BufferId) -> Result<Entity<Buffer>> {
1046        self.get(buffer_id)
1047            .with_context(|| format!("unknown buffer id {buffer_id}"))
1048    }
1049
1050    pub fn get_possibly_incomplete(&self, buffer_id: BufferId) -> Option<Entity<Buffer>> {
1051        self.get(buffer_id).or_else(|| {
1052            self.as_remote()
1053                .and_then(|remote| remote.loading_remote_buffers_by_id.get(&buffer_id).cloned())
1054        })
1055    }
1056
1057    pub fn buffer_version_info(&self, cx: &App) -> (Vec<proto::BufferVersion>, Vec<BufferId>) {
1058        let buffers = self
1059            .buffers()
1060            .map(|buffer| {
1061                let buffer = buffer.read(cx);
1062                proto::BufferVersion {
1063                    id: buffer.remote_id().into(),
1064                    version: language::proto::serialize_version(&buffer.version),
1065                }
1066            })
1067            .collect();
1068        let incomplete_buffer_ids = self
1069            .as_remote()
1070            .map(|remote| remote.incomplete_buffer_ids())
1071            .unwrap_or_default();
1072        (buffers, incomplete_buffer_ids)
1073    }
1074
1075    pub fn disconnected_from_host(&mut self, cx: &mut App) {
1076        for open_buffer in self.opened_buffers.values_mut() {
1077            if let Some(buffer) = open_buffer.upgrade() {
1078                buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1079            }
1080        }
1081
1082        for buffer in self.buffers() {
1083            buffer.update(cx, |buffer, cx| {
1084                buffer.set_capability(Capability::ReadOnly, cx)
1085            });
1086        }
1087
1088        if let Some(remote) = self.as_remote_mut() {
1089            // Wake up all futures currently waiting on a buffer to get opened,
1090            // to give them a chance to fail now that we've disconnected.
1091            remote.remote_buffer_listeners.clear()
1092        }
1093    }
1094
1095    pub fn shared(&mut self, remote_id: u64, downstream_client: AnyProtoClient, _cx: &mut App) {
1096        self.downstream_client = Some((downstream_client, remote_id));
1097    }
1098
1099    pub fn unshared(&mut self, _cx: &mut Context<Self>) {
1100        self.downstream_client.take();
1101        self.forget_shared_buffers();
1102    }
1103
1104    pub fn discard_incomplete(&mut self) {
1105        self.opened_buffers
1106            .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
1107    }
1108
1109    fn buffer_changed_file(&mut self, buffer: Entity<Buffer>, cx: &mut App) -> Option<()> {
1110        let file = File::from_dyn(buffer.read(cx).file())?;
1111
1112        let remote_id = buffer.read(cx).remote_id();
1113        if let Some(entry_id) = file.entry_id {
1114            if let Some(local) = self.as_local_mut() {
1115                match local.local_buffer_ids_by_entry_id.get(&entry_id) {
1116                    Some(_) => {
1117                        return None;
1118                    }
1119                    None => {
1120                        local
1121                            .local_buffer_ids_by_entry_id
1122                            .insert(entry_id, remote_id);
1123                    }
1124                }
1125            }
1126            self.path_to_buffer_id.insert(
1127                ProjectPath {
1128                    worktree_id: file.worktree_id(cx),
1129                    path: file.path.clone(),
1130                },
1131                remote_id,
1132            );
1133        };
1134
1135        Some(())
1136    }
1137
1138    fn on_buffer_event(
1139        &mut self,
1140        buffer: Entity<Buffer>,
1141        event: &BufferEvent,
1142        cx: &mut Context<Self>,
1143    ) {
1144        match event {
1145            BufferEvent::FileHandleChanged => {
1146                self.buffer_changed_file(buffer, cx);
1147            }
1148            BufferEvent::Reloaded => {
1149                let Some((downstream_client, project_id)) = self.downstream_client.as_ref() else {
1150                    return;
1151                };
1152                let buffer = buffer.read(cx);
1153                downstream_client
1154                    .send(proto::BufferReloaded {
1155                        project_id: *project_id,
1156                        buffer_id: buffer.remote_id().to_proto(),
1157                        version: serialize_version(&buffer.version()),
1158                        mtime: buffer.saved_mtime().map(|t| t.into()),
1159                        line_ending: serialize_line_ending(buffer.line_ending()) as i32,
1160                    })
1161                    .log_err();
1162            }
1163            BufferEvent::LanguageChanged(_) => {}
1164            _ => {}
1165        }
1166    }
1167
1168    pub async fn handle_update_buffer(
1169        this: Entity<Self>,
1170        envelope: TypedEnvelope<proto::UpdateBuffer>,
1171        mut cx: AsyncApp,
1172    ) -> Result<proto::Ack> {
1173        let payload = envelope.payload;
1174        let buffer_id = BufferId::new(payload.buffer_id)?;
1175        let ops = payload
1176            .operations
1177            .into_iter()
1178            .map(language::proto::deserialize_operation)
1179            .collect::<Result<Vec<_>, _>>()?;
1180        this.update(&mut cx, |this, cx| {
1181            match this.opened_buffers.entry(buffer_id) {
1182                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
1183                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
1184                    OpenBuffer::Complete { buffer, .. } => {
1185                        if let Some(buffer) = buffer.upgrade() {
1186                            buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx));
1187                        }
1188                    }
1189                },
1190                hash_map::Entry::Vacant(e) => {
1191                    e.insert(OpenBuffer::Operations(ops));
1192                }
1193            }
1194            Ok(proto::Ack {})
1195        })
1196    }
1197
1198    pub fn register_shared_lsp_handle(
1199        &mut self,
1200        peer_id: proto::PeerId,
1201        buffer_id: BufferId,
1202        handle: OpenLspBufferHandle,
1203    ) {
1204        if let Some(shared_buffers) = self.shared_buffers.get_mut(&peer_id)
1205            && let Some(buffer) = shared_buffers.get_mut(&buffer_id)
1206        {
1207            buffer.lsp_handle = Some(handle);
1208            return;
1209        }
1210        debug_panic!("tried to register shared lsp handle, but buffer was not shared")
1211    }
1212
1213    pub fn handle_synchronize_buffers(
1214        &mut self,
1215        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
1216        cx: &mut Context<Self>,
1217        client: Arc<Client>,
1218    ) -> Result<proto::SynchronizeBuffersResponse> {
1219        let project_id = envelope.payload.project_id;
1220        let mut response = proto::SynchronizeBuffersResponse {
1221            buffers: Default::default(),
1222        };
1223        let Some(guest_id) = envelope.original_sender_id else {
1224            anyhow::bail!("missing original_sender_id on SynchronizeBuffers request");
1225        };
1226
1227        self.shared_buffers.entry(guest_id).or_default().clear();
1228        for buffer in envelope.payload.buffers {
1229            let buffer_id = BufferId::new(buffer.id)?;
1230            let remote_version = language::proto::deserialize_version(&buffer.version);
1231            if let Some(buffer) = self.get(buffer_id) {
1232                self.shared_buffers
1233                    .entry(guest_id)
1234                    .or_default()
1235                    .entry(buffer_id)
1236                    .or_insert_with(|| SharedBuffer {
1237                        buffer: buffer.clone(),
1238                        lsp_handle: None,
1239                    });
1240
1241                let buffer = buffer.read(cx);
1242                response.buffers.push(proto::BufferVersion {
1243                    id: buffer_id.into(),
1244                    version: language::proto::serialize_version(&buffer.version),
1245                });
1246
1247                let operations = buffer.serialize_ops(Some(remote_version), cx);
1248                let client = client.clone();
1249                if let Some(file) = buffer.file() {
1250                    client
1251                        .send(proto::UpdateBufferFile {
1252                            project_id,
1253                            buffer_id: buffer_id.into(),
1254                            file: Some(file.to_proto(cx)),
1255                        })
1256                        .log_err();
1257                }
1258
1259                // TODO(max): do something
1260                // client
1261                //     .send(proto::UpdateStagedText {
1262                //         project_id,
1263                //         buffer_id: buffer_id.into(),
1264                //         diff_base: buffer.diff_base().map(ToString::to_string),
1265                //     })
1266                //     .log_err();
1267
1268                client
1269                    .send(proto::BufferReloaded {
1270                        project_id,
1271                        buffer_id: buffer_id.into(),
1272                        version: language::proto::serialize_version(buffer.saved_version()),
1273                        mtime: buffer.saved_mtime().map(|time| time.into()),
1274                        line_ending: language::proto::serialize_line_ending(buffer.line_ending())
1275                            as i32,
1276                    })
1277                    .log_err();
1278
1279                cx.background_spawn(
1280                    async move {
1281                        let operations = operations.await;
1282                        for chunk in split_operations(operations) {
1283                            client
1284                                .request(proto::UpdateBuffer {
1285                                    project_id,
1286                                    buffer_id: buffer_id.into(),
1287                                    operations: chunk,
1288                                })
1289                                .await?;
1290                        }
1291                        anyhow::Ok(())
1292                    }
1293                    .log_err(),
1294                )
1295                .detach();
1296            }
1297        }
1298        Ok(response)
1299    }
1300
1301    pub fn handle_create_buffer_for_peer(
1302        &mut self,
1303        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
1304        replica_id: ReplicaId,
1305        capability: Capability,
1306        cx: &mut Context<Self>,
1307    ) -> Result<()> {
1308        let remote = self
1309            .as_remote_mut()
1310            .context("buffer store is not a remote")?;
1311
1312        if let Some(buffer) =
1313            remote.handle_create_buffer_for_peer(envelope, replica_id, capability, cx)?
1314        {
1315            self.add_buffer(buffer, cx)?;
1316        }
1317
1318        Ok(())
1319    }
1320
1321    pub async fn handle_update_buffer_file(
1322        this: Entity<Self>,
1323        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1324        mut cx: AsyncApp,
1325    ) -> Result<()> {
1326        let buffer_id = envelope.payload.buffer_id;
1327        let buffer_id = BufferId::new(buffer_id)?;
1328
1329        this.update(&mut cx, |this, cx| {
1330            let payload = envelope.payload.clone();
1331            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1332                let file = payload.file.context("invalid file")?;
1333                let worktree = this
1334                    .worktree_store
1335                    .read(cx)
1336                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1337                    .context("no such worktree")?;
1338                let file = File::from_proto(file, worktree, cx)?;
1339                let old_file = buffer.update(cx, |buffer, cx| {
1340                    let old_file = buffer.file().cloned();
1341                    let new_path = file.path.clone();
1342
1343                    buffer.file_updated(Arc::new(file), cx);
1344                    if old_file.as_ref().is_none_or(|old| *old.path() != new_path) {
1345                        Some(old_file)
1346                    } else {
1347                        None
1348                    }
1349                });
1350                if let Some(old_file) = old_file {
1351                    cx.emit(BufferStoreEvent::BufferChangedFilePath { buffer, old_file });
1352                }
1353            }
1354            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1355                downstream_client
1356                    .send(proto::UpdateBufferFile {
1357                        project_id: *project_id,
1358                        buffer_id: buffer_id.into(),
1359                        file: envelope.payload.file,
1360                    })
1361                    .log_err();
1362            }
1363            Ok(())
1364        })
1365    }
1366
1367    pub async fn handle_save_buffer(
1368        this: Entity<Self>,
1369        envelope: TypedEnvelope<proto::SaveBuffer>,
1370        mut cx: AsyncApp,
1371    ) -> Result<proto::BufferSaved> {
1372        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1373        let (buffer, project_id) = this.read_with(&cx, |this, _| {
1374            anyhow::Ok((
1375                this.get_existing(buffer_id)?,
1376                this.downstream_client
1377                    .as_ref()
1378                    .map(|(_, project_id)| *project_id)
1379                    .context("project is not shared")?,
1380            ))
1381        })?;
1382        buffer
1383            .update(&mut cx, |buffer, _| {
1384                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
1385            })
1386            .await?;
1387        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
1388
1389        if let Some(new_path) = envelope.payload.new_path
1390            && let Some(new_path) = ProjectPath::from_proto(new_path)
1391        {
1392            this.update(&mut cx, |this, cx| {
1393                this.save_buffer_as(buffer.clone(), new_path, cx)
1394            })
1395            .await?;
1396        } else {
1397            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
1398                .await?;
1399        }
1400
1401        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
1402            project_id,
1403            buffer_id: buffer_id.into(),
1404            version: serialize_version(buffer.saved_version()),
1405            mtime: buffer.saved_mtime().map(|time| time.into()),
1406        }))
1407    }
1408
1409    pub async fn handle_close_buffer(
1410        this: Entity<Self>,
1411        envelope: TypedEnvelope<proto::CloseBuffer>,
1412        mut cx: AsyncApp,
1413    ) -> Result<()> {
1414        let peer_id = envelope.sender_id;
1415        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1416        this.update(&mut cx, |this, cx| {
1417            if let Some(shared) = this.shared_buffers.get_mut(&peer_id)
1418                && shared.remove(&buffer_id).is_some()
1419            {
1420                cx.emit(BufferStoreEvent::SharedBufferClosed(peer_id, buffer_id));
1421                if shared.is_empty() {
1422                    this.shared_buffers.remove(&peer_id);
1423                }
1424                return;
1425            }
1426            debug_panic!(
1427                "peer_id {} closed buffer_id {} which was either not open or already closed",
1428                peer_id,
1429                buffer_id
1430            )
1431        });
1432        Ok(())
1433    }
1434
1435    pub async fn handle_buffer_saved(
1436        this: Entity<Self>,
1437        envelope: TypedEnvelope<proto::BufferSaved>,
1438        mut cx: AsyncApp,
1439    ) -> Result<()> {
1440        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1441        let version = deserialize_version(&envelope.payload.version);
1442        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1443        this.update(&mut cx, move |this, cx| {
1444            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1445                buffer.update(cx, |buffer, cx| {
1446                    buffer.did_save(version, mtime, cx);
1447                });
1448            }
1449
1450            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1451                downstream_client
1452                    .send(proto::BufferSaved {
1453                        project_id: *project_id,
1454                        buffer_id: buffer_id.into(),
1455                        mtime: envelope.payload.mtime,
1456                        version: envelope.payload.version,
1457                    })
1458                    .log_err();
1459            }
1460        });
1461        Ok(())
1462    }
1463
1464    pub async fn handle_buffer_reloaded(
1465        this: Entity<Self>,
1466        envelope: TypedEnvelope<proto::BufferReloaded>,
1467        mut cx: AsyncApp,
1468    ) -> Result<()> {
1469        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
1470        let version = deserialize_version(&envelope.payload.version);
1471        let mtime = envelope.payload.mtime.clone().map(|time| time.into());
1472        let line_ending = deserialize_line_ending(
1473            proto::LineEnding::from_i32(envelope.payload.line_ending)
1474                .context("missing line ending")?,
1475        );
1476        this.update(&mut cx, |this, cx| {
1477            if let Some(buffer) = this.get_possibly_incomplete(buffer_id) {
1478                buffer.update(cx, |buffer, cx| {
1479                    buffer.did_reload(version, line_ending, mtime, cx);
1480                });
1481            }
1482
1483            if let Some((downstream_client, project_id)) = this.downstream_client.as_ref() {
1484                downstream_client
1485                    .send(proto::BufferReloaded {
1486                        project_id: *project_id,
1487                        buffer_id: buffer_id.into(),
1488                        mtime: envelope.payload.mtime,
1489                        version: envelope.payload.version,
1490                        line_ending: envelope.payload.line_ending,
1491                    })
1492                    .log_err();
1493            }
1494        });
1495        Ok(())
1496    }
1497
1498    pub fn reload_buffers(
1499        &self,
1500        buffers: HashSet<Entity<Buffer>>,
1501        push_to_history: bool,
1502        cx: &mut Context<Self>,
1503    ) -> Task<Result<ProjectTransaction>> {
1504        if buffers.is_empty() {
1505            return Task::ready(Ok(ProjectTransaction::default()));
1506        }
1507        match &self.state {
1508            BufferStoreState::Local(this) => this.reload_buffers(buffers, push_to_history, cx),
1509            BufferStoreState::Remote(this) => this.reload_buffers(buffers, push_to_history, cx),
1510        }
1511    }
1512
1513    async fn handle_reload_buffers(
1514        this: Entity<Self>,
1515        envelope: TypedEnvelope<proto::ReloadBuffers>,
1516        mut cx: AsyncApp,
1517    ) -> Result<proto::ReloadBuffersResponse> {
1518        let sender_id = envelope.original_sender_id().unwrap_or_default();
1519        let reload = this.update(&mut cx, |this, cx| {
1520            let mut buffers = HashSet::default();
1521            for buffer_id in &envelope.payload.buffer_ids {
1522                let buffer_id = BufferId::new(*buffer_id)?;
1523                buffers.insert(this.get_existing(buffer_id)?);
1524            }
1525            anyhow::Ok(this.reload_buffers(buffers, false, cx))
1526        })?;
1527
1528        let project_transaction = reload.await?;
1529        let project_transaction = this.update(&mut cx, |this, cx| {
1530            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
1531        });
1532        Ok(proto::ReloadBuffersResponse {
1533            transaction: Some(project_transaction),
1534        })
1535    }
1536
1537    pub fn create_buffer_for_peer(
1538        &mut self,
1539        buffer: &Entity<Buffer>,
1540        peer_id: proto::PeerId,
1541        cx: &mut Context<Self>,
1542    ) -> Task<Result<()>> {
1543        let buffer_id = buffer.read(cx).remote_id();
1544        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1545        if shared_buffers.contains_key(&buffer_id) {
1546            return Task::ready(Ok(()));
1547        }
1548        shared_buffers.insert(
1549            buffer_id,
1550            SharedBuffer {
1551                buffer: buffer.clone(),
1552                lsp_handle: None,
1553            },
1554        );
1555
1556        let Some((client, project_id)) = self.downstream_client.clone() else {
1557            return Task::ready(Ok(()));
1558        };
1559
1560        cx.spawn(async move |this, cx| {
1561            let Some(buffer) = this.read_with(cx, |this, _| this.get(buffer_id))? else {
1562                return anyhow::Ok(());
1563            };
1564
1565            let operations = buffer.update(cx, |b, cx| b.serialize_ops(None, cx));
1566            let operations = operations.await;
1567            let state = buffer.update(cx, |buffer, cx| buffer.to_proto(cx));
1568
1569            let initial_state = proto::CreateBufferForPeer {
1570                project_id,
1571                peer_id: Some(peer_id),
1572                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1573            };
1574
1575            if client.send(initial_state).log_err().is_some() {
1576                let client = client.clone();
1577                cx.background_spawn(async move {
1578                    let mut chunks = split_operations(operations).peekable();
1579                    while let Some(chunk) = chunks.next() {
1580                        let is_last = chunks.peek().is_none();
1581                        client.send(proto::CreateBufferForPeer {
1582                            project_id,
1583                            peer_id: Some(peer_id),
1584                            variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
1585                                proto::BufferChunk {
1586                                    buffer_id: buffer_id.into(),
1587                                    operations: chunk,
1588                                    is_last,
1589                                },
1590                            )),
1591                        })?;
1592                    }
1593                    anyhow::Ok(())
1594                })
1595                .await
1596                .log_err();
1597            }
1598            Ok(())
1599        })
1600    }
1601
1602    pub fn forget_shared_buffers(&mut self) {
1603        self.shared_buffers.clear();
1604    }
1605
1606    pub fn forget_shared_buffers_for(&mut self, peer_id: &proto::PeerId) {
1607        self.shared_buffers.remove(peer_id);
1608    }
1609
1610    pub fn update_peer_id(&mut self, old_peer_id: &proto::PeerId, new_peer_id: proto::PeerId) {
1611        if let Some(buffers) = self.shared_buffers.remove(old_peer_id) {
1612            self.shared_buffers.insert(new_peer_id, buffers);
1613        }
1614    }
1615
1616    pub fn has_shared_buffers(&self) -> bool {
1617        !self.shared_buffers.is_empty()
1618    }
1619
1620    pub fn create_local_buffer(
1621        &mut self,
1622        text: &str,
1623        language: Option<Arc<Language>>,
1624        project_searchable: bool,
1625        cx: &mut Context<Self>,
1626    ) -> Entity<Buffer> {
1627        let buffer = cx.new(|cx| {
1628            Buffer::local(text, cx)
1629                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1630        });
1631
1632        self.add_buffer(buffer.clone(), cx).log_err();
1633        let buffer_id = buffer.read(cx).remote_id();
1634        if !project_searchable {
1635            self.non_searchable_buffers.insert(buffer_id);
1636        }
1637
1638        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1639            self.path_to_buffer_id.insert(
1640                ProjectPath {
1641                    worktree_id: file.worktree_id(cx),
1642                    path: file.path.clone(),
1643                },
1644                buffer_id,
1645            );
1646            let this = self
1647                .as_local_mut()
1648                .expect("local-only method called in a non-local context");
1649            if let Some(entry_id) = file.entry_id {
1650                this.local_buffer_ids_by_entry_id
1651                    .insert(entry_id, buffer_id);
1652            }
1653        }
1654        buffer
1655    }
1656
1657    pub fn deserialize_project_transaction(
1658        &mut self,
1659        message: proto::ProjectTransaction,
1660        push_to_history: bool,
1661        cx: &mut Context<Self>,
1662    ) -> Task<Result<ProjectTransaction>> {
1663        if let Some(this) = self.as_remote_mut() {
1664            this.deserialize_project_transaction(message, push_to_history, cx)
1665        } else {
1666            debug_panic!("not a remote buffer store");
1667            Task::ready(Err(anyhow!("not a remote buffer store")))
1668        }
1669    }
1670
1671    pub fn wait_for_remote_buffer(
1672        &mut self,
1673        id: BufferId,
1674        cx: &mut Context<BufferStore>,
1675    ) -> Task<Result<Entity<Buffer>>> {
1676        if let Some(this) = self.as_remote_mut() {
1677            this.wait_for_remote_buffer(id, cx)
1678        } else {
1679            debug_panic!("not a remote buffer store");
1680            Task::ready(Err(anyhow!("not a remote buffer store")))
1681        }
1682    }
1683
1684    pub fn serialize_project_transaction_for_peer(
1685        &mut self,
1686        project_transaction: ProjectTransaction,
1687        peer_id: proto::PeerId,
1688        cx: &mut Context<Self>,
1689    ) -> proto::ProjectTransaction {
1690        let mut serialized_transaction = proto::ProjectTransaction {
1691            buffer_ids: Default::default(),
1692            transactions: Default::default(),
1693        };
1694        for (buffer, transaction) in project_transaction.0 {
1695            self.create_buffer_for_peer(&buffer, peer_id, cx)
1696                .detach_and_log_err(cx);
1697            serialized_transaction
1698                .buffer_ids
1699                .push(buffer.read(cx).remote_id().into());
1700            serialized_transaction
1701                .transactions
1702                .push(language::proto::serialize_transaction(&transaction));
1703        }
1704        serialized_transaction
1705    }
1706
1707    pub(crate) fn register_project_search_result_handle(
1708        &mut self,
1709    ) -> (u64, smol::channel::Receiver<BufferId>) {
1710        let (tx, rx) = smol::channel::unbounded();
1711        let handle = util::post_inc(&mut self.project_search.next_id);
1712        let _old_entry = self.project_search.chunks.insert(handle, tx);
1713        debug_assert!(_old_entry.is_none());
1714        (handle, rx)
1715    }
1716
1717    pub fn register_ongoing_project_search(
1718        &mut self,
1719        id: (PeerId, u64),
1720        search: Task<anyhow::Result<()>>,
1721    ) {
1722        let _old = self.project_search.searches_in_progress.insert(id, search);
1723        debug_assert!(_old.is_none());
1724    }
1725
1726    pub async fn handle_find_search_candidates_cancel(
1727        this: Entity<Self>,
1728        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
1729        mut cx: AsyncApp,
1730    ) -> Result<()> {
1731        let id = (
1732            envelope.original_sender_id.unwrap_or(envelope.sender_id),
1733            envelope.payload.handle,
1734        );
1735        let _ = this.update(&mut cx, |this, _| {
1736            this.project_search.searches_in_progress.remove(&id)
1737        });
1738        Ok(())
1739    }
1740
1741    pub(crate) async fn handle_find_search_candidates_chunk(
1742        this: Entity<Self>,
1743        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
1744        mut cx: AsyncApp,
1745    ) -> Result<proto::Ack> {
1746        use proto::find_search_candidates_chunk::Variant;
1747        let handle = envelope.payload.handle;
1748
1749        let buffer_ids = match envelope
1750            .payload
1751            .variant
1752            .context("Expected non-null variant")?
1753        {
1754            Variant::Matches(find_search_candidates_matches) => find_search_candidates_matches
1755                .buffer_ids
1756                .into_iter()
1757                .filter_map(|buffer_id| BufferId::new(buffer_id).ok())
1758                .collect::<Vec<_>>(),
1759            Variant::Done(_) => {
1760                this.update(&mut cx, |this, _| {
1761                    this.project_search.chunks.remove(&handle)
1762                });
1763                return Ok(proto::Ack {});
1764            }
1765        };
1766        let Some(sender) = this.read_with(&mut cx, |this, _| {
1767            this.project_search.chunks.get(&handle).cloned()
1768        }) else {
1769            return Ok(proto::Ack {});
1770        };
1771
1772        for buffer_id in buffer_ids {
1773            let Ok(_) = sender.send(buffer_id).await else {
1774                this.update(&mut cx, |this, _| {
1775                    this.project_search.chunks.remove(&handle)
1776                });
1777                return Ok(proto::Ack {});
1778            };
1779        }
1780        Ok(proto::Ack {})
1781    }
1782}
1783
1784impl OpenBuffer {
1785    fn upgrade(&self) -> Option<Entity<Buffer>> {
1786        match self {
1787            OpenBuffer::Complete { buffer, .. } => buffer.upgrade(),
1788            OpenBuffer::Operations(_) => None,
1789        }
1790    }
1791}
1792
1793fn is_not_found_error(error: &anyhow::Error) -> bool {
1794    error
1795        .root_cause()
1796        .downcast_ref::<io::Error>()
1797        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
1798}