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