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