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