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