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    BufferOpened {
  90        buffer: Entity<Buffer>,
  91        project_path: ProjectPath,
  92    },
  93    SharedBufferClosed(proto::PeerId, BufferId),
  94    BufferDropped(BufferId),
  95    BufferChangedFilePath {
  96        buffer: Entity<Buffer>,
  97        old_file: Option<Arc<dyn language::File>>,
  98    },
  99}
 100
 101#[derive(Default, Debug, Clone)]
 102pub struct ProjectTransaction(pub HashMap<Entity<Buffer>, language::Transaction>);
 103
 104impl PartialEq for ProjectTransaction {
 105    fn eq(&self, other: &Self) -> bool {
 106        self.0.len() == other.0.len()
 107            && self.0.iter().all(|(buffer, transaction)| {
 108                other.0.get(buffer).is_some_and(|t| t.id == transaction.id)
 109            })
 110    }
 111}
 112
 113impl EventEmitter<BufferStoreEvent> for BufferStore {}
 114
 115impl RemoteBufferStore {
 116    pub fn wait_for_remote_buffer(
 117        &mut self,
 118        id: BufferId,
 119        cx: &mut Context<BufferStore>,
 120    ) -> Task<Result<Entity<Buffer>>> {
 121        let (tx, rx) = oneshot::channel();
 122        self.remote_buffer_listeners.entry(id).or_default().push(tx);
 123
 124        cx.spawn(async move |this, cx| {
 125            if let Some(buffer) = this
 126                .read_with(cx, |buffer_store, _| buffer_store.get(id))
 127                .ok()
 128                .flatten()
 129            {
 130                return Ok(buffer);
 131            }
 132
 133            cx.background_spawn(async move { rx.await? }).await
 134        })
 135    }
 136
 137    fn save_remote_buffer(
 138        &self,
 139        buffer_handle: Entity<Buffer>,
 140        new_path: Option<proto::ProjectPath>,
 141        cx: &Context<BufferStore>,
 142    ) -> Task<Result<()>> {
 143        let buffer = buffer_handle.read(cx);
 144        let buffer_id = buffer.remote_id().into();
 145        let version = buffer.version();
 146        let rpc = self.upstream_client.clone();
 147        let project_id = self.project_id;
 148        cx.spawn(async move |_, cx| {
 149            let response = rpc
 150                .request(proto::SaveBuffer {
 151                    project_id,
 152                    buffer_id,
 153                    new_path,
 154                    version: serialize_version(&version),
 155                })
 156                .await?;
 157            let version = deserialize_version(&response.version);
 158            let mtime = response.mtime.map(|mtime| mtime.into());
 159
 160            buffer_handle.update(cx, |buffer, cx| {
 161                buffer.did_save(version.clone(), mtime, cx);
 162            });
 163
 164            Ok(())
 165        })
 166    }
 167
 168    pub fn handle_create_buffer_for_peer(
 169        &mut self,
 170        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 171        replica_id: ReplicaId,
 172        capability: Capability,
 173        cx: &mut Context<BufferStore>,
 174    ) -> Result<Option<Entity<Buffer>>> {
 175        match envelope.payload.variant.context("missing variant")? {
 176            proto::create_buffer_for_peer::Variant::State(mut state) => {
 177                let buffer_id = BufferId::new(state.id)?;
 178
 179                let buffer_result = maybe!({
 180                    let mut buffer_file = None;
 181                    if let Some(file) = state.file.take() {
 182                        let worktree_id = worktree::WorktreeId::from_proto(file.worktree_id);
 183                        let worktree = self
 184                            .worktree_store
 185                            .read(cx)
 186                            .worktree_for_id(worktree_id, cx)
 187                            .with_context(|| {
 188                                format!("no worktree found for id {}", file.worktree_id)
 189                            })?;
 190                        buffer_file = Some(Arc::new(File::from_proto(file, worktree, cx)?)
 191                            as Arc<dyn language::File>);
 192                    }
 193                    Buffer::from_proto(replica_id, capability, state, buffer_file)
 194                });
 195
 196                match buffer_result {
 197                    Ok(buffer) => {
 198                        let buffer = cx.new(|_| buffer);
 199                        self.loading_remote_buffers_by_id.insert(buffer_id, buffer);
 200                    }
 201                    Err(error) => {
 202                        if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 203                            for listener in listeners {
 204                                listener.send(Err(anyhow!(error.cloned()))).ok();
 205                            }
 206                        }
 207                    }
 208                }
 209            }
 210            proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 211                let buffer_id = BufferId::new(chunk.buffer_id)?;
 212                let buffer = self
 213                    .loading_remote_buffers_by_id
 214                    .get(&buffer_id)
 215                    .cloned()
 216                    .with_context(|| {
 217                        format!(
 218                            "received chunk for buffer {} without initial state",
 219                            chunk.buffer_id
 220                        )
 221                    })?;
 222
 223                let result = maybe!({
 224                    let operations = chunk
 225                        .operations
 226                        .into_iter()
 227                        .map(language::proto::deserialize_operation)
 228                        .collect::<Result<Vec<_>>>()?;
 229                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx));
 230                    anyhow::Ok(())
 231                });
 232
 233                if let Err(error) = result {
 234                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 235                    if let Some(listeners) = self.remote_buffer_listeners.remove(&buffer_id) {
 236                        for listener in listeners {
 237                            listener.send(Err(error.cloned())).ok();
 238                        }
 239                    }
 240                } else if chunk.is_last {
 241                    self.loading_remote_buffers_by_id.remove(&buffer_id);
 242                    if self.upstream_client.is_via_collab() {
 243                        // retain buffers sent by peers to avoid races.
 244                        self.shared_with_me.insert(buffer.clone());
 245                    }
 246
 247                    if let Some(senders) = self.remote_buffer_listeners.remove(&buffer_id) {
 248                        for sender in senders {
 249                            sender.send(Ok(buffer.clone())).ok();
 250                        }
 251                    }
 252                    return Ok(Some(buffer));
 253                }
 254            }
 255        }
 256        Ok(None)
 257    }
 258
 259    pub fn incomplete_buffer_ids(&self) -> Vec<BufferId> {
 260        self.loading_remote_buffers_by_id
 261            .keys()
 262            .copied()
 263            .collect::<Vec<_>>()
 264    }
 265
 266    pub fn deserialize_project_transaction(
 267        &self,
 268        message: proto::ProjectTransaction,
 269        push_to_history: bool,
 270        cx: &mut Context<BufferStore>,
 271    ) -> Task<Result<ProjectTransaction>> {
 272        cx.spawn(async move |this, cx| {
 273            let mut project_transaction = ProjectTransaction::default();
 274            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 275            {
 276                let buffer_id = BufferId::new(buffer_id)?;
 277                let buffer = this
 278                    .update(cx, |this, cx| this.wait_for_remote_buffer(buffer_id, cx))?
 279                    .await?;
 280                let transaction = language::proto::deserialize_transaction(transaction)?;
 281                project_transaction.0.insert(buffer, transaction);
 282            }
 283
 284            for (buffer, transaction) in &project_transaction.0 {
 285                buffer
 286                    .update(cx, |buffer, _| {
 287                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 288                    })
 289                    .await?;
 290
 291                if push_to_history {
 292                    buffer.update(cx, |buffer, _| {
 293                        buffer.push_transaction(transaction.clone(), Instant::now());
 294                        buffer.finalize_last_transaction();
 295                    });
 296                }
 297            }
 298
 299            Ok(project_transaction)
 300        })
 301    }
 302
 303    fn open_buffer(
 304        &self,
 305        path: Arc<RelPath>,
 306        worktree: Entity<Worktree>,
 307        cx: &mut Context<BufferStore>,
 308    ) -> Task<Result<Entity<Buffer>>> {
 309        let worktree_id = worktree.read(cx).id().to_proto();
 310        let project_id = self.project_id;
 311        let client = self.upstream_client.clone();
 312        cx.spawn(async move |this, cx| {
 313            let response = client
 314                .request(proto::OpenBufferByPath {
 315                    project_id,
 316                    worktree_id,
 317                    path: path.to_proto(),
 318                })
 319                .await?;
 320            let buffer_id = BufferId::new(response.buffer_id)?;
 321
 322            let buffer = this
 323                .update(cx, {
 324                    |this, cx| this.wait_for_remote_buffer(buffer_id, cx)
 325                })?
 326                .await?;
 327
 328            Ok(buffer)
 329        })
 330    }
 331
 332    fn create_buffer(
 333        &self,
 334        project_searchable: bool,
 335        cx: &mut Context<BufferStore>,
 336    ) -> Task<Result<Entity<Buffer>>> {
 337        let create = self.upstream_client.request(proto::OpenNewBuffer {
 338            project_id: self.project_id,
 339        });
 340        cx.spawn(async move |this, cx| {
 341            let response = create.await?;
 342            let buffer_id = BufferId::new(response.buffer_id)?;
 343
 344            this.update(cx, |this, cx| {
 345                if !project_searchable {
 346                    this.non_searchable_buffers.insert(buffer_id);
 347                }
 348                this.wait_for_remote_buffer(buffer_id, cx)
 349            })?
 350            .await
 351        })
 352    }
 353
 354    fn reload_buffers(
 355        &self,
 356        buffers: HashSet<Entity<Buffer>>,
 357        push_to_history: bool,
 358        cx: &mut Context<BufferStore>,
 359    ) -> Task<Result<ProjectTransaction>> {
 360        let request = self.upstream_client.request(proto::ReloadBuffers {
 361            project_id: self.project_id,
 362            buffer_ids: buffers
 363                .iter()
 364                .map(|buffer| buffer.read(cx).remote_id().to_proto())
 365                .collect(),
 366        });
 367
 368        cx.spawn(async move |this, cx| {
 369            let response = request.await?.transaction.context("missing transaction")?;
 370            this.update(cx, |this, cx| {
 371                this.deserialize_project_transaction(response, push_to_history, cx)
 372            })?
 373            .await
 374        })
 375    }
 376}
 377
 378impl LocalBufferStore {
 379    fn save_local_buffer(
 380        &self,
 381        buffer_handle: Entity<Buffer>,
 382        worktree: Entity<Worktree>,
 383        path: Arc<RelPath>,
 384        mut has_changed_file: bool,
 385        cx: &mut Context<BufferStore>,
 386    ) -> Task<Result<()>> {
 387        let buffer = buffer_handle.read(cx);
 388
 389        let text = buffer.as_rope().clone();
 390        let line_ending = buffer.line_ending();
 391        let encoding = buffer.encoding();
 392        let has_bom = buffer.has_bom();
 393        let version = buffer.version();
 394        let buffer_id = buffer.remote_id();
 395        let file = buffer.file().cloned();
 396        if file
 397            .as_ref()
 398            .is_some_and(|file| file.disk_state() == DiskState::New)
 399        {
 400            has_changed_file = true;
 401        }
 402
 403        let save = worktree.update(cx, |worktree, cx| {
 404            worktree.write_file(path, text, line_ending, encoding, has_bom, cx)
 405        });
 406
 407        cx.spawn(async move |this, cx| {
 408            let new_file = save.await?;
 409            let mtime = new_file.disk_state().mtime();
 410            this.update(cx, |this, cx| {
 411                if let Some((downstream_client, project_id)) = this.downstream_client.clone() {
 412                    if has_changed_file {
 413                        downstream_client
 414                            .send(proto::UpdateBufferFile {
 415                                project_id,
 416                                buffer_id: buffer_id.to_proto(),
 417                                file: Some(language::File::to_proto(&*new_file, cx)),
 418                            })
 419                            .log_err();
 420                    }
 421                    downstream_client
 422                        .send(proto::BufferSaved {
 423                            project_id,
 424                            buffer_id: buffer_id.to_proto(),
 425                            version: serialize_version(&version),
 426                            mtime: mtime.map(|time| time.into()),
 427                        })
 428                        .log_err();
 429                }
 430            })?;
 431            buffer_handle.update(cx, |buffer, cx| {
 432                if has_changed_file {
 433                    buffer.file_updated(new_file, cx);
 434                }
 435                buffer.did_save(version.clone(), mtime, cx);
 436            });
 437            Ok(())
 438        })
 439    }
 440
 441    fn subscribe_to_worktree(
 442        &mut self,
 443        worktree: &Entity<Worktree>,
 444        cx: &mut Context<BufferStore>,
 445    ) {
 446        cx.subscribe(worktree, |this, worktree, event, cx| {
 447            if worktree.read(cx).is_local()
 448                && let worktree::Event::UpdatedEntries(changes) = event
 449            {
 450                Self::local_worktree_entries_changed(this, &worktree, changes, cx);
 451            }
 452        })
 453        .detach();
 454    }
 455
 456    fn local_worktree_entries_changed(
 457        this: &mut BufferStore,
 458        worktree_handle: &Entity<Worktree>,
 459        changes: &[(Arc<RelPath>, ProjectEntryId, PathChange)],
 460        cx: &mut Context<BufferStore>,
 461    ) {
 462        let snapshot = worktree_handle.read(cx).snapshot();
 463        for (path, entry_id, _) in changes {
 464            Self::local_worktree_entry_changed(
 465                this,
 466                *entry_id,
 467                path,
 468                worktree_handle,
 469                &snapshot,
 470                cx,
 471            );
 472        }
 473    }
 474
 475    fn local_worktree_entry_changed(
 476        this: &mut BufferStore,
 477        entry_id: ProjectEntryId,
 478        path: &Arc<RelPath>,
 479        worktree: &Entity<worktree::Worktree>,
 480        snapshot: &worktree::Snapshot,
 481        cx: &mut Context<BufferStore>,
 482    ) -> Option<()> {
 483        let project_path = ProjectPath {
 484            worktree_id: snapshot.id(),
 485            path: path.clone(),
 486        };
 487
 488        let buffer_id = this
 489            .as_local_mut()
 490            .and_then(|local| local.local_buffer_ids_by_entry_id.get(&entry_id))
 491            .copied()
 492            .or_else(|| this.path_to_buffer_id.get(&project_path).copied())?;
 493
 494        let buffer = if let Some(buffer) = this.get(buffer_id) {
 495            Some(buffer)
 496        } else {
 497            this.opened_buffers.remove(&buffer_id);
 498            this.non_searchable_buffers.remove(&buffer_id);
 499            None
 500        };
 501
 502        let buffer = if let Some(buffer) = buffer {
 503            buffer
 504        } else {
 505            this.path_to_buffer_id.remove(&project_path);
 506            let this = this.as_local_mut()?;
 507            this.local_buffer_ids_by_entry_id.remove(&entry_id);
 508            return None;
 509        };
 510
 511        let events = buffer.update(cx, |buffer, cx| {
 512            let file = buffer.file()?;
 513            let old_file = File::from_dyn(Some(file))?;
 514            if old_file.worktree != *worktree {
 515                return None;
 516            }
 517
 518            let snapshot_entry = old_file
 519                .entry_id
 520                .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 521                .or_else(|| snapshot.entry_for_path(old_file.path.as_ref()));
 522
 523            let new_file = if let Some(entry) = snapshot_entry {
 524                File {
 525                    disk_state: match entry.mtime {
 526                        Some(mtime) => DiskState::Present { mtime },
 527                        None => old_file.disk_state,
 528                    },
 529                    is_local: true,
 530                    entry_id: Some(entry.id),
 531                    path: entry.path.clone(),
 532                    worktree: worktree.clone(),
 533                    is_private: entry.is_private,
 534                }
 535            } else {
 536                File {
 537                    disk_state: DiskState::Deleted,
 538                    is_local: true,
 539                    entry_id: old_file.entry_id,
 540                    path: old_file.path.clone(),
 541                    worktree: worktree.clone(),
 542                    is_private: old_file.is_private,
 543                }
 544            };
 545
 546            if new_file == *old_file {
 547                return None;
 548            }
 549
 550            let mut events = Vec::new();
 551            if new_file.path != old_file.path {
 552                this.path_to_buffer_id.remove(&ProjectPath {
 553                    path: old_file.path.clone(),
 554                    worktree_id: old_file.worktree_id(cx),
 555                });
 556                this.path_to_buffer_id.insert(
 557                    ProjectPath {
 558                        worktree_id: new_file.worktree_id(cx),
 559                        path: new_file.path.clone(),
 560                    },
 561                    buffer_id,
 562                );
 563                events.push(BufferStoreEvent::BufferChangedFilePath {
 564                    buffer: cx.entity(),
 565                    old_file: buffer.file().cloned(),
 566                });
 567            }
 568            let local = this.as_local_mut()?;
 569            if new_file.entry_id != old_file.entry_id {
 570                if let Some(entry_id) = old_file.entry_id {
 571                    local.local_buffer_ids_by_entry_id.remove(&entry_id);
 572                }
 573                if let Some(entry_id) = new_file.entry_id {
 574                    local
 575                        .local_buffer_ids_by_entry_id
 576                        .insert(entry_id, buffer_id);
 577                }
 578            }
 579
 580            if let Some((client, project_id)) = &this.downstream_client {
 581                client
 582                    .send(proto::UpdateBufferFile {
 583                        project_id: *project_id,
 584                        buffer_id: buffer_id.to_proto(),
 585                        file: Some(new_file.to_proto(cx)),
 586                    })
 587                    .ok();
 588            }
 589
 590            buffer.file_updated(Arc::new(new_file), cx);
 591            Some(events)
 592        })?;
 593
 594        for event in events {
 595            cx.emit(event);
 596        }
 597
 598        None
 599    }
 600
 601    fn save_buffer(
 602        &self,
 603        buffer: Entity<Buffer>,
 604        cx: &mut Context<BufferStore>,
 605    ) -> Task<Result<()>> {
 606        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 607            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 608        };
 609        let worktree = file.worktree.clone();
 610        self.save_local_buffer(buffer, worktree, file.path.clone(), false, cx)
 611    }
 612
 613    fn save_buffer_as(
 614        &self,
 615        buffer: Entity<Buffer>,
 616        path: ProjectPath,
 617        cx: &mut Context<BufferStore>,
 618    ) -> Task<Result<()>> {
 619        let Some(worktree) = self
 620            .worktree_store
 621            .read(cx)
 622            .worktree_for_id(path.worktree_id, cx)
 623        else {
 624            return Task::ready(Err(anyhow!("no such worktree")));
 625        };
 626        self.save_local_buffer(buffer, worktree, path.path, true, cx)
 627    }
 628
 629    fn open_buffer(
 630        &self,
 631        path: Arc<RelPath>,
 632        worktree: Entity<Worktree>,
 633        cx: &mut Context<BufferStore>,
 634    ) -> Task<Result<Entity<Buffer>>> {
 635        let load_file = worktree.update(cx, |worktree, cx| worktree.load_file(path.as_ref(), cx));
 636        cx.spawn(async move |this, cx| {
 637            let path = path.clone();
 638            let buffer = match load_file.await {
 639                Ok(loaded) => {
 640                    let reservation = cx.reserve_entity::<Buffer>();
 641                    let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 642                    let text_buffer = cx
 643                        .background_spawn(async move {
 644                            text::Buffer::new(ReplicaId::LOCAL, buffer_id, loaded.text)
 645                        })
 646                        .await;
 647                    cx.insert_entity(reservation, |_| {
 648                        let mut buffer =
 649                            Buffer::build(text_buffer, Some(loaded.file), Capability::ReadWrite);
 650                        buffer.set_encoding(loaded.encoding);
 651                        buffer.set_has_bom(loaded.has_bom);
 652                        buffer
 653                    })
 654                }
 655                Err(error) if is_not_found_error(&error) => cx.new(|cx| {
 656                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 657                    let text_buffer = text::Buffer::new(ReplicaId::LOCAL, buffer_id, "");
 658                    Buffer::build(
 659                        text_buffer,
 660                        Some(Arc::new(File {
 661                            worktree,
 662                            path,
 663                            disk_state: DiskState::New,
 664                            entry_id: None,
 665                            is_local: true,
 666                            is_private: false,
 667                        })),
 668                        Capability::ReadWrite,
 669                    )
 670                }),
 671                Err(e) => return Err(e),
 672            };
 673            this.update(cx, |this, cx| {
 674                this.add_buffer(buffer.clone(), cx)?;
 675                let buffer_id = buffer.read(cx).remote_id();
 676                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 677                    let project_path = ProjectPath {
 678                        worktree_id: file.worktree_id(cx),
 679                        path: file.path.clone(),
 680                    };
 681                    let entry_id = file.entry_id;
 682
 683                    // Check if the file should be read-only based on settings
 684                    let settings = WorktreeSettings::get(Some((&project_path).into()), cx);
 685                    let is_read_only = if project_path.path.is_empty() {
 686                        settings.is_std_path_read_only(&file.full_path(cx))
 687                    } else {
 688                        settings.is_path_read_only(&project_path.path)
 689                    };
 690                    if is_read_only {
 691                        buffer.update(cx, |buffer, cx| {
 692                            buffer.set_capability(Capability::Read, cx);
 693                        });
 694                    }
 695
 696                    this.path_to_buffer_id.insert(project_path, buffer_id);
 697                    let this = this.as_local_mut().unwrap();
 698                    if let Some(entry_id) = entry_id {
 699                        this.local_buffer_ids_by_entry_id
 700                            .insert(entry_id, buffer_id);
 701                    }
 702                }
 703
 704                anyhow::Ok(())
 705            })??;
 706
 707            Ok(buffer)
 708        })
 709    }
 710
 711    fn create_buffer(
 712        &self,
 713        project_searchable: bool,
 714        cx: &mut Context<BufferStore>,
 715    ) -> Task<Result<Entity<Buffer>>> {
 716        cx.spawn(async move |buffer_store, cx| {
 717            let buffer =
 718                cx.new(|cx| Buffer::local("", cx).with_language(language::PLAIN_TEXT.clone(), cx));
 719            buffer_store.update(cx, |buffer_store, cx| {
 720                buffer_store.add_buffer(buffer.clone(), cx).log_err();
 721                if !project_searchable {
 722                    buffer_store
 723                        .non_searchable_buffers
 724                        .insert(buffer.read(cx).remote_id());
 725                }
 726            })?;
 727            Ok(buffer)
 728        })
 729    }
 730
 731    fn reload_buffers(
 732        &self,
 733        buffers: HashSet<Entity<Buffer>>,
 734        push_to_history: bool,
 735        cx: &mut Context<BufferStore>,
 736    ) -> Task<Result<ProjectTransaction>> {
 737        cx.spawn(async move |_, cx| {
 738            let mut project_transaction = ProjectTransaction::default();
 739            for buffer in buffers {
 740                let transaction = buffer.update(cx, |buffer, cx| buffer.reload(cx)).await?;
 741                buffer.update(cx, |buffer, cx| {
 742                    if let Some(transaction) = transaction {
 743                        if !push_to_history {
 744                            buffer.forget_transaction(transaction.id);
 745                        }
 746                        project_transaction.0.insert(cx.entity(), transaction);
 747                    }
 748                });
 749            }
 750
 751            Ok(project_transaction)
 752        })
 753    }
 754}
 755
 756impl BufferStore {
 757    pub fn init(client: &AnyProtoClient) {
 758        client.add_entity_message_handler(Self::handle_buffer_reloaded);
 759        client.add_entity_message_handler(Self::handle_buffer_saved);
 760        client.add_entity_message_handler(Self::handle_update_buffer_file);
 761        client.add_entity_request_handler(Self::handle_save_buffer);
 762        client.add_entity_request_handler(Self::handle_reload_buffers);
 763    }
 764
 765    /// Creates a buffer store, optionally retaining its buffers.
 766    pub fn local(worktree_store: Entity<WorktreeStore>, cx: &mut Context<Self>) -> Self {
 767        Self {
 768            state: BufferStoreState::Local(LocalBufferStore {
 769                local_buffer_ids_by_entry_id: Default::default(),
 770                worktree_store: worktree_store.clone(),
 771                _subscription: cx.subscribe(&worktree_store, |this, _, event, cx| {
 772                    if let WorktreeStoreEvent::WorktreeAdded(worktree) = event {
 773                        let this = this.as_local_mut().unwrap();
 774                        this.subscribe_to_worktree(worktree, cx);
 775                    }
 776                }),
 777            }),
 778            downstream_client: None,
 779            opened_buffers: Default::default(),
 780            path_to_buffer_id: Default::default(),
 781            shared_buffers: Default::default(),
 782            loading_buffers: Default::default(),
 783            non_searchable_buffers: Default::default(),
 784            worktree_store,
 785            project_search: Default::default(),
 786        }
 787    }
 788
 789    pub fn remote(
 790        worktree_store: Entity<WorktreeStore>,
 791        upstream_client: AnyProtoClient,
 792        remote_id: u64,
 793        _cx: &mut Context<Self>,
 794    ) -> Self {
 795        Self {
 796            state: BufferStoreState::Remote(RemoteBufferStore {
 797                shared_with_me: Default::default(),
 798                loading_remote_buffers_by_id: Default::default(),
 799                remote_buffer_listeners: Default::default(),
 800                project_id: remote_id,
 801                upstream_client,
 802                worktree_store: worktree_store.clone(),
 803            }),
 804            downstream_client: None,
 805            opened_buffers: Default::default(),
 806            path_to_buffer_id: Default::default(),
 807            loading_buffers: Default::default(),
 808            shared_buffers: Default::default(),
 809            non_searchable_buffers: Default::default(),
 810            worktree_store,
 811            project_search: Default::default(),
 812        }
 813    }
 814
 815    fn as_local_mut(&mut self) -> Option<&mut LocalBufferStore> {
 816        match &mut self.state {
 817            BufferStoreState::Local(state) => Some(state),
 818            _ => None,
 819        }
 820    }
 821
 822    fn as_remote_mut(&mut self) -> Option<&mut RemoteBufferStore> {
 823        match &mut self.state {
 824            BufferStoreState::Remote(state) => Some(state),
 825            _ => None,
 826        }
 827    }
 828
 829    fn as_remote(&self) -> Option<&RemoteBufferStore> {
 830        match &self.state {
 831            BufferStoreState::Remote(state) => Some(state),
 832            _ => None,
 833        }
 834    }
 835
 836    pub fn open_buffer(
 837        &mut self,
 838        project_path: ProjectPath,
 839        cx: &mut Context<Self>,
 840    ) -> Task<Result<Entity<Buffer>>> {
 841        if let Some(buffer) = self.get_by_path(&project_path) {
 842            cx.emit(BufferStoreEvent::BufferOpened {
 843                buffer: buffer.clone(),
 844                project_path,
 845            });
 846
 847            return Task::ready(Ok(buffer));
 848        }
 849
 850        let task = match self.loading_buffers.entry(project_path.clone()) {
 851            hash_map::Entry::Occupied(e) => e.get().clone(),
 852            hash_map::Entry::Vacant(entry) => {
 853                let path = project_path.path.clone();
 854                let Some(worktree) = self
 855                    .worktree_store
 856                    .read(cx)
 857                    .worktree_for_id(project_path.worktree_id, cx)
 858                else {
 859                    return Task::ready(Err(anyhow!("no such worktree")));
 860                };
 861                let load_buffer = match &self.state {
 862                    BufferStoreState::Local(this) => this.open_buffer(path, worktree, cx),
 863                    BufferStoreState::Remote(this) => this.open_buffer(path, worktree, cx),
 864                };
 865
 866                entry
 867                    .insert(
 868                        // todo(lw): hot foreground spawn
 869                        cx.spawn(async move |this, cx| {
 870                            let load_result = load_buffer.await;
 871                            this.update(cx, |this, cx| {
 872                                // Record the fact that the buffer is no longer loading.
 873                                this.loading_buffers.remove(&project_path);
 874
 875                                let buffer = load_result.map_err(Arc::new)?;
 876                                cx.emit(BufferStoreEvent::BufferOpened {
 877                                    buffer: buffer.clone(),
 878                                    project_path,
 879                                });
 880
 881                                Ok(buffer)
 882                            })?
 883                        })
 884                        .shared(),
 885                    )
 886                    .clone()
 887            }
 888        };
 889
 890        cx.background_spawn(async move {
 891            task.await.map_err(|e| {
 892                if e.error_code() != ErrorCode::Internal {
 893                    anyhow!(e.error_code())
 894                } else {
 895                    anyhow!("{e}")
 896                }
 897            })
 898        })
 899    }
 900
 901    pub fn create_buffer(
 902        &mut self,
 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(project_searchable, cx),
 908            BufferStoreState::Remote(this) => this.create_buffer(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}