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