buffer_store.rs

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