project.rs

   1mod db;
   2pub mod fs;
   3mod ignore;
   4mod lsp_command;
   5pub mod search;
   6pub mod worktree;
   7
   8#[cfg(test)]
   9mod project_tests;
  10
  11use anyhow::{anyhow, Context, Result};
  12use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
  13use clock::ReplicaId;
  14use collections::{hash_map, BTreeMap, HashMap, HashSet};
  15use futures::{future::Shared, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt};
  16use gpui::{
  17    AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
  18    MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
  19};
  20use language::{
  21    point_to_lsp,
  22    proto::{
  23        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
  24        serialize_version,
  25    },
  26    range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CharKind, CodeAction,
  27    CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent,
  28    File as _, Language, LanguageRegistry, LanguageServerName, LineEnding, LocalFile,
  29    OffsetRangeExt, Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16,
  30    Transaction,
  31};
  32use lsp::{
  33    DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
  34    MarkedString,
  35};
  36use lsp_command::*;
  37use parking_lot::Mutex;
  38use postage::stream::Stream;
  39use postage::watch;
  40use rand::prelude::*;
  41use search::SearchQuery;
  42use serde::Serialize;
  43use settings::Settings;
  44use sha2::{Digest, Sha256};
  45use similar::{ChangeTag, TextDiff};
  46use std::{
  47    cell::RefCell,
  48    cmp::{self, Ordering},
  49    convert::TryInto,
  50    ffi::OsString,
  51    hash::Hash,
  52    mem,
  53    num::NonZeroU32,
  54    ops::Range,
  55    os::unix::{ffi::OsStrExt, prelude::OsStringExt},
  56    path::{Component, Path, PathBuf},
  57    rc::Rc,
  58    str,
  59    sync::{
  60        atomic::{AtomicUsize, Ordering::SeqCst},
  61        Arc,
  62    },
  63    time::Instant,
  64};
  65use thiserror::Error;
  66use util::{post_inc, ResultExt, TryFutureExt as _};
  67
  68pub use db::Db;
  69pub use fs::*;
  70pub use worktree::*;
  71
  72pub trait Item: Entity {
  73    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  74}
  75
  76pub struct ProjectStore {
  77    db: Arc<Db>,
  78    projects: Vec<WeakModelHandle<Project>>,
  79}
  80
  81// Language server state is stored across 3 collections:
  82//     language_servers =>
  83//         a mapping from unique server id to LanguageServerState which can either be a task for a
  84//         server in the process of starting, or a running server with adapter and language server arcs
  85//     language_server_ids => a mapping from worktreeId and server name to the unique server id
  86//     language_server_statuses => a mapping from unique server id to the current server status
  87//
  88// Multiple worktrees can map to the same language server for example when you jump to the definition
  89// of a file in the standard library. So language_server_ids is used to look up which server is active
  90// for a given worktree and language server name
  91//
  92// When starting a language server, first the id map is checked to make sure a server isn't already available
  93// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
  94// the Starting variant of LanguageServerState is stored in the language_servers map.
  95pub struct Project {
  96    worktrees: Vec<WorktreeHandle>,
  97    active_entry: Option<ProjectEntryId>,
  98    languages: Arc<LanguageRegistry>,
  99    language_servers: HashMap<usize, LanguageServerState>,
 100    language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
 101    language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
 102    language_server_settings: Arc<Mutex<serde_json::Value>>,
 103    last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
 104    next_language_server_id: usize,
 105    client: Arc<client::Client>,
 106    next_entry_id: Arc<AtomicUsize>,
 107    next_diagnostic_group_id: usize,
 108    user_store: ModelHandle<UserStore>,
 109    project_store: ModelHandle<ProjectStore>,
 110    fs: Arc<dyn Fs>,
 111    client_state: ProjectClientState,
 112    collaborators: HashMap<PeerId, Collaborator>,
 113    client_subscriptions: Vec<client::Subscription>,
 114    _subscriptions: Vec<gpui::Subscription>,
 115    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 116    shared_buffers: HashMap<PeerId, HashSet<u64>>,
 117    #[allow(clippy::type_complexity)]
 118    loading_buffers: HashMap<
 119        ProjectPath,
 120        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 121    >,
 122    #[allow(clippy::type_complexity)]
 123    loading_local_worktrees:
 124        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 125    opened_buffers: HashMap<u64, OpenBuffer>,
 126    incomplete_buffers: HashMap<u64, ModelHandle<Buffer>>,
 127    buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
 128    nonce: u128,
 129    initialized_persistent_state: bool,
 130    _maintain_buffer_languages: Task<()>,
 131}
 132
 133#[derive(Error, Debug)]
 134pub enum JoinProjectError {
 135    #[error("host declined join request")]
 136    HostDeclined,
 137    #[error("host closed the project")]
 138    HostClosedProject,
 139    #[error("host went offline")]
 140    HostWentOffline,
 141    #[error("{0}")]
 142    Other(#[from] anyhow::Error),
 143}
 144
 145enum OpenBuffer {
 146    Strong(ModelHandle<Buffer>),
 147    Weak(WeakModelHandle<Buffer>),
 148    Operations(Vec<Operation>),
 149}
 150
 151enum WorktreeHandle {
 152    Strong(ModelHandle<Worktree>),
 153    Weak(WeakModelHandle<Worktree>),
 154}
 155
 156enum ProjectClientState {
 157    Local {
 158        is_shared: bool,
 159        remote_id_tx: watch::Sender<Option<u64>>,
 160        remote_id_rx: watch::Receiver<Option<u64>>,
 161        online_tx: watch::Sender<bool>,
 162        online_rx: watch::Receiver<bool>,
 163        _maintain_remote_id: Task<Option<()>>,
 164        _maintain_online_status: Task<Option<()>>,
 165    },
 166    Remote {
 167        sharing_has_stopped: bool,
 168        remote_id: u64,
 169        replica_id: ReplicaId,
 170        _detect_unshare: Task<Option<()>>,
 171    },
 172}
 173
 174#[derive(Clone, Debug)]
 175pub struct Collaborator {
 176    pub user: Arc<User>,
 177    pub peer_id: PeerId,
 178    pub replica_id: ReplicaId,
 179}
 180
 181#[derive(Clone, Debug, PartialEq, Eq)]
 182pub enum Event {
 183    ActiveEntryChanged(Option<ProjectEntryId>),
 184    WorktreeAdded,
 185    WorktreeRemoved(WorktreeId),
 186    DiskBasedDiagnosticsStarted {
 187        language_server_id: usize,
 188    },
 189    DiskBasedDiagnosticsFinished {
 190        language_server_id: usize,
 191    },
 192    DiagnosticsUpdated {
 193        path: ProjectPath,
 194        language_server_id: usize,
 195    },
 196    RemoteIdChanged(Option<u64>),
 197    DisconnectedFromHost,
 198    CollaboratorLeft(PeerId),
 199    ContactRequestedJoin(Arc<User>),
 200    ContactCancelledJoinRequest(Arc<User>),
 201}
 202
 203pub enum LanguageServerState {
 204    Starting(Task<Option<Arc<LanguageServer>>>),
 205    Running {
 206        language: Arc<Language>,
 207        adapter: Arc<CachedLspAdapter>,
 208        server: Arc<LanguageServer>,
 209    },
 210}
 211
 212#[derive(Serialize)]
 213pub struct LanguageServerStatus {
 214    pub name: String,
 215    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 216    pub has_pending_diagnostic_updates: bool,
 217    progress_tokens: HashSet<String>,
 218}
 219
 220#[derive(Clone, Debug, Serialize)]
 221pub struct LanguageServerProgress {
 222    pub message: Option<String>,
 223    pub percentage: Option<usize>,
 224    #[serde(skip_serializing)]
 225    pub last_update_at: Instant,
 226}
 227
 228#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 229pub struct ProjectPath {
 230    pub worktree_id: WorktreeId,
 231    pub path: Arc<Path>,
 232}
 233
 234#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 235pub struct DiagnosticSummary {
 236    pub language_server_id: usize,
 237    pub error_count: usize,
 238    pub warning_count: usize,
 239}
 240
 241#[derive(Debug, Clone)]
 242pub struct Location {
 243    pub buffer: ModelHandle<Buffer>,
 244    pub range: Range<language::Anchor>,
 245}
 246
 247#[derive(Debug, Clone)]
 248pub struct LocationLink {
 249    pub origin: Option<Location>,
 250    pub target: Location,
 251}
 252
 253#[derive(Debug)]
 254pub struct DocumentHighlight {
 255    pub range: Range<language::Anchor>,
 256    pub kind: DocumentHighlightKind,
 257}
 258
 259#[derive(Clone, Debug)]
 260pub struct Symbol {
 261    pub language_server_name: LanguageServerName,
 262    pub source_worktree_id: WorktreeId,
 263    pub path: ProjectPath,
 264    pub label: CodeLabel,
 265    pub name: String,
 266    pub kind: lsp::SymbolKind,
 267    pub range: Range<PointUtf16>,
 268    pub signature: [u8; 32],
 269}
 270
 271#[derive(Clone, Debug, PartialEq)]
 272pub struct HoverBlock {
 273    pub text: String,
 274    pub language: Option<String>,
 275}
 276
 277impl HoverBlock {
 278    fn try_new(marked_string: MarkedString) -> Option<Self> {
 279        let result = match marked_string {
 280            MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
 281                text: value,
 282                language: Some(language),
 283            },
 284            MarkedString::String(text) => HoverBlock {
 285                text,
 286                language: None,
 287            },
 288        };
 289        if result.text.is_empty() {
 290            None
 291        } else {
 292            Some(result)
 293        }
 294    }
 295}
 296
 297#[derive(Debug)]
 298pub struct Hover {
 299    pub contents: Vec<HoverBlock>,
 300    pub range: Option<Range<language::Anchor>>,
 301}
 302
 303#[derive(Default)]
 304pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 305
 306impl DiagnosticSummary {
 307    fn new<'a, T: 'a>(
 308        language_server_id: usize,
 309        diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
 310    ) -> Self {
 311        let mut this = Self {
 312            language_server_id,
 313            error_count: 0,
 314            warning_count: 0,
 315        };
 316
 317        for entry in diagnostics {
 318            if entry.diagnostic.is_primary {
 319                match entry.diagnostic.severity {
 320                    DiagnosticSeverity::ERROR => this.error_count += 1,
 321                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 322                    _ => {}
 323                }
 324            }
 325        }
 326
 327        this
 328    }
 329
 330    pub fn is_empty(&self) -> bool {
 331        self.error_count == 0 && self.warning_count == 0
 332    }
 333
 334    pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
 335        proto::DiagnosticSummary {
 336            path: path.to_string_lossy().to_string(),
 337            language_server_id: self.language_server_id as u64,
 338            error_count: self.error_count as u32,
 339            warning_count: self.warning_count as u32,
 340        }
 341    }
 342}
 343
 344#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 345pub struct ProjectEntryId(usize);
 346
 347impl ProjectEntryId {
 348    pub const MAX: Self = Self(usize::MAX);
 349
 350    pub fn new(counter: &AtomicUsize) -> Self {
 351        Self(counter.fetch_add(1, SeqCst))
 352    }
 353
 354    pub fn from_proto(id: u64) -> Self {
 355        Self(id as usize)
 356    }
 357
 358    pub fn to_proto(&self) -> u64 {
 359        self.0 as u64
 360    }
 361
 362    pub fn to_usize(&self) -> usize {
 363        self.0
 364    }
 365}
 366
 367impl Project {
 368    pub fn init(client: &Arc<Client>) {
 369        client.add_model_message_handler(Self::handle_request_join_project);
 370        client.add_model_message_handler(Self::handle_add_collaborator);
 371        client.add_model_message_handler(Self::handle_buffer_reloaded);
 372        client.add_model_message_handler(Self::handle_buffer_saved);
 373        client.add_model_message_handler(Self::handle_start_language_server);
 374        client.add_model_message_handler(Self::handle_update_language_server);
 375        client.add_model_message_handler(Self::handle_remove_collaborator);
 376        client.add_model_message_handler(Self::handle_join_project_request_cancelled);
 377        client.add_model_message_handler(Self::handle_update_project);
 378        client.add_model_message_handler(Self::handle_unregister_project);
 379        client.add_model_message_handler(Self::handle_project_unshared);
 380        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 381        client.add_model_message_handler(Self::handle_update_buffer_file);
 382        client.add_model_message_handler(Self::handle_update_buffer);
 383        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 384        client.add_model_message_handler(Self::handle_update_worktree);
 385        client.add_model_request_handler(Self::handle_create_project_entry);
 386        client.add_model_request_handler(Self::handle_rename_project_entry);
 387        client.add_model_request_handler(Self::handle_copy_project_entry);
 388        client.add_model_request_handler(Self::handle_delete_project_entry);
 389        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 390        client.add_model_request_handler(Self::handle_apply_code_action);
 391        client.add_model_request_handler(Self::handle_reload_buffers);
 392        client.add_model_request_handler(Self::handle_format_buffers);
 393        client.add_model_request_handler(Self::handle_get_code_actions);
 394        client.add_model_request_handler(Self::handle_get_completions);
 395        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 396        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 397        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 398        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 399        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 400        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 401        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 402        client.add_model_request_handler(Self::handle_search_project);
 403        client.add_model_request_handler(Self::handle_get_project_symbols);
 404        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 405        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 406        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 407        client.add_model_request_handler(Self::handle_save_buffer);
 408    }
 409
 410    pub fn local(
 411        online: bool,
 412        client: Arc<Client>,
 413        user_store: ModelHandle<UserStore>,
 414        project_store: ModelHandle<ProjectStore>,
 415        languages: Arc<LanguageRegistry>,
 416        fs: Arc<dyn Fs>,
 417        cx: &mut MutableAppContext,
 418    ) -> ModelHandle<Self> {
 419        cx.add_model(|cx: &mut ModelContext<Self>| {
 420            let (remote_id_tx, remote_id_rx) = watch::channel();
 421            let _maintain_remote_id = cx.spawn_weak({
 422                let mut status_rx = client.clone().status();
 423                move |this, mut cx| async move {
 424                    while let Some(status) = status_rx.recv().await {
 425                        let this = this.upgrade(&cx)?;
 426                        if status.is_connected() {
 427                            this.update(&mut cx, |this, cx| this.register(cx))
 428                                .await
 429                                .log_err()?;
 430                        } else {
 431                            this.update(&mut cx, |this, cx| this.unregister(cx))
 432                                .await
 433                                .log_err();
 434                        }
 435                    }
 436                    None
 437                }
 438            });
 439
 440            let (online_tx, online_rx) = watch::channel_with(online);
 441            let _maintain_online_status = cx.spawn_weak({
 442                let mut online_rx = online_rx.clone();
 443                move |this, mut cx| async move {
 444                    while let Some(online) = online_rx.recv().await {
 445                        let this = this.upgrade(&cx)?;
 446                        this.update(&mut cx, |this, cx| {
 447                            if !online {
 448                                this.unshared(cx);
 449                            }
 450                            this.metadata_changed(false, cx)
 451                        });
 452                    }
 453                    None
 454                }
 455            });
 456
 457            let handle = cx.weak_handle();
 458            project_store.update(cx, |store, cx| store.add_project(handle, cx));
 459
 460            Self {
 461                worktrees: Default::default(),
 462                collaborators: Default::default(),
 463                opened_buffers: Default::default(),
 464                shared_buffers: Default::default(),
 465                incomplete_buffers: Default::default(),
 466                loading_buffers: Default::default(),
 467                loading_local_worktrees: Default::default(),
 468                buffer_snapshots: Default::default(),
 469                client_state: ProjectClientState::Local {
 470                    is_shared: false,
 471                    remote_id_tx,
 472                    remote_id_rx,
 473                    online_tx,
 474                    online_rx,
 475                    _maintain_remote_id,
 476                    _maintain_online_status,
 477                },
 478                opened_buffer: watch::channel(),
 479                client_subscriptions: Vec::new(),
 480                _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
 481                _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 482                active_entry: None,
 483                languages,
 484                client,
 485                user_store,
 486                project_store,
 487                fs,
 488                next_entry_id: Default::default(),
 489                next_diagnostic_group_id: Default::default(),
 490                language_servers: Default::default(),
 491                language_server_ids: Default::default(),
 492                language_server_statuses: Default::default(),
 493                last_workspace_edits_by_language_server: Default::default(),
 494                language_server_settings: Default::default(),
 495                next_language_server_id: 0,
 496                nonce: StdRng::from_entropy().gen(),
 497                initialized_persistent_state: false,
 498            }
 499        })
 500    }
 501
 502    pub async fn remote(
 503        remote_id: u64,
 504        client: Arc<Client>,
 505        user_store: ModelHandle<UserStore>,
 506        project_store: ModelHandle<ProjectStore>,
 507        languages: Arc<LanguageRegistry>,
 508        fs: Arc<dyn Fs>,
 509        mut cx: AsyncAppContext,
 510    ) -> Result<ModelHandle<Self>, JoinProjectError> {
 511        client.authenticate_and_connect(true, &cx).await?;
 512
 513        let response = client
 514            .request(proto::JoinProject {
 515                project_id: remote_id,
 516            })
 517            .await?;
 518
 519        let response = match response.variant.ok_or_else(|| anyhow!("missing variant"))? {
 520            proto::join_project_response::Variant::Accept(response) => response,
 521            proto::join_project_response::Variant::Decline(decline) => {
 522                match proto::join_project_response::decline::Reason::from_i32(decline.reason) {
 523                    Some(proto::join_project_response::decline::Reason::Declined) => {
 524                        Err(JoinProjectError::HostDeclined)?
 525                    }
 526                    Some(proto::join_project_response::decline::Reason::Closed) => {
 527                        Err(JoinProjectError::HostClosedProject)?
 528                    }
 529                    Some(proto::join_project_response::decline::Reason::WentOffline) => {
 530                        Err(JoinProjectError::HostWentOffline)?
 531                    }
 532                    None => Err(anyhow!("missing decline reason"))?,
 533                }
 534            }
 535        };
 536
 537        let replica_id = response.replica_id as ReplicaId;
 538
 539        let mut worktrees = Vec::new();
 540        for worktree in response.worktrees {
 541            let worktree = cx
 542                .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
 543            worktrees.push(worktree);
 544        }
 545
 546        let this = cx.add_model(|cx: &mut ModelContext<Self>| {
 547            let handle = cx.weak_handle();
 548            project_store.update(cx, |store, cx| store.add_project(handle, cx));
 549
 550            let mut this = Self {
 551                worktrees: Vec::new(),
 552                loading_buffers: Default::default(),
 553                opened_buffer: watch::channel(),
 554                shared_buffers: Default::default(),
 555                incomplete_buffers: Default::default(),
 556                loading_local_worktrees: Default::default(),
 557                active_entry: None,
 558                collaborators: Default::default(),
 559                _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 560                languages,
 561                user_store: user_store.clone(),
 562                project_store,
 563                fs,
 564                next_entry_id: Default::default(),
 565                next_diagnostic_group_id: Default::default(),
 566                client_subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
 567                _subscriptions: Default::default(),
 568                client: client.clone(),
 569                client_state: ProjectClientState::Remote {
 570                    sharing_has_stopped: false,
 571                    remote_id,
 572                    replica_id,
 573                    _detect_unshare: cx.spawn_weak(move |this, mut cx| {
 574                        async move {
 575                            let mut status = client.status();
 576                            let is_connected =
 577                                status.next().await.map_or(false, |s| s.is_connected());
 578                            // Even if we're initially connected, any future change of the status means we momentarily disconnected.
 579                            if !is_connected || status.next().await.is_some() {
 580                                if let Some(this) = this.upgrade(&cx) {
 581                                    this.update(&mut cx, |this, cx| this.disconnected_from_host(cx))
 582                                }
 583                            }
 584                            Ok(())
 585                        }
 586                        .log_err()
 587                    }),
 588                },
 589                language_servers: Default::default(),
 590                language_server_ids: Default::default(),
 591                language_server_settings: Default::default(),
 592                language_server_statuses: response
 593                    .language_servers
 594                    .into_iter()
 595                    .map(|server| {
 596                        (
 597                            server.id as usize,
 598                            LanguageServerStatus {
 599                                name: server.name,
 600                                pending_work: Default::default(),
 601                                has_pending_diagnostic_updates: false,
 602                                progress_tokens: Default::default(),
 603                            },
 604                        )
 605                    })
 606                    .collect(),
 607                last_workspace_edits_by_language_server: Default::default(),
 608                next_language_server_id: 0,
 609                opened_buffers: Default::default(),
 610                buffer_snapshots: Default::default(),
 611                nonce: StdRng::from_entropy().gen(),
 612                initialized_persistent_state: false,
 613            };
 614            for worktree in worktrees {
 615                this.add_worktree(&worktree, cx);
 616            }
 617            this
 618        });
 619
 620        let user_ids = response
 621            .collaborators
 622            .iter()
 623            .map(|peer| peer.user_id)
 624            .collect();
 625        user_store
 626            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 627            .await?;
 628        let mut collaborators = HashMap::default();
 629        for message in response.collaborators {
 630            let collaborator = Collaborator::from_proto(message, &user_store, &mut cx).await?;
 631            collaborators.insert(collaborator.peer_id, collaborator);
 632        }
 633
 634        this.update(&mut cx, |this, _| {
 635            this.collaborators = collaborators;
 636        });
 637
 638        Ok(this)
 639    }
 640
 641    #[cfg(any(test, feature = "test-support"))]
 642    pub async fn test(
 643        fs: Arc<dyn Fs>,
 644        root_paths: impl IntoIterator<Item = &Path>,
 645        cx: &mut gpui::TestAppContext,
 646    ) -> ModelHandle<Project> {
 647        if !cx.read(|cx| cx.has_global::<Settings>()) {
 648            cx.update(|cx| cx.set_global(Settings::test(cx)));
 649        }
 650
 651        let languages = Arc::new(LanguageRegistry::test());
 652        let http_client = client::test::FakeHttpClient::with_404_response();
 653        let client = client::Client::new(http_client.clone());
 654        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 655        let project_store = cx.add_model(|_| ProjectStore::new(Db::open_fake()));
 656        let project = cx.update(|cx| {
 657            Project::local(true, client, user_store, project_store, languages, fs, cx)
 658        });
 659        for path in root_paths {
 660            let (tree, _) = project
 661                .update(cx, |project, cx| {
 662                    project.find_or_create_local_worktree(path, true, cx)
 663                })
 664                .await
 665                .unwrap();
 666            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 667                .await;
 668        }
 669        project
 670    }
 671
 672    pub fn restore_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 673        if self.is_remote() {
 674            return Task::ready(Ok(()));
 675        }
 676
 677        let db = self.project_store.read(cx).db.clone();
 678        let keys = self.db_keys_for_online_state(cx);
 679        let online_by_default = cx.global::<Settings>().projects_online_by_default;
 680        let read_online = cx.background().spawn(async move {
 681            let values = db.read(keys)?;
 682            anyhow::Ok(
 683                values
 684                    .into_iter()
 685                    .all(|e| e.map_or(online_by_default, |e| e == [true as u8])),
 686            )
 687        });
 688        cx.spawn(|this, mut cx| async move {
 689            let online = read_online.await.log_err().unwrap_or(false);
 690            this.update(&mut cx, |this, cx| {
 691                this.initialized_persistent_state = true;
 692                if let ProjectClientState::Local { online_tx, .. } = &mut this.client_state {
 693                    let mut online_tx = online_tx.borrow_mut();
 694                    if *online_tx != online {
 695                        *online_tx = online;
 696                        drop(online_tx);
 697                        this.metadata_changed(false, cx);
 698                    }
 699                }
 700            });
 701            Ok(())
 702        })
 703    }
 704
 705    fn persist_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 706        if self.is_remote() || !self.initialized_persistent_state {
 707            return Task::ready(Ok(()));
 708        }
 709
 710        let db = self.project_store.read(cx).db.clone();
 711        let keys = self.db_keys_for_online_state(cx);
 712        let is_online = self.is_online();
 713        cx.background().spawn(async move {
 714            let value = &[is_online as u8];
 715            db.write(keys.into_iter().map(|key| (key, value)))
 716        })
 717    }
 718
 719    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 720        let settings = cx.global::<Settings>();
 721
 722        let mut language_servers_to_start = Vec::new();
 723        for buffer in self.opened_buffers.values() {
 724            if let Some(buffer) = buffer.upgrade(cx) {
 725                let buffer = buffer.read(cx);
 726                if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
 727                {
 728                    if settings.enable_language_server(Some(&language.name())) {
 729                        let worktree = file.worktree.read(cx);
 730                        language_servers_to_start.push((
 731                            worktree.id(),
 732                            worktree.as_local().unwrap().abs_path().clone(),
 733                            language.clone(),
 734                        ));
 735                    }
 736                }
 737            }
 738        }
 739
 740        let mut language_servers_to_stop = Vec::new();
 741        for language in self.languages.to_vec() {
 742            if let Some(lsp_adapter) = language.lsp_adapter() {
 743                if !settings.enable_language_server(Some(&language.name())) {
 744                    let lsp_name = &lsp_adapter.name;
 745                    for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 746                        if lsp_name == started_lsp_name {
 747                            language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 748                        }
 749                    }
 750                }
 751            }
 752        }
 753
 754        // Stop all newly-disabled language servers.
 755        for (worktree_id, adapter_name) in language_servers_to_stop {
 756            self.stop_language_server(worktree_id, adapter_name, cx)
 757                .detach();
 758        }
 759
 760        // Start all the newly-enabled language servers.
 761        for (worktree_id, worktree_path, language) in language_servers_to_start {
 762            self.start_language_server(worktree_id, worktree_path, language, cx);
 763        }
 764
 765        cx.notify();
 766    }
 767
 768    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 769        self.opened_buffers
 770            .get(&remote_id)
 771            .and_then(|buffer| buffer.upgrade(cx))
 772    }
 773
 774    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 775        &self.languages
 776    }
 777
 778    pub fn client(&self) -> Arc<Client> {
 779        self.client.clone()
 780    }
 781
 782    pub fn user_store(&self) -> ModelHandle<UserStore> {
 783        self.user_store.clone()
 784    }
 785
 786    pub fn project_store(&self) -> ModelHandle<ProjectStore> {
 787        self.project_store.clone()
 788    }
 789
 790    #[cfg(any(test, feature = "test-support"))]
 791    pub fn check_invariants(&self, cx: &AppContext) {
 792        if self.is_local() {
 793            let mut worktree_root_paths = HashMap::default();
 794            for worktree in self.worktrees(cx) {
 795                let worktree = worktree.read(cx);
 796                let abs_path = worktree.as_local().unwrap().abs_path().clone();
 797                let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
 798                assert_eq!(
 799                    prev_worktree_id,
 800                    None,
 801                    "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
 802                    abs_path,
 803                    worktree.id(),
 804                    prev_worktree_id
 805                )
 806            }
 807        } else {
 808            let replica_id = self.replica_id();
 809            for buffer in self.opened_buffers.values() {
 810                if let Some(buffer) = buffer.upgrade(cx) {
 811                    let buffer = buffer.read(cx);
 812                    assert_eq!(
 813                        buffer.deferred_ops_len(),
 814                        0,
 815                        "replica {}, buffer {} has deferred operations",
 816                        replica_id,
 817                        buffer.remote_id()
 818                    );
 819                }
 820            }
 821        }
 822    }
 823
 824    #[cfg(any(test, feature = "test-support"))]
 825    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 826        let path = path.into();
 827        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 828            self.opened_buffers.iter().any(|(_, buffer)| {
 829                if let Some(buffer) = buffer.upgrade(cx) {
 830                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 831                        if file.worktree == worktree && file.path() == &path.path {
 832                            return true;
 833                        }
 834                    }
 835                }
 836                false
 837            })
 838        } else {
 839            false
 840        }
 841    }
 842
 843    pub fn fs(&self) -> &Arc<dyn Fs> {
 844        &self.fs
 845    }
 846
 847    pub fn set_online(&mut self, online: bool, _: &mut ModelContext<Self>) {
 848        if let ProjectClientState::Local { online_tx, .. } = &mut self.client_state {
 849            let mut online_tx = online_tx.borrow_mut();
 850            if *online_tx != online {
 851                *online_tx = online;
 852            }
 853        }
 854    }
 855
 856    pub fn is_online(&self) -> bool {
 857        match &self.client_state {
 858            ProjectClientState::Local { online_rx, .. } => *online_rx.borrow(),
 859            ProjectClientState::Remote { .. } => true,
 860        }
 861    }
 862
 863    fn unregister(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 864        self.unshared(cx);
 865        if let ProjectClientState::Local { remote_id_rx, .. } = &mut self.client_state {
 866            if let Some(remote_id) = *remote_id_rx.borrow() {
 867                let request = self.client.request(proto::UnregisterProject {
 868                    project_id: remote_id,
 869                });
 870                return cx.spawn(|this, mut cx| async move {
 871                    let response = request.await;
 872
 873                    // Unregistering the project causes the server to send out a
 874                    // contact update removing this project from the host's list
 875                    // of online projects. Wait until this contact update has been
 876                    // processed before clearing out this project's remote id, so
 877                    // that there is no moment where this project appears in the
 878                    // contact metadata and *also* has no remote id.
 879                    this.update(&mut cx, |this, cx| {
 880                        this.user_store()
 881                            .update(cx, |store, _| store.contact_updates_done())
 882                    })
 883                    .await;
 884
 885                    this.update(&mut cx, |this, cx| {
 886                        if let ProjectClientState::Local { remote_id_tx, .. } =
 887                            &mut this.client_state
 888                        {
 889                            *remote_id_tx.borrow_mut() = None;
 890                        }
 891                        this.client_subscriptions.clear();
 892                        this.metadata_changed(false, cx);
 893                    });
 894                    response.map(drop)
 895                });
 896            }
 897        }
 898        Task::ready(Ok(()))
 899    }
 900
 901    fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 902        if let ProjectClientState::Local {
 903            remote_id_rx,
 904            online_rx,
 905            ..
 906        } = &self.client_state
 907        {
 908            if remote_id_rx.borrow().is_some() {
 909                return Task::ready(Ok(()));
 910            }
 911
 912            let response = self.client.request(proto::RegisterProject {
 913                online: *online_rx.borrow(),
 914            });
 915            cx.spawn(|this, mut cx| async move {
 916                let remote_id = response.await?.project_id;
 917                this.update(&mut cx, |this, cx| {
 918                    if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
 919                        *remote_id_tx.borrow_mut() = Some(remote_id);
 920                    }
 921
 922                    this.metadata_changed(false, cx);
 923                    cx.emit(Event::RemoteIdChanged(Some(remote_id)));
 924                    this.client_subscriptions
 925                        .push(this.client.add_model_for_remote_entity(remote_id, cx));
 926                    Ok(())
 927                })
 928            })
 929        } else {
 930            Task::ready(Err(anyhow!("can't register a remote project")))
 931        }
 932    }
 933
 934    pub fn remote_id(&self) -> Option<u64> {
 935        match &self.client_state {
 936            ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
 937            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 938        }
 939    }
 940
 941    pub fn next_remote_id(&self) -> impl Future<Output = u64> {
 942        let mut id = None;
 943        let mut watch = None;
 944        match &self.client_state {
 945            ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
 946            ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
 947        }
 948
 949        async move {
 950            if let Some(id) = id {
 951                return id;
 952            }
 953            let mut watch = watch.unwrap();
 954            loop {
 955                let id = *watch.borrow();
 956                if let Some(id) = id {
 957                    return id;
 958                }
 959                watch.next().await;
 960            }
 961        }
 962    }
 963
 964    pub fn shared_remote_id(&self) -> Option<u64> {
 965        match &self.client_state {
 966            ProjectClientState::Local {
 967                remote_id_rx,
 968                is_shared,
 969                ..
 970            } => {
 971                if *is_shared {
 972                    *remote_id_rx.borrow()
 973                } else {
 974                    None
 975                }
 976            }
 977            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 978        }
 979    }
 980
 981    pub fn replica_id(&self) -> ReplicaId {
 982        match &self.client_state {
 983            ProjectClientState::Local { .. } => 0,
 984            ProjectClientState::Remote { replica_id, .. } => *replica_id,
 985        }
 986    }
 987
 988    fn metadata_changed(&mut self, persist: bool, cx: &mut ModelContext<Self>) {
 989        if let ProjectClientState::Local {
 990            remote_id_rx,
 991            online_rx,
 992            ..
 993        } = &self.client_state
 994        {
 995            // Broadcast worktrees only if the project is online.
 996            let worktrees = if *online_rx.borrow() {
 997                self.worktrees
 998                    .iter()
 999                    .filter_map(|worktree| {
1000                        worktree
1001                            .upgrade(cx)
1002                            .map(|worktree| worktree.read(cx).as_local().unwrap().metadata_proto())
1003                    })
1004                    .collect()
1005            } else {
1006                Default::default()
1007            };
1008            if let Some(project_id) = *remote_id_rx.borrow() {
1009                let online = *online_rx.borrow();
1010                self.client
1011                    .send(proto::UpdateProject {
1012                        project_id,
1013                        worktrees,
1014                        online,
1015                    })
1016                    .log_err();
1017
1018                if online {
1019                    let worktrees = self.visible_worktrees(cx).collect::<Vec<_>>();
1020                    let scans_complete =
1021                        futures::future::join_all(worktrees.iter().filter_map(|worktree| {
1022                            Some(worktree.read(cx).as_local()?.scan_complete())
1023                        }));
1024
1025                    let worktrees = worktrees.into_iter().map(|handle| handle.downgrade());
1026                    cx.spawn_weak(move |_, cx| async move {
1027                        scans_complete.await;
1028                        cx.read(|cx| {
1029                            for worktree in worktrees {
1030                                if let Some(worktree) = worktree
1031                                    .upgrade(cx)
1032                                    .and_then(|worktree| worktree.read(cx).as_local())
1033                                {
1034                                    worktree.send_extension_counts(project_id);
1035                                }
1036                            }
1037                        })
1038                    })
1039                    .detach();
1040                }
1041            }
1042
1043            self.project_store.update(cx, |_, cx| cx.notify());
1044            if persist {
1045                self.persist_state(cx).detach_and_log_err(cx);
1046            }
1047            cx.notify();
1048        }
1049    }
1050
1051    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
1052        &self.collaborators
1053    }
1054
1055    pub fn worktrees<'a>(
1056        &'a self,
1057        cx: &'a AppContext,
1058    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1059        self.worktrees
1060            .iter()
1061            .filter_map(move |worktree| worktree.upgrade(cx))
1062    }
1063
1064    pub fn visible_worktrees<'a>(
1065        &'a self,
1066        cx: &'a AppContext,
1067    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1068        self.worktrees.iter().filter_map(|worktree| {
1069            worktree.upgrade(cx).and_then(|worktree| {
1070                if worktree.read(cx).is_visible() {
1071                    Some(worktree)
1072                } else {
1073                    None
1074                }
1075            })
1076        })
1077    }
1078
1079    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1080        self.visible_worktrees(cx)
1081            .map(|tree| tree.read(cx).root_name())
1082    }
1083
1084    fn db_keys_for_online_state(&self, cx: &AppContext) -> Vec<String> {
1085        self.worktrees
1086            .iter()
1087            .filter_map(|worktree| {
1088                let worktree = worktree.upgrade(cx)?.read(cx);
1089                if worktree.is_visible() {
1090                    Some(format!(
1091                        "project-path-online:{}",
1092                        worktree.as_local().unwrap().abs_path().to_string_lossy()
1093                    ))
1094                } else {
1095                    None
1096                }
1097            })
1098            .collect::<Vec<_>>()
1099    }
1100
1101    pub fn worktree_for_id(
1102        &self,
1103        id: WorktreeId,
1104        cx: &AppContext,
1105    ) -> Option<ModelHandle<Worktree>> {
1106        self.worktrees(cx)
1107            .find(|worktree| worktree.read(cx).id() == id)
1108    }
1109
1110    pub fn worktree_for_entry(
1111        &self,
1112        entry_id: ProjectEntryId,
1113        cx: &AppContext,
1114    ) -> Option<ModelHandle<Worktree>> {
1115        self.worktrees(cx)
1116            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1117    }
1118
1119    pub fn worktree_id_for_entry(
1120        &self,
1121        entry_id: ProjectEntryId,
1122        cx: &AppContext,
1123    ) -> Option<WorktreeId> {
1124        self.worktree_for_entry(entry_id, cx)
1125            .map(|worktree| worktree.read(cx).id())
1126    }
1127
1128    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1129        paths.iter().all(|path| self.contains_path(path, cx))
1130    }
1131
1132    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1133        for worktree in self.worktrees(cx) {
1134            let worktree = worktree.read(cx).as_local();
1135            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1136                return true;
1137            }
1138        }
1139        false
1140    }
1141
1142    pub fn create_entry(
1143        &mut self,
1144        project_path: impl Into<ProjectPath>,
1145        is_directory: bool,
1146        cx: &mut ModelContext<Self>,
1147    ) -> Option<Task<Result<Entry>>> {
1148        let project_path = project_path.into();
1149        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1150        if self.is_local() {
1151            Some(worktree.update(cx, |worktree, cx| {
1152                worktree
1153                    .as_local_mut()
1154                    .unwrap()
1155                    .create_entry(project_path.path, is_directory, cx)
1156            }))
1157        } else {
1158            let client = self.client.clone();
1159            let project_id = self.remote_id().unwrap();
1160            Some(cx.spawn_weak(|_, mut cx| async move {
1161                let response = client
1162                    .request(proto::CreateProjectEntry {
1163                        worktree_id: project_path.worktree_id.to_proto(),
1164                        project_id,
1165                        path: project_path.path.as_os_str().as_bytes().to_vec(),
1166                        is_directory,
1167                    })
1168                    .await?;
1169                let entry = response
1170                    .entry
1171                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1172                worktree
1173                    .update(&mut cx, |worktree, cx| {
1174                        worktree.as_remote_mut().unwrap().insert_entry(
1175                            entry,
1176                            response.worktree_scan_id as usize,
1177                            cx,
1178                        )
1179                    })
1180                    .await
1181            }))
1182        }
1183    }
1184
1185    pub fn copy_entry(
1186        &mut self,
1187        entry_id: ProjectEntryId,
1188        new_path: impl Into<Arc<Path>>,
1189        cx: &mut ModelContext<Self>,
1190    ) -> Option<Task<Result<Entry>>> {
1191        let worktree = self.worktree_for_entry(entry_id, cx)?;
1192        let new_path = new_path.into();
1193        if self.is_local() {
1194            worktree.update(cx, |worktree, cx| {
1195                worktree
1196                    .as_local_mut()
1197                    .unwrap()
1198                    .copy_entry(entry_id, new_path, cx)
1199            })
1200        } else {
1201            let client = self.client.clone();
1202            let project_id = self.remote_id().unwrap();
1203
1204            Some(cx.spawn_weak(|_, mut cx| async move {
1205                let response = client
1206                    .request(proto::CopyProjectEntry {
1207                        project_id,
1208                        entry_id: entry_id.to_proto(),
1209                        new_path: new_path.as_os_str().as_bytes().to_vec(),
1210                    })
1211                    .await?;
1212                let entry = response
1213                    .entry
1214                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1215                worktree
1216                    .update(&mut cx, |worktree, cx| {
1217                        worktree.as_remote_mut().unwrap().insert_entry(
1218                            entry,
1219                            response.worktree_scan_id as usize,
1220                            cx,
1221                        )
1222                    })
1223                    .await
1224            }))
1225        }
1226    }
1227
1228    pub fn rename_entry(
1229        &mut self,
1230        entry_id: ProjectEntryId,
1231        new_path: impl Into<Arc<Path>>,
1232        cx: &mut ModelContext<Self>,
1233    ) -> Option<Task<Result<Entry>>> {
1234        let worktree = self.worktree_for_entry(entry_id, cx)?;
1235        let new_path = new_path.into();
1236        if self.is_local() {
1237            worktree.update(cx, |worktree, cx| {
1238                worktree
1239                    .as_local_mut()
1240                    .unwrap()
1241                    .rename_entry(entry_id, new_path, cx)
1242            })
1243        } else {
1244            let client = self.client.clone();
1245            let project_id = self.remote_id().unwrap();
1246
1247            Some(cx.spawn_weak(|_, mut cx| async move {
1248                let response = client
1249                    .request(proto::RenameProjectEntry {
1250                        project_id,
1251                        entry_id: entry_id.to_proto(),
1252                        new_path: new_path.as_os_str().as_bytes().to_vec(),
1253                    })
1254                    .await?;
1255                let entry = response
1256                    .entry
1257                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1258                worktree
1259                    .update(&mut cx, |worktree, cx| {
1260                        worktree.as_remote_mut().unwrap().insert_entry(
1261                            entry,
1262                            response.worktree_scan_id as usize,
1263                            cx,
1264                        )
1265                    })
1266                    .await
1267            }))
1268        }
1269    }
1270
1271    pub fn delete_entry(
1272        &mut self,
1273        entry_id: ProjectEntryId,
1274        cx: &mut ModelContext<Self>,
1275    ) -> Option<Task<Result<()>>> {
1276        let worktree = self.worktree_for_entry(entry_id, cx)?;
1277        if self.is_local() {
1278            worktree.update(cx, |worktree, cx| {
1279                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1280            })
1281        } else {
1282            let client = self.client.clone();
1283            let project_id = self.remote_id().unwrap();
1284            Some(cx.spawn_weak(|_, mut cx| async move {
1285                let response = client
1286                    .request(proto::DeleteProjectEntry {
1287                        project_id,
1288                        entry_id: entry_id.to_proto(),
1289                    })
1290                    .await?;
1291                worktree
1292                    .update(&mut cx, move |worktree, cx| {
1293                        worktree.as_remote_mut().unwrap().delete_entry(
1294                            entry_id,
1295                            response.worktree_scan_id as usize,
1296                            cx,
1297                        )
1298                    })
1299                    .await
1300            }))
1301        }
1302    }
1303
1304    fn share(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1305        if !self.is_online() {
1306            return Task::ready(Err(anyhow!("can't share an offline project")));
1307        }
1308
1309        let project_id;
1310        if let ProjectClientState::Local {
1311            remote_id_rx,
1312            is_shared,
1313            ..
1314        } = &mut self.client_state
1315        {
1316            if *is_shared {
1317                return Task::ready(Ok(()));
1318            }
1319            *is_shared = true;
1320            if let Some(id) = *remote_id_rx.borrow() {
1321                project_id = id;
1322            } else {
1323                return Task::ready(Err(anyhow!("project hasn't been registered")));
1324            }
1325        } else {
1326            return Task::ready(Err(anyhow!("can't share a remote project")));
1327        };
1328
1329        for open_buffer in self.opened_buffers.values_mut() {
1330            match open_buffer {
1331                OpenBuffer::Strong(_) => {}
1332                OpenBuffer::Weak(buffer) => {
1333                    if let Some(buffer) = buffer.upgrade(cx) {
1334                        *open_buffer = OpenBuffer::Strong(buffer);
1335                    }
1336                }
1337                OpenBuffer::Operations(_) => unreachable!(),
1338            }
1339        }
1340
1341        for worktree_handle in self.worktrees.iter_mut() {
1342            match worktree_handle {
1343                WorktreeHandle::Strong(_) => {}
1344                WorktreeHandle::Weak(worktree) => {
1345                    if let Some(worktree) = worktree.upgrade(cx) {
1346                        *worktree_handle = WorktreeHandle::Strong(worktree);
1347                    }
1348                }
1349            }
1350        }
1351
1352        let mut tasks = Vec::new();
1353        for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1354            worktree.update(cx, |worktree, cx| {
1355                let worktree = worktree.as_local_mut().unwrap();
1356                tasks.push(worktree.share(project_id, cx));
1357            });
1358        }
1359
1360        for (server_id, status) in &self.language_server_statuses {
1361            self.client
1362                .send(proto::StartLanguageServer {
1363                    project_id,
1364                    server: Some(proto::LanguageServer {
1365                        id: *server_id as u64,
1366                        name: status.name.clone(),
1367                    }),
1368                })
1369                .log_err();
1370        }
1371
1372        cx.spawn(|this, mut cx| async move {
1373            for task in tasks {
1374                task.await?;
1375            }
1376            this.update(&mut cx, |_, cx| cx.notify());
1377            Ok(())
1378        })
1379    }
1380
1381    fn unshared(&mut self, cx: &mut ModelContext<Self>) {
1382        if let ProjectClientState::Local { is_shared, .. } = &mut self.client_state {
1383            if !*is_shared {
1384                return;
1385            }
1386
1387            *is_shared = false;
1388            self.collaborators.clear();
1389            self.shared_buffers.clear();
1390            for worktree_handle in self.worktrees.iter_mut() {
1391                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1392                    let is_visible = worktree.update(cx, |worktree, _| {
1393                        worktree.as_local_mut().unwrap().unshare();
1394                        worktree.is_visible()
1395                    });
1396                    if !is_visible {
1397                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1398                    }
1399                }
1400            }
1401
1402            for open_buffer in self.opened_buffers.values_mut() {
1403                if let OpenBuffer::Strong(buffer) = open_buffer {
1404                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1405                }
1406            }
1407
1408            cx.notify();
1409        } else {
1410            log::error!("attempted to unshare a remote project");
1411        }
1412    }
1413
1414    pub fn respond_to_join_request(
1415        &mut self,
1416        requester_id: u64,
1417        allow: bool,
1418        cx: &mut ModelContext<Self>,
1419    ) {
1420        if let Some(project_id) = self.remote_id() {
1421            let share = if self.is_online() && allow {
1422                Some(self.share(cx))
1423            } else {
1424                None
1425            };
1426            let client = self.client.clone();
1427            cx.foreground()
1428                .spawn(async move {
1429                    client.send(proto::RespondToJoinProjectRequest {
1430                        requester_id,
1431                        project_id,
1432                        allow,
1433                    })?;
1434                    if let Some(share) = share {
1435                        share.await?;
1436                    }
1437                    anyhow::Ok(())
1438                })
1439                .detach_and_log_err(cx);
1440        }
1441    }
1442
1443    fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1444        if let ProjectClientState::Remote {
1445            sharing_has_stopped,
1446            ..
1447        } = &mut self.client_state
1448        {
1449            *sharing_has_stopped = true;
1450            self.collaborators.clear();
1451            for worktree in &self.worktrees {
1452                if let Some(worktree) = worktree.upgrade(cx) {
1453                    worktree.update(cx, |worktree, _| {
1454                        if let Some(worktree) = worktree.as_remote_mut() {
1455                            worktree.disconnected_from_host();
1456                        }
1457                    });
1458                }
1459            }
1460            cx.emit(Event::DisconnectedFromHost);
1461            cx.notify();
1462
1463            // Wake up all futures currently waiting on a buffer to get opened,
1464            // to give them a chance to fail now that we've disconnected.
1465            *self.opened_buffer.0.borrow_mut() = ();
1466        }
1467    }
1468
1469    pub fn is_read_only(&self) -> bool {
1470        match &self.client_state {
1471            ProjectClientState::Local { .. } => false,
1472            ProjectClientState::Remote {
1473                sharing_has_stopped,
1474                ..
1475            } => *sharing_has_stopped,
1476        }
1477    }
1478
1479    pub fn is_local(&self) -> bool {
1480        match &self.client_state {
1481            ProjectClientState::Local { .. } => true,
1482            ProjectClientState::Remote { .. } => false,
1483        }
1484    }
1485
1486    pub fn is_remote(&self) -> bool {
1487        !self.is_local()
1488    }
1489
1490    pub fn create_buffer(
1491        &mut self,
1492        text: &str,
1493        language: Option<Arc<Language>>,
1494        cx: &mut ModelContext<Self>,
1495    ) -> Result<ModelHandle<Buffer>> {
1496        if self.is_remote() {
1497            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1498        }
1499
1500        let buffer = cx.add_model(|cx| {
1501            Buffer::new(self.replica_id(), text, cx)
1502                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1503        });
1504        self.register_buffer(&buffer, cx)?;
1505        Ok(buffer)
1506    }
1507
1508    pub fn open_path(
1509        &mut self,
1510        path: impl Into<ProjectPath>,
1511        cx: &mut ModelContext<Self>,
1512    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1513        let task = self.open_buffer(path, cx);
1514        cx.spawn_weak(|_, cx| async move {
1515            let buffer = task.await?;
1516            let project_entry_id = buffer
1517                .read_with(&cx, |buffer, cx| {
1518                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1519                })
1520                .ok_or_else(|| anyhow!("no project entry"))?;
1521            Ok((project_entry_id, buffer.into()))
1522        })
1523    }
1524
1525    pub fn open_local_buffer(
1526        &mut self,
1527        abs_path: impl AsRef<Path>,
1528        cx: &mut ModelContext<Self>,
1529    ) -> Task<Result<ModelHandle<Buffer>>> {
1530        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1531            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1532        } else {
1533            Task::ready(Err(anyhow!("no such path")))
1534        }
1535    }
1536
1537    pub fn open_buffer(
1538        &mut self,
1539        path: impl Into<ProjectPath>,
1540        cx: &mut ModelContext<Self>,
1541    ) -> Task<Result<ModelHandle<Buffer>>> {
1542        let project_path = path.into();
1543        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1544            worktree
1545        } else {
1546            return Task::ready(Err(anyhow!("no such worktree")));
1547        };
1548
1549        // If there is already a buffer for the given path, then return it.
1550        let existing_buffer = self.get_open_buffer(&project_path, cx);
1551        if let Some(existing_buffer) = existing_buffer {
1552            return Task::ready(Ok(existing_buffer));
1553        }
1554
1555        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1556            // If the given path is already being loaded, then wait for that existing
1557            // task to complete and return the same buffer.
1558            hash_map::Entry::Occupied(e) => e.get().clone(),
1559
1560            // Otherwise, record the fact that this path is now being loaded.
1561            hash_map::Entry::Vacant(entry) => {
1562                let (mut tx, rx) = postage::watch::channel();
1563                entry.insert(rx.clone());
1564
1565                let load_buffer = if worktree.read(cx).is_local() {
1566                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1567                } else {
1568                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1569                };
1570
1571                cx.spawn(move |this, mut cx| async move {
1572                    let load_result = load_buffer.await;
1573                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1574                        // Record the fact that the buffer is no longer loading.
1575                        this.loading_buffers.remove(&project_path);
1576                        let buffer = load_result.map_err(Arc::new)?;
1577                        Ok(buffer)
1578                    }));
1579                })
1580                .detach();
1581                rx
1582            }
1583        };
1584
1585        cx.foreground().spawn(async move {
1586            loop {
1587                if let Some(result) = loading_watch.borrow().as_ref() {
1588                    match result {
1589                        Ok(buffer) => return Ok(buffer.clone()),
1590                        Err(error) => return Err(anyhow!("{}", error)),
1591                    }
1592                }
1593                loading_watch.next().await;
1594            }
1595        })
1596    }
1597
1598    fn open_local_buffer_internal(
1599        &mut self,
1600        path: &Arc<Path>,
1601        worktree: &ModelHandle<Worktree>,
1602        cx: &mut ModelContext<Self>,
1603    ) -> Task<Result<ModelHandle<Buffer>>> {
1604        let load_buffer = worktree.update(cx, |worktree, cx| {
1605            let worktree = worktree.as_local_mut().unwrap();
1606            worktree.load_buffer(path, cx)
1607        });
1608        cx.spawn(|this, mut cx| async move {
1609            let buffer = load_buffer.await?;
1610            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1611            Ok(buffer)
1612        })
1613    }
1614
1615    fn open_remote_buffer_internal(
1616        &mut self,
1617        path: &Arc<Path>,
1618        worktree: &ModelHandle<Worktree>,
1619        cx: &mut ModelContext<Self>,
1620    ) -> Task<Result<ModelHandle<Buffer>>> {
1621        let rpc = self.client.clone();
1622        let project_id = self.remote_id().unwrap();
1623        let remote_worktree_id = worktree.read(cx).id();
1624        let path = path.clone();
1625        let path_string = path.to_string_lossy().to_string();
1626        cx.spawn(|this, mut cx| async move {
1627            let response = rpc
1628                .request(proto::OpenBufferByPath {
1629                    project_id,
1630                    worktree_id: remote_worktree_id.to_proto(),
1631                    path: path_string,
1632                })
1633                .await?;
1634            this.update(&mut cx, |this, cx| {
1635                this.wait_for_buffer(response.buffer_id, cx)
1636            })
1637            .await
1638        })
1639    }
1640
1641    /// LanguageServerName is owned, because it is inserted into a map
1642    fn open_local_buffer_via_lsp(
1643        &mut self,
1644        abs_path: lsp::Url,
1645        language_server_id: usize,
1646        language_server_name: LanguageServerName,
1647        cx: &mut ModelContext<Self>,
1648    ) -> Task<Result<ModelHandle<Buffer>>> {
1649        cx.spawn(|this, mut cx| async move {
1650            let abs_path = abs_path
1651                .to_file_path()
1652                .map_err(|_| anyhow!("can't convert URI to path"))?;
1653            let (worktree, relative_path) = if let Some(result) =
1654                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1655            {
1656                result
1657            } else {
1658                let worktree = this
1659                    .update(&mut cx, |this, cx| {
1660                        this.create_local_worktree(&abs_path, false, cx)
1661                    })
1662                    .await?;
1663                this.update(&mut cx, |this, cx| {
1664                    this.language_server_ids.insert(
1665                        (worktree.read(cx).id(), language_server_name),
1666                        language_server_id,
1667                    );
1668                });
1669                (worktree, PathBuf::new())
1670            };
1671
1672            let project_path = ProjectPath {
1673                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1674                path: relative_path.into(),
1675            };
1676            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1677                .await
1678        })
1679    }
1680
1681    pub fn open_buffer_by_id(
1682        &mut self,
1683        id: u64,
1684        cx: &mut ModelContext<Self>,
1685    ) -> Task<Result<ModelHandle<Buffer>>> {
1686        if let Some(buffer) = self.buffer_for_id(id, cx) {
1687            Task::ready(Ok(buffer))
1688        } else if self.is_local() {
1689            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1690        } else if let Some(project_id) = self.remote_id() {
1691            let request = self
1692                .client
1693                .request(proto::OpenBufferById { project_id, id });
1694            cx.spawn(|this, mut cx| async move {
1695                let buffer_id = request.await?.buffer_id;
1696                this.update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
1697                    .await
1698            })
1699        } else {
1700            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1701        }
1702    }
1703
1704    pub fn save_buffer_as(
1705        &mut self,
1706        buffer: ModelHandle<Buffer>,
1707        abs_path: PathBuf,
1708        cx: &mut ModelContext<Project>,
1709    ) -> Task<Result<()>> {
1710        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1711        let old_path =
1712            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1713        cx.spawn(|this, mut cx| async move {
1714            if let Some(old_path) = old_path {
1715                this.update(&mut cx, |this, cx| {
1716                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1717                });
1718            }
1719            let (worktree, path) = worktree_task.await?;
1720            worktree
1721                .update(&mut cx, |worktree, cx| {
1722                    worktree
1723                        .as_local_mut()
1724                        .unwrap()
1725                        .save_buffer_as(buffer.clone(), path, cx)
1726                })
1727                .await?;
1728            this.update(&mut cx, |this, cx| {
1729                this.assign_language_to_buffer(&buffer, cx);
1730                this.register_buffer_with_language_server(&buffer, cx);
1731            });
1732            Ok(())
1733        })
1734    }
1735
1736    pub fn get_open_buffer(
1737        &mut self,
1738        path: &ProjectPath,
1739        cx: &mut ModelContext<Self>,
1740    ) -> Option<ModelHandle<Buffer>> {
1741        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1742        self.opened_buffers.values().find_map(|buffer| {
1743            let buffer = buffer.upgrade(cx)?;
1744            let file = File::from_dyn(buffer.read(cx).file())?;
1745            if file.worktree == worktree && file.path() == &path.path {
1746                Some(buffer)
1747            } else {
1748                None
1749            }
1750        })
1751    }
1752
1753    fn register_buffer(
1754        &mut self,
1755        buffer: &ModelHandle<Buffer>,
1756        cx: &mut ModelContext<Self>,
1757    ) -> Result<()> {
1758        let remote_id = buffer.read(cx).remote_id();
1759        let open_buffer = if self.is_remote() || self.is_shared() {
1760            OpenBuffer::Strong(buffer.clone())
1761        } else {
1762            OpenBuffer::Weak(buffer.downgrade())
1763        };
1764
1765        match self.opened_buffers.insert(remote_id, open_buffer) {
1766            None => {}
1767            Some(OpenBuffer::Operations(operations)) => {
1768                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1769            }
1770            Some(OpenBuffer::Weak(existing_handle)) => {
1771                if existing_handle.upgrade(cx).is_some() {
1772                    Err(anyhow!(
1773                        "already registered buffer with remote id {}",
1774                        remote_id
1775                    ))?
1776                }
1777            }
1778            Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1779                "already registered buffer with remote id {}",
1780                remote_id
1781            ))?,
1782        }
1783        cx.subscribe(buffer, |this, buffer, event, cx| {
1784            this.on_buffer_event(buffer, event, cx);
1785        })
1786        .detach();
1787
1788        self.assign_language_to_buffer(buffer, cx);
1789        self.register_buffer_with_language_server(buffer, cx);
1790        cx.observe_release(buffer, |this, buffer, cx| {
1791            if let Some(file) = File::from_dyn(buffer.file()) {
1792                if file.is_local() {
1793                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1794                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1795                        server
1796                            .notify::<lsp::notification::DidCloseTextDocument>(
1797                                lsp::DidCloseTextDocumentParams {
1798                                    text_document: lsp::TextDocumentIdentifier::new(uri),
1799                                },
1800                            )
1801                            .log_err();
1802                    }
1803                }
1804            }
1805        })
1806        .detach();
1807
1808        *self.opened_buffer.0.borrow_mut() = ();
1809        Ok(())
1810    }
1811
1812    fn register_buffer_with_language_server(
1813        &mut self,
1814        buffer_handle: &ModelHandle<Buffer>,
1815        cx: &mut ModelContext<Self>,
1816    ) {
1817        let buffer = buffer_handle.read(cx);
1818        let buffer_id = buffer.remote_id();
1819        if let Some(file) = File::from_dyn(buffer.file()) {
1820            if file.is_local() {
1821                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1822                let initial_snapshot = buffer.text_snapshot();
1823
1824                let mut language_server = None;
1825                let mut language_id = None;
1826                if let Some(language) = buffer.language() {
1827                    let worktree_id = file.worktree_id(cx);
1828                    if let Some(adapter) = language.lsp_adapter() {
1829                        language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1830                        language_server = self
1831                            .language_server_ids
1832                            .get(&(worktree_id, adapter.name.clone()))
1833                            .and_then(|id| self.language_servers.get(id))
1834                            .and_then(|server_state| {
1835                                if let LanguageServerState::Running { server, .. } = server_state {
1836                                    Some(server.clone())
1837                                } else {
1838                                    None
1839                                }
1840                            });
1841                    }
1842                }
1843
1844                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1845                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1846                        self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1847                            .log_err();
1848                    }
1849                }
1850
1851                if let Some(server) = language_server {
1852                    server
1853                        .notify::<lsp::notification::DidOpenTextDocument>(
1854                            lsp::DidOpenTextDocumentParams {
1855                                text_document: lsp::TextDocumentItem::new(
1856                                    uri,
1857                                    language_id.unwrap_or_default(),
1858                                    0,
1859                                    initial_snapshot.text(),
1860                                ),
1861                            },
1862                        )
1863                        .log_err();
1864                    buffer_handle.update(cx, |buffer, cx| {
1865                        buffer.set_completion_triggers(
1866                            server
1867                                .capabilities()
1868                                .completion_provider
1869                                .as_ref()
1870                                .and_then(|provider| provider.trigger_characters.clone())
1871                                .unwrap_or_default(),
1872                            cx,
1873                        )
1874                    });
1875                    self.buffer_snapshots
1876                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1877                }
1878            }
1879        }
1880    }
1881
1882    fn unregister_buffer_from_language_server(
1883        &mut self,
1884        buffer: &ModelHandle<Buffer>,
1885        old_path: PathBuf,
1886        cx: &mut ModelContext<Self>,
1887    ) {
1888        buffer.update(cx, |buffer, cx| {
1889            buffer.update_diagnostics(Default::default(), cx);
1890            self.buffer_snapshots.remove(&buffer.remote_id());
1891            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1892                language_server
1893                    .notify::<lsp::notification::DidCloseTextDocument>(
1894                        lsp::DidCloseTextDocumentParams {
1895                            text_document: lsp::TextDocumentIdentifier::new(
1896                                lsp::Url::from_file_path(old_path).unwrap(),
1897                            ),
1898                        },
1899                    )
1900                    .log_err();
1901            }
1902        });
1903    }
1904
1905    fn on_buffer_event(
1906        &mut self,
1907        buffer: ModelHandle<Buffer>,
1908        event: &BufferEvent,
1909        cx: &mut ModelContext<Self>,
1910    ) -> Option<()> {
1911        match event {
1912            BufferEvent::Operation(operation) => {
1913                if let Some(project_id) = self.shared_remote_id() {
1914                    let request = self.client.request(proto::UpdateBuffer {
1915                        project_id,
1916                        buffer_id: buffer.read(cx).remote_id(),
1917                        operations: vec![language::proto::serialize_operation(operation)],
1918                    });
1919                    cx.background().spawn(request).detach_and_log_err(cx);
1920                } else if let Some(project_id) = self.remote_id() {
1921                    let _ = self
1922                        .client
1923                        .send(proto::RegisterProjectActivity { project_id });
1924                }
1925            }
1926            BufferEvent::Edited { .. } => {
1927                let language_server = self
1928                    .language_server_for_buffer(buffer.read(cx), cx)
1929                    .map(|(_, server)| server.clone())?;
1930                let buffer = buffer.read(cx);
1931                let file = File::from_dyn(buffer.file())?;
1932                let abs_path = file.as_local()?.abs_path(cx);
1933                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1934                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1935                let (version, prev_snapshot) = buffer_snapshots.last()?;
1936                let next_snapshot = buffer.text_snapshot();
1937                let next_version = version + 1;
1938
1939                let content_changes = buffer
1940                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1941                    .map(|edit| {
1942                        let edit_start = edit.new.start.0;
1943                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1944                        let new_text = next_snapshot
1945                            .text_for_range(edit.new.start.1..edit.new.end.1)
1946                            .collect();
1947                        lsp::TextDocumentContentChangeEvent {
1948                            range: Some(lsp::Range::new(
1949                                point_to_lsp(edit_start),
1950                                point_to_lsp(edit_end),
1951                            )),
1952                            range_length: None,
1953                            text: new_text,
1954                        }
1955                    })
1956                    .collect();
1957
1958                buffer_snapshots.push((next_version, next_snapshot));
1959
1960                language_server
1961                    .notify::<lsp::notification::DidChangeTextDocument>(
1962                        lsp::DidChangeTextDocumentParams {
1963                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1964                                uri,
1965                                next_version,
1966                            ),
1967                            content_changes,
1968                        },
1969                    )
1970                    .log_err();
1971            }
1972            BufferEvent::Saved => {
1973                let file = File::from_dyn(buffer.read(cx).file())?;
1974                let worktree_id = file.worktree_id(cx);
1975                let abs_path = file.as_local()?.abs_path(cx);
1976                let text_document = lsp::TextDocumentIdentifier {
1977                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1978                };
1979
1980                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1981                    server
1982                        .notify::<lsp::notification::DidSaveTextDocument>(
1983                            lsp::DidSaveTextDocumentParams {
1984                                text_document: text_document.clone(),
1985                                text: None,
1986                            },
1987                        )
1988                        .log_err();
1989                }
1990
1991                // After saving a buffer, simulate disk-based diagnostics being finished for languages
1992                // that don't support a disk-based progress token.
1993                let (lsp_adapter, language_server) =
1994                    self.language_server_for_buffer(buffer.read(cx), cx)?;
1995                if lsp_adapter.disk_based_diagnostics_progress_token.is_none() {
1996                    let server_id = language_server.server_id();
1997                    self.disk_based_diagnostics_finished(server_id, cx);
1998                    self.broadcast_language_server_update(
1999                        server_id,
2000                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2001                            proto::LspDiskBasedDiagnosticsUpdated {},
2002                        ),
2003                    );
2004                }
2005            }
2006            _ => {}
2007        }
2008
2009        None
2010    }
2011
2012    fn language_servers_for_worktree(
2013        &self,
2014        worktree_id: WorktreeId,
2015    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2016        self.language_server_ids
2017            .iter()
2018            .filter_map(move |((language_server_worktree_id, _), id)| {
2019                if *language_server_worktree_id == worktree_id {
2020                    if let Some(LanguageServerState::Running {
2021                        adapter,
2022                        language,
2023                        server,
2024                    }) = self.language_servers.get(id)
2025                    {
2026                        return Some((adapter, language, server));
2027                    }
2028                }
2029                None
2030            })
2031    }
2032
2033    fn maintain_buffer_languages(
2034        languages: &LanguageRegistry,
2035        cx: &mut ModelContext<Project>,
2036    ) -> Task<()> {
2037        let mut subscription = languages.subscribe();
2038        cx.spawn_weak(|project, mut cx| async move {
2039            while let Some(()) = subscription.next().await {
2040                if let Some(project) = project.upgrade(&cx) {
2041                    project.update(&mut cx, |project, cx| {
2042                        let mut buffers_without_language = Vec::new();
2043                        for buffer in project.opened_buffers.values() {
2044                            if let Some(buffer) = buffer.upgrade(cx) {
2045                                if buffer.read(cx).language().is_none() {
2046                                    buffers_without_language.push(buffer);
2047                                }
2048                            }
2049                        }
2050
2051                        for buffer in buffers_without_language {
2052                            project.assign_language_to_buffer(&buffer, cx);
2053                            project.register_buffer_with_language_server(&buffer, cx);
2054                        }
2055                    });
2056                }
2057            }
2058        })
2059    }
2060
2061    fn assign_language_to_buffer(
2062        &mut self,
2063        buffer: &ModelHandle<Buffer>,
2064        cx: &mut ModelContext<Self>,
2065    ) -> Option<()> {
2066        // If the buffer has a language, set it and start the language server if we haven't already.
2067        let full_path = buffer.read(cx).file()?.full_path(cx);
2068        let language = self.languages.select_language(&full_path)?;
2069        buffer.update(cx, |buffer, cx| {
2070            buffer.set_language(Some(language.clone()), cx);
2071        });
2072
2073        let file = File::from_dyn(buffer.read(cx).file())?;
2074        let worktree = file.worktree.read(cx).as_local()?;
2075        let worktree_id = worktree.id();
2076        let worktree_abs_path = worktree.abs_path().clone();
2077        self.start_language_server(worktree_id, worktree_abs_path, language, cx);
2078
2079        None
2080    }
2081
2082    fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
2083        use serde_json::Value;
2084
2085        match (source, target) {
2086            (Value::Object(source), Value::Object(target)) => {
2087                for (key, value) in source {
2088                    if let Some(target) = target.get_mut(&key) {
2089                        Self::merge_json_value_into(value, target);
2090                    } else {
2091                        target.insert(key.clone(), value);
2092                    }
2093                }
2094            }
2095
2096            (source, target) => *target = source,
2097        }
2098    }
2099
2100    fn start_language_server(
2101        &mut self,
2102        worktree_id: WorktreeId,
2103        worktree_path: Arc<Path>,
2104        language: Arc<Language>,
2105        cx: &mut ModelContext<Self>,
2106    ) {
2107        if !cx
2108            .global::<Settings>()
2109            .enable_language_server(Some(&language.name()))
2110        {
2111            return;
2112        }
2113
2114        let adapter = if let Some(adapter) = language.lsp_adapter() {
2115            adapter
2116        } else {
2117            return;
2118        };
2119        let key = (worktree_id, adapter.name.clone());
2120
2121        let mut initialization_options = adapter.initialization_options.clone();
2122
2123        let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
2124        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2125        match (&mut initialization_options, override_options) {
2126            (Some(initialization_options), Some(override_options)) => {
2127                Self::merge_json_value_into(override_options, initialization_options);
2128            }
2129
2130            (None, override_options) => initialization_options = override_options,
2131
2132            _ => {}
2133        }
2134
2135        self.language_server_ids
2136            .entry(key.clone())
2137            .or_insert_with(|| {
2138                let server_id = post_inc(&mut self.next_language_server_id);
2139                let language_server = self.languages.start_language_server(
2140                    server_id,
2141                    language.clone(),
2142                    worktree_path,
2143                    self.client.http_client(),
2144                    cx,
2145                );
2146                self.language_servers.insert(
2147                    server_id,
2148                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2149                        let language_server = language_server?.await.log_err()?;
2150                        let language_server = language_server
2151                            .initialize(initialization_options)
2152                            .await
2153                            .log_err()?;
2154                        let this = this.upgrade(&cx)?;
2155
2156                        language_server
2157                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
2158                                let this = this.downgrade();
2159                                let adapter = adapter.clone();
2160                                move |mut params, cx| {
2161                                    let this = this;
2162                                    let adapter = adapter.clone();
2163                                    cx.spawn(|mut cx| async move {
2164                                        adapter.process_diagnostics(&mut params).await;
2165                                        if let Some(this) = this.upgrade(&cx) {
2166                                            this.update(&mut cx, |this, cx| {
2167                                                this.update_diagnostics(
2168                                                    server_id,
2169                                                    params,
2170                                                    &adapter.disk_based_diagnostic_sources,
2171                                                    cx,
2172                                                )
2173                                                .log_err();
2174                                            });
2175                                        }
2176                                    })
2177                                    .detach();
2178                                }
2179                            })
2180                            .detach();
2181
2182                        language_server
2183                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2184                                let settings = this.read_with(&cx, |this, _| {
2185                                    this.language_server_settings.clone()
2186                                });
2187                                move |params, _| {
2188                                    let settings = settings.lock().clone();
2189                                    async move {
2190                                        Ok(params
2191                                            .items
2192                                            .into_iter()
2193                                            .map(|item| {
2194                                                if let Some(section) = &item.section {
2195                                                    settings
2196                                                        .get(section)
2197                                                        .cloned()
2198                                                        .unwrap_or(serde_json::Value::Null)
2199                                                } else {
2200                                                    settings.clone()
2201                                                }
2202                                            })
2203                                            .collect())
2204                                    }
2205                                }
2206                            })
2207                            .detach();
2208
2209                        // Even though we don't have handling for these requests, respond to them to
2210                        // avoid stalling any language server like `gopls` which waits for a response
2211                        // to these requests when initializing.
2212                        language_server
2213                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2214                                let this = this.downgrade();
2215                                move |params, mut cx| async move {
2216                                    if let Some(this) = this.upgrade(&cx) {
2217                                        this.update(&mut cx, |this, _| {
2218                                            if let Some(status) =
2219                                                this.language_server_statuses.get_mut(&server_id)
2220                                            {
2221                                                if let lsp::NumberOrString::String(token) =
2222                                                    params.token
2223                                                {
2224                                                    status.progress_tokens.insert(token);
2225                                                }
2226                                            }
2227                                        });
2228                                    }
2229                                    Ok(())
2230                                }
2231                            })
2232                            .detach();
2233                        language_server
2234                            .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2235                                Ok(())
2236                            })
2237                            .detach();
2238
2239                        language_server
2240                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2241                                let this = this.downgrade();
2242                                let adapter = adapter.clone();
2243                                let language_server = language_server.clone();
2244                                move |params, cx| {
2245                                    Self::on_lsp_workspace_edit(
2246                                        this,
2247                                        params,
2248                                        server_id,
2249                                        adapter.clone(),
2250                                        language_server.clone(),
2251                                        cx,
2252                                    )
2253                                }
2254                            })
2255                            .detach();
2256
2257                        let disk_based_diagnostics_progress_token =
2258                            adapter.disk_based_diagnostics_progress_token.clone();
2259
2260                        language_server
2261                            .on_notification::<lsp::notification::Progress, _>({
2262                                let this = this.downgrade();
2263                                move |params, mut cx| {
2264                                    if let Some(this) = this.upgrade(&cx) {
2265                                        this.update(&mut cx, |this, cx| {
2266                                            this.on_lsp_progress(
2267                                                params,
2268                                                server_id,
2269                                                disk_based_diagnostics_progress_token.clone(),
2270                                                cx,
2271                                            );
2272                                        });
2273                                    }
2274                                }
2275                            })
2276                            .detach();
2277
2278                        this.update(&mut cx, |this, cx| {
2279                            // If the language server for this key doesn't match the server id, don't store the
2280                            // server. Which will cause it to be dropped, killing the process
2281                            if this
2282                                .language_server_ids
2283                                .get(&key)
2284                                .map(|id| id != &server_id)
2285                                .unwrap_or(false)
2286                            {
2287                                return None;
2288                            }
2289
2290                            // Update language_servers collection with Running variant of LanguageServerState
2291                            // indicating that the server is up and running and ready
2292                            this.language_servers.insert(
2293                                server_id,
2294                                LanguageServerState::Running {
2295                                    adapter: adapter.clone(),
2296                                    language,
2297                                    server: language_server.clone(),
2298                                },
2299                            );
2300                            this.language_server_statuses.insert(
2301                                server_id,
2302                                LanguageServerStatus {
2303                                    name: language_server.name().to_string(),
2304                                    pending_work: Default::default(),
2305                                    has_pending_diagnostic_updates: false,
2306                                    progress_tokens: Default::default(),
2307                                },
2308                            );
2309                            language_server
2310                                .notify::<lsp::notification::DidChangeConfiguration>(
2311                                    lsp::DidChangeConfigurationParams {
2312                                        settings: this.language_server_settings.lock().clone(),
2313                                    },
2314                                )
2315                                .ok();
2316
2317                            if let Some(project_id) = this.shared_remote_id() {
2318                                this.client
2319                                    .send(proto::StartLanguageServer {
2320                                        project_id,
2321                                        server: Some(proto::LanguageServer {
2322                                            id: server_id as u64,
2323                                            name: language_server.name().to_string(),
2324                                        }),
2325                                    })
2326                                    .log_err();
2327                            }
2328
2329                            // Tell the language server about every open buffer in the worktree that matches the language.
2330                            for buffer in this.opened_buffers.values() {
2331                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2332                                    let buffer = buffer_handle.read(cx);
2333                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2334                                        file
2335                                    } else {
2336                                        continue;
2337                                    };
2338                                    let language = if let Some(language) = buffer.language() {
2339                                        language
2340                                    } else {
2341                                        continue;
2342                                    };
2343                                    if file.worktree.read(cx).id() != key.0
2344                                        || language.lsp_adapter().map(|a| a.name.clone())
2345                                            != Some(key.1.clone())
2346                                    {
2347                                        continue;
2348                                    }
2349
2350                                    let file = file.as_local()?;
2351                                    let versions = this
2352                                        .buffer_snapshots
2353                                        .entry(buffer.remote_id())
2354                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2355                                    let (version, initial_snapshot) = versions.last().unwrap();
2356                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2357                                    language_server
2358                                        .notify::<lsp::notification::DidOpenTextDocument>(
2359                                            lsp::DidOpenTextDocumentParams {
2360                                                text_document: lsp::TextDocumentItem::new(
2361                                                    uri,
2362                                                    adapter
2363                                                        .language_ids
2364                                                        .get(language.name().as_ref())
2365                                                        .cloned()
2366                                                        .unwrap_or_default(),
2367                                                    *version,
2368                                                    initial_snapshot.text(),
2369                                                ),
2370                                            },
2371                                        )
2372                                        .log_err()?;
2373                                    buffer_handle.update(cx, |buffer, cx| {
2374                                        buffer.set_completion_triggers(
2375                                            language_server
2376                                                .capabilities()
2377                                                .completion_provider
2378                                                .as_ref()
2379                                                .and_then(|provider| {
2380                                                    provider.trigger_characters.clone()
2381                                                })
2382                                                .unwrap_or_default(),
2383                                            cx,
2384                                        )
2385                                    });
2386                                }
2387                            }
2388
2389                            cx.notify();
2390                            Some(language_server)
2391                        })
2392                    })),
2393                );
2394
2395                server_id
2396            });
2397    }
2398
2399    // Returns a list of all of the worktrees which no longer have a language server and the root path
2400    // for the stopped server
2401    fn stop_language_server(
2402        &mut self,
2403        worktree_id: WorktreeId,
2404        adapter_name: LanguageServerName,
2405        cx: &mut ModelContext<Self>,
2406    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2407        let key = (worktree_id, adapter_name);
2408        if let Some(server_id) = self.language_server_ids.remove(&key) {
2409            // Remove other entries for this language server as well
2410            let mut orphaned_worktrees = vec![worktree_id];
2411            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2412            for other_key in other_keys {
2413                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2414                    self.language_server_ids.remove(&other_key);
2415                    orphaned_worktrees.push(other_key.0);
2416                }
2417            }
2418
2419            self.language_server_statuses.remove(&server_id);
2420            cx.notify();
2421
2422            let server_state = self.language_servers.remove(&server_id);
2423            cx.spawn_weak(|this, mut cx| async move {
2424                let mut root_path = None;
2425
2426                let server = match server_state {
2427                    Some(LanguageServerState::Starting(started_language_server)) => {
2428                        started_language_server.await
2429                    }
2430                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2431                    None => None,
2432                };
2433
2434                if let Some(server) = server {
2435                    root_path = Some(server.root_path().clone());
2436                    if let Some(shutdown) = server.shutdown() {
2437                        shutdown.await;
2438                    }
2439                }
2440
2441                if let Some(this) = this.upgrade(&cx) {
2442                    this.update(&mut cx, |this, cx| {
2443                        this.language_server_statuses.remove(&server_id);
2444                        cx.notify();
2445                    });
2446                }
2447
2448                (root_path, orphaned_worktrees)
2449            })
2450        } else {
2451            Task::ready((None, Vec::new()))
2452        }
2453    }
2454
2455    pub fn restart_language_servers_for_buffers(
2456        &mut self,
2457        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2458        cx: &mut ModelContext<Self>,
2459    ) -> Option<()> {
2460        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2461            .into_iter()
2462            .filter_map(|buffer| {
2463                let file = File::from_dyn(buffer.read(cx).file())?;
2464                let worktree = file.worktree.read(cx).as_local()?;
2465                let worktree_id = worktree.id();
2466                let worktree_abs_path = worktree.abs_path().clone();
2467                let full_path = file.full_path(cx);
2468                Some((worktree_id, worktree_abs_path, full_path))
2469            })
2470            .collect();
2471        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2472            let language = self.languages.select_language(&full_path)?;
2473            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2474        }
2475
2476        None
2477    }
2478
2479    fn restart_language_server(
2480        &mut self,
2481        worktree_id: WorktreeId,
2482        fallback_path: Arc<Path>,
2483        language: Arc<Language>,
2484        cx: &mut ModelContext<Self>,
2485    ) {
2486        let adapter = if let Some(adapter) = language.lsp_adapter() {
2487            adapter
2488        } else {
2489            return;
2490        };
2491
2492        let server_name = adapter.name.clone();
2493        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2494        cx.spawn_weak(|this, mut cx| async move {
2495            let (original_root_path, orphaned_worktrees) = stop.await;
2496            if let Some(this) = this.upgrade(&cx) {
2497                this.update(&mut cx, |this, cx| {
2498                    // Attempt to restart using original server path. Fallback to passed in
2499                    // path if we could not retrieve the root path
2500                    let root_path = original_root_path
2501                        .map(|path_buf| Arc::from(path_buf.as_path()))
2502                        .unwrap_or(fallback_path);
2503
2504                    this.start_language_server(worktree_id, root_path, language, cx);
2505
2506                    // Lookup new server id and set it for each of the orphaned worktrees
2507                    if let Some(new_server_id) = this
2508                        .language_server_ids
2509                        .get(&(worktree_id, server_name.clone()))
2510                        .cloned()
2511                    {
2512                        for orphaned_worktree in orphaned_worktrees {
2513                            this.language_server_ids
2514                                .insert((orphaned_worktree, server_name.clone()), new_server_id);
2515                        }
2516                    }
2517                });
2518            }
2519        })
2520        .detach();
2521    }
2522
2523    fn on_lsp_progress(
2524        &mut self,
2525        progress: lsp::ProgressParams,
2526        server_id: usize,
2527        disk_based_diagnostics_progress_token: Option<String>,
2528        cx: &mut ModelContext<Self>,
2529    ) {
2530        let token = match progress.token {
2531            lsp::NumberOrString::String(token) => token,
2532            lsp::NumberOrString::Number(token) => {
2533                log::info!("skipping numeric progress token {}", token);
2534                return;
2535            }
2536        };
2537        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2538        let language_server_status =
2539            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2540                status
2541            } else {
2542                return;
2543            };
2544
2545        if !language_server_status.progress_tokens.contains(&token) {
2546            return;
2547        }
2548
2549        let is_disk_based_diagnostics_progress =
2550            Some(token.as_ref()) == disk_based_diagnostics_progress_token.as_deref();
2551
2552        match progress {
2553            lsp::WorkDoneProgress::Begin(report) => {
2554                if is_disk_based_diagnostics_progress {
2555                    language_server_status.has_pending_diagnostic_updates = true;
2556                    self.disk_based_diagnostics_started(server_id, cx);
2557                    self.broadcast_language_server_update(
2558                        server_id,
2559                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2560                            proto::LspDiskBasedDiagnosticsUpdating {},
2561                        ),
2562                    );
2563                } else {
2564                    self.on_lsp_work_start(
2565                        server_id,
2566                        token.clone(),
2567                        LanguageServerProgress {
2568                            message: report.message.clone(),
2569                            percentage: report.percentage.map(|p| p as usize),
2570                            last_update_at: Instant::now(),
2571                        },
2572                        cx,
2573                    );
2574                    self.broadcast_language_server_update(
2575                        server_id,
2576                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2577                            token,
2578                            message: report.message,
2579                            percentage: report.percentage.map(|p| p as u32),
2580                        }),
2581                    );
2582                }
2583            }
2584            lsp::WorkDoneProgress::Report(report) => {
2585                if !is_disk_based_diagnostics_progress {
2586                    self.on_lsp_work_progress(
2587                        server_id,
2588                        token.clone(),
2589                        LanguageServerProgress {
2590                            message: report.message.clone(),
2591                            percentage: report.percentage.map(|p| p as usize),
2592                            last_update_at: Instant::now(),
2593                        },
2594                        cx,
2595                    );
2596                    self.broadcast_language_server_update(
2597                        server_id,
2598                        proto::update_language_server::Variant::WorkProgress(
2599                            proto::LspWorkProgress {
2600                                token,
2601                                message: report.message,
2602                                percentage: report.percentage.map(|p| p as u32),
2603                            },
2604                        ),
2605                    );
2606                }
2607            }
2608            lsp::WorkDoneProgress::End(_) => {
2609                language_server_status.progress_tokens.remove(&token);
2610
2611                if is_disk_based_diagnostics_progress {
2612                    language_server_status.has_pending_diagnostic_updates = false;
2613                    self.disk_based_diagnostics_finished(server_id, cx);
2614                    self.broadcast_language_server_update(
2615                        server_id,
2616                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2617                            proto::LspDiskBasedDiagnosticsUpdated {},
2618                        ),
2619                    );
2620                } else {
2621                    self.on_lsp_work_end(server_id, token.clone(), cx);
2622                    self.broadcast_language_server_update(
2623                        server_id,
2624                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2625                            token,
2626                        }),
2627                    );
2628                }
2629            }
2630        }
2631    }
2632
2633    fn on_lsp_work_start(
2634        &mut self,
2635        language_server_id: usize,
2636        token: String,
2637        progress: LanguageServerProgress,
2638        cx: &mut ModelContext<Self>,
2639    ) {
2640        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2641            status.pending_work.insert(token, progress);
2642            cx.notify();
2643        }
2644    }
2645
2646    fn on_lsp_work_progress(
2647        &mut self,
2648        language_server_id: usize,
2649        token: String,
2650        progress: LanguageServerProgress,
2651        cx: &mut ModelContext<Self>,
2652    ) {
2653        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2654            let entry = status
2655                .pending_work
2656                .entry(token)
2657                .or_insert(LanguageServerProgress {
2658                    message: Default::default(),
2659                    percentage: Default::default(),
2660                    last_update_at: progress.last_update_at,
2661                });
2662            if progress.message.is_some() {
2663                entry.message = progress.message;
2664            }
2665            if progress.percentage.is_some() {
2666                entry.percentage = progress.percentage;
2667            }
2668            entry.last_update_at = progress.last_update_at;
2669            cx.notify();
2670        }
2671    }
2672
2673    fn on_lsp_work_end(
2674        &mut self,
2675        language_server_id: usize,
2676        token: String,
2677        cx: &mut ModelContext<Self>,
2678    ) {
2679        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2680            status.pending_work.remove(&token);
2681            cx.notify();
2682        }
2683    }
2684
2685    async fn on_lsp_workspace_edit(
2686        this: WeakModelHandle<Self>,
2687        params: lsp::ApplyWorkspaceEditParams,
2688        server_id: usize,
2689        adapter: Arc<CachedLspAdapter>,
2690        language_server: Arc<LanguageServer>,
2691        mut cx: AsyncAppContext,
2692    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2693        let this = this
2694            .upgrade(&cx)
2695            .ok_or_else(|| anyhow!("project project closed"))?;
2696        let transaction = Self::deserialize_workspace_edit(
2697            this.clone(),
2698            params.edit,
2699            true,
2700            adapter.clone(),
2701            language_server.clone(),
2702            &mut cx,
2703        )
2704        .await
2705        .log_err();
2706        this.update(&mut cx, |this, _| {
2707            if let Some(transaction) = transaction {
2708                this.last_workspace_edits_by_language_server
2709                    .insert(server_id, transaction);
2710            }
2711        });
2712        Ok(lsp::ApplyWorkspaceEditResponse {
2713            applied: true,
2714            failed_change: None,
2715            failure_reason: None,
2716        })
2717    }
2718
2719    fn broadcast_language_server_update(
2720        &self,
2721        language_server_id: usize,
2722        event: proto::update_language_server::Variant,
2723    ) {
2724        if let Some(project_id) = self.shared_remote_id() {
2725            self.client
2726                .send(proto::UpdateLanguageServer {
2727                    project_id,
2728                    language_server_id: language_server_id as u64,
2729                    variant: Some(event),
2730                })
2731                .log_err();
2732        }
2733    }
2734
2735    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2736        for server_state in self.language_servers.values() {
2737            if let LanguageServerState::Running { server, .. } = server_state {
2738                server
2739                    .notify::<lsp::notification::DidChangeConfiguration>(
2740                        lsp::DidChangeConfigurationParams {
2741                            settings: settings.clone(),
2742                        },
2743                    )
2744                    .ok();
2745            }
2746        }
2747        *self.language_server_settings.lock() = settings;
2748    }
2749
2750    pub fn language_server_statuses(
2751        &self,
2752    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2753        self.language_server_statuses.values()
2754    }
2755
2756    pub fn update_diagnostics(
2757        &mut self,
2758        language_server_id: usize,
2759        params: lsp::PublishDiagnosticsParams,
2760        disk_based_sources: &[String],
2761        cx: &mut ModelContext<Self>,
2762    ) -> Result<()> {
2763        let abs_path = params
2764            .uri
2765            .to_file_path()
2766            .map_err(|_| anyhow!("URI is not a file"))?;
2767        let mut diagnostics = Vec::default();
2768        let mut primary_diagnostic_group_ids = HashMap::default();
2769        let mut sources_by_group_id = HashMap::default();
2770        let mut supporting_diagnostics = HashMap::default();
2771        for diagnostic in &params.diagnostics {
2772            let source = diagnostic.source.as_ref();
2773            let code = diagnostic.code.as_ref().map(|code| match code {
2774                lsp::NumberOrString::Number(code) => code.to_string(),
2775                lsp::NumberOrString::String(code) => code.clone(),
2776            });
2777            let range = range_from_lsp(diagnostic.range);
2778            let is_supporting = diagnostic
2779                .related_information
2780                .as_ref()
2781                .map_or(false, |infos| {
2782                    infos.iter().any(|info| {
2783                        primary_diagnostic_group_ids.contains_key(&(
2784                            source,
2785                            code.clone(),
2786                            range_from_lsp(info.location.range),
2787                        ))
2788                    })
2789                });
2790
2791            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2792                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2793            });
2794
2795            if is_supporting {
2796                supporting_diagnostics.insert(
2797                    (source, code.clone(), range),
2798                    (diagnostic.severity, is_unnecessary),
2799                );
2800            } else {
2801                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2802                let is_disk_based =
2803                    source.map_or(false, |source| disk_based_sources.contains(source));
2804
2805                sources_by_group_id.insert(group_id, source);
2806                primary_diagnostic_group_ids
2807                    .insert((source, code.clone(), range.clone()), group_id);
2808
2809                diagnostics.push(DiagnosticEntry {
2810                    range,
2811                    diagnostic: Diagnostic {
2812                        code: code.clone(),
2813                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2814                        message: diagnostic.message.clone(),
2815                        group_id,
2816                        is_primary: true,
2817                        is_valid: true,
2818                        is_disk_based,
2819                        is_unnecessary,
2820                    },
2821                });
2822                if let Some(infos) = &diagnostic.related_information {
2823                    for info in infos {
2824                        if info.location.uri == params.uri && !info.message.is_empty() {
2825                            let range = range_from_lsp(info.location.range);
2826                            diagnostics.push(DiagnosticEntry {
2827                                range,
2828                                diagnostic: Diagnostic {
2829                                    code: code.clone(),
2830                                    severity: DiagnosticSeverity::INFORMATION,
2831                                    message: info.message.clone(),
2832                                    group_id,
2833                                    is_primary: false,
2834                                    is_valid: true,
2835                                    is_disk_based,
2836                                    is_unnecessary: false,
2837                                },
2838                            });
2839                        }
2840                    }
2841                }
2842            }
2843        }
2844
2845        for entry in &mut diagnostics {
2846            let diagnostic = &mut entry.diagnostic;
2847            if !diagnostic.is_primary {
2848                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2849                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2850                    source,
2851                    diagnostic.code.clone(),
2852                    entry.range.clone(),
2853                )) {
2854                    if let Some(severity) = severity {
2855                        diagnostic.severity = severity;
2856                    }
2857                    diagnostic.is_unnecessary = is_unnecessary;
2858                }
2859            }
2860        }
2861
2862        self.update_diagnostic_entries(
2863            language_server_id,
2864            abs_path,
2865            params.version,
2866            diagnostics,
2867            cx,
2868        )?;
2869        Ok(())
2870    }
2871
2872    pub fn update_diagnostic_entries(
2873        &mut self,
2874        language_server_id: usize,
2875        abs_path: PathBuf,
2876        version: Option<i32>,
2877        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2878        cx: &mut ModelContext<Project>,
2879    ) -> Result<(), anyhow::Error> {
2880        let (worktree, relative_path) = self
2881            .find_local_worktree(&abs_path, cx)
2882            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2883
2884        let project_path = ProjectPath {
2885            worktree_id: worktree.read(cx).id(),
2886            path: relative_path.into(),
2887        };
2888        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2889            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2890        }
2891
2892        let updated = worktree.update(cx, |worktree, cx| {
2893            worktree
2894                .as_local_mut()
2895                .ok_or_else(|| anyhow!("not a local worktree"))?
2896                .update_diagnostics(
2897                    language_server_id,
2898                    project_path.path.clone(),
2899                    diagnostics,
2900                    cx,
2901                )
2902        })?;
2903        if updated {
2904            cx.emit(Event::DiagnosticsUpdated {
2905                language_server_id,
2906                path: project_path,
2907            });
2908        }
2909        Ok(())
2910    }
2911
2912    fn update_buffer_diagnostics(
2913        &mut self,
2914        buffer: &ModelHandle<Buffer>,
2915        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2916        version: Option<i32>,
2917        cx: &mut ModelContext<Self>,
2918    ) -> Result<()> {
2919        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2920            Ordering::Equal
2921                .then_with(|| b.is_primary.cmp(&a.is_primary))
2922                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2923                .then_with(|| a.severity.cmp(&b.severity))
2924                .then_with(|| a.message.cmp(&b.message))
2925        }
2926
2927        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2928
2929        diagnostics.sort_unstable_by(|a, b| {
2930            Ordering::Equal
2931                .then_with(|| a.range.start.cmp(&b.range.start))
2932                .then_with(|| b.range.end.cmp(&a.range.end))
2933                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2934        });
2935
2936        let mut sanitized_diagnostics = Vec::new();
2937        let edits_since_save = Patch::new(
2938            snapshot
2939                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2940                .collect(),
2941        );
2942        for entry in diagnostics {
2943            let start;
2944            let end;
2945            if entry.diagnostic.is_disk_based {
2946                // Some diagnostics are based on files on disk instead of buffers'
2947                // current contents. Adjust these diagnostics' ranges to reflect
2948                // any unsaved edits.
2949                start = edits_since_save.old_to_new(entry.range.start);
2950                end = edits_since_save.old_to_new(entry.range.end);
2951            } else {
2952                start = entry.range.start;
2953                end = entry.range.end;
2954            }
2955
2956            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2957                ..snapshot.clip_point_utf16(end, Bias::Right);
2958
2959            // Expand empty ranges by one character
2960            if range.start == range.end {
2961                range.end.column += 1;
2962                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2963                if range.start == range.end && range.end.column > 0 {
2964                    range.start.column -= 1;
2965                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2966                }
2967            }
2968
2969            sanitized_diagnostics.push(DiagnosticEntry {
2970                range,
2971                diagnostic: entry.diagnostic,
2972            });
2973        }
2974        drop(edits_since_save);
2975
2976        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2977        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2978        Ok(())
2979    }
2980
2981    pub fn reload_buffers(
2982        &self,
2983        buffers: HashSet<ModelHandle<Buffer>>,
2984        push_to_history: bool,
2985        cx: &mut ModelContext<Self>,
2986    ) -> Task<Result<ProjectTransaction>> {
2987        let mut local_buffers = Vec::new();
2988        let mut remote_buffers = None;
2989        for buffer_handle in buffers {
2990            let buffer = buffer_handle.read(cx);
2991            if buffer.is_dirty() {
2992                if let Some(file) = File::from_dyn(buffer.file()) {
2993                    if file.is_local() {
2994                        local_buffers.push(buffer_handle);
2995                    } else {
2996                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2997                    }
2998                }
2999            }
3000        }
3001
3002        let remote_buffers = self.remote_id().zip(remote_buffers);
3003        let client = self.client.clone();
3004
3005        cx.spawn(|this, mut cx| async move {
3006            let mut project_transaction = ProjectTransaction::default();
3007
3008            if let Some((project_id, remote_buffers)) = remote_buffers {
3009                let response = client
3010                    .request(proto::ReloadBuffers {
3011                        project_id,
3012                        buffer_ids: remote_buffers
3013                            .iter()
3014                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3015                            .collect(),
3016                    })
3017                    .await?
3018                    .transaction
3019                    .ok_or_else(|| anyhow!("missing transaction"))?;
3020                project_transaction = this
3021                    .update(&mut cx, |this, cx| {
3022                        this.deserialize_project_transaction(response, push_to_history, cx)
3023                    })
3024                    .await?;
3025            }
3026
3027            for buffer in local_buffers {
3028                let transaction = buffer
3029                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
3030                    .await?;
3031                buffer.update(&mut cx, |buffer, cx| {
3032                    if let Some(transaction) = transaction {
3033                        if !push_to_history {
3034                            buffer.forget_transaction(transaction.id);
3035                        }
3036                        project_transaction.0.insert(cx.handle(), transaction);
3037                    }
3038                });
3039            }
3040
3041            Ok(project_transaction)
3042        })
3043    }
3044
3045    pub fn format(
3046        &self,
3047        buffers: HashSet<ModelHandle<Buffer>>,
3048        push_to_history: bool,
3049        cx: &mut ModelContext<Project>,
3050    ) -> Task<Result<ProjectTransaction>> {
3051        let mut local_buffers = Vec::new();
3052        let mut remote_buffers = None;
3053        for buffer_handle in buffers {
3054            let buffer = buffer_handle.read(cx);
3055            if let Some(file) = File::from_dyn(buffer.file()) {
3056                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
3057                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
3058                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
3059                    }
3060                } else {
3061                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3062                }
3063            } else {
3064                return Task::ready(Ok(Default::default()));
3065            }
3066        }
3067
3068        let remote_buffers = self.remote_id().zip(remote_buffers);
3069        let client = self.client.clone();
3070
3071        cx.spawn(|this, mut cx| async move {
3072            let mut project_transaction = ProjectTransaction::default();
3073
3074            if let Some((project_id, remote_buffers)) = remote_buffers {
3075                let response = client
3076                    .request(proto::FormatBuffers {
3077                        project_id,
3078                        buffer_ids: remote_buffers
3079                            .iter()
3080                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3081                            .collect(),
3082                    })
3083                    .await?
3084                    .transaction
3085                    .ok_or_else(|| anyhow!("missing transaction"))?;
3086                project_transaction = this
3087                    .update(&mut cx, |this, cx| {
3088                        this.deserialize_project_transaction(response, push_to_history, cx)
3089                    })
3090                    .await?;
3091            }
3092
3093            for (buffer, buffer_abs_path, language_server) in local_buffers {
3094                let (format_on_save, tab_size) = buffer.read_with(&cx, |buffer, cx| {
3095                    let settings = cx.global::<Settings>();
3096                    let language_name = buffer.language().map(|language| language.name());
3097                    (
3098                        settings.format_on_save(language_name.as_deref()),
3099                        settings.tab_size(language_name.as_deref()),
3100                    )
3101                });
3102
3103                let transaction = match format_on_save {
3104                    settings::FormatOnSave::Off => continue,
3105                    settings::FormatOnSave::LanguageServer => Self::format_via_lsp(
3106                        &this,
3107                        &buffer,
3108                        &buffer_abs_path,
3109                        &language_server,
3110                        tab_size,
3111                        &mut cx,
3112                    )
3113                    .await
3114                    .context("failed to format via language server")?,
3115                    settings::FormatOnSave::External { command, arguments } => {
3116                        Self::format_via_external_command(
3117                            &buffer,
3118                            &buffer_abs_path,
3119                            &command,
3120                            &arguments,
3121                            &mut cx,
3122                        )
3123                        .await
3124                        .context(format!(
3125                            "failed to format via external command {:?}",
3126                            command
3127                        ))?
3128                    }
3129                };
3130
3131                if let Some(transaction) = transaction {
3132                    if !push_to_history {
3133                        buffer.update(&mut cx, |buffer, _| {
3134                            buffer.forget_transaction(transaction.id)
3135                        });
3136                    }
3137                    project_transaction.0.insert(buffer, transaction);
3138                }
3139            }
3140
3141            Ok(project_transaction)
3142        })
3143    }
3144
3145    async fn format_via_lsp(
3146        this: &ModelHandle<Self>,
3147        buffer: &ModelHandle<Buffer>,
3148        abs_path: &Path,
3149        language_server: &Arc<LanguageServer>,
3150        tab_size: NonZeroU32,
3151        cx: &mut AsyncAppContext,
3152    ) -> Result<Option<Transaction>> {
3153        let text_document =
3154            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3155        let capabilities = &language_server.capabilities();
3156        let lsp_edits = if capabilities
3157            .document_formatting_provider
3158            .as_ref()
3159            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3160        {
3161            language_server
3162                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3163                    text_document,
3164                    options: lsp::FormattingOptions {
3165                        tab_size: tab_size.into(),
3166                        insert_spaces: true,
3167                        insert_final_newline: Some(true),
3168                        ..Default::default()
3169                    },
3170                    work_done_progress_params: Default::default(),
3171                })
3172                .await?
3173        } else if capabilities
3174            .document_range_formatting_provider
3175            .as_ref()
3176            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3177        {
3178            let buffer_start = lsp::Position::new(0, 0);
3179            let buffer_end =
3180                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3181            language_server
3182                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3183                    text_document,
3184                    range: lsp::Range::new(buffer_start, buffer_end),
3185                    options: lsp::FormattingOptions {
3186                        tab_size: tab_size.into(),
3187                        insert_spaces: true,
3188                        insert_final_newline: Some(true),
3189                        ..Default::default()
3190                    },
3191                    work_done_progress_params: Default::default(),
3192                })
3193                .await?
3194        } else {
3195            None
3196        };
3197
3198        if let Some(lsp_edits) = lsp_edits {
3199            let edits = this
3200                .update(cx, |this, cx| {
3201                    this.edits_from_lsp(buffer, lsp_edits, None, cx)
3202                })
3203                .await?;
3204            buffer.update(cx, |buffer, cx| {
3205                buffer.finalize_last_transaction();
3206                buffer.start_transaction();
3207                for (range, text) in edits {
3208                    buffer.edit([(range, text)], None, cx);
3209                }
3210                if buffer.end_transaction(cx).is_some() {
3211                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
3212                    Ok(Some(transaction))
3213                } else {
3214                    Ok(None)
3215                }
3216            })
3217        } else {
3218            Ok(None)
3219        }
3220    }
3221
3222    async fn format_via_external_command(
3223        buffer: &ModelHandle<Buffer>,
3224        buffer_abs_path: &Path,
3225        command: &str,
3226        arguments: &[String],
3227        cx: &mut AsyncAppContext,
3228    ) -> Result<Option<Transaction>> {
3229        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3230            let file = File::from_dyn(buffer.file())?;
3231            let worktree = file.worktree.read(cx).as_local()?;
3232            let mut worktree_path = worktree.abs_path().to_path_buf();
3233            if worktree.root_entry()?.is_file() {
3234                worktree_path.pop();
3235            }
3236            Some(worktree_path)
3237        });
3238
3239        if let Some(working_dir_path) = working_dir_path {
3240            let mut child =
3241                smol::process::Command::new(command)
3242                    .args(arguments.iter().map(|arg| {
3243                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3244                    }))
3245                    .current_dir(&working_dir_path)
3246                    .stdin(smol::process::Stdio::piped())
3247                    .stdout(smol::process::Stdio::piped())
3248                    .stderr(smol::process::Stdio::piped())
3249                    .spawn()?;
3250            let stdin = child
3251                .stdin
3252                .as_mut()
3253                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3254            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3255            for chunk in text.chunks() {
3256                stdin.write_all(chunk.as_bytes()).await?;
3257            }
3258            stdin.flush().await?;
3259
3260            let output = child.output().await?;
3261            if !output.status.success() {
3262                return Err(anyhow!(
3263                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3264                    output.status.code(),
3265                    String::from_utf8_lossy(&output.stdout),
3266                    String::from_utf8_lossy(&output.stderr),
3267                ));
3268            }
3269
3270            let stdout = String::from_utf8(output.stdout)?;
3271            let diff = buffer
3272                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3273                .await;
3274            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3275        } else {
3276            Ok(None)
3277        }
3278    }
3279
3280    pub fn definition<T: ToPointUtf16>(
3281        &self,
3282        buffer: &ModelHandle<Buffer>,
3283        position: T,
3284        cx: &mut ModelContext<Self>,
3285    ) -> Task<Result<Vec<LocationLink>>> {
3286        let position = position.to_point_utf16(buffer.read(cx));
3287        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3288    }
3289
3290    pub fn type_definition<T: ToPointUtf16>(
3291        &self,
3292        buffer: &ModelHandle<Buffer>,
3293        position: T,
3294        cx: &mut ModelContext<Self>,
3295    ) -> Task<Result<Vec<LocationLink>>> {
3296        let position = position.to_point_utf16(buffer.read(cx));
3297        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3298    }
3299
3300    pub fn references<T: ToPointUtf16>(
3301        &self,
3302        buffer: &ModelHandle<Buffer>,
3303        position: T,
3304        cx: &mut ModelContext<Self>,
3305    ) -> Task<Result<Vec<Location>>> {
3306        let position = position.to_point_utf16(buffer.read(cx));
3307        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3308    }
3309
3310    pub fn document_highlights<T: ToPointUtf16>(
3311        &self,
3312        buffer: &ModelHandle<Buffer>,
3313        position: T,
3314        cx: &mut ModelContext<Self>,
3315    ) -> Task<Result<Vec<DocumentHighlight>>> {
3316        let position = position.to_point_utf16(buffer.read(cx));
3317        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3318    }
3319
3320    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3321        if self.is_local() {
3322            let mut requests = Vec::new();
3323            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3324                let worktree_id = *worktree_id;
3325                if let Some(worktree) = self
3326                    .worktree_for_id(worktree_id, cx)
3327                    .and_then(|worktree| worktree.read(cx).as_local())
3328                {
3329                    if let Some(LanguageServerState::Running {
3330                        adapter,
3331                        language,
3332                        server,
3333                    }) = self.language_servers.get(server_id)
3334                    {
3335                        let adapter = adapter.clone();
3336                        let language = language.clone();
3337                        let worktree_abs_path = worktree.abs_path().clone();
3338                        requests.push(
3339                            server
3340                                .request::<lsp::request::WorkspaceSymbol>(
3341                                    lsp::WorkspaceSymbolParams {
3342                                        query: query.to_string(),
3343                                        ..Default::default()
3344                                    },
3345                                )
3346                                .log_err()
3347                                .map(move |response| {
3348                                    (
3349                                        adapter,
3350                                        language,
3351                                        worktree_id,
3352                                        worktree_abs_path,
3353                                        response.unwrap_or_default(),
3354                                    )
3355                                }),
3356                        );
3357                    }
3358                }
3359            }
3360
3361            cx.spawn_weak(|this, cx| async move {
3362                let responses = futures::future::join_all(requests).await;
3363                let this = if let Some(this) = this.upgrade(&cx) {
3364                    this
3365                } else {
3366                    return Ok(Default::default());
3367                };
3368                let symbols = this.read_with(&cx, |this, cx| {
3369                    let mut symbols = Vec::new();
3370                    for (
3371                        adapter,
3372                        adapter_language,
3373                        source_worktree_id,
3374                        worktree_abs_path,
3375                        response,
3376                    ) in responses
3377                    {
3378                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3379                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3380                            let mut worktree_id = source_worktree_id;
3381                            let path;
3382                            if let Some((worktree, rel_path)) =
3383                                this.find_local_worktree(&abs_path, cx)
3384                            {
3385                                worktree_id = worktree.read(cx).id();
3386                                path = rel_path;
3387                            } else {
3388                                path = relativize_path(&worktree_abs_path, &abs_path);
3389                            }
3390
3391                            let project_path = ProjectPath {
3392                                worktree_id,
3393                                path: path.into(),
3394                            };
3395                            let signature = this.symbol_signature(&project_path);
3396                            let language = this
3397                                .languages
3398                                .select_language(&project_path.path)
3399                                .unwrap_or(adapter_language.clone());
3400                            let language_server_name = adapter.name.clone();
3401                            Some(async move {
3402                                let label = language
3403                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3404                                    .await;
3405
3406                                Symbol {
3407                                    language_server_name,
3408                                    source_worktree_id,
3409                                    path: project_path,
3410                                    label: label.unwrap_or_else(|| {
3411                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3412                                    }),
3413                                    kind: lsp_symbol.kind,
3414                                    name: lsp_symbol.name,
3415                                    range: range_from_lsp(lsp_symbol.location.range),
3416                                    signature,
3417                                }
3418                            })
3419                        }));
3420                    }
3421                    symbols
3422                });
3423                Ok(futures::future::join_all(symbols).await)
3424            })
3425        } else if let Some(project_id) = self.remote_id() {
3426            let request = self.client.request(proto::GetProjectSymbols {
3427                project_id,
3428                query: query.to_string(),
3429            });
3430            cx.spawn_weak(|this, cx| async move {
3431                let response = request.await?;
3432                let mut symbols = Vec::new();
3433                if let Some(this) = this.upgrade(&cx) {
3434                    let new_symbols = this.read_with(&cx, |this, _| {
3435                        response
3436                            .symbols
3437                            .into_iter()
3438                            .map(|symbol| this.deserialize_symbol(symbol))
3439                            .collect::<Vec<_>>()
3440                    });
3441                    symbols = futures::future::join_all(new_symbols)
3442                        .await
3443                        .into_iter()
3444                        .filter_map(|symbol| symbol.log_err())
3445                        .collect::<Vec<_>>();
3446                }
3447                Ok(symbols)
3448            })
3449        } else {
3450            Task::ready(Ok(Default::default()))
3451        }
3452    }
3453
3454    pub fn open_buffer_for_symbol(
3455        &mut self,
3456        symbol: &Symbol,
3457        cx: &mut ModelContext<Self>,
3458    ) -> Task<Result<ModelHandle<Buffer>>> {
3459        if self.is_local() {
3460            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3461                symbol.source_worktree_id,
3462                symbol.language_server_name.clone(),
3463            )) {
3464                *id
3465            } else {
3466                return Task::ready(Err(anyhow!(
3467                    "language server for worktree and language not found"
3468                )));
3469            };
3470
3471            let worktree_abs_path = if let Some(worktree_abs_path) = self
3472                .worktree_for_id(symbol.path.worktree_id, cx)
3473                .and_then(|worktree| worktree.read(cx).as_local())
3474                .map(|local_worktree| local_worktree.abs_path())
3475            {
3476                worktree_abs_path
3477            } else {
3478                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3479            };
3480            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3481            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3482                uri
3483            } else {
3484                return Task::ready(Err(anyhow!("invalid symbol path")));
3485            };
3486
3487            self.open_local_buffer_via_lsp(
3488                symbol_uri,
3489                language_server_id,
3490                symbol.language_server_name.clone(),
3491                cx,
3492            )
3493        } else if let Some(project_id) = self.remote_id() {
3494            let request = self.client.request(proto::OpenBufferForSymbol {
3495                project_id,
3496                symbol: Some(serialize_symbol(symbol)),
3497            });
3498            cx.spawn(|this, mut cx| async move {
3499                let response = request.await?;
3500                this.update(&mut cx, |this, cx| {
3501                    this.wait_for_buffer(response.buffer_id, cx)
3502                })
3503                .await
3504            })
3505        } else {
3506            Task::ready(Err(anyhow!("project does not have a remote id")))
3507        }
3508    }
3509
3510    pub fn hover<T: ToPointUtf16>(
3511        &self,
3512        buffer: &ModelHandle<Buffer>,
3513        position: T,
3514        cx: &mut ModelContext<Self>,
3515    ) -> Task<Result<Option<Hover>>> {
3516        let position = position.to_point_utf16(buffer.read(cx));
3517        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3518    }
3519
3520    pub fn completions<T: ToPointUtf16>(
3521        &self,
3522        source_buffer_handle: &ModelHandle<Buffer>,
3523        position: T,
3524        cx: &mut ModelContext<Self>,
3525    ) -> Task<Result<Vec<Completion>>> {
3526        let source_buffer_handle = source_buffer_handle.clone();
3527        let source_buffer = source_buffer_handle.read(cx);
3528        let buffer_id = source_buffer.remote_id();
3529        let language = source_buffer.language().cloned();
3530        let worktree;
3531        let buffer_abs_path;
3532        if let Some(file) = File::from_dyn(source_buffer.file()) {
3533            worktree = file.worktree.clone();
3534            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3535        } else {
3536            return Task::ready(Ok(Default::default()));
3537        };
3538
3539        let position = position.to_point_utf16(source_buffer);
3540        let anchor = source_buffer.anchor_after(position);
3541
3542        if worktree.read(cx).as_local().is_some() {
3543            let buffer_abs_path = buffer_abs_path.unwrap();
3544            let lang_server =
3545                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3546                    server.clone()
3547                } else {
3548                    return Task::ready(Ok(Default::default()));
3549                };
3550
3551            cx.spawn(|_, cx| async move {
3552                let completions = lang_server
3553                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3554                        text_document_position: lsp::TextDocumentPositionParams::new(
3555                            lsp::TextDocumentIdentifier::new(
3556                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3557                            ),
3558                            point_to_lsp(position),
3559                        ),
3560                        context: Default::default(),
3561                        work_done_progress_params: Default::default(),
3562                        partial_result_params: Default::default(),
3563                    })
3564                    .await
3565                    .context("lsp completion request failed")?;
3566
3567                let completions = if let Some(completions) = completions {
3568                    match completions {
3569                        lsp::CompletionResponse::Array(completions) => completions,
3570                        lsp::CompletionResponse::List(list) => list.items,
3571                    }
3572                } else {
3573                    Default::default()
3574                };
3575
3576                let completions = source_buffer_handle.read_with(&cx, |this, _| {
3577                    let snapshot = this.snapshot();
3578                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3579                    let mut range_for_token = None;
3580                    completions.into_iter().filter_map(move |lsp_completion| {
3581                        // For now, we can only handle additional edits if they are returned
3582                        // when resolving the completion, not if they are present initially.
3583                        if lsp_completion
3584                            .additional_text_edits
3585                            .as_ref()
3586                            .map_or(false, |edits| !edits.is_empty())
3587                        {
3588                            return None;
3589                        }
3590
3591                        let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref() {
3592                            // If the language server provides a range to overwrite, then
3593                            // check that the range is valid.
3594                            Some(lsp::CompletionTextEdit::Edit(edit)) => {
3595                                let range = range_from_lsp(edit.range);
3596                                let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3597                                let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3598                                if start != range.start || end != range.end {
3599                                    log::info!("completion out of expected range");
3600                                    return None;
3601                                }
3602                                (
3603                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3604                                    edit.new_text.clone(),
3605                                )
3606                            }
3607                            // If the language server does not provide a range, then infer
3608                            // the range based on the syntax tree.
3609                            None => {
3610                                if position != clipped_position {
3611                                    log::info!("completion out of expected range");
3612                                    return None;
3613                                }
3614                                let Range { start, end } = range_for_token
3615                                    .get_or_insert_with(|| {
3616                                        let offset = position.to_offset(&snapshot);
3617                                        let (range, kind) = snapshot.surrounding_word(offset);
3618                                        if kind == Some(CharKind::Word) {
3619                                            range
3620                                        } else {
3621                                            offset..offset
3622                                        }
3623                                    })
3624                                    .clone();
3625                                let text = lsp_completion
3626                                    .insert_text
3627                                    .as_ref()
3628                                    .unwrap_or(&lsp_completion.label)
3629                                    .clone();
3630                                (
3631                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3632                                    text,
3633                                )
3634                            }
3635                            Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3636                                log::info!("unsupported insert/replace completion");
3637                                return None;
3638                            }
3639                        };
3640
3641                        LineEnding::normalize(&mut new_text);
3642                        let language = language.clone();
3643                        Some(async move {
3644                            let label = if let Some(language) = language {
3645                                language.label_for_completion(&lsp_completion).await
3646                            } else {
3647                                None
3648                            };
3649                            Completion {
3650                                old_range,
3651                                new_text,
3652                                label: label.unwrap_or_else(|| {
3653                                    CodeLabel::plain(
3654                                        lsp_completion.label.clone(),
3655                                        lsp_completion.filter_text.as_deref(),
3656                                    )
3657                                }),
3658                                lsp_completion,
3659                            }
3660                        })
3661                    })
3662                });
3663
3664                Ok(futures::future::join_all(completions).await)
3665            })
3666        } else if let Some(project_id) = self.remote_id() {
3667            let rpc = self.client.clone();
3668            let message = proto::GetCompletions {
3669                project_id,
3670                buffer_id,
3671                position: Some(language::proto::serialize_anchor(&anchor)),
3672                version: serialize_version(&source_buffer.version()),
3673            };
3674            cx.spawn_weak(|_, mut cx| async move {
3675                let response = rpc.request(message).await?;
3676
3677                source_buffer_handle
3678                    .update(&mut cx, |buffer, _| {
3679                        buffer.wait_for_version(deserialize_version(response.version))
3680                    })
3681                    .await;
3682
3683                let completions = response.completions.into_iter().map(|completion| {
3684                    language::proto::deserialize_completion(completion, language.clone())
3685                });
3686                futures::future::try_join_all(completions).await
3687            })
3688        } else {
3689            Task::ready(Ok(Default::default()))
3690        }
3691    }
3692
3693    pub fn apply_additional_edits_for_completion(
3694        &self,
3695        buffer_handle: ModelHandle<Buffer>,
3696        completion: Completion,
3697        push_to_history: bool,
3698        cx: &mut ModelContext<Self>,
3699    ) -> Task<Result<Option<Transaction>>> {
3700        let buffer = buffer_handle.read(cx);
3701        let buffer_id = buffer.remote_id();
3702
3703        if self.is_local() {
3704            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3705            {
3706                server.clone()
3707            } else {
3708                return Task::ready(Ok(Default::default()));
3709            };
3710
3711            cx.spawn(|this, mut cx| async move {
3712                let resolved_completion = lang_server
3713                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3714                    .await?;
3715                if let Some(edits) = resolved_completion.additional_text_edits {
3716                    let edits = this
3717                        .update(&mut cx, |this, cx| {
3718                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3719                        })
3720                        .await?;
3721                    buffer_handle.update(&mut cx, |buffer, cx| {
3722                        buffer.finalize_last_transaction();
3723                        buffer.start_transaction();
3724                        for (range, text) in edits {
3725                            buffer.edit([(range, text)], None, cx);
3726                        }
3727                        let transaction = if buffer.end_transaction(cx).is_some() {
3728                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3729                            if !push_to_history {
3730                                buffer.forget_transaction(transaction.id);
3731                            }
3732                            Some(transaction)
3733                        } else {
3734                            None
3735                        };
3736                        Ok(transaction)
3737                    })
3738                } else {
3739                    Ok(None)
3740                }
3741            })
3742        } else if let Some(project_id) = self.remote_id() {
3743            let client = self.client.clone();
3744            cx.spawn(|_, mut cx| async move {
3745                let response = client
3746                    .request(proto::ApplyCompletionAdditionalEdits {
3747                        project_id,
3748                        buffer_id,
3749                        completion: Some(language::proto::serialize_completion(&completion)),
3750                    })
3751                    .await?;
3752
3753                if let Some(transaction) = response.transaction {
3754                    let transaction = language::proto::deserialize_transaction(transaction)?;
3755                    buffer_handle
3756                        .update(&mut cx, |buffer, _| {
3757                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3758                        })
3759                        .await;
3760                    if push_to_history {
3761                        buffer_handle.update(&mut cx, |buffer, _| {
3762                            buffer.push_transaction(transaction.clone(), Instant::now());
3763                        });
3764                    }
3765                    Ok(Some(transaction))
3766                } else {
3767                    Ok(None)
3768                }
3769            })
3770        } else {
3771            Task::ready(Err(anyhow!("project does not have a remote id")))
3772        }
3773    }
3774
3775    pub fn code_actions<T: Clone + ToOffset>(
3776        &self,
3777        buffer_handle: &ModelHandle<Buffer>,
3778        range: Range<T>,
3779        cx: &mut ModelContext<Self>,
3780    ) -> Task<Result<Vec<CodeAction>>> {
3781        let buffer_handle = buffer_handle.clone();
3782        let buffer = buffer_handle.read(cx);
3783        let snapshot = buffer.snapshot();
3784        let relevant_diagnostics = snapshot
3785            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3786            .map(|entry| entry.to_lsp_diagnostic_stub())
3787            .collect();
3788        let buffer_id = buffer.remote_id();
3789        let worktree;
3790        let buffer_abs_path;
3791        if let Some(file) = File::from_dyn(buffer.file()) {
3792            worktree = file.worktree.clone();
3793            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3794        } else {
3795            return Task::ready(Ok(Default::default()));
3796        };
3797        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3798
3799        if worktree.read(cx).as_local().is_some() {
3800            let buffer_abs_path = buffer_abs_path.unwrap();
3801            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3802            {
3803                server.clone()
3804            } else {
3805                return Task::ready(Ok(Default::default()));
3806            };
3807
3808            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3809            cx.foreground().spawn(async move {
3810                if lang_server.capabilities().code_action_provider.is_none() {
3811                    return Ok(Default::default());
3812                }
3813
3814                Ok(lang_server
3815                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3816                        text_document: lsp::TextDocumentIdentifier::new(
3817                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3818                        ),
3819                        range: lsp_range,
3820                        work_done_progress_params: Default::default(),
3821                        partial_result_params: Default::default(),
3822                        context: lsp::CodeActionContext {
3823                            diagnostics: relevant_diagnostics,
3824                            only: Some(vec![
3825                                lsp::CodeActionKind::QUICKFIX,
3826                                lsp::CodeActionKind::REFACTOR,
3827                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3828                                lsp::CodeActionKind::SOURCE,
3829                            ]),
3830                        },
3831                    })
3832                    .await?
3833                    .unwrap_or_default()
3834                    .into_iter()
3835                    .filter_map(|entry| {
3836                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3837                            Some(CodeAction {
3838                                range: range.clone(),
3839                                lsp_action,
3840                            })
3841                        } else {
3842                            None
3843                        }
3844                    })
3845                    .collect())
3846            })
3847        } else if let Some(project_id) = self.remote_id() {
3848            let rpc = self.client.clone();
3849            let version = buffer.version();
3850            cx.spawn_weak(|_, mut cx| async move {
3851                let response = rpc
3852                    .request(proto::GetCodeActions {
3853                        project_id,
3854                        buffer_id,
3855                        start: Some(language::proto::serialize_anchor(&range.start)),
3856                        end: Some(language::proto::serialize_anchor(&range.end)),
3857                        version: serialize_version(&version),
3858                    })
3859                    .await?;
3860
3861                buffer_handle
3862                    .update(&mut cx, |buffer, _| {
3863                        buffer.wait_for_version(deserialize_version(response.version))
3864                    })
3865                    .await;
3866
3867                response
3868                    .actions
3869                    .into_iter()
3870                    .map(language::proto::deserialize_code_action)
3871                    .collect()
3872            })
3873        } else {
3874            Task::ready(Ok(Default::default()))
3875        }
3876    }
3877
3878    pub fn apply_code_action(
3879        &self,
3880        buffer_handle: ModelHandle<Buffer>,
3881        mut action: CodeAction,
3882        push_to_history: bool,
3883        cx: &mut ModelContext<Self>,
3884    ) -> Task<Result<ProjectTransaction>> {
3885        if self.is_local() {
3886            let buffer = buffer_handle.read(cx);
3887            let (lsp_adapter, lang_server) =
3888                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3889                    (adapter.clone(), server.clone())
3890                } else {
3891                    return Task::ready(Ok(Default::default()));
3892                };
3893            let range = action.range.to_point_utf16(buffer);
3894
3895            cx.spawn(|this, mut cx| async move {
3896                if let Some(lsp_range) = action
3897                    .lsp_action
3898                    .data
3899                    .as_mut()
3900                    .and_then(|d| d.get_mut("codeActionParams"))
3901                    .and_then(|d| d.get_mut("range"))
3902                {
3903                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3904                    action.lsp_action = lang_server
3905                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3906                        .await?;
3907                } else {
3908                    let actions = this
3909                        .update(&mut cx, |this, cx| {
3910                            this.code_actions(&buffer_handle, action.range, cx)
3911                        })
3912                        .await?;
3913                    action.lsp_action = actions
3914                        .into_iter()
3915                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3916                        .ok_or_else(|| anyhow!("code action is outdated"))?
3917                        .lsp_action;
3918                }
3919
3920                if let Some(edit) = action.lsp_action.edit {
3921                    if edit.changes.is_some() || edit.document_changes.is_some() {
3922                        return Self::deserialize_workspace_edit(
3923                            this,
3924                            edit,
3925                            push_to_history,
3926                            lsp_adapter.clone(),
3927                            lang_server.clone(),
3928                            &mut cx,
3929                        )
3930                        .await;
3931                    }
3932                }
3933
3934                if let Some(command) = action.lsp_action.command {
3935                    this.update(&mut cx, |this, _| {
3936                        this.last_workspace_edits_by_language_server
3937                            .remove(&lang_server.server_id());
3938                    });
3939                    lang_server
3940                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3941                            command: command.command,
3942                            arguments: command.arguments.unwrap_or_default(),
3943                            ..Default::default()
3944                        })
3945                        .await?;
3946                    return Ok(this.update(&mut cx, |this, _| {
3947                        this.last_workspace_edits_by_language_server
3948                            .remove(&lang_server.server_id())
3949                            .unwrap_or_default()
3950                    }));
3951                }
3952
3953                Ok(ProjectTransaction::default())
3954            })
3955        } else if let Some(project_id) = self.remote_id() {
3956            let client = self.client.clone();
3957            let request = proto::ApplyCodeAction {
3958                project_id,
3959                buffer_id: buffer_handle.read(cx).remote_id(),
3960                action: Some(language::proto::serialize_code_action(&action)),
3961            };
3962            cx.spawn(|this, mut cx| async move {
3963                let response = client
3964                    .request(request)
3965                    .await?
3966                    .transaction
3967                    .ok_or_else(|| anyhow!("missing transaction"))?;
3968                this.update(&mut cx, |this, cx| {
3969                    this.deserialize_project_transaction(response, push_to_history, cx)
3970                })
3971                .await
3972            })
3973        } else {
3974            Task::ready(Err(anyhow!("project does not have a remote id")))
3975        }
3976    }
3977
3978    async fn deserialize_workspace_edit(
3979        this: ModelHandle<Self>,
3980        edit: lsp::WorkspaceEdit,
3981        push_to_history: bool,
3982        lsp_adapter: Arc<CachedLspAdapter>,
3983        language_server: Arc<LanguageServer>,
3984        cx: &mut AsyncAppContext,
3985    ) -> Result<ProjectTransaction> {
3986        let fs = this.read_with(cx, |this, _| this.fs.clone());
3987        let mut operations = Vec::new();
3988        if let Some(document_changes) = edit.document_changes {
3989            match document_changes {
3990                lsp::DocumentChanges::Edits(edits) => {
3991                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3992                }
3993                lsp::DocumentChanges::Operations(ops) => operations = ops,
3994            }
3995        } else if let Some(changes) = edit.changes {
3996            operations.extend(changes.into_iter().map(|(uri, edits)| {
3997                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3998                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3999                        uri,
4000                        version: None,
4001                    },
4002                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
4003                })
4004            }));
4005        }
4006
4007        let mut project_transaction = ProjectTransaction::default();
4008        for operation in operations {
4009            match operation {
4010                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4011                    let abs_path = op
4012                        .uri
4013                        .to_file_path()
4014                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4015
4016                    if let Some(parent_path) = abs_path.parent() {
4017                        fs.create_dir(parent_path).await?;
4018                    }
4019                    if abs_path.ends_with("/") {
4020                        fs.create_dir(&abs_path).await?;
4021                    } else {
4022                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4023                            .await?;
4024                    }
4025                }
4026                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4027                    let source_abs_path = op
4028                        .old_uri
4029                        .to_file_path()
4030                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4031                    let target_abs_path = op
4032                        .new_uri
4033                        .to_file_path()
4034                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4035                    fs.rename(
4036                        &source_abs_path,
4037                        &target_abs_path,
4038                        op.options.map(Into::into).unwrap_or_default(),
4039                    )
4040                    .await?;
4041                }
4042                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4043                    let abs_path = op
4044                        .uri
4045                        .to_file_path()
4046                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4047                    let options = op.options.map(Into::into).unwrap_or_default();
4048                    if abs_path.ends_with("/") {
4049                        fs.remove_dir(&abs_path, options).await?;
4050                    } else {
4051                        fs.remove_file(&abs_path, options).await?;
4052                    }
4053                }
4054                lsp::DocumentChangeOperation::Edit(op) => {
4055                    let buffer_to_edit = this
4056                        .update(cx, |this, cx| {
4057                            this.open_local_buffer_via_lsp(
4058                                op.text_document.uri,
4059                                language_server.server_id(),
4060                                lsp_adapter.name.clone(),
4061                                cx,
4062                            )
4063                        })
4064                        .await?;
4065
4066                    let edits = this
4067                        .update(cx, |this, cx| {
4068                            let edits = op.edits.into_iter().map(|edit| match edit {
4069                                lsp::OneOf::Left(edit) => edit,
4070                                lsp::OneOf::Right(edit) => edit.text_edit,
4071                            });
4072                            this.edits_from_lsp(
4073                                &buffer_to_edit,
4074                                edits,
4075                                op.text_document.version,
4076                                cx,
4077                            )
4078                        })
4079                        .await?;
4080
4081                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4082                        buffer.finalize_last_transaction();
4083                        buffer.start_transaction();
4084                        for (range, text) in edits {
4085                            buffer.edit([(range, text)], None, cx);
4086                        }
4087                        let transaction = if buffer.end_transaction(cx).is_some() {
4088                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4089                            if !push_to_history {
4090                                buffer.forget_transaction(transaction.id);
4091                            }
4092                            Some(transaction)
4093                        } else {
4094                            None
4095                        };
4096
4097                        transaction
4098                    });
4099                    if let Some(transaction) = transaction {
4100                        project_transaction.0.insert(buffer_to_edit, transaction);
4101                    }
4102                }
4103            }
4104        }
4105
4106        Ok(project_transaction)
4107    }
4108
4109    pub fn prepare_rename<T: ToPointUtf16>(
4110        &self,
4111        buffer: ModelHandle<Buffer>,
4112        position: T,
4113        cx: &mut ModelContext<Self>,
4114    ) -> Task<Result<Option<Range<Anchor>>>> {
4115        let position = position.to_point_utf16(buffer.read(cx));
4116        self.request_lsp(buffer, PrepareRename { position }, cx)
4117    }
4118
4119    pub fn perform_rename<T: ToPointUtf16>(
4120        &self,
4121        buffer: ModelHandle<Buffer>,
4122        position: T,
4123        new_name: String,
4124        push_to_history: bool,
4125        cx: &mut ModelContext<Self>,
4126    ) -> Task<Result<ProjectTransaction>> {
4127        let position = position.to_point_utf16(buffer.read(cx));
4128        self.request_lsp(
4129            buffer,
4130            PerformRename {
4131                position,
4132                new_name,
4133                push_to_history,
4134            },
4135            cx,
4136        )
4137    }
4138
4139    #[allow(clippy::type_complexity)]
4140    pub fn search(
4141        &self,
4142        query: SearchQuery,
4143        cx: &mut ModelContext<Self>,
4144    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4145        if self.is_local() {
4146            let snapshots = self
4147                .visible_worktrees(cx)
4148                .filter_map(|tree| {
4149                    let tree = tree.read(cx).as_local()?;
4150                    Some(tree.snapshot())
4151                })
4152                .collect::<Vec<_>>();
4153
4154            let background = cx.background().clone();
4155            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4156            if path_count == 0 {
4157                return Task::ready(Ok(Default::default()));
4158            }
4159            let workers = background.num_cpus().min(path_count);
4160            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4161            cx.background()
4162                .spawn({
4163                    let fs = self.fs.clone();
4164                    let background = cx.background().clone();
4165                    let query = query.clone();
4166                    async move {
4167                        let fs = &fs;
4168                        let query = &query;
4169                        let matching_paths_tx = &matching_paths_tx;
4170                        let paths_per_worker = (path_count + workers - 1) / workers;
4171                        let snapshots = &snapshots;
4172                        background
4173                            .scoped(|scope| {
4174                                for worker_ix in 0..workers {
4175                                    let worker_start_ix = worker_ix * paths_per_worker;
4176                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4177                                    scope.spawn(async move {
4178                                        let mut snapshot_start_ix = 0;
4179                                        let mut abs_path = PathBuf::new();
4180                                        for snapshot in snapshots {
4181                                            let snapshot_end_ix =
4182                                                snapshot_start_ix + snapshot.visible_file_count();
4183                                            if worker_end_ix <= snapshot_start_ix {
4184                                                break;
4185                                            } else if worker_start_ix > snapshot_end_ix {
4186                                                snapshot_start_ix = snapshot_end_ix;
4187                                                continue;
4188                                            } else {
4189                                                let start_in_snapshot = worker_start_ix
4190                                                    .saturating_sub(snapshot_start_ix);
4191                                                let end_in_snapshot =
4192                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4193                                                        - snapshot_start_ix;
4194
4195                                                for entry in snapshot
4196                                                    .files(false, start_in_snapshot)
4197                                                    .take(end_in_snapshot - start_in_snapshot)
4198                                                {
4199                                                    if matching_paths_tx.is_closed() {
4200                                                        break;
4201                                                    }
4202
4203                                                    abs_path.clear();
4204                                                    abs_path.push(&snapshot.abs_path());
4205                                                    abs_path.push(&entry.path);
4206                                                    let matches = if let Some(file) =
4207                                                        fs.open_sync(&abs_path).await.log_err()
4208                                                    {
4209                                                        query.detect(file).unwrap_or(false)
4210                                                    } else {
4211                                                        false
4212                                                    };
4213
4214                                                    if matches {
4215                                                        let project_path =
4216                                                            (snapshot.id(), entry.path.clone());
4217                                                        if matching_paths_tx
4218                                                            .send(project_path)
4219                                                            .await
4220                                                            .is_err()
4221                                                        {
4222                                                            break;
4223                                                        }
4224                                                    }
4225                                                }
4226
4227                                                snapshot_start_ix = snapshot_end_ix;
4228                                            }
4229                                        }
4230                                    });
4231                                }
4232                            })
4233                            .await;
4234                    }
4235                })
4236                .detach();
4237
4238            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4239            let open_buffers = self
4240                .opened_buffers
4241                .values()
4242                .filter_map(|b| b.upgrade(cx))
4243                .collect::<HashSet<_>>();
4244            cx.spawn(|this, cx| async move {
4245                for buffer in &open_buffers {
4246                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4247                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4248                }
4249
4250                let open_buffers = Rc::new(RefCell::new(open_buffers));
4251                while let Some(project_path) = matching_paths_rx.next().await {
4252                    if buffers_tx.is_closed() {
4253                        break;
4254                    }
4255
4256                    let this = this.clone();
4257                    let open_buffers = open_buffers.clone();
4258                    let buffers_tx = buffers_tx.clone();
4259                    cx.spawn(|mut cx| async move {
4260                        if let Some(buffer) = this
4261                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4262                            .await
4263                            .log_err()
4264                        {
4265                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4266                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4267                                buffers_tx.send((buffer, snapshot)).await?;
4268                            }
4269                        }
4270
4271                        Ok::<_, anyhow::Error>(())
4272                    })
4273                    .detach();
4274                }
4275
4276                Ok::<_, anyhow::Error>(())
4277            })
4278            .detach_and_log_err(cx);
4279
4280            let background = cx.background().clone();
4281            cx.background().spawn(async move {
4282                let query = &query;
4283                let mut matched_buffers = Vec::new();
4284                for _ in 0..workers {
4285                    matched_buffers.push(HashMap::default());
4286                }
4287                background
4288                    .scoped(|scope| {
4289                        for worker_matched_buffers in matched_buffers.iter_mut() {
4290                            let mut buffers_rx = buffers_rx.clone();
4291                            scope.spawn(async move {
4292                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4293                                    let buffer_matches = query
4294                                        .search(snapshot.as_rope())
4295                                        .await
4296                                        .iter()
4297                                        .map(|range| {
4298                                            snapshot.anchor_before(range.start)
4299                                                ..snapshot.anchor_after(range.end)
4300                                        })
4301                                        .collect::<Vec<_>>();
4302                                    if !buffer_matches.is_empty() {
4303                                        worker_matched_buffers
4304                                            .insert(buffer.clone(), buffer_matches);
4305                                    }
4306                                }
4307                            });
4308                        }
4309                    })
4310                    .await;
4311                Ok(matched_buffers.into_iter().flatten().collect())
4312            })
4313        } else if let Some(project_id) = self.remote_id() {
4314            let request = self.client.request(query.to_proto(project_id));
4315            cx.spawn(|this, mut cx| async move {
4316                let response = request.await?;
4317                let mut result = HashMap::default();
4318                for location in response.locations {
4319                    let target_buffer = this
4320                        .update(&mut cx, |this, cx| {
4321                            this.wait_for_buffer(location.buffer_id, cx)
4322                        })
4323                        .await?;
4324                    let start = location
4325                        .start
4326                        .and_then(deserialize_anchor)
4327                        .ok_or_else(|| anyhow!("missing target start"))?;
4328                    let end = location
4329                        .end
4330                        .and_then(deserialize_anchor)
4331                        .ok_or_else(|| anyhow!("missing target end"))?;
4332                    result
4333                        .entry(target_buffer)
4334                        .or_insert(Vec::new())
4335                        .push(start..end)
4336                }
4337                Ok(result)
4338            })
4339        } else {
4340            Task::ready(Ok(Default::default()))
4341        }
4342    }
4343
4344    fn request_lsp<R: LspCommand>(
4345        &self,
4346        buffer_handle: ModelHandle<Buffer>,
4347        request: R,
4348        cx: &mut ModelContext<Self>,
4349    ) -> Task<Result<R::Response>>
4350    where
4351        <R::LspRequest as lsp::request::Request>::Result: Send,
4352    {
4353        let buffer = buffer_handle.read(cx);
4354        if self.is_local() {
4355            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4356            if let Some((file, language_server)) = file.zip(
4357                self.language_server_for_buffer(buffer, cx)
4358                    .map(|(_, server)| server.clone()),
4359            ) {
4360                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4361                return cx.spawn(|this, cx| async move {
4362                    if !request.check_capabilities(language_server.capabilities()) {
4363                        return Ok(Default::default());
4364                    }
4365
4366                    let response = language_server
4367                        .request::<R::LspRequest>(lsp_params)
4368                        .await
4369                        .context("lsp request failed")?;
4370                    request
4371                        .response_from_lsp(response, this, buffer_handle, cx)
4372                        .await
4373                });
4374            }
4375        } else if let Some(project_id) = self.remote_id() {
4376            let rpc = self.client.clone();
4377            let message = request.to_proto(project_id, buffer);
4378            return cx.spawn(|this, cx| async move {
4379                let response = rpc.request(message).await?;
4380                request
4381                    .response_from_proto(response, this, buffer_handle, cx)
4382                    .await
4383            });
4384        }
4385        Task::ready(Ok(Default::default()))
4386    }
4387
4388    pub fn find_or_create_local_worktree(
4389        &mut self,
4390        abs_path: impl AsRef<Path>,
4391        visible: bool,
4392        cx: &mut ModelContext<Self>,
4393    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4394        let abs_path = abs_path.as_ref();
4395        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4396            Task::ready(Ok((tree, relative_path)))
4397        } else {
4398            let worktree = self.create_local_worktree(abs_path, visible, cx);
4399            cx.foreground()
4400                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4401        }
4402    }
4403
4404    pub fn find_local_worktree(
4405        &self,
4406        abs_path: &Path,
4407        cx: &AppContext,
4408    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4409        for tree in &self.worktrees {
4410            if let Some(tree) = tree.upgrade(cx) {
4411                if let Some(relative_path) = tree
4412                    .read(cx)
4413                    .as_local()
4414                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4415                {
4416                    return Some((tree.clone(), relative_path.into()));
4417                }
4418            }
4419        }
4420        None
4421    }
4422
4423    pub fn is_shared(&self) -> bool {
4424        match &self.client_state {
4425            ProjectClientState::Local { is_shared, .. } => *is_shared,
4426            ProjectClientState::Remote { .. } => false,
4427        }
4428    }
4429
4430    fn create_local_worktree(
4431        &mut self,
4432        abs_path: impl AsRef<Path>,
4433        visible: bool,
4434        cx: &mut ModelContext<Self>,
4435    ) -> Task<Result<ModelHandle<Worktree>>> {
4436        let fs = self.fs.clone();
4437        let client = self.client.clone();
4438        let next_entry_id = self.next_entry_id.clone();
4439        let path: Arc<Path> = abs_path.as_ref().into();
4440        let task = self
4441            .loading_local_worktrees
4442            .entry(path.clone())
4443            .or_insert_with(|| {
4444                cx.spawn(|project, mut cx| {
4445                    async move {
4446                        let worktree = Worktree::local(
4447                            client.clone(),
4448                            path.clone(),
4449                            visible,
4450                            fs,
4451                            next_entry_id,
4452                            &mut cx,
4453                        )
4454                        .await;
4455                        project.update(&mut cx, |project, _| {
4456                            project.loading_local_worktrees.remove(&path);
4457                        });
4458                        let worktree = worktree?;
4459
4460                        let project_id = project.update(&mut cx, |project, cx| {
4461                            project.add_worktree(&worktree, cx);
4462                            project.shared_remote_id()
4463                        });
4464
4465                        if let Some(project_id) = project_id {
4466                            worktree
4467                                .update(&mut cx, |worktree, cx| {
4468                                    worktree.as_local_mut().unwrap().share(project_id, cx)
4469                                })
4470                                .await
4471                                .log_err();
4472                        }
4473
4474                        Ok(worktree)
4475                    }
4476                    .map_err(Arc::new)
4477                })
4478                .shared()
4479            })
4480            .clone();
4481        cx.foreground().spawn(async move {
4482            match task.await {
4483                Ok(worktree) => Ok(worktree),
4484                Err(err) => Err(anyhow!("{}", err)),
4485            }
4486        })
4487    }
4488
4489    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4490        self.worktrees.retain(|worktree| {
4491            if let Some(worktree) = worktree.upgrade(cx) {
4492                let id = worktree.read(cx).id();
4493                if id == id_to_remove {
4494                    cx.emit(Event::WorktreeRemoved(id));
4495                    false
4496                } else {
4497                    true
4498                }
4499            } else {
4500                false
4501            }
4502        });
4503        self.metadata_changed(true, cx);
4504        cx.notify();
4505    }
4506
4507    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4508        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4509        if worktree.read(cx).is_local() {
4510            cx.subscribe(worktree, |this, worktree, _, cx| {
4511                this.update_local_worktree_buffers(worktree, cx);
4512            })
4513            .detach();
4514        }
4515
4516        let push_strong_handle = {
4517            let worktree = worktree.read(cx);
4518            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4519        };
4520        if push_strong_handle {
4521            self.worktrees
4522                .push(WorktreeHandle::Strong(worktree.clone()));
4523        } else {
4524            self.worktrees
4525                .push(WorktreeHandle::Weak(worktree.downgrade()));
4526        }
4527
4528        self.metadata_changed(true, cx);
4529        cx.observe_release(worktree, |this, worktree, cx| {
4530            this.remove_worktree(worktree.id(), cx);
4531            cx.notify();
4532        })
4533        .detach();
4534
4535        cx.emit(Event::WorktreeAdded);
4536        cx.notify();
4537    }
4538
4539    fn update_local_worktree_buffers(
4540        &mut self,
4541        worktree_handle: ModelHandle<Worktree>,
4542        cx: &mut ModelContext<Self>,
4543    ) {
4544        let snapshot = worktree_handle.read(cx).snapshot();
4545        let mut buffers_to_delete = Vec::new();
4546        let mut renamed_buffers = Vec::new();
4547        for (buffer_id, buffer) in &self.opened_buffers {
4548            if let Some(buffer) = buffer.upgrade(cx) {
4549                buffer.update(cx, |buffer, cx| {
4550                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4551                        if old_file.worktree != worktree_handle {
4552                            return;
4553                        }
4554
4555                        let new_file = if let Some(entry) = old_file
4556                            .entry_id
4557                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4558                        {
4559                            File {
4560                                is_local: true,
4561                                entry_id: Some(entry.id),
4562                                mtime: entry.mtime,
4563                                path: entry.path.clone(),
4564                                worktree: worktree_handle.clone(),
4565                            }
4566                        } else if let Some(entry) =
4567                            snapshot.entry_for_path(old_file.path().as_ref())
4568                        {
4569                            File {
4570                                is_local: true,
4571                                entry_id: Some(entry.id),
4572                                mtime: entry.mtime,
4573                                path: entry.path.clone(),
4574                                worktree: worktree_handle.clone(),
4575                            }
4576                        } else {
4577                            File {
4578                                is_local: true,
4579                                entry_id: None,
4580                                path: old_file.path().clone(),
4581                                mtime: old_file.mtime(),
4582                                worktree: worktree_handle.clone(),
4583                            }
4584                        };
4585
4586                        let old_path = old_file.abs_path(cx);
4587                        if new_file.abs_path(cx) != old_path {
4588                            renamed_buffers.push((cx.handle(), old_path));
4589                        }
4590
4591                        if let Some(project_id) = self.shared_remote_id() {
4592                            self.client
4593                                .send(proto::UpdateBufferFile {
4594                                    project_id,
4595                                    buffer_id: *buffer_id as u64,
4596                                    file: Some(new_file.to_proto()),
4597                                })
4598                                .log_err();
4599                        }
4600                        buffer.file_updated(Arc::new(new_file), cx).detach();
4601                    }
4602                });
4603            } else {
4604                buffers_to_delete.push(*buffer_id);
4605            }
4606        }
4607
4608        for buffer_id in buffers_to_delete {
4609            self.opened_buffers.remove(&buffer_id);
4610        }
4611
4612        for (buffer, old_path) in renamed_buffers {
4613            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4614            self.assign_language_to_buffer(&buffer, cx);
4615            self.register_buffer_with_language_server(&buffer, cx);
4616        }
4617    }
4618
4619    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4620        let new_active_entry = entry.and_then(|project_path| {
4621            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4622            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4623            Some(entry.id)
4624        });
4625        if new_active_entry != self.active_entry {
4626            self.active_entry = new_active_entry;
4627            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4628        }
4629    }
4630
4631    pub fn language_servers_running_disk_based_diagnostics(
4632        &self,
4633    ) -> impl Iterator<Item = usize> + '_ {
4634        self.language_server_statuses
4635            .iter()
4636            .filter_map(|(id, status)| {
4637                if status.has_pending_diagnostic_updates {
4638                    Some(*id)
4639                } else {
4640                    None
4641                }
4642            })
4643    }
4644
4645    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4646        let mut summary = DiagnosticSummary::default();
4647        for (_, path_summary) in self.diagnostic_summaries(cx) {
4648            summary.error_count += path_summary.error_count;
4649            summary.warning_count += path_summary.warning_count;
4650        }
4651        summary
4652    }
4653
4654    pub fn diagnostic_summaries<'a>(
4655        &'a self,
4656        cx: &'a AppContext,
4657    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4658        self.visible_worktrees(cx).flat_map(move |worktree| {
4659            let worktree = worktree.read(cx);
4660            let worktree_id = worktree.id();
4661            worktree
4662                .diagnostic_summaries()
4663                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4664        })
4665    }
4666
4667    pub fn disk_based_diagnostics_started(
4668        &mut self,
4669        language_server_id: usize,
4670        cx: &mut ModelContext<Self>,
4671    ) {
4672        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4673    }
4674
4675    pub fn disk_based_diagnostics_finished(
4676        &mut self,
4677        language_server_id: usize,
4678        cx: &mut ModelContext<Self>,
4679    ) {
4680        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4681    }
4682
4683    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4684        self.active_entry
4685    }
4686
4687    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4688        self.worktree_for_id(path.worktree_id, cx)?
4689            .read(cx)
4690            .entry_for_path(&path.path)
4691            .cloned()
4692    }
4693
4694    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4695        let worktree = self.worktree_for_entry(entry_id, cx)?;
4696        let worktree = worktree.read(cx);
4697        let worktree_id = worktree.id();
4698        let path = worktree.entry_for_id(entry_id)?.path.clone();
4699        Some(ProjectPath { worktree_id, path })
4700    }
4701
4702    // RPC message handlers
4703
4704    async fn handle_request_join_project(
4705        this: ModelHandle<Self>,
4706        message: TypedEnvelope<proto::RequestJoinProject>,
4707        _: Arc<Client>,
4708        mut cx: AsyncAppContext,
4709    ) -> Result<()> {
4710        let user_id = message.payload.requester_id;
4711        if this.read_with(&cx, |project, _| {
4712            project.collaborators.values().any(|c| c.user.id == user_id)
4713        }) {
4714            this.update(&mut cx, |this, cx| {
4715                this.respond_to_join_request(user_id, true, cx)
4716            });
4717        } else {
4718            let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4719            let user = user_store
4720                .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4721                .await?;
4722            this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4723        }
4724        Ok(())
4725    }
4726
4727    async fn handle_unregister_project(
4728        this: ModelHandle<Self>,
4729        _: TypedEnvelope<proto::UnregisterProject>,
4730        _: Arc<Client>,
4731        mut cx: AsyncAppContext,
4732    ) -> Result<()> {
4733        this.update(&mut cx, |this, cx| this.disconnected_from_host(cx));
4734        Ok(())
4735    }
4736
4737    async fn handle_project_unshared(
4738        this: ModelHandle<Self>,
4739        _: TypedEnvelope<proto::ProjectUnshared>,
4740        _: Arc<Client>,
4741        mut cx: AsyncAppContext,
4742    ) -> Result<()> {
4743        this.update(&mut cx, |this, cx| this.unshared(cx));
4744        Ok(())
4745    }
4746
4747    async fn handle_add_collaborator(
4748        this: ModelHandle<Self>,
4749        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4750        _: Arc<Client>,
4751        mut cx: AsyncAppContext,
4752    ) -> Result<()> {
4753        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4754        let collaborator = envelope
4755            .payload
4756            .collaborator
4757            .take()
4758            .ok_or_else(|| anyhow!("empty collaborator"))?;
4759
4760        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4761        this.update(&mut cx, |this, cx| {
4762            this.collaborators
4763                .insert(collaborator.peer_id, collaborator);
4764            cx.notify();
4765        });
4766
4767        Ok(())
4768    }
4769
4770    async fn handle_remove_collaborator(
4771        this: ModelHandle<Self>,
4772        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4773        _: Arc<Client>,
4774        mut cx: AsyncAppContext,
4775    ) -> Result<()> {
4776        this.update(&mut cx, |this, cx| {
4777            let peer_id = PeerId(envelope.payload.peer_id);
4778            let replica_id = this
4779                .collaborators
4780                .remove(&peer_id)
4781                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4782                .replica_id;
4783            for buffer in this.opened_buffers.values() {
4784                if let Some(buffer) = buffer.upgrade(cx) {
4785                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4786                }
4787            }
4788
4789            cx.emit(Event::CollaboratorLeft(peer_id));
4790            cx.notify();
4791            Ok(())
4792        })
4793    }
4794
4795    async fn handle_join_project_request_cancelled(
4796        this: ModelHandle<Self>,
4797        envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4798        _: Arc<Client>,
4799        mut cx: AsyncAppContext,
4800    ) -> Result<()> {
4801        let user = this
4802            .update(&mut cx, |this, cx| {
4803                this.user_store.update(cx, |user_store, cx| {
4804                    user_store.fetch_user(envelope.payload.requester_id, cx)
4805                })
4806            })
4807            .await?;
4808
4809        this.update(&mut cx, |_, cx| {
4810            cx.emit(Event::ContactCancelledJoinRequest(user));
4811        });
4812
4813        Ok(())
4814    }
4815
4816    async fn handle_update_project(
4817        this: ModelHandle<Self>,
4818        envelope: TypedEnvelope<proto::UpdateProject>,
4819        client: Arc<Client>,
4820        mut cx: AsyncAppContext,
4821    ) -> Result<()> {
4822        this.update(&mut cx, |this, cx| {
4823            let replica_id = this.replica_id();
4824            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4825
4826            let mut old_worktrees_by_id = this
4827                .worktrees
4828                .drain(..)
4829                .filter_map(|worktree| {
4830                    let worktree = worktree.upgrade(cx)?;
4831                    Some((worktree.read(cx).id(), worktree))
4832                })
4833                .collect::<HashMap<_, _>>();
4834
4835            for worktree in envelope.payload.worktrees {
4836                if let Some(old_worktree) =
4837                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4838                {
4839                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4840                } else {
4841                    let worktree =
4842                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4843                    this.add_worktree(&worktree, cx);
4844                }
4845            }
4846
4847            this.metadata_changed(true, cx);
4848            for (id, _) in old_worktrees_by_id {
4849                cx.emit(Event::WorktreeRemoved(id));
4850            }
4851
4852            Ok(())
4853        })
4854    }
4855
4856    async fn handle_update_worktree(
4857        this: ModelHandle<Self>,
4858        envelope: TypedEnvelope<proto::UpdateWorktree>,
4859        _: Arc<Client>,
4860        mut cx: AsyncAppContext,
4861    ) -> Result<()> {
4862        this.update(&mut cx, |this, cx| {
4863            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4864            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4865                worktree.update(cx, |worktree, _| {
4866                    let worktree = worktree.as_remote_mut().unwrap();
4867                    worktree.update_from_remote(envelope.payload);
4868                });
4869            }
4870            Ok(())
4871        })
4872    }
4873
4874    async fn handle_create_project_entry(
4875        this: ModelHandle<Self>,
4876        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4877        _: Arc<Client>,
4878        mut cx: AsyncAppContext,
4879    ) -> Result<proto::ProjectEntryResponse> {
4880        let worktree = this.update(&mut cx, |this, cx| {
4881            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4882            this.worktree_for_id(worktree_id, cx)
4883                .ok_or_else(|| anyhow!("worktree not found"))
4884        })?;
4885        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4886        let entry = worktree
4887            .update(&mut cx, |worktree, cx| {
4888                let worktree = worktree.as_local_mut().unwrap();
4889                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4890                worktree.create_entry(path, envelope.payload.is_directory, cx)
4891            })
4892            .await?;
4893        Ok(proto::ProjectEntryResponse {
4894            entry: Some((&entry).into()),
4895            worktree_scan_id: worktree_scan_id as u64,
4896        })
4897    }
4898
4899    async fn handle_rename_project_entry(
4900        this: ModelHandle<Self>,
4901        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4902        _: Arc<Client>,
4903        mut cx: AsyncAppContext,
4904    ) -> Result<proto::ProjectEntryResponse> {
4905        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4906        let worktree = this.read_with(&cx, |this, cx| {
4907            this.worktree_for_entry(entry_id, cx)
4908                .ok_or_else(|| anyhow!("worktree not found"))
4909        })?;
4910        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4911        let entry = worktree
4912            .update(&mut cx, |worktree, cx| {
4913                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4914                worktree
4915                    .as_local_mut()
4916                    .unwrap()
4917                    .rename_entry(entry_id, new_path, cx)
4918                    .ok_or_else(|| anyhow!("invalid entry"))
4919            })?
4920            .await?;
4921        Ok(proto::ProjectEntryResponse {
4922            entry: Some((&entry).into()),
4923            worktree_scan_id: worktree_scan_id as u64,
4924        })
4925    }
4926
4927    async fn handle_copy_project_entry(
4928        this: ModelHandle<Self>,
4929        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4930        _: Arc<Client>,
4931        mut cx: AsyncAppContext,
4932    ) -> Result<proto::ProjectEntryResponse> {
4933        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4934        let worktree = this.read_with(&cx, |this, cx| {
4935            this.worktree_for_entry(entry_id, cx)
4936                .ok_or_else(|| anyhow!("worktree not found"))
4937        })?;
4938        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4939        let entry = worktree
4940            .update(&mut cx, |worktree, cx| {
4941                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4942                worktree
4943                    .as_local_mut()
4944                    .unwrap()
4945                    .copy_entry(entry_id, new_path, cx)
4946                    .ok_or_else(|| anyhow!("invalid entry"))
4947            })?
4948            .await?;
4949        Ok(proto::ProjectEntryResponse {
4950            entry: Some((&entry).into()),
4951            worktree_scan_id: worktree_scan_id as u64,
4952        })
4953    }
4954
4955    async fn handle_delete_project_entry(
4956        this: ModelHandle<Self>,
4957        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4958        _: Arc<Client>,
4959        mut cx: AsyncAppContext,
4960    ) -> Result<proto::ProjectEntryResponse> {
4961        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4962        let worktree = this.read_with(&cx, |this, cx| {
4963            this.worktree_for_entry(entry_id, cx)
4964                .ok_or_else(|| anyhow!("worktree not found"))
4965        })?;
4966        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4967        worktree
4968            .update(&mut cx, |worktree, cx| {
4969                worktree
4970                    .as_local_mut()
4971                    .unwrap()
4972                    .delete_entry(entry_id, cx)
4973                    .ok_or_else(|| anyhow!("invalid entry"))
4974            })?
4975            .await?;
4976        Ok(proto::ProjectEntryResponse {
4977            entry: None,
4978            worktree_scan_id: worktree_scan_id as u64,
4979        })
4980    }
4981
4982    async fn handle_update_diagnostic_summary(
4983        this: ModelHandle<Self>,
4984        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4985        _: Arc<Client>,
4986        mut cx: AsyncAppContext,
4987    ) -> Result<()> {
4988        this.update(&mut cx, |this, cx| {
4989            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4990            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4991                if let Some(summary) = envelope.payload.summary {
4992                    let project_path = ProjectPath {
4993                        worktree_id,
4994                        path: Path::new(&summary.path).into(),
4995                    };
4996                    worktree.update(cx, |worktree, _| {
4997                        worktree
4998                            .as_remote_mut()
4999                            .unwrap()
5000                            .update_diagnostic_summary(project_path.path.clone(), &summary);
5001                    });
5002                    cx.emit(Event::DiagnosticsUpdated {
5003                        language_server_id: summary.language_server_id as usize,
5004                        path: project_path,
5005                    });
5006                }
5007            }
5008            Ok(())
5009        })
5010    }
5011
5012    async fn handle_start_language_server(
5013        this: ModelHandle<Self>,
5014        envelope: TypedEnvelope<proto::StartLanguageServer>,
5015        _: Arc<Client>,
5016        mut cx: AsyncAppContext,
5017    ) -> Result<()> {
5018        let server = envelope
5019            .payload
5020            .server
5021            .ok_or_else(|| anyhow!("invalid server"))?;
5022        this.update(&mut cx, |this, cx| {
5023            this.language_server_statuses.insert(
5024                server.id as usize,
5025                LanguageServerStatus {
5026                    name: server.name,
5027                    pending_work: Default::default(),
5028                    has_pending_diagnostic_updates: false,
5029                    progress_tokens: Default::default(),
5030                },
5031            );
5032            cx.notify();
5033        });
5034        Ok(())
5035    }
5036
5037    async fn handle_update_language_server(
5038        this: ModelHandle<Self>,
5039        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5040        _: Arc<Client>,
5041        mut cx: AsyncAppContext,
5042    ) -> Result<()> {
5043        let language_server_id = envelope.payload.language_server_id as usize;
5044        match envelope
5045            .payload
5046            .variant
5047            .ok_or_else(|| anyhow!("invalid variant"))?
5048        {
5049            proto::update_language_server::Variant::WorkStart(payload) => {
5050                this.update(&mut cx, |this, cx| {
5051                    this.on_lsp_work_start(
5052                        language_server_id,
5053                        payload.token,
5054                        LanguageServerProgress {
5055                            message: payload.message,
5056                            percentage: payload.percentage.map(|p| p as usize),
5057                            last_update_at: Instant::now(),
5058                        },
5059                        cx,
5060                    );
5061                })
5062            }
5063            proto::update_language_server::Variant::WorkProgress(payload) => {
5064                this.update(&mut cx, |this, cx| {
5065                    this.on_lsp_work_progress(
5066                        language_server_id,
5067                        payload.token,
5068                        LanguageServerProgress {
5069                            message: payload.message,
5070                            percentage: payload.percentage.map(|p| p as usize),
5071                            last_update_at: Instant::now(),
5072                        },
5073                        cx,
5074                    );
5075                })
5076            }
5077            proto::update_language_server::Variant::WorkEnd(payload) => {
5078                this.update(&mut cx, |this, cx| {
5079                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5080                })
5081            }
5082            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5083                this.update(&mut cx, |this, cx| {
5084                    this.disk_based_diagnostics_started(language_server_id, cx);
5085                })
5086            }
5087            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5088                this.update(&mut cx, |this, cx| {
5089                    this.disk_based_diagnostics_finished(language_server_id, cx)
5090                });
5091            }
5092        }
5093
5094        Ok(())
5095    }
5096
5097    async fn handle_update_buffer(
5098        this: ModelHandle<Self>,
5099        envelope: TypedEnvelope<proto::UpdateBuffer>,
5100        _: Arc<Client>,
5101        mut cx: AsyncAppContext,
5102    ) -> Result<()> {
5103        this.update(&mut cx, |this, cx| {
5104            let payload = envelope.payload.clone();
5105            let buffer_id = payload.buffer_id;
5106            let ops = payload
5107                .operations
5108                .into_iter()
5109                .map(language::proto::deserialize_operation)
5110                .collect::<Result<Vec<_>, _>>()?;
5111            let is_remote = this.is_remote();
5112            match this.opened_buffers.entry(buffer_id) {
5113                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5114                    OpenBuffer::Strong(buffer) => {
5115                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5116                    }
5117                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5118                    OpenBuffer::Weak(_) => {}
5119                },
5120                hash_map::Entry::Vacant(e) => {
5121                    assert!(
5122                        is_remote,
5123                        "received buffer update from {:?}",
5124                        envelope.original_sender_id
5125                    );
5126                    e.insert(OpenBuffer::Operations(ops));
5127                }
5128            }
5129            Ok(())
5130        })
5131    }
5132
5133    async fn handle_create_buffer_for_peer(
5134        this: ModelHandle<Self>,
5135        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5136        _: Arc<Client>,
5137        mut cx: AsyncAppContext,
5138    ) -> Result<()> {
5139        this.update(&mut cx, |this, cx| {
5140            match envelope
5141                .payload
5142                .variant
5143                .ok_or_else(|| anyhow!("missing variant"))?
5144            {
5145                proto::create_buffer_for_peer::Variant::State(mut state) => {
5146                    let mut buffer_file = None;
5147                    if let Some(file) = state.file.take() {
5148                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5149                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5150                            anyhow!("no worktree found for id {}", file.worktree_id)
5151                        })?;
5152                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5153                            as Arc<dyn language::File>);
5154                    }
5155
5156                    let buffer_id = state.id;
5157                    let buffer = cx.add_model(|_| {
5158                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5159                    });
5160                    this.incomplete_buffers.insert(buffer_id, buffer);
5161                }
5162                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5163                    let buffer = this
5164                        .incomplete_buffers
5165                        .get(&chunk.buffer_id)
5166                        .ok_or_else(|| {
5167                            anyhow!(
5168                                "received chunk for buffer {} without initial state",
5169                                chunk.buffer_id
5170                            )
5171                        })?
5172                        .clone();
5173                    let operations = chunk
5174                        .operations
5175                        .into_iter()
5176                        .map(language::proto::deserialize_operation)
5177                        .collect::<Result<Vec<_>>>()?;
5178                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5179
5180                    if chunk.is_last {
5181                        this.incomplete_buffers.remove(&chunk.buffer_id);
5182                        this.register_buffer(&buffer, cx)?;
5183                    }
5184                }
5185            }
5186
5187            Ok(())
5188        })
5189    }
5190
5191    async fn handle_update_buffer_file(
5192        this: ModelHandle<Self>,
5193        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5194        _: Arc<Client>,
5195        mut cx: AsyncAppContext,
5196    ) -> Result<()> {
5197        this.update(&mut cx, |this, cx| {
5198            let payload = envelope.payload.clone();
5199            let buffer_id = payload.buffer_id;
5200            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5201            let worktree = this
5202                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5203                .ok_or_else(|| anyhow!("no such worktree"))?;
5204            let file = File::from_proto(file, worktree, cx)?;
5205            let buffer = this
5206                .opened_buffers
5207                .get_mut(&buffer_id)
5208                .and_then(|b| b.upgrade(cx))
5209                .ok_or_else(|| anyhow!("no such buffer"))?;
5210            buffer.update(cx, |buffer, cx| {
5211                buffer.file_updated(Arc::new(file), cx).detach();
5212            });
5213            Ok(())
5214        })
5215    }
5216
5217    async fn handle_save_buffer(
5218        this: ModelHandle<Self>,
5219        envelope: TypedEnvelope<proto::SaveBuffer>,
5220        _: Arc<Client>,
5221        mut cx: AsyncAppContext,
5222    ) -> Result<proto::BufferSaved> {
5223        let buffer_id = envelope.payload.buffer_id;
5224        let requested_version = deserialize_version(envelope.payload.version);
5225
5226        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5227            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5228            let buffer = this
5229                .opened_buffers
5230                .get(&buffer_id)
5231                .and_then(|buffer| buffer.upgrade(cx))
5232                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5233            Ok::<_, anyhow::Error>((project_id, buffer))
5234        })?;
5235        buffer
5236            .update(&mut cx, |buffer, _| {
5237                buffer.wait_for_version(requested_version)
5238            })
5239            .await;
5240
5241        let (saved_version, fingerprint, mtime) =
5242            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5243        Ok(proto::BufferSaved {
5244            project_id,
5245            buffer_id,
5246            version: serialize_version(&saved_version),
5247            mtime: Some(mtime.into()),
5248            fingerprint,
5249        })
5250    }
5251
5252    async fn handle_reload_buffers(
5253        this: ModelHandle<Self>,
5254        envelope: TypedEnvelope<proto::ReloadBuffers>,
5255        _: Arc<Client>,
5256        mut cx: AsyncAppContext,
5257    ) -> Result<proto::ReloadBuffersResponse> {
5258        let sender_id = envelope.original_sender_id()?;
5259        let reload = this.update(&mut cx, |this, cx| {
5260            let mut buffers = HashSet::default();
5261            for buffer_id in &envelope.payload.buffer_ids {
5262                buffers.insert(
5263                    this.opened_buffers
5264                        .get(buffer_id)
5265                        .and_then(|buffer| buffer.upgrade(cx))
5266                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5267                );
5268            }
5269            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5270        })?;
5271
5272        let project_transaction = reload.await?;
5273        let project_transaction = this.update(&mut cx, |this, cx| {
5274            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5275        });
5276        Ok(proto::ReloadBuffersResponse {
5277            transaction: Some(project_transaction),
5278        })
5279    }
5280
5281    async fn handle_format_buffers(
5282        this: ModelHandle<Self>,
5283        envelope: TypedEnvelope<proto::FormatBuffers>,
5284        _: Arc<Client>,
5285        mut cx: AsyncAppContext,
5286    ) -> Result<proto::FormatBuffersResponse> {
5287        let sender_id = envelope.original_sender_id()?;
5288        let format = this.update(&mut cx, |this, cx| {
5289            let mut buffers = HashSet::default();
5290            for buffer_id in &envelope.payload.buffer_ids {
5291                buffers.insert(
5292                    this.opened_buffers
5293                        .get(buffer_id)
5294                        .and_then(|buffer| buffer.upgrade(cx))
5295                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5296                );
5297            }
5298            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
5299        })?;
5300
5301        let project_transaction = format.await?;
5302        let project_transaction = this.update(&mut cx, |this, cx| {
5303            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5304        });
5305        Ok(proto::FormatBuffersResponse {
5306            transaction: Some(project_transaction),
5307        })
5308    }
5309
5310    async fn handle_get_completions(
5311        this: ModelHandle<Self>,
5312        envelope: TypedEnvelope<proto::GetCompletions>,
5313        _: Arc<Client>,
5314        mut cx: AsyncAppContext,
5315    ) -> Result<proto::GetCompletionsResponse> {
5316        let position = envelope
5317            .payload
5318            .position
5319            .and_then(language::proto::deserialize_anchor)
5320            .ok_or_else(|| anyhow!("invalid position"))?;
5321        let version = deserialize_version(envelope.payload.version);
5322        let buffer = this.read_with(&cx, |this, cx| {
5323            this.opened_buffers
5324                .get(&envelope.payload.buffer_id)
5325                .and_then(|buffer| buffer.upgrade(cx))
5326                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5327        })?;
5328        buffer
5329            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5330            .await;
5331        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5332        let completions = this
5333            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5334            .await?;
5335
5336        Ok(proto::GetCompletionsResponse {
5337            completions: completions
5338                .iter()
5339                .map(language::proto::serialize_completion)
5340                .collect(),
5341            version: serialize_version(&version),
5342        })
5343    }
5344
5345    async fn handle_apply_additional_edits_for_completion(
5346        this: ModelHandle<Self>,
5347        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5348        _: Arc<Client>,
5349        mut cx: AsyncAppContext,
5350    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5351        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5352            let buffer = this
5353                .opened_buffers
5354                .get(&envelope.payload.buffer_id)
5355                .and_then(|buffer| buffer.upgrade(cx))
5356                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5357            let language = buffer.read(cx).language();
5358            let completion = language::proto::deserialize_completion(
5359                envelope
5360                    .payload
5361                    .completion
5362                    .ok_or_else(|| anyhow!("invalid completion"))?,
5363                language.cloned(),
5364            );
5365            Ok::<_, anyhow::Error>((buffer, completion))
5366        })?;
5367
5368        let completion = completion.await?;
5369
5370        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5371            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5372        });
5373
5374        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5375            transaction: apply_additional_edits
5376                .await?
5377                .as_ref()
5378                .map(language::proto::serialize_transaction),
5379        })
5380    }
5381
5382    async fn handle_get_code_actions(
5383        this: ModelHandle<Self>,
5384        envelope: TypedEnvelope<proto::GetCodeActions>,
5385        _: Arc<Client>,
5386        mut cx: AsyncAppContext,
5387    ) -> Result<proto::GetCodeActionsResponse> {
5388        let start = envelope
5389            .payload
5390            .start
5391            .and_then(language::proto::deserialize_anchor)
5392            .ok_or_else(|| anyhow!("invalid start"))?;
5393        let end = envelope
5394            .payload
5395            .end
5396            .and_then(language::proto::deserialize_anchor)
5397            .ok_or_else(|| anyhow!("invalid end"))?;
5398        let buffer = this.update(&mut cx, |this, cx| {
5399            this.opened_buffers
5400                .get(&envelope.payload.buffer_id)
5401                .and_then(|buffer| buffer.upgrade(cx))
5402                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5403        })?;
5404        buffer
5405            .update(&mut cx, |buffer, _| {
5406                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5407            })
5408            .await;
5409
5410        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5411        let code_actions = this.update(&mut cx, |this, cx| {
5412            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5413        })?;
5414
5415        Ok(proto::GetCodeActionsResponse {
5416            actions: code_actions
5417                .await?
5418                .iter()
5419                .map(language::proto::serialize_code_action)
5420                .collect(),
5421            version: serialize_version(&version),
5422        })
5423    }
5424
5425    async fn handle_apply_code_action(
5426        this: ModelHandle<Self>,
5427        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5428        _: Arc<Client>,
5429        mut cx: AsyncAppContext,
5430    ) -> Result<proto::ApplyCodeActionResponse> {
5431        let sender_id = envelope.original_sender_id()?;
5432        let action = language::proto::deserialize_code_action(
5433            envelope
5434                .payload
5435                .action
5436                .ok_or_else(|| anyhow!("invalid action"))?,
5437        )?;
5438        let apply_code_action = this.update(&mut cx, |this, cx| {
5439            let buffer = this
5440                .opened_buffers
5441                .get(&envelope.payload.buffer_id)
5442                .and_then(|buffer| buffer.upgrade(cx))
5443                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5444            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5445        })?;
5446
5447        let project_transaction = apply_code_action.await?;
5448        let project_transaction = this.update(&mut cx, |this, cx| {
5449            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5450        });
5451        Ok(proto::ApplyCodeActionResponse {
5452            transaction: Some(project_transaction),
5453        })
5454    }
5455
5456    async fn handle_lsp_command<T: LspCommand>(
5457        this: ModelHandle<Self>,
5458        envelope: TypedEnvelope<T::ProtoRequest>,
5459        _: Arc<Client>,
5460        mut cx: AsyncAppContext,
5461    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5462    where
5463        <T::LspRequest as lsp::request::Request>::Result: Send,
5464    {
5465        let sender_id = envelope.original_sender_id()?;
5466        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5467        let buffer_handle = this.read_with(&cx, |this, _| {
5468            this.opened_buffers
5469                .get(&buffer_id)
5470                .and_then(|buffer| buffer.upgrade(&cx))
5471                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5472        })?;
5473        let request = T::from_proto(
5474            envelope.payload,
5475            this.clone(),
5476            buffer_handle.clone(),
5477            cx.clone(),
5478        )
5479        .await?;
5480        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5481        let response = this
5482            .update(&mut cx, |this, cx| {
5483                this.request_lsp(buffer_handle, request, cx)
5484            })
5485            .await?;
5486        this.update(&mut cx, |this, cx| {
5487            Ok(T::response_to_proto(
5488                response,
5489                this,
5490                sender_id,
5491                &buffer_version,
5492                cx,
5493            ))
5494        })
5495    }
5496
5497    async fn handle_get_project_symbols(
5498        this: ModelHandle<Self>,
5499        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5500        _: Arc<Client>,
5501        mut cx: AsyncAppContext,
5502    ) -> Result<proto::GetProjectSymbolsResponse> {
5503        let symbols = this
5504            .update(&mut cx, |this, cx| {
5505                this.symbols(&envelope.payload.query, cx)
5506            })
5507            .await?;
5508
5509        Ok(proto::GetProjectSymbolsResponse {
5510            symbols: symbols.iter().map(serialize_symbol).collect(),
5511        })
5512    }
5513
5514    async fn handle_search_project(
5515        this: ModelHandle<Self>,
5516        envelope: TypedEnvelope<proto::SearchProject>,
5517        _: Arc<Client>,
5518        mut cx: AsyncAppContext,
5519    ) -> Result<proto::SearchProjectResponse> {
5520        let peer_id = envelope.original_sender_id()?;
5521        let query = SearchQuery::from_proto(envelope.payload)?;
5522        let result = this
5523            .update(&mut cx, |this, cx| this.search(query, cx))
5524            .await?;
5525
5526        this.update(&mut cx, |this, cx| {
5527            let mut locations = Vec::new();
5528            for (buffer, ranges) in result {
5529                for range in ranges {
5530                    let start = serialize_anchor(&range.start);
5531                    let end = serialize_anchor(&range.end);
5532                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5533                    locations.push(proto::Location {
5534                        buffer_id,
5535                        start: Some(start),
5536                        end: Some(end),
5537                    });
5538                }
5539            }
5540            Ok(proto::SearchProjectResponse { locations })
5541        })
5542    }
5543
5544    async fn handle_open_buffer_for_symbol(
5545        this: ModelHandle<Self>,
5546        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5547        _: Arc<Client>,
5548        mut cx: AsyncAppContext,
5549    ) -> Result<proto::OpenBufferForSymbolResponse> {
5550        let peer_id = envelope.original_sender_id()?;
5551        let symbol = envelope
5552            .payload
5553            .symbol
5554            .ok_or_else(|| anyhow!("invalid symbol"))?;
5555        let symbol = this
5556            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5557            .await?;
5558        let symbol = this.read_with(&cx, |this, _| {
5559            let signature = this.symbol_signature(&symbol.path);
5560            if signature == symbol.signature {
5561                Ok(symbol)
5562            } else {
5563                Err(anyhow!("invalid symbol signature"))
5564            }
5565        })?;
5566        let buffer = this
5567            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5568            .await?;
5569
5570        Ok(proto::OpenBufferForSymbolResponse {
5571            buffer_id: this.update(&mut cx, |this, cx| {
5572                this.create_buffer_for_peer(&buffer, peer_id, cx)
5573            }),
5574        })
5575    }
5576
5577    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5578        let mut hasher = Sha256::new();
5579        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5580        hasher.update(project_path.path.to_string_lossy().as_bytes());
5581        hasher.update(self.nonce.to_be_bytes());
5582        hasher.finalize().as_slice().try_into().unwrap()
5583    }
5584
5585    async fn handle_open_buffer_by_id(
5586        this: ModelHandle<Self>,
5587        envelope: TypedEnvelope<proto::OpenBufferById>,
5588        _: Arc<Client>,
5589        mut cx: AsyncAppContext,
5590    ) -> Result<proto::OpenBufferResponse> {
5591        let peer_id = envelope.original_sender_id()?;
5592        let buffer = this
5593            .update(&mut cx, |this, cx| {
5594                this.open_buffer_by_id(envelope.payload.id, cx)
5595            })
5596            .await?;
5597        this.update(&mut cx, |this, cx| {
5598            Ok(proto::OpenBufferResponse {
5599                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5600            })
5601        })
5602    }
5603
5604    async fn handle_open_buffer_by_path(
5605        this: ModelHandle<Self>,
5606        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5607        _: Arc<Client>,
5608        mut cx: AsyncAppContext,
5609    ) -> Result<proto::OpenBufferResponse> {
5610        let peer_id = envelope.original_sender_id()?;
5611        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5612        let open_buffer = this.update(&mut cx, |this, cx| {
5613            this.open_buffer(
5614                ProjectPath {
5615                    worktree_id,
5616                    path: PathBuf::from(envelope.payload.path).into(),
5617                },
5618                cx,
5619            )
5620        });
5621
5622        let buffer = open_buffer.await?;
5623        this.update(&mut cx, |this, cx| {
5624            Ok(proto::OpenBufferResponse {
5625                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5626            })
5627        })
5628    }
5629
5630    fn serialize_project_transaction_for_peer(
5631        &mut self,
5632        project_transaction: ProjectTransaction,
5633        peer_id: PeerId,
5634        cx: &AppContext,
5635    ) -> proto::ProjectTransaction {
5636        let mut serialized_transaction = proto::ProjectTransaction {
5637            buffer_ids: Default::default(),
5638            transactions: Default::default(),
5639        };
5640        for (buffer, transaction) in project_transaction.0 {
5641            serialized_transaction
5642                .buffer_ids
5643                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5644            serialized_transaction
5645                .transactions
5646                .push(language::proto::serialize_transaction(&transaction));
5647        }
5648        serialized_transaction
5649    }
5650
5651    fn deserialize_project_transaction(
5652        &mut self,
5653        message: proto::ProjectTransaction,
5654        push_to_history: bool,
5655        cx: &mut ModelContext<Self>,
5656    ) -> Task<Result<ProjectTransaction>> {
5657        cx.spawn(|this, mut cx| async move {
5658            let mut project_transaction = ProjectTransaction::default();
5659            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5660            {
5661                let buffer = this
5662                    .update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
5663                    .await?;
5664                let transaction = language::proto::deserialize_transaction(transaction)?;
5665                project_transaction.0.insert(buffer, transaction);
5666            }
5667
5668            for (buffer, transaction) in &project_transaction.0 {
5669                buffer
5670                    .update(&mut cx, |buffer, _| {
5671                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5672                    })
5673                    .await;
5674
5675                if push_to_history {
5676                    buffer.update(&mut cx, |buffer, _| {
5677                        buffer.push_transaction(transaction.clone(), Instant::now());
5678                    });
5679                }
5680            }
5681
5682            Ok(project_transaction)
5683        })
5684    }
5685
5686    fn create_buffer_for_peer(
5687        &mut self,
5688        buffer: &ModelHandle<Buffer>,
5689        peer_id: PeerId,
5690        cx: &AppContext,
5691    ) -> u64 {
5692        let buffer_id = buffer.read(cx).remote_id();
5693        if let Some(project_id) = self.remote_id() {
5694            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5695            if shared_buffers.insert(buffer_id) {
5696                let buffer = buffer.read(cx);
5697                let state = buffer.to_proto();
5698                let operations = buffer.serialize_ops(cx);
5699                let client = self.client.clone();
5700                cx.background()
5701                    .spawn(
5702                        async move {
5703                            let mut operations = operations.await;
5704
5705                            client.send(proto::CreateBufferForPeer {
5706                                project_id,
5707                                peer_id: peer_id.0,
5708                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5709                            })?;
5710
5711                            loop {
5712                                #[cfg(any(test, feature = "test-support"))]
5713                                const CHUNK_SIZE: usize = 5;
5714
5715                                #[cfg(not(any(test, feature = "test-support")))]
5716                                const CHUNK_SIZE: usize = 100;
5717
5718                                let chunk = operations
5719                                    .drain(..cmp::min(CHUNK_SIZE, operations.len()))
5720                                    .collect();
5721                                let is_last = operations.is_empty();
5722                                client.send(proto::CreateBufferForPeer {
5723                                    project_id,
5724                                    peer_id: peer_id.0,
5725                                    variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5726                                        proto::BufferChunk {
5727                                            buffer_id,
5728                                            operations: chunk,
5729                                            is_last,
5730                                        },
5731                                    )),
5732                                })?;
5733
5734                                if is_last {
5735                                    break;
5736                                }
5737                            }
5738
5739                            Ok(())
5740                        }
5741                        .log_err(),
5742                    )
5743                    .detach();
5744            }
5745        }
5746
5747        buffer_id
5748    }
5749
5750    fn wait_for_buffer(
5751        &self,
5752        id: u64,
5753        cx: &mut ModelContext<Self>,
5754    ) -> Task<Result<ModelHandle<Buffer>>> {
5755        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5756        cx.spawn(|this, cx| async move {
5757            let buffer = loop {
5758                let buffer = this.read_with(&cx, |this, cx| {
5759                    this.opened_buffers
5760                        .get(&id)
5761                        .and_then(|buffer| buffer.upgrade(cx))
5762                });
5763                if let Some(buffer) = buffer {
5764                    break buffer;
5765                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5766                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5767                }
5768
5769                opened_buffer_rx
5770                    .next()
5771                    .await
5772                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5773            };
5774            Ok(buffer)
5775        })
5776    }
5777
5778    fn deserialize_symbol(
5779        &self,
5780        serialized_symbol: proto::Symbol,
5781    ) -> impl Future<Output = Result<Symbol>> {
5782        let languages = self.languages.clone();
5783        async move {
5784            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5785            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5786            let start = serialized_symbol
5787                .start
5788                .ok_or_else(|| anyhow!("invalid start"))?;
5789            let end = serialized_symbol
5790                .end
5791                .ok_or_else(|| anyhow!("invalid end"))?;
5792            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5793            let path = ProjectPath {
5794                worktree_id,
5795                path: PathBuf::from(serialized_symbol.path).into(),
5796            };
5797            let language = languages.select_language(&path.path);
5798            Ok(Symbol {
5799                language_server_name: LanguageServerName(
5800                    serialized_symbol.language_server_name.into(),
5801                ),
5802                source_worktree_id,
5803                path,
5804                label: {
5805                    match language {
5806                        Some(language) => {
5807                            language
5808                                .label_for_symbol(&serialized_symbol.name, kind)
5809                                .await
5810                        }
5811                        None => None,
5812                    }
5813                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5814                },
5815
5816                name: serialized_symbol.name,
5817                range: PointUtf16::new(start.row, start.column)
5818                    ..PointUtf16::new(end.row, end.column),
5819                kind,
5820                signature: serialized_symbol
5821                    .signature
5822                    .try_into()
5823                    .map_err(|_| anyhow!("invalid signature"))?,
5824            })
5825        }
5826    }
5827
5828    async fn handle_buffer_saved(
5829        this: ModelHandle<Self>,
5830        envelope: TypedEnvelope<proto::BufferSaved>,
5831        _: Arc<Client>,
5832        mut cx: AsyncAppContext,
5833    ) -> Result<()> {
5834        let version = deserialize_version(envelope.payload.version);
5835        let mtime = envelope
5836            .payload
5837            .mtime
5838            .ok_or_else(|| anyhow!("missing mtime"))?
5839            .into();
5840
5841        this.update(&mut cx, |this, cx| {
5842            let buffer = this
5843                .opened_buffers
5844                .get(&envelope.payload.buffer_id)
5845                .and_then(|buffer| buffer.upgrade(cx));
5846            if let Some(buffer) = buffer {
5847                buffer.update(cx, |buffer, cx| {
5848                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5849                });
5850            }
5851            Ok(())
5852        })
5853    }
5854
5855    async fn handle_buffer_reloaded(
5856        this: ModelHandle<Self>,
5857        envelope: TypedEnvelope<proto::BufferReloaded>,
5858        _: Arc<Client>,
5859        mut cx: AsyncAppContext,
5860    ) -> Result<()> {
5861        let payload = envelope.payload;
5862        let version = deserialize_version(payload.version);
5863        let line_ending = deserialize_line_ending(
5864            proto::LineEnding::from_i32(payload.line_ending)
5865                .ok_or_else(|| anyhow!("missing line ending"))?,
5866        );
5867        let mtime = payload
5868            .mtime
5869            .ok_or_else(|| anyhow!("missing mtime"))?
5870            .into();
5871        this.update(&mut cx, |this, cx| {
5872            let buffer = this
5873                .opened_buffers
5874                .get(&payload.buffer_id)
5875                .and_then(|buffer| buffer.upgrade(cx));
5876            if let Some(buffer) = buffer {
5877                buffer.update(cx, |buffer, cx| {
5878                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5879                });
5880            }
5881            Ok(())
5882        })
5883    }
5884
5885    #[allow(clippy::type_complexity)]
5886    fn edits_from_lsp(
5887        &mut self,
5888        buffer: &ModelHandle<Buffer>,
5889        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5890        version: Option<i32>,
5891        cx: &mut ModelContext<Self>,
5892    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5893        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5894        cx.background().spawn(async move {
5895            let snapshot = snapshot?;
5896            let mut lsp_edits = lsp_edits
5897                .into_iter()
5898                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5899                .collect::<Vec<_>>();
5900            lsp_edits.sort_by_key(|(range, _)| range.start);
5901
5902            let mut lsp_edits = lsp_edits.into_iter().peekable();
5903            let mut edits = Vec::new();
5904            while let Some((mut range, mut new_text)) = lsp_edits.next() {
5905                // Clip invalid ranges provided by the language server.
5906                range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
5907                range.end = snapshot.clip_point_utf16(range.end, Bias::Left);
5908
5909                // Combine any LSP edits that are adjacent.
5910                //
5911                // Also, combine LSP edits that are separated from each other by only
5912                // a newline. This is important because for some code actions,
5913                // Rust-analyzer rewrites the entire buffer via a series of edits that
5914                // are separated by unchanged newline characters.
5915                //
5916                // In order for the diffing logic below to work properly, any edits that
5917                // cancel each other out must be combined into one.
5918                while let Some((next_range, next_text)) = lsp_edits.peek() {
5919                    if next_range.start > range.end {
5920                        if next_range.start.row > range.end.row + 1
5921                            || next_range.start.column > 0
5922                            || snapshot.clip_point_utf16(
5923                                PointUtf16::new(range.end.row, u32::MAX),
5924                                Bias::Left,
5925                            ) > range.end
5926                        {
5927                            break;
5928                        }
5929                        new_text.push('\n');
5930                    }
5931                    range.end = next_range.end;
5932                    new_text.push_str(next_text);
5933                    lsp_edits.next();
5934                }
5935
5936                // For multiline edits, perform a diff of the old and new text so that
5937                // we can identify the changes more precisely, preserving the locations
5938                // of any anchors positioned in the unchanged regions.
5939                if range.end.row > range.start.row {
5940                    let mut offset = range.start.to_offset(&snapshot);
5941                    let old_text = snapshot.text_for_range(range).collect::<String>();
5942
5943                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5944                    let mut moved_since_edit = true;
5945                    for change in diff.iter_all_changes() {
5946                        let tag = change.tag();
5947                        let value = change.value();
5948                        match tag {
5949                            ChangeTag::Equal => {
5950                                offset += value.len();
5951                                moved_since_edit = true;
5952                            }
5953                            ChangeTag::Delete => {
5954                                let start = snapshot.anchor_after(offset);
5955                                let end = snapshot.anchor_before(offset + value.len());
5956                                if moved_since_edit {
5957                                    edits.push((start..end, String::new()));
5958                                } else {
5959                                    edits.last_mut().unwrap().0.end = end;
5960                                }
5961                                offset += value.len();
5962                                moved_since_edit = false;
5963                            }
5964                            ChangeTag::Insert => {
5965                                if moved_since_edit {
5966                                    let anchor = snapshot.anchor_after(offset);
5967                                    edits.push((anchor..anchor, value.to_string()));
5968                                } else {
5969                                    edits.last_mut().unwrap().1.push_str(value);
5970                                }
5971                                moved_since_edit = false;
5972                            }
5973                        }
5974                    }
5975                } else if range.end == range.start {
5976                    let anchor = snapshot.anchor_after(range.start);
5977                    edits.push((anchor..anchor, new_text));
5978                } else {
5979                    let edit_start = snapshot.anchor_after(range.start);
5980                    let edit_end = snapshot.anchor_before(range.end);
5981                    edits.push((edit_start..edit_end, new_text));
5982                }
5983            }
5984
5985            Ok(edits)
5986        })
5987    }
5988
5989    fn buffer_snapshot_for_lsp_version(
5990        &mut self,
5991        buffer: &ModelHandle<Buffer>,
5992        version: Option<i32>,
5993        cx: &AppContext,
5994    ) -> Result<TextBufferSnapshot> {
5995        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5996
5997        if let Some(version) = version {
5998            let buffer_id = buffer.read(cx).remote_id();
5999            let snapshots = self
6000                .buffer_snapshots
6001                .get_mut(&buffer_id)
6002                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6003            let mut found_snapshot = None;
6004            snapshots.retain(|(snapshot_version, snapshot)| {
6005                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
6006                    false
6007                } else {
6008                    if *snapshot_version == version {
6009                        found_snapshot = Some(snapshot.clone());
6010                    }
6011                    true
6012                }
6013            });
6014
6015            found_snapshot.ok_or_else(|| {
6016                anyhow!(
6017                    "snapshot not found for buffer {} at version {}",
6018                    buffer_id,
6019                    version
6020                )
6021            })
6022        } else {
6023            Ok((buffer.read(cx)).text_snapshot())
6024        }
6025    }
6026
6027    fn language_server_for_buffer(
6028        &self,
6029        buffer: &Buffer,
6030        cx: &AppContext,
6031    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6032        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6033            let name = language.lsp_adapter()?.name.clone();
6034            let worktree_id = file.worktree_id(cx);
6035            let key = (worktree_id, name);
6036
6037            if let Some(server_id) = self.language_server_ids.get(&key) {
6038                if let Some(LanguageServerState::Running {
6039                    adapter, server, ..
6040                }) = self.language_servers.get(server_id)
6041                {
6042                    return Some((adapter, server));
6043                }
6044            }
6045        }
6046
6047        None
6048    }
6049}
6050
6051impl ProjectStore {
6052    pub fn new(db: Arc<Db>) -> Self {
6053        Self {
6054            db,
6055            projects: Default::default(),
6056        }
6057    }
6058
6059    pub fn projects<'a>(
6060        &'a self,
6061        cx: &'a AppContext,
6062    ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
6063        self.projects
6064            .iter()
6065            .filter_map(|project| project.upgrade(cx))
6066    }
6067
6068    fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
6069        if let Err(ix) = self
6070            .projects
6071            .binary_search_by_key(&project.id(), WeakModelHandle::id)
6072        {
6073            self.projects.insert(ix, project);
6074        }
6075        cx.notify();
6076    }
6077
6078    fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
6079        let mut did_change = false;
6080        self.projects.retain(|project| {
6081            if project.is_upgradable(cx) {
6082                true
6083            } else {
6084                did_change = true;
6085                false
6086            }
6087        });
6088        if did_change {
6089            cx.notify();
6090        }
6091    }
6092}
6093
6094impl WorktreeHandle {
6095    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6096        match self {
6097            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6098            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6099        }
6100    }
6101}
6102
6103impl OpenBuffer {
6104    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6105        match self {
6106            OpenBuffer::Strong(handle) => Some(handle.clone()),
6107            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6108            OpenBuffer::Operations(_) => None,
6109        }
6110    }
6111}
6112
6113pub struct PathMatchCandidateSet {
6114    pub snapshot: Snapshot,
6115    pub include_ignored: bool,
6116    pub include_root_name: bool,
6117}
6118
6119impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6120    type Candidates = PathMatchCandidateSetIter<'a>;
6121
6122    fn id(&self) -> usize {
6123        self.snapshot.id().to_usize()
6124    }
6125
6126    fn len(&self) -> usize {
6127        if self.include_ignored {
6128            self.snapshot.file_count()
6129        } else {
6130            self.snapshot.visible_file_count()
6131        }
6132    }
6133
6134    fn prefix(&self) -> Arc<str> {
6135        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6136            self.snapshot.root_name().into()
6137        } else if self.include_root_name {
6138            format!("{}/", self.snapshot.root_name()).into()
6139        } else {
6140            "".into()
6141        }
6142    }
6143
6144    fn candidates(&'a self, start: usize) -> Self::Candidates {
6145        PathMatchCandidateSetIter {
6146            traversal: self.snapshot.files(self.include_ignored, start),
6147        }
6148    }
6149}
6150
6151pub struct PathMatchCandidateSetIter<'a> {
6152    traversal: Traversal<'a>,
6153}
6154
6155impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6156    type Item = fuzzy::PathMatchCandidate<'a>;
6157
6158    fn next(&mut self) -> Option<Self::Item> {
6159        self.traversal.next().map(|entry| {
6160            if let EntryKind::File(char_bag) = entry.kind {
6161                fuzzy::PathMatchCandidate {
6162                    path: &entry.path,
6163                    char_bag,
6164                }
6165            } else {
6166                unreachable!()
6167            }
6168        })
6169    }
6170}
6171
6172impl Entity for ProjectStore {
6173    type Event = ();
6174}
6175
6176impl Entity for Project {
6177    type Event = Event;
6178
6179    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
6180        self.project_store.update(cx, ProjectStore::prune_projects);
6181
6182        match &self.client_state {
6183            ProjectClientState::Local { remote_id_rx, .. } => {
6184                if let Some(project_id) = *remote_id_rx.borrow() {
6185                    self.client
6186                        .send(proto::UnregisterProject { project_id })
6187                        .log_err();
6188                }
6189            }
6190            ProjectClientState::Remote { remote_id, .. } => {
6191                self.client
6192                    .send(proto::LeaveProject {
6193                        project_id: *remote_id,
6194                    })
6195                    .log_err();
6196            }
6197        }
6198    }
6199
6200    fn app_will_quit(
6201        &mut self,
6202        _: &mut MutableAppContext,
6203    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6204        let shutdown_futures = self
6205            .language_servers
6206            .drain()
6207            .map(|(_, server_state)| async {
6208                match server_state {
6209                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6210                    LanguageServerState::Starting(starting_server) => {
6211                        starting_server.await?.shutdown()?.await
6212                    }
6213                }
6214            })
6215            .collect::<Vec<_>>();
6216
6217        Some(
6218            async move {
6219                futures::future::join_all(shutdown_futures).await;
6220            }
6221            .boxed(),
6222        )
6223    }
6224}
6225
6226impl Collaborator {
6227    fn from_proto(
6228        message: proto::Collaborator,
6229        user_store: &ModelHandle<UserStore>,
6230        cx: &mut AsyncAppContext,
6231    ) -> impl Future<Output = Result<Self>> {
6232        let user = user_store.update(cx, |user_store, cx| {
6233            user_store.fetch_user(message.user_id, cx)
6234        });
6235
6236        async move {
6237            Ok(Self {
6238                peer_id: PeerId(message.peer_id),
6239                user: user.await?,
6240                replica_id: message.replica_id as ReplicaId,
6241            })
6242        }
6243    }
6244}
6245
6246impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6247    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6248        Self {
6249            worktree_id,
6250            path: path.as_ref().into(),
6251        }
6252    }
6253}
6254
6255impl From<lsp::CreateFileOptions> for fs::CreateOptions {
6256    fn from(options: lsp::CreateFileOptions) -> Self {
6257        Self {
6258            overwrite: options.overwrite.unwrap_or(false),
6259            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6260        }
6261    }
6262}
6263
6264impl From<lsp::RenameFileOptions> for fs::RenameOptions {
6265    fn from(options: lsp::RenameFileOptions) -> Self {
6266        Self {
6267            overwrite: options.overwrite.unwrap_or(false),
6268            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6269        }
6270    }
6271}
6272
6273impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6274    fn from(options: lsp::DeleteFileOptions) -> Self {
6275        Self {
6276            recursive: options.recursive.unwrap_or(false),
6277            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6278        }
6279    }
6280}
6281
6282fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6283    proto::Symbol {
6284        language_server_name: symbol.language_server_name.0.to_string(),
6285        source_worktree_id: symbol.source_worktree_id.to_proto(),
6286        worktree_id: symbol.path.worktree_id.to_proto(),
6287        path: symbol.path.path.to_string_lossy().to_string(),
6288        name: symbol.name.clone(),
6289        kind: unsafe { mem::transmute(symbol.kind) },
6290        start: Some(proto::Point {
6291            row: symbol.range.start.row,
6292            column: symbol.range.start.column,
6293        }),
6294        end: Some(proto::Point {
6295            row: symbol.range.end.row,
6296            column: symbol.range.end.column,
6297        }),
6298        signature: symbol.signature.to_vec(),
6299    }
6300}
6301
6302fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6303    let mut path_components = path.components();
6304    let mut base_components = base.components();
6305    let mut components: Vec<Component> = Vec::new();
6306    loop {
6307        match (path_components.next(), base_components.next()) {
6308            (None, None) => break,
6309            (Some(a), None) => {
6310                components.push(a);
6311                components.extend(path_components.by_ref());
6312                break;
6313            }
6314            (None, _) => components.push(Component::ParentDir),
6315            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6316            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6317            (Some(a), Some(_)) => {
6318                components.push(Component::ParentDir);
6319                for _ in base_components {
6320                    components.push(Component::ParentDir);
6321                }
6322                components.push(a);
6323                components.extend(path_components.by_ref());
6324                break;
6325            }
6326        }
6327    }
6328    components.iter().map(|c| c.as_os_str()).collect()
6329}
6330
6331impl Item for Buffer {
6332    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6333        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6334    }
6335}