project.rs

   1mod db;
   2pub mod fs;
   3mod ignore;
   4mod lsp_command;
   5pub mod search;
   6pub mod worktree;
   7
   8#[cfg(test)]
   9mod project_tests;
  10
  11use anyhow::{anyhow, Context, Result};
  12use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
  13use clock::ReplicaId;
  14use collections::{hash_map, BTreeMap, HashMap, HashSet};
  15use futures::{future::Shared, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt};
  16use gpui::{
  17    AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
  18    MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
  19};
  20use language::{
  21    point_to_lsp,
  22    proto::{
  23        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
  24        serialize_version,
  25    },
  26    range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CharKind, CodeAction, CodeLabel,
  27    Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _,
  28    Language, LanguageRegistry, LanguageServerName, LineEnding, LocalFile, LspAdapter,
  29    OffsetRangeExt, Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16,
  30    Transaction,
  31};
  32use lsp::{
  33    DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
  34    MarkedString,
  35};
  36use lsp_command::*;
  37use parking_lot::Mutex;
  38use postage::stream::Stream;
  39use postage::watch;
  40use rand::prelude::*;
  41use search::SearchQuery;
  42use serde::Serialize;
  43use settings::Settings;
  44use sha2::{Digest, Sha256};
  45use similar::{ChangeTag, TextDiff};
  46use std::{
  47    cell::RefCell,
  48    cmp::{self, Ordering},
  49    convert::TryInto,
  50    ffi::OsString,
  51    hash::Hash,
  52    mem,
  53    num::NonZeroU32,
  54    ops::Range,
  55    os::unix::{ffi::OsStrExt, prelude::OsStringExt},
  56    path::{Component, Path, PathBuf},
  57    rc::Rc,
  58    str,
  59    sync::{
  60        atomic::{AtomicUsize, Ordering::SeqCst},
  61        Arc,
  62    },
  63    time::Instant,
  64};
  65use thiserror::Error;
  66use util::{post_inc, ResultExt, TryFutureExt as _};
  67
  68pub use db::Db;
  69pub use fs::*;
  70pub use worktree::*;
  71
  72pub trait Item: Entity {
  73    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  74}
  75
  76pub struct ProjectStore {
  77    db: Arc<Db>,
  78    projects: Vec<WeakModelHandle<Project>>,
  79}
  80
  81// Language server state is stored across 3 collections:
  82//     language_servers =>
  83//         a mapping from unique server id to LanguageServerState which can either be a task for a
  84//         server in the process of starting, or a running server with adapter and language server arcs
  85//     language_server_ids => a mapping from worktreeId and server name to the unique server id
  86//     language_server_statuses => a mapping from unique server id to the current server status
  87//
  88// Multiple worktrees can map to the same language server for example when you jump to the definition
  89// of a file in the standard library. So language_server_ids is used to look up which server is active
  90// for a given worktree and language server name
  91//
  92// When starting a language server, first the id map is checked to make sure a server isn't already available
  93// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
  94// the Starting variant of LanguageServerState is stored in the language_servers map.
  95pub struct Project {
  96    worktrees: Vec<WorktreeHandle>,
  97    active_entry: Option<ProjectEntryId>,
  98    languages: Arc<LanguageRegistry>,
  99    language_servers: HashMap<usize, LanguageServerState>,
 100    language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
 101    language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
 102    language_server_settings: Arc<Mutex<serde_json::Value>>,
 103    last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
 104    next_language_server_id: usize,
 105    client: Arc<client::Client>,
 106    next_entry_id: Arc<AtomicUsize>,
 107    next_diagnostic_group_id: usize,
 108    user_store: ModelHandle<UserStore>,
 109    project_store: ModelHandle<ProjectStore>,
 110    fs: Arc<dyn Fs>,
 111    client_state: ProjectClientState,
 112    collaborators: HashMap<PeerId, Collaborator>,
 113    client_subscriptions: Vec<client::Subscription>,
 114    _subscriptions: Vec<gpui::Subscription>,
 115    opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
 116    shared_buffers: HashMap<PeerId, HashSet<u64>>,
 117    loading_buffers: HashMap<
 118        ProjectPath,
 119        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 120    >,
 121    loading_local_worktrees:
 122        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 123    opened_buffers: HashMap<u64, OpenBuffer>,
 124    buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
 125    nonce: u128,
 126    initialized_persistent_state: bool,
 127}
 128
 129#[derive(Error, Debug)]
 130pub enum JoinProjectError {
 131    #[error("host declined join request")]
 132    HostDeclined,
 133    #[error("host closed the project")]
 134    HostClosedProject,
 135    #[error("host went offline")]
 136    HostWentOffline,
 137    #[error("{0}")]
 138    Other(#[from] anyhow::Error),
 139}
 140
 141enum OpenBuffer {
 142    Strong(ModelHandle<Buffer>),
 143    Weak(WeakModelHandle<Buffer>),
 144    Loading(Vec<Operation>),
 145}
 146
 147enum WorktreeHandle {
 148    Strong(ModelHandle<Worktree>),
 149    Weak(WeakModelHandle<Worktree>),
 150}
 151
 152enum ProjectClientState {
 153    Local {
 154        is_shared: bool,
 155        remote_id_tx: watch::Sender<Option<u64>>,
 156        remote_id_rx: watch::Receiver<Option<u64>>,
 157        online_tx: watch::Sender<bool>,
 158        online_rx: watch::Receiver<bool>,
 159        _maintain_remote_id: Task<Option<()>>,
 160        _maintain_online_status: Task<Option<()>>,
 161    },
 162    Remote {
 163        sharing_has_stopped: bool,
 164        remote_id: u64,
 165        replica_id: ReplicaId,
 166        _detect_unshare: Task<Option<()>>,
 167    },
 168}
 169
 170#[derive(Clone, Debug)]
 171pub struct Collaborator {
 172    pub user: Arc<User>,
 173    pub peer_id: PeerId,
 174    pub replica_id: ReplicaId,
 175}
 176
 177#[derive(Clone, Debug, PartialEq, Eq)]
 178pub enum Event {
 179    ActiveEntryChanged(Option<ProjectEntryId>),
 180    WorktreeAdded,
 181    WorktreeRemoved(WorktreeId),
 182    DiskBasedDiagnosticsStarted {
 183        language_server_id: usize,
 184    },
 185    DiskBasedDiagnosticsFinished {
 186        language_server_id: usize,
 187    },
 188    DiagnosticsUpdated {
 189        path: ProjectPath,
 190        language_server_id: usize,
 191    },
 192    RemoteIdChanged(Option<u64>),
 193    DisconnectedFromHost,
 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.disconnected_from_host(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();
 737                    for (worktree_id, started_lsp_name) in self.language_server_ids.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 disconnected_from_host(&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.emit(Event::DisconnectedFromHost);
1456            cx.notify();
1457        }
1458    }
1459
1460    pub fn is_read_only(&self) -> bool {
1461        match &self.client_state {
1462            ProjectClientState::Local { .. } => false,
1463            ProjectClientState::Remote {
1464                sharing_has_stopped,
1465                ..
1466            } => *sharing_has_stopped,
1467        }
1468    }
1469
1470    pub fn is_local(&self) -> bool {
1471        match &self.client_state {
1472            ProjectClientState::Local { .. } => true,
1473            ProjectClientState::Remote { .. } => false,
1474        }
1475    }
1476
1477    pub fn is_remote(&self) -> bool {
1478        !self.is_local()
1479    }
1480
1481    pub fn create_buffer(
1482        &mut self,
1483        text: &str,
1484        language: Option<Arc<Language>>,
1485        cx: &mut ModelContext<Self>,
1486    ) -> Result<ModelHandle<Buffer>> {
1487        if self.is_remote() {
1488            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1489        }
1490
1491        let buffer = cx.add_model(|cx| {
1492            Buffer::new(self.replica_id(), text, cx)
1493                .with_language(language.unwrap_or(language::PLAIN_TEXT.clone()), cx)
1494        });
1495        self.register_buffer(&buffer, cx)?;
1496        Ok(buffer)
1497    }
1498
1499    pub fn open_path(
1500        &mut self,
1501        path: impl Into<ProjectPath>,
1502        cx: &mut ModelContext<Self>,
1503    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1504        let task = self.open_buffer(path, cx);
1505        cx.spawn_weak(|_, cx| async move {
1506            let buffer = task.await?;
1507            let project_entry_id = buffer
1508                .read_with(&cx, |buffer, cx| {
1509                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1510                })
1511                .ok_or_else(|| anyhow!("no project entry"))?;
1512            Ok((project_entry_id, buffer.into()))
1513        })
1514    }
1515
1516    pub fn open_local_buffer(
1517        &mut self,
1518        abs_path: impl AsRef<Path>,
1519        cx: &mut ModelContext<Self>,
1520    ) -> Task<Result<ModelHandle<Buffer>>> {
1521        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1522            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1523        } else {
1524            Task::ready(Err(anyhow!("no such path")))
1525        }
1526    }
1527
1528    pub fn open_buffer(
1529        &mut self,
1530        path: impl Into<ProjectPath>,
1531        cx: &mut ModelContext<Self>,
1532    ) -> Task<Result<ModelHandle<Buffer>>> {
1533        let project_path = path.into();
1534        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1535            worktree
1536        } else {
1537            return Task::ready(Err(anyhow!("no such worktree")));
1538        };
1539
1540        // If there is already a buffer for the given path, then return it.
1541        let existing_buffer = self.get_open_buffer(&project_path, cx);
1542        if let Some(existing_buffer) = existing_buffer {
1543            return Task::ready(Ok(existing_buffer));
1544        }
1545
1546        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1547            // If the given path is already being loaded, then wait for that existing
1548            // task to complete and return the same buffer.
1549            hash_map::Entry::Occupied(e) => e.get().clone(),
1550
1551            // Otherwise, record the fact that this path is now being loaded.
1552            hash_map::Entry::Vacant(entry) => {
1553                let (mut tx, rx) = postage::watch::channel();
1554                entry.insert(rx.clone());
1555
1556                let load_buffer = if worktree.read(cx).is_local() {
1557                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1558                } else {
1559                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1560                };
1561
1562                cx.spawn(move |this, mut cx| async move {
1563                    let load_result = load_buffer.await;
1564                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1565                        // Record the fact that the buffer is no longer loading.
1566                        this.loading_buffers.remove(&project_path);
1567                        let buffer = load_result.map_err(Arc::new)?;
1568                        Ok(buffer)
1569                    }));
1570                })
1571                .detach();
1572                rx
1573            }
1574        };
1575
1576        cx.foreground().spawn(async move {
1577            loop {
1578                if let Some(result) = loading_watch.borrow().as_ref() {
1579                    match result {
1580                        Ok(buffer) => return Ok(buffer.clone()),
1581                        Err(error) => return Err(anyhow!("{}", error)),
1582                    }
1583                }
1584                loading_watch.next().await;
1585            }
1586        })
1587    }
1588
1589    fn open_local_buffer_internal(
1590        &mut self,
1591        path: &Arc<Path>,
1592        worktree: &ModelHandle<Worktree>,
1593        cx: &mut ModelContext<Self>,
1594    ) -> Task<Result<ModelHandle<Buffer>>> {
1595        let load_buffer = worktree.update(cx, |worktree, cx| {
1596            let worktree = worktree.as_local_mut().unwrap();
1597            worktree.load_buffer(path, cx)
1598        });
1599        cx.spawn(|this, mut cx| async move {
1600            let buffer = load_buffer.await?;
1601            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1602            Ok(buffer)
1603        })
1604    }
1605
1606    fn open_remote_buffer_internal(
1607        &mut self,
1608        path: &Arc<Path>,
1609        worktree: &ModelHandle<Worktree>,
1610        cx: &mut ModelContext<Self>,
1611    ) -> Task<Result<ModelHandle<Buffer>>> {
1612        let rpc = self.client.clone();
1613        let project_id = self.remote_id().unwrap();
1614        let remote_worktree_id = worktree.read(cx).id();
1615        let path = path.clone();
1616        let path_string = path.to_string_lossy().to_string();
1617        cx.spawn(|this, mut cx| async move {
1618            let response = rpc
1619                .request(proto::OpenBufferByPath {
1620                    project_id,
1621                    worktree_id: remote_worktree_id.to_proto(),
1622                    path: path_string,
1623                })
1624                .await?;
1625            let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
1626            this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1627                .await
1628        })
1629    }
1630
1631    fn open_local_buffer_via_lsp(
1632        &mut self,
1633        abs_path: lsp::Url,
1634        language_server_id: usize,
1635        language_server_name: LanguageServerName,
1636        cx: &mut ModelContext<Self>,
1637    ) -> Task<Result<ModelHandle<Buffer>>> {
1638        cx.spawn(|this, mut cx| async move {
1639            let abs_path = abs_path
1640                .to_file_path()
1641                .map_err(|_| anyhow!("can't convert URI to path"))?;
1642            let (worktree, relative_path) = if let Some(result) =
1643                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1644            {
1645                result
1646            } else {
1647                let worktree = this
1648                    .update(&mut cx, |this, cx| {
1649                        this.create_local_worktree(&abs_path, false, cx)
1650                    })
1651                    .await?;
1652                this.update(&mut cx, |this, cx| {
1653                    this.language_server_ids.insert(
1654                        (worktree.read(cx).id(), language_server_name),
1655                        language_server_id,
1656                    );
1657                });
1658                (worktree, PathBuf::new())
1659            };
1660
1661            let project_path = ProjectPath {
1662                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1663                path: relative_path.into(),
1664            };
1665            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1666                .await
1667        })
1668    }
1669
1670    pub fn open_buffer_by_id(
1671        &mut self,
1672        id: u64,
1673        cx: &mut ModelContext<Self>,
1674    ) -> Task<Result<ModelHandle<Buffer>>> {
1675        if let Some(buffer) = self.buffer_for_id(id, cx) {
1676            Task::ready(Ok(buffer))
1677        } else if self.is_local() {
1678            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1679        } else if let Some(project_id) = self.remote_id() {
1680            let request = self
1681                .client
1682                .request(proto::OpenBufferById { project_id, id });
1683            cx.spawn(|this, mut cx| async move {
1684                let buffer = request
1685                    .await?
1686                    .buffer
1687                    .ok_or_else(|| anyhow!("invalid buffer"))?;
1688                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1689                    .await
1690            })
1691        } else {
1692            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1693        }
1694    }
1695
1696    pub fn save_buffer_as(
1697        &mut self,
1698        buffer: ModelHandle<Buffer>,
1699        abs_path: PathBuf,
1700        cx: &mut ModelContext<Project>,
1701    ) -> Task<Result<()>> {
1702        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1703        let old_path =
1704            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1705        cx.spawn(|this, mut cx| async move {
1706            if let Some(old_path) = old_path {
1707                this.update(&mut cx, |this, cx| {
1708                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1709                });
1710            }
1711            let (worktree, path) = worktree_task.await?;
1712            worktree
1713                .update(&mut cx, |worktree, cx| {
1714                    worktree
1715                        .as_local_mut()
1716                        .unwrap()
1717                        .save_buffer_as(buffer.clone(), path, cx)
1718                })
1719                .await?;
1720            this.update(&mut cx, |this, cx| {
1721                this.assign_language_to_buffer(&buffer, cx);
1722                this.register_buffer_with_language_server(&buffer, cx);
1723            });
1724            Ok(())
1725        })
1726    }
1727
1728    pub fn get_open_buffer(
1729        &mut self,
1730        path: &ProjectPath,
1731        cx: &mut ModelContext<Self>,
1732    ) -> Option<ModelHandle<Buffer>> {
1733        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1734        self.opened_buffers.values().find_map(|buffer| {
1735            let buffer = buffer.upgrade(cx)?;
1736            let file = File::from_dyn(buffer.read(cx).file())?;
1737            if file.worktree == worktree && file.path() == &path.path {
1738                Some(buffer)
1739            } else {
1740                None
1741            }
1742        })
1743    }
1744
1745    fn register_buffer(
1746        &mut self,
1747        buffer: &ModelHandle<Buffer>,
1748        cx: &mut ModelContext<Self>,
1749    ) -> Result<()> {
1750        let remote_id = buffer.read(cx).remote_id();
1751        let open_buffer = if self.is_remote() || self.is_shared() {
1752            OpenBuffer::Strong(buffer.clone())
1753        } else {
1754            OpenBuffer::Weak(buffer.downgrade())
1755        };
1756
1757        match self.opened_buffers.insert(remote_id, open_buffer) {
1758            None => {}
1759            Some(OpenBuffer::Loading(operations)) => {
1760                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1761            }
1762            Some(OpenBuffer::Weak(existing_handle)) => {
1763                if existing_handle.upgrade(cx).is_some() {
1764                    Err(anyhow!(
1765                        "already registered buffer with remote id {}",
1766                        remote_id
1767                    ))?
1768                }
1769            }
1770            Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1771                "already registered buffer with remote id {}",
1772                remote_id
1773            ))?,
1774        }
1775        cx.subscribe(buffer, |this, buffer, event, cx| {
1776            this.on_buffer_event(buffer, event, cx);
1777        })
1778        .detach();
1779
1780        self.assign_language_to_buffer(buffer, cx);
1781        self.register_buffer_with_language_server(buffer, cx);
1782        cx.observe_release(buffer, |this, buffer, cx| {
1783            if let Some(file) = File::from_dyn(buffer.file()) {
1784                if file.is_local() {
1785                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1786                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1787                        server
1788                            .notify::<lsp::notification::DidCloseTextDocument>(
1789                                lsp::DidCloseTextDocumentParams {
1790                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1791                                },
1792                            )
1793                            .log_err();
1794                    }
1795                }
1796            }
1797        })
1798        .detach();
1799
1800        Ok(())
1801    }
1802
1803    fn register_buffer_with_language_server(
1804        &mut self,
1805        buffer_handle: &ModelHandle<Buffer>,
1806        cx: &mut ModelContext<Self>,
1807    ) {
1808        let buffer = buffer_handle.read(cx);
1809        let buffer_id = buffer.remote_id();
1810        if let Some(file) = File::from_dyn(buffer.file()) {
1811            if file.is_local() {
1812                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1813                let initial_snapshot = buffer.text_snapshot();
1814
1815                let mut language_server = None;
1816                let mut language_id = None;
1817                if let Some(language) = buffer.language() {
1818                    let worktree_id = file.worktree_id(cx);
1819                    if let Some(adapter) = language.lsp_adapter() {
1820                        language_id = adapter.id_for_language(language.name().as_ref());
1821                        language_server = self
1822                            .language_server_ids
1823                            .get(&(worktree_id, adapter.name()))
1824                            .and_then(|id| self.language_servers.get(&id))
1825                            .and_then(|server_state| {
1826                                if let LanguageServerState::Running { server, .. } = server_state {
1827                                    Some(server.clone())
1828                                } else {
1829                                    None
1830                                }
1831                            });
1832                    }
1833                }
1834
1835                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1836                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1837                        self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1838                            .log_err();
1839                    }
1840                }
1841
1842                if let Some(server) = language_server {
1843                    server
1844                        .notify::<lsp::notification::DidOpenTextDocument>(
1845                            lsp::DidOpenTextDocumentParams {
1846                                text_document: lsp::TextDocumentItem::new(
1847                                    uri,
1848                                    language_id.unwrap_or_default(),
1849                                    0,
1850                                    initial_snapshot.text(),
1851                                ),
1852                            }
1853                            .clone(),
1854                        )
1855                        .log_err();
1856                    buffer_handle.update(cx, |buffer, cx| {
1857                        buffer.set_completion_triggers(
1858                            server
1859                                .capabilities()
1860                                .completion_provider
1861                                .as_ref()
1862                                .and_then(|provider| provider.trigger_characters.clone())
1863                                .unwrap_or(Vec::new()),
1864                            cx,
1865                        )
1866                    });
1867                    self.buffer_snapshots
1868                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1869                }
1870            }
1871        }
1872    }
1873
1874    fn unregister_buffer_from_language_server(
1875        &mut self,
1876        buffer: &ModelHandle<Buffer>,
1877        old_path: PathBuf,
1878        cx: &mut ModelContext<Self>,
1879    ) {
1880        buffer.update(cx, |buffer, cx| {
1881            buffer.update_diagnostics(Default::default(), cx);
1882            self.buffer_snapshots.remove(&buffer.remote_id());
1883            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1884                language_server
1885                    .notify::<lsp::notification::DidCloseTextDocument>(
1886                        lsp::DidCloseTextDocumentParams {
1887                            text_document: lsp::TextDocumentIdentifier::new(
1888                                lsp::Url::from_file_path(old_path).unwrap(),
1889                            ),
1890                        },
1891                    )
1892                    .log_err();
1893            }
1894        });
1895    }
1896
1897    fn on_buffer_event(
1898        &mut self,
1899        buffer: ModelHandle<Buffer>,
1900        event: &BufferEvent,
1901        cx: &mut ModelContext<Self>,
1902    ) -> Option<()> {
1903        match event {
1904            BufferEvent::Operation(operation) => {
1905                if let Some(project_id) = self.shared_remote_id() {
1906                    let request = self.client.request(proto::UpdateBuffer {
1907                        project_id,
1908                        buffer_id: buffer.read(cx).remote_id(),
1909                        operations: vec![language::proto::serialize_operation(&operation)],
1910                    });
1911                    cx.background().spawn(request).detach_and_log_err(cx);
1912                } else if let Some(project_id) = self.remote_id() {
1913                    let _ = self
1914                        .client
1915                        .send(proto::RegisterProjectActivity { project_id });
1916                }
1917            }
1918            BufferEvent::Edited { .. } => {
1919                let language_server = self
1920                    .language_server_for_buffer(buffer.read(cx), cx)
1921                    .map(|(_, server)| server.clone())?;
1922                let buffer = buffer.read(cx);
1923                let file = File::from_dyn(buffer.file())?;
1924                let abs_path = file.as_local()?.abs_path(cx);
1925                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1926                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1927                let (version, prev_snapshot) = buffer_snapshots.last()?;
1928                let next_snapshot = buffer.text_snapshot();
1929                let next_version = version + 1;
1930
1931                let content_changes = buffer
1932                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1933                    .map(|edit| {
1934                        let edit_start = edit.new.start.0;
1935                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1936                        let new_text = next_snapshot
1937                            .text_for_range(edit.new.start.1..edit.new.end.1)
1938                            .collect();
1939                        lsp::TextDocumentContentChangeEvent {
1940                            range: Some(lsp::Range::new(
1941                                point_to_lsp(edit_start),
1942                                point_to_lsp(edit_end),
1943                            )),
1944                            range_length: None,
1945                            text: new_text,
1946                        }
1947                    })
1948                    .collect();
1949
1950                buffer_snapshots.push((next_version, next_snapshot));
1951
1952                language_server
1953                    .notify::<lsp::notification::DidChangeTextDocument>(
1954                        lsp::DidChangeTextDocumentParams {
1955                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1956                                uri,
1957                                next_version,
1958                            ),
1959                            content_changes,
1960                        },
1961                    )
1962                    .log_err();
1963            }
1964            BufferEvent::Saved => {
1965                let file = File::from_dyn(buffer.read(cx).file())?;
1966                let worktree_id = file.worktree_id(cx);
1967                let abs_path = file.as_local()?.abs_path(cx);
1968                let text_document = lsp::TextDocumentIdentifier {
1969                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1970                };
1971
1972                for (_, server) in self.language_servers_for_worktree(worktree_id) {
1973                    server
1974                        .notify::<lsp::notification::DidSaveTextDocument>(
1975                            lsp::DidSaveTextDocumentParams {
1976                                text_document: text_document.clone(),
1977                                text: None,
1978                            },
1979                        )
1980                        .log_err();
1981                }
1982
1983                // After saving a buffer, simulate disk-based diagnostics being finished for languages
1984                // that don't support a disk-based progress token.
1985                let (lsp_adapter, language_server) =
1986                    self.language_server_for_buffer(buffer.read(cx), cx)?;
1987                if lsp_adapter
1988                    .disk_based_diagnostics_progress_token()
1989                    .is_none()
1990                {
1991                    let server_id = language_server.server_id();
1992                    self.disk_based_diagnostics_finished(server_id, cx);
1993                    self.broadcast_language_server_update(
1994                        server_id,
1995                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1996                            proto::LspDiskBasedDiagnosticsUpdated {},
1997                        ),
1998                    );
1999                }
2000            }
2001            _ => {}
2002        }
2003
2004        None
2005    }
2006
2007    fn language_servers_for_worktree(
2008        &self,
2009        worktree_id: WorktreeId,
2010    ) -> impl Iterator<Item = (&Arc<dyn LspAdapter>, &Arc<LanguageServer>)> {
2011        self.language_server_ids
2012            .iter()
2013            .filter_map(move |((language_server_worktree_id, _), id)| {
2014                if *language_server_worktree_id == worktree_id {
2015                    if let Some(LanguageServerState::Running { adapter, server }) =
2016                        self.language_servers.get(&id)
2017                    {
2018                        return Some((adapter, server));
2019                    }
2020                }
2021                None
2022            })
2023    }
2024
2025    fn assign_language_to_buffer(
2026        &mut self,
2027        buffer: &ModelHandle<Buffer>,
2028        cx: &mut ModelContext<Self>,
2029    ) -> Option<()> {
2030        // If the buffer has a language, set it and start the language server if we haven't already.
2031        let full_path = buffer.read(cx).file()?.full_path(cx);
2032        let language = self.languages.select_language(&full_path)?;
2033        buffer.update(cx, |buffer, cx| {
2034            buffer.set_language(Some(language.clone()), cx);
2035        });
2036
2037        let file = File::from_dyn(buffer.read(cx).file())?;
2038        let worktree = file.worktree.read(cx).as_local()?;
2039        let worktree_id = worktree.id();
2040        let worktree_abs_path = worktree.abs_path().clone();
2041        self.start_language_server(worktree_id, worktree_abs_path, language, cx);
2042
2043        None
2044    }
2045
2046    fn start_language_server(
2047        &mut self,
2048        worktree_id: WorktreeId,
2049        worktree_path: Arc<Path>,
2050        language: Arc<Language>,
2051        cx: &mut ModelContext<Self>,
2052    ) {
2053        if !cx
2054            .global::<Settings>()
2055            .enable_language_server(Some(&language.name()))
2056        {
2057            return;
2058        }
2059
2060        let adapter = if let Some(adapter) = language.lsp_adapter() {
2061            adapter
2062        } else {
2063            return;
2064        };
2065        let key = (worktree_id, adapter.name());
2066
2067        self.language_server_ids
2068            .entry(key.clone())
2069            .or_insert_with(|| {
2070                let server_id = post_inc(&mut self.next_language_server_id);
2071                let language_server = self.languages.start_language_server(
2072                    server_id,
2073                    language.clone(),
2074                    worktree_path,
2075                    self.client.http_client(),
2076                    cx,
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    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
2410        let server_name = adapter.name();
2411        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2412        cx.spawn_weak(|this, mut cx| async move {
2413            let (original_root_path, orphaned_worktrees) = stop.await;
2414            if let Some(this) = this.upgrade(&cx) {
2415                this.update(&mut cx, |this, cx| {
2416                    // Attempt to restart using original server path. Fallback to passed in
2417                    // path if we could not retrieve the root path
2418                    let root_path = original_root_path
2419                        .map(|path_buf| Arc::from(path_buf.as_path()))
2420                        .unwrap_or(fallback_path);
2421
2422                    this.start_language_server(worktree_id, root_path, language, cx);
2423
2424                    // Lookup new server id and set it for each of the orphaned worktrees
2425                    if let Some(new_server_id) = this
2426                        .language_server_ids
2427                        .get(&(worktree_id, server_name.clone()))
2428                        .cloned()
2429                    {
2430                        for orphaned_worktree in orphaned_worktrees {
2431                            this.language_server_ids.insert(
2432                                (orphaned_worktree, server_name.clone()),
2433                                new_server_id.clone(),
2434                            );
2435                        }
2436                    }
2437                });
2438            }
2439        })
2440        .detach();
2441    }
2442
2443    fn on_lsp_diagnostics_published(
2444        &mut self,
2445        server_id: usize,
2446        mut params: lsp::PublishDiagnosticsParams,
2447        adapter: &Arc<dyn LspAdapter>,
2448        cx: &mut ModelContext<Self>,
2449    ) {
2450        adapter.process_diagnostics(&mut params);
2451        self.update_diagnostics(
2452            server_id,
2453            params,
2454            adapter.disk_based_diagnostic_sources(),
2455            cx,
2456        )
2457        .log_err();
2458    }
2459
2460    fn on_lsp_progress(
2461        &mut self,
2462        progress: lsp::ProgressParams,
2463        server_id: usize,
2464        disk_based_diagnostics_progress_token: Option<&str>,
2465        cx: &mut ModelContext<Self>,
2466    ) {
2467        let token = match progress.token {
2468            lsp::NumberOrString::String(token) => token,
2469            lsp::NumberOrString::Number(token) => {
2470                log::info!("skipping numeric progress token {}", token);
2471                return;
2472            }
2473        };
2474        let progress = match progress.value {
2475            lsp::ProgressParamsValue::WorkDone(value) => value,
2476        };
2477        let language_server_status =
2478            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2479                status
2480            } else {
2481                return;
2482            };
2483
2484        if !language_server_status.progress_tokens.contains(&token) {
2485            return;
2486        }
2487
2488        match progress {
2489            lsp::WorkDoneProgress::Begin(report) => {
2490                if Some(token.as_str()) == disk_based_diagnostics_progress_token {
2491                    language_server_status.has_pending_diagnostic_updates = true;
2492                    self.disk_based_diagnostics_started(server_id, cx);
2493                    self.broadcast_language_server_update(
2494                        server_id,
2495                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2496                            proto::LspDiskBasedDiagnosticsUpdating {},
2497                        ),
2498                    );
2499                } else {
2500                    self.on_lsp_work_start(
2501                        server_id,
2502                        token.clone(),
2503                        LanguageServerProgress {
2504                            message: report.message.clone(),
2505                            percentage: report.percentage.map(|p| p as usize),
2506                            last_update_at: Instant::now(),
2507                        },
2508                        cx,
2509                    );
2510                    self.broadcast_language_server_update(
2511                        server_id,
2512                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2513                            token,
2514                            message: report.message,
2515                            percentage: report.percentage.map(|p| p as u32),
2516                        }),
2517                    );
2518                }
2519            }
2520            lsp::WorkDoneProgress::Report(report) => {
2521                if Some(token.as_str()) != disk_based_diagnostics_progress_token {
2522                    self.on_lsp_work_progress(
2523                        server_id,
2524                        token.clone(),
2525                        LanguageServerProgress {
2526                            message: report.message.clone(),
2527                            percentage: report.percentage.map(|p| p as usize),
2528                            last_update_at: Instant::now(),
2529                        },
2530                        cx,
2531                    );
2532                    self.broadcast_language_server_update(
2533                        server_id,
2534                        proto::update_language_server::Variant::WorkProgress(
2535                            proto::LspWorkProgress {
2536                                token,
2537                                message: report.message,
2538                                percentage: report.percentage.map(|p| p as u32),
2539                            },
2540                        ),
2541                    );
2542                }
2543            }
2544            lsp::WorkDoneProgress::End(_) => {
2545                language_server_status.progress_tokens.remove(&token);
2546
2547                if Some(token.as_str()) == disk_based_diagnostics_progress_token {
2548                    language_server_status.has_pending_diagnostic_updates = false;
2549                    self.disk_based_diagnostics_finished(server_id, cx);
2550                    self.broadcast_language_server_update(
2551                        server_id,
2552                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2553                            proto::LspDiskBasedDiagnosticsUpdated {},
2554                        ),
2555                    );
2556                } else {
2557                    self.on_lsp_work_end(server_id, token.clone(), cx);
2558                    self.broadcast_language_server_update(
2559                        server_id,
2560                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2561                            token,
2562                        }),
2563                    );
2564                }
2565            }
2566        }
2567    }
2568
2569    fn on_lsp_work_start(
2570        &mut self,
2571        language_server_id: usize,
2572        token: String,
2573        progress: LanguageServerProgress,
2574        cx: &mut ModelContext<Self>,
2575    ) {
2576        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2577            status.pending_work.insert(token, progress);
2578            cx.notify();
2579        }
2580    }
2581
2582    fn on_lsp_work_progress(
2583        &mut self,
2584        language_server_id: usize,
2585        token: String,
2586        progress: LanguageServerProgress,
2587        cx: &mut ModelContext<Self>,
2588    ) {
2589        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2590            let entry = status
2591                .pending_work
2592                .entry(token)
2593                .or_insert(LanguageServerProgress {
2594                    message: Default::default(),
2595                    percentage: Default::default(),
2596                    last_update_at: progress.last_update_at,
2597                });
2598            if progress.message.is_some() {
2599                entry.message = progress.message;
2600            }
2601            if progress.percentage.is_some() {
2602                entry.percentage = progress.percentage;
2603            }
2604            entry.last_update_at = progress.last_update_at;
2605            cx.notify();
2606        }
2607    }
2608
2609    fn on_lsp_work_end(
2610        &mut self,
2611        language_server_id: usize,
2612        token: String,
2613        cx: &mut ModelContext<Self>,
2614    ) {
2615        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2616            status.pending_work.remove(&token);
2617            cx.notify();
2618        }
2619    }
2620
2621    async fn on_lsp_workspace_edit(
2622        this: WeakModelHandle<Self>,
2623        params: lsp::ApplyWorkspaceEditParams,
2624        server_id: usize,
2625        adapter: Arc<dyn LspAdapter>,
2626        language_server: Arc<LanguageServer>,
2627        mut cx: AsyncAppContext,
2628    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2629        let this = this
2630            .upgrade(&cx)
2631            .ok_or_else(|| anyhow!("project project closed"))?;
2632        let transaction = Self::deserialize_workspace_edit(
2633            this.clone(),
2634            params.edit,
2635            true,
2636            adapter.clone(),
2637            language_server.clone(),
2638            &mut cx,
2639        )
2640        .await
2641        .log_err();
2642        this.update(&mut cx, |this, _| {
2643            if let Some(transaction) = transaction {
2644                this.last_workspace_edits_by_language_server
2645                    .insert(server_id, transaction);
2646            }
2647        });
2648        Ok(lsp::ApplyWorkspaceEditResponse {
2649            applied: true,
2650            failed_change: None,
2651            failure_reason: None,
2652        })
2653    }
2654
2655    fn broadcast_language_server_update(
2656        &self,
2657        language_server_id: usize,
2658        event: proto::update_language_server::Variant,
2659    ) {
2660        if let Some(project_id) = self.shared_remote_id() {
2661            self.client
2662                .send(proto::UpdateLanguageServer {
2663                    project_id,
2664                    language_server_id: language_server_id as u64,
2665                    variant: Some(event),
2666                })
2667                .log_err();
2668        }
2669    }
2670
2671    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2672        for server_state in self.language_servers.values() {
2673            if let LanguageServerState::Running { server, .. } = server_state {
2674                server
2675                    .notify::<lsp::notification::DidChangeConfiguration>(
2676                        lsp::DidChangeConfigurationParams {
2677                            settings: settings.clone(),
2678                        },
2679                    )
2680                    .ok();
2681            }
2682        }
2683        *self.language_server_settings.lock() = settings;
2684    }
2685
2686    pub fn language_server_statuses(
2687        &self,
2688    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2689        self.language_server_statuses.values()
2690    }
2691
2692    pub fn update_diagnostics(
2693        &mut self,
2694        language_server_id: usize,
2695        params: lsp::PublishDiagnosticsParams,
2696        disk_based_sources: &[&str],
2697        cx: &mut ModelContext<Self>,
2698    ) -> Result<()> {
2699        let abs_path = params
2700            .uri
2701            .to_file_path()
2702            .map_err(|_| anyhow!("URI is not a file"))?;
2703        let mut diagnostics = Vec::default();
2704        let mut primary_diagnostic_group_ids = HashMap::default();
2705        let mut sources_by_group_id = HashMap::default();
2706        let mut supporting_diagnostics = HashMap::default();
2707        for diagnostic in &params.diagnostics {
2708            let source = diagnostic.source.as_ref();
2709            let code = diagnostic.code.as_ref().map(|code| match code {
2710                lsp::NumberOrString::Number(code) => code.to_string(),
2711                lsp::NumberOrString::String(code) => code.clone(),
2712            });
2713            let range = range_from_lsp(diagnostic.range);
2714            let is_supporting = diagnostic
2715                .related_information
2716                .as_ref()
2717                .map_or(false, |infos| {
2718                    infos.iter().any(|info| {
2719                        primary_diagnostic_group_ids.contains_key(&(
2720                            source,
2721                            code.clone(),
2722                            range_from_lsp(info.location.range),
2723                        ))
2724                    })
2725                });
2726
2727            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2728                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2729            });
2730
2731            if is_supporting {
2732                supporting_diagnostics.insert(
2733                    (source, code.clone(), range),
2734                    (diagnostic.severity, is_unnecessary),
2735                );
2736            } else {
2737                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2738                let is_disk_based = source.map_or(false, |source| {
2739                    disk_based_sources.contains(&source.as_str())
2740                });
2741
2742                sources_by_group_id.insert(group_id, source);
2743                primary_diagnostic_group_ids
2744                    .insert((source, code.clone(), range.clone()), group_id);
2745
2746                diagnostics.push(DiagnosticEntry {
2747                    range,
2748                    diagnostic: Diagnostic {
2749                        code: code.clone(),
2750                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2751                        message: diagnostic.message.clone(),
2752                        group_id,
2753                        is_primary: true,
2754                        is_valid: true,
2755                        is_disk_based,
2756                        is_unnecessary,
2757                    },
2758                });
2759                if let Some(infos) = &diagnostic.related_information {
2760                    for info in infos {
2761                        if info.location.uri == params.uri && !info.message.is_empty() {
2762                            let range = range_from_lsp(info.location.range);
2763                            diagnostics.push(DiagnosticEntry {
2764                                range,
2765                                diagnostic: Diagnostic {
2766                                    code: code.clone(),
2767                                    severity: DiagnosticSeverity::INFORMATION,
2768                                    message: info.message.clone(),
2769                                    group_id,
2770                                    is_primary: false,
2771                                    is_valid: true,
2772                                    is_disk_based,
2773                                    is_unnecessary: false,
2774                                },
2775                            });
2776                        }
2777                    }
2778                }
2779            }
2780        }
2781
2782        for entry in &mut diagnostics {
2783            let diagnostic = &mut entry.diagnostic;
2784            if !diagnostic.is_primary {
2785                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2786                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2787                    source,
2788                    diagnostic.code.clone(),
2789                    entry.range.clone(),
2790                )) {
2791                    if let Some(severity) = severity {
2792                        diagnostic.severity = severity;
2793                    }
2794                    diagnostic.is_unnecessary = is_unnecessary;
2795                }
2796            }
2797        }
2798
2799        self.update_diagnostic_entries(
2800            language_server_id,
2801            abs_path,
2802            params.version,
2803            diagnostics,
2804            cx,
2805        )?;
2806        Ok(())
2807    }
2808
2809    pub fn update_diagnostic_entries(
2810        &mut self,
2811        language_server_id: usize,
2812        abs_path: PathBuf,
2813        version: Option<i32>,
2814        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2815        cx: &mut ModelContext<Project>,
2816    ) -> Result<(), anyhow::Error> {
2817        let (worktree, relative_path) = self
2818            .find_local_worktree(&abs_path, cx)
2819            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2820
2821        let project_path = ProjectPath {
2822            worktree_id: worktree.read(cx).id(),
2823            path: relative_path.into(),
2824        };
2825        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2826            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2827        }
2828
2829        let updated = worktree.update(cx, |worktree, cx| {
2830            worktree
2831                .as_local_mut()
2832                .ok_or_else(|| anyhow!("not a local worktree"))?
2833                .update_diagnostics(
2834                    language_server_id,
2835                    project_path.path.clone(),
2836                    diagnostics,
2837                    cx,
2838                )
2839        })?;
2840        if updated {
2841            cx.emit(Event::DiagnosticsUpdated {
2842                language_server_id,
2843                path: project_path,
2844            });
2845        }
2846        Ok(())
2847    }
2848
2849    fn update_buffer_diagnostics(
2850        &mut self,
2851        buffer: &ModelHandle<Buffer>,
2852        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2853        version: Option<i32>,
2854        cx: &mut ModelContext<Self>,
2855    ) -> Result<()> {
2856        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2857            Ordering::Equal
2858                .then_with(|| b.is_primary.cmp(&a.is_primary))
2859                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2860                .then_with(|| a.severity.cmp(&b.severity))
2861                .then_with(|| a.message.cmp(&b.message))
2862        }
2863
2864        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2865
2866        diagnostics.sort_unstable_by(|a, b| {
2867            Ordering::Equal
2868                .then_with(|| a.range.start.cmp(&b.range.start))
2869                .then_with(|| b.range.end.cmp(&a.range.end))
2870                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2871        });
2872
2873        let mut sanitized_diagnostics = Vec::new();
2874        let edits_since_save = Patch::new(
2875            snapshot
2876                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2877                .collect(),
2878        );
2879        for entry in diagnostics {
2880            let start;
2881            let end;
2882            if entry.diagnostic.is_disk_based {
2883                // Some diagnostics are based on files on disk instead of buffers'
2884                // current contents. Adjust these diagnostics' ranges to reflect
2885                // any unsaved edits.
2886                start = edits_since_save.old_to_new(entry.range.start);
2887                end = edits_since_save.old_to_new(entry.range.end);
2888            } else {
2889                start = entry.range.start;
2890                end = entry.range.end;
2891            }
2892
2893            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2894                ..snapshot.clip_point_utf16(end, Bias::Right);
2895
2896            // Expand empty ranges by one character
2897            if range.start == range.end {
2898                range.end.column += 1;
2899                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2900                if range.start == range.end && range.end.column > 0 {
2901                    range.start.column -= 1;
2902                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2903                }
2904            }
2905
2906            sanitized_diagnostics.push(DiagnosticEntry {
2907                range,
2908                diagnostic: entry.diagnostic,
2909            });
2910        }
2911        drop(edits_since_save);
2912
2913        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2914        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2915        Ok(())
2916    }
2917
2918    pub fn reload_buffers(
2919        &self,
2920        buffers: HashSet<ModelHandle<Buffer>>,
2921        push_to_history: bool,
2922        cx: &mut ModelContext<Self>,
2923    ) -> Task<Result<ProjectTransaction>> {
2924        let mut local_buffers = Vec::new();
2925        let mut remote_buffers = None;
2926        for buffer_handle in buffers {
2927            let buffer = buffer_handle.read(cx);
2928            if buffer.is_dirty() {
2929                if let Some(file) = File::from_dyn(buffer.file()) {
2930                    if file.is_local() {
2931                        local_buffers.push(buffer_handle);
2932                    } else {
2933                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2934                    }
2935                }
2936            }
2937        }
2938
2939        let remote_buffers = self.remote_id().zip(remote_buffers);
2940        let client = self.client.clone();
2941
2942        cx.spawn(|this, mut cx| async move {
2943            let mut project_transaction = ProjectTransaction::default();
2944
2945            if let Some((project_id, remote_buffers)) = remote_buffers {
2946                let response = client
2947                    .request(proto::ReloadBuffers {
2948                        project_id,
2949                        buffer_ids: remote_buffers
2950                            .iter()
2951                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2952                            .collect(),
2953                    })
2954                    .await?
2955                    .transaction
2956                    .ok_or_else(|| anyhow!("missing transaction"))?;
2957                project_transaction = this
2958                    .update(&mut cx, |this, cx| {
2959                        this.deserialize_project_transaction(response, push_to_history, cx)
2960                    })
2961                    .await?;
2962            }
2963
2964            for buffer in local_buffers {
2965                let transaction = buffer
2966                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2967                    .await?;
2968                buffer.update(&mut cx, |buffer, cx| {
2969                    if let Some(transaction) = transaction {
2970                        if !push_to_history {
2971                            buffer.forget_transaction(transaction.id);
2972                        }
2973                        project_transaction.0.insert(cx.handle(), transaction);
2974                    }
2975                });
2976            }
2977
2978            Ok(project_transaction)
2979        })
2980    }
2981
2982    pub fn format(
2983        &self,
2984        buffers: HashSet<ModelHandle<Buffer>>,
2985        push_to_history: bool,
2986        cx: &mut ModelContext<Project>,
2987    ) -> Task<Result<ProjectTransaction>> {
2988        let mut local_buffers = Vec::new();
2989        let mut remote_buffers = None;
2990        for buffer_handle in buffers {
2991            let buffer = buffer_handle.read(cx);
2992            if let Some(file) = File::from_dyn(buffer.file()) {
2993                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2994                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2995                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2996                    }
2997                } else {
2998                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2999                }
3000            } else {
3001                return Task::ready(Ok(Default::default()));
3002            }
3003        }
3004
3005        let remote_buffers = self.remote_id().zip(remote_buffers);
3006        let client = self.client.clone();
3007
3008        cx.spawn(|this, mut cx| async move {
3009            let mut project_transaction = ProjectTransaction::default();
3010
3011            if let Some((project_id, remote_buffers)) = remote_buffers {
3012                let response = client
3013                    .request(proto::FormatBuffers {
3014                        project_id,
3015                        buffer_ids: remote_buffers
3016                            .iter()
3017                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3018                            .collect(),
3019                    })
3020                    .await?
3021                    .transaction
3022                    .ok_or_else(|| anyhow!("missing transaction"))?;
3023                project_transaction = this
3024                    .update(&mut cx, |this, cx| {
3025                        this.deserialize_project_transaction(response, push_to_history, cx)
3026                    })
3027                    .await?;
3028            }
3029
3030            for (buffer, buffer_abs_path, language_server) in local_buffers {
3031                let (format_on_save, tab_size) = buffer.read_with(&cx, |buffer, cx| {
3032                    let settings = cx.global::<Settings>();
3033                    let language_name = buffer.language().map(|language| language.name());
3034                    (
3035                        settings.format_on_save(language_name.as_deref()),
3036                        settings.tab_size(language_name.as_deref()),
3037                    )
3038                });
3039
3040                let transaction = match format_on_save {
3041                    settings::FormatOnSave::Off => continue,
3042                    settings::FormatOnSave::LanguageServer => Self::format_via_lsp(
3043                        &this,
3044                        &buffer,
3045                        &buffer_abs_path,
3046                        &language_server,
3047                        tab_size,
3048                        &mut cx,
3049                    )
3050                    .await
3051                    .context("failed to format via language server")?,
3052                    settings::FormatOnSave::External { command, arguments } => {
3053                        Self::format_via_external_command(
3054                            &buffer,
3055                            &buffer_abs_path,
3056                            &command,
3057                            &arguments,
3058                            &mut cx,
3059                        )
3060                        .await
3061                        .context(format!(
3062                            "failed to format via external command {:?}",
3063                            command
3064                        ))?
3065                    }
3066                };
3067
3068                if let Some(transaction) = transaction {
3069                    if !push_to_history {
3070                        buffer.update(&mut cx, |buffer, _| {
3071                            buffer.forget_transaction(transaction.id)
3072                        });
3073                    }
3074                    project_transaction.0.insert(buffer, transaction);
3075                }
3076            }
3077
3078            Ok(project_transaction)
3079        })
3080    }
3081
3082    async fn format_via_lsp(
3083        this: &ModelHandle<Self>,
3084        buffer: &ModelHandle<Buffer>,
3085        abs_path: &Path,
3086        language_server: &Arc<LanguageServer>,
3087        tab_size: NonZeroU32,
3088        cx: &mut AsyncAppContext,
3089    ) -> Result<Option<Transaction>> {
3090        let text_document =
3091            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3092        let capabilities = &language_server.capabilities();
3093        let lsp_edits = if capabilities
3094            .document_formatting_provider
3095            .as_ref()
3096            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3097        {
3098            language_server
3099                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3100                    text_document,
3101                    options: lsp::FormattingOptions {
3102                        tab_size: tab_size.into(),
3103                        insert_spaces: true,
3104                        insert_final_newline: Some(true),
3105                        ..Default::default()
3106                    },
3107                    work_done_progress_params: Default::default(),
3108                })
3109                .await?
3110        } else if capabilities
3111            .document_range_formatting_provider
3112            .as_ref()
3113            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3114        {
3115            let buffer_start = lsp::Position::new(0, 0);
3116            let buffer_end =
3117                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3118            language_server
3119                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3120                    text_document,
3121                    range: lsp::Range::new(buffer_start, buffer_end),
3122                    options: lsp::FormattingOptions {
3123                        tab_size: tab_size.into(),
3124                        insert_spaces: true,
3125                        insert_final_newline: Some(true),
3126                        ..Default::default()
3127                    },
3128                    work_done_progress_params: Default::default(),
3129                })
3130                .await?
3131        } else {
3132            None
3133        };
3134
3135        if let Some(lsp_edits) = lsp_edits {
3136            let edits = this
3137                .update(cx, |this, cx| {
3138                    this.edits_from_lsp(&buffer, lsp_edits, None, cx)
3139                })
3140                .await?;
3141            buffer.update(cx, |buffer, cx| {
3142                buffer.finalize_last_transaction();
3143                buffer.start_transaction();
3144                for (range, text) in edits {
3145                    buffer.edit([(range, text)], cx);
3146                }
3147                if buffer.end_transaction(cx).is_some() {
3148                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
3149                    Ok(Some(transaction))
3150                } else {
3151                    Ok(None)
3152                }
3153            })
3154        } else {
3155            Ok(None)
3156        }
3157    }
3158
3159    async fn format_via_external_command(
3160        buffer: &ModelHandle<Buffer>,
3161        buffer_abs_path: &Path,
3162        command: &str,
3163        arguments: &[String],
3164        cx: &mut AsyncAppContext,
3165    ) -> Result<Option<Transaction>> {
3166        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3167            let file = File::from_dyn(buffer.file())?;
3168            let worktree = file.worktree.read(cx).as_local()?;
3169            let mut worktree_path = worktree.abs_path().to_path_buf();
3170            if worktree.root_entry()?.is_file() {
3171                worktree_path.pop();
3172            }
3173            Some(worktree_path)
3174        });
3175
3176        if let Some(working_dir_path) = working_dir_path {
3177            let mut child =
3178                smol::process::Command::new(command)
3179                    .args(arguments.iter().map(|arg| {
3180                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3181                    }))
3182                    .current_dir(&working_dir_path)
3183                    .stdin(smol::process::Stdio::piped())
3184                    .stdout(smol::process::Stdio::piped())
3185                    .stderr(smol::process::Stdio::piped())
3186                    .spawn()?;
3187            let stdin = child
3188                .stdin
3189                .as_mut()
3190                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3191            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3192            for chunk in text.chunks() {
3193                stdin.write_all(chunk.as_bytes()).await?;
3194            }
3195            stdin.flush().await?;
3196
3197            let output = child.output().await?;
3198            if !output.status.success() {
3199                return Err(anyhow!(
3200                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3201                    output.status.code(),
3202                    String::from_utf8_lossy(&output.stdout),
3203                    String::from_utf8_lossy(&output.stderr),
3204                ));
3205            }
3206
3207            let stdout = String::from_utf8(output.stdout)?;
3208            let diff = buffer
3209                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3210                .await;
3211            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3212        } else {
3213            Ok(None)
3214        }
3215    }
3216
3217    pub fn definition<T: ToPointUtf16>(
3218        &self,
3219        buffer: &ModelHandle<Buffer>,
3220        position: T,
3221        cx: &mut ModelContext<Self>,
3222    ) -> Task<Result<Vec<LocationLink>>> {
3223        let position = position.to_point_utf16(buffer.read(cx));
3224        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3225    }
3226
3227    pub fn references<T: ToPointUtf16>(
3228        &self,
3229        buffer: &ModelHandle<Buffer>,
3230        position: T,
3231        cx: &mut ModelContext<Self>,
3232    ) -> Task<Result<Vec<Location>>> {
3233        let position = position.to_point_utf16(buffer.read(cx));
3234        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3235    }
3236
3237    pub fn document_highlights<T: ToPointUtf16>(
3238        &self,
3239        buffer: &ModelHandle<Buffer>,
3240        position: T,
3241        cx: &mut ModelContext<Self>,
3242    ) -> Task<Result<Vec<DocumentHighlight>>> {
3243        let position = position.to_point_utf16(buffer.read(cx));
3244
3245        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3246    }
3247
3248    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3249        if self.is_local() {
3250            let mut requests = Vec::new();
3251            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3252                let worktree_id = *worktree_id;
3253                if let Some(worktree) = self
3254                    .worktree_for_id(worktree_id, cx)
3255                    .and_then(|worktree| worktree.read(cx).as_local())
3256                {
3257                    if let Some(LanguageServerState::Running { adapter, server }) =
3258                        self.language_servers.get(server_id)
3259                    {
3260                        let adapter = adapter.clone();
3261                        let worktree_abs_path = worktree.abs_path().clone();
3262                        requests.push(
3263                            server
3264                                .request::<lsp::request::WorkspaceSymbol>(
3265                                    lsp::WorkspaceSymbolParams {
3266                                        query: query.to_string(),
3267                                        ..Default::default()
3268                                    },
3269                                )
3270                                .log_err()
3271                                .map(move |response| {
3272                                    (
3273                                        adapter,
3274                                        worktree_id,
3275                                        worktree_abs_path,
3276                                        response.unwrap_or_default(),
3277                                    )
3278                                }),
3279                        );
3280                    }
3281                }
3282            }
3283
3284            cx.spawn_weak(|this, cx| async move {
3285                let responses = futures::future::join_all(requests).await;
3286                let this = if let Some(this) = this.upgrade(&cx) {
3287                    this
3288                } else {
3289                    return Ok(Default::default());
3290                };
3291                this.read_with(&cx, |this, cx| {
3292                    let mut symbols = Vec::new();
3293                    for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
3294                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3295                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3296                            let mut worktree_id = source_worktree_id;
3297                            let path;
3298                            if let Some((worktree, rel_path)) =
3299                                this.find_local_worktree(&abs_path, cx)
3300                            {
3301                                worktree_id = worktree.read(cx).id();
3302                                path = rel_path;
3303                            } else {
3304                                path = relativize_path(&worktree_abs_path, &abs_path);
3305                            }
3306
3307                            let label = this
3308                                .languages
3309                                .select_language(&path)
3310                                .and_then(|language| {
3311                                    language.label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
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(),
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                    this.read_with(&cx, |this, _| {
3342                        symbols.extend(
3343                            response
3344                                .symbols
3345                                .into_iter()
3346                                .filter_map(|symbol| this.deserialize_symbol(symbol).log_err()),
3347                        );
3348                    })
3349                }
3350                Ok(symbols)
3351            })
3352        } else {
3353            Task::ready(Ok(Default::default()))
3354        }
3355    }
3356
3357    pub fn open_buffer_for_symbol(
3358        &mut self,
3359        symbol: &Symbol,
3360        cx: &mut ModelContext<Self>,
3361    ) -> Task<Result<ModelHandle<Buffer>>> {
3362        if self.is_local() {
3363            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3364                symbol.source_worktree_id,
3365                symbol.language_server_name.clone(),
3366            )) {
3367                *id
3368            } else {
3369                return Task::ready(Err(anyhow!(
3370                    "language server for worktree and language not found"
3371                )));
3372            };
3373
3374            let worktree_abs_path = if let Some(worktree_abs_path) = self
3375                .worktree_for_id(symbol.worktree_id, cx)
3376                .and_then(|worktree| worktree.read(cx).as_local())
3377                .map(|local_worktree| local_worktree.abs_path())
3378            {
3379                worktree_abs_path
3380            } else {
3381                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3382            };
3383            let symbol_abs_path = worktree_abs_path.join(&symbol.path);
3384            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3385                uri
3386            } else {
3387                return Task::ready(Err(anyhow!("invalid symbol path")));
3388            };
3389
3390            self.open_local_buffer_via_lsp(
3391                symbol_uri,
3392                language_server_id,
3393                symbol.language_server_name.clone(),
3394                cx,
3395            )
3396        } else if let Some(project_id) = self.remote_id() {
3397            let request = self.client.request(proto::OpenBufferForSymbol {
3398                project_id,
3399                symbol: Some(serialize_symbol(symbol)),
3400            });
3401            cx.spawn(|this, mut cx| async move {
3402                let response = request.await?;
3403                let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
3404                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3405                    .await
3406            })
3407        } else {
3408            Task::ready(Err(anyhow!("project does not have a remote id")))
3409        }
3410    }
3411
3412    pub fn hover<T: ToPointUtf16>(
3413        &self,
3414        buffer: &ModelHandle<Buffer>,
3415        position: T,
3416        cx: &mut ModelContext<Self>,
3417    ) -> Task<Result<Option<Hover>>> {
3418        let position = position.to_point_utf16(buffer.read(cx));
3419        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3420    }
3421
3422    pub fn completions<T: ToPointUtf16>(
3423        &self,
3424        source_buffer_handle: &ModelHandle<Buffer>,
3425        position: T,
3426        cx: &mut ModelContext<Self>,
3427    ) -> Task<Result<Vec<Completion>>> {
3428        let source_buffer_handle = source_buffer_handle.clone();
3429        let source_buffer = source_buffer_handle.read(cx);
3430        let buffer_id = source_buffer.remote_id();
3431        let language = source_buffer.language().cloned();
3432        let worktree;
3433        let buffer_abs_path;
3434        if let Some(file) = File::from_dyn(source_buffer.file()) {
3435            worktree = file.worktree.clone();
3436            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3437        } else {
3438            return Task::ready(Ok(Default::default()));
3439        };
3440
3441        let position = position.to_point_utf16(source_buffer);
3442        let anchor = source_buffer.anchor_after(position);
3443
3444        if worktree.read(cx).as_local().is_some() {
3445            let buffer_abs_path = buffer_abs_path.unwrap();
3446            let lang_server =
3447                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3448                    server.clone()
3449                } else {
3450                    return Task::ready(Ok(Default::default()));
3451                };
3452
3453            cx.spawn(|_, cx| async move {
3454                let completions = lang_server
3455                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3456                        text_document_position: lsp::TextDocumentPositionParams::new(
3457                            lsp::TextDocumentIdentifier::new(
3458                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3459                            ),
3460                            point_to_lsp(position),
3461                        ),
3462                        context: Default::default(),
3463                        work_done_progress_params: Default::default(),
3464                        partial_result_params: Default::default(),
3465                    })
3466                    .await
3467                    .context("lsp completion request failed")?;
3468
3469                let completions = if let Some(completions) = completions {
3470                    match completions {
3471                        lsp::CompletionResponse::Array(completions) => completions,
3472                        lsp::CompletionResponse::List(list) => list.items,
3473                    }
3474                } else {
3475                    Default::default()
3476                };
3477
3478                source_buffer_handle.read_with(&cx, |this, _| {
3479                    let snapshot = this.snapshot();
3480                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3481                    let mut range_for_token = None;
3482                    Ok(completions
3483                        .into_iter()
3484                        .filter_map(|lsp_completion| {
3485                            // For now, we can only handle additional edits if they are returned
3486                            // when resolving the completion, not if they are present initially.
3487                            if lsp_completion
3488                                .additional_text_edits
3489                                .as_ref()
3490                                .map_or(false, |edits| !edits.is_empty())
3491                            {
3492                                return None;
3493                            }
3494
3495                            let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3496                            {
3497                                // If the language server provides a range to overwrite, then
3498                                // check that the range is valid.
3499                                Some(lsp::CompletionTextEdit::Edit(edit)) => {
3500                                    let range = range_from_lsp(edit.range);
3501                                    let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3502                                    let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3503                                    if start != range.start || end != range.end {
3504                                        log::info!("completion out of expected range");
3505                                        return None;
3506                                    }
3507                                    (
3508                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3509                                        edit.new_text.clone(),
3510                                    )
3511                                }
3512                                // If the language server does not provide a range, then infer
3513                                // the range based on the syntax tree.
3514                                None => {
3515                                    if position != clipped_position {
3516                                        log::info!("completion out of expected range");
3517                                        return None;
3518                                    }
3519                                    let Range { start, end } = range_for_token
3520                                        .get_or_insert_with(|| {
3521                                            let offset = position.to_offset(&snapshot);
3522                                            let (range, kind) = snapshot.surrounding_word(offset);
3523                                            if kind == Some(CharKind::Word) {
3524                                                range
3525                                            } else {
3526                                                offset..offset
3527                                            }
3528                                        })
3529                                        .clone();
3530                                    let text = lsp_completion
3531                                        .insert_text
3532                                        .as_ref()
3533                                        .unwrap_or(&lsp_completion.label)
3534                                        .clone();
3535                                    (
3536                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3537                                        text.clone(),
3538                                    )
3539                                }
3540                                Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3541                                    log::info!("unsupported insert/replace completion");
3542                                    return None;
3543                                }
3544                            };
3545
3546                            LineEnding::normalize(&mut new_text);
3547                            Some(Completion {
3548                                old_range,
3549                                new_text,
3550                                label: language
3551                                    .as_ref()
3552                                    .and_then(|l| l.label_for_completion(&lsp_completion))
3553                                    .unwrap_or_else(|| {
3554                                        CodeLabel::plain(
3555                                            lsp_completion.label.clone(),
3556                                            lsp_completion.filter_text.as_deref(),
3557                                        )
3558                                    }),
3559                                lsp_completion,
3560                            })
3561                        })
3562                        .collect())
3563                })
3564            })
3565        } else if let Some(project_id) = self.remote_id() {
3566            let rpc = self.client.clone();
3567            let message = proto::GetCompletions {
3568                project_id,
3569                buffer_id,
3570                position: Some(language::proto::serialize_anchor(&anchor)),
3571                version: serialize_version(&source_buffer.version()),
3572            };
3573            cx.spawn_weak(|_, mut cx| async move {
3574                let response = rpc.request(message).await?;
3575
3576                source_buffer_handle
3577                    .update(&mut cx, |buffer, _| {
3578                        buffer.wait_for_version(deserialize_version(response.version))
3579                    })
3580                    .await;
3581
3582                response
3583                    .completions
3584                    .into_iter()
3585                    .map(|completion| {
3586                        language::proto::deserialize_completion(completion, language.as_ref())
3587                    })
3588                    .collect()
3589            })
3590        } else {
3591            Task::ready(Ok(Default::default()))
3592        }
3593    }
3594
3595    pub fn apply_additional_edits_for_completion(
3596        &self,
3597        buffer_handle: ModelHandle<Buffer>,
3598        completion: Completion,
3599        push_to_history: bool,
3600        cx: &mut ModelContext<Self>,
3601    ) -> Task<Result<Option<Transaction>>> {
3602        let buffer = buffer_handle.read(cx);
3603        let buffer_id = buffer.remote_id();
3604
3605        if self.is_local() {
3606            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3607            {
3608                server.clone()
3609            } else {
3610                return Task::ready(Ok(Default::default()));
3611            };
3612
3613            cx.spawn(|this, mut cx| async move {
3614                let resolved_completion = lang_server
3615                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3616                    .await?;
3617                if let Some(edits) = resolved_completion.additional_text_edits {
3618                    let edits = this
3619                        .update(&mut cx, |this, cx| {
3620                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3621                        })
3622                        .await?;
3623                    buffer_handle.update(&mut cx, |buffer, cx| {
3624                        buffer.finalize_last_transaction();
3625                        buffer.start_transaction();
3626                        for (range, text) in edits {
3627                            buffer.edit([(range, text)], cx);
3628                        }
3629                        let transaction = if buffer.end_transaction(cx).is_some() {
3630                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3631                            if !push_to_history {
3632                                buffer.forget_transaction(transaction.id);
3633                            }
3634                            Some(transaction)
3635                        } else {
3636                            None
3637                        };
3638                        Ok(transaction)
3639                    })
3640                } else {
3641                    Ok(None)
3642                }
3643            })
3644        } else if let Some(project_id) = self.remote_id() {
3645            let client = self.client.clone();
3646            cx.spawn(|_, mut cx| async move {
3647                let response = client
3648                    .request(proto::ApplyCompletionAdditionalEdits {
3649                        project_id,
3650                        buffer_id,
3651                        completion: Some(language::proto::serialize_completion(&completion)),
3652                    })
3653                    .await?;
3654
3655                if let Some(transaction) = response.transaction {
3656                    let transaction = language::proto::deserialize_transaction(transaction)?;
3657                    buffer_handle
3658                        .update(&mut cx, |buffer, _| {
3659                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3660                        })
3661                        .await;
3662                    if push_to_history {
3663                        buffer_handle.update(&mut cx, |buffer, _| {
3664                            buffer.push_transaction(transaction.clone(), Instant::now());
3665                        });
3666                    }
3667                    Ok(Some(transaction))
3668                } else {
3669                    Ok(None)
3670                }
3671            })
3672        } else {
3673            Task::ready(Err(anyhow!("project does not have a remote id")))
3674        }
3675    }
3676
3677    pub fn code_actions<T: Clone + ToOffset>(
3678        &self,
3679        buffer_handle: &ModelHandle<Buffer>,
3680        range: Range<T>,
3681        cx: &mut ModelContext<Self>,
3682    ) -> Task<Result<Vec<CodeAction>>> {
3683        let buffer_handle = buffer_handle.clone();
3684        let buffer = buffer_handle.read(cx);
3685        let snapshot = buffer.snapshot();
3686        let relevant_diagnostics = snapshot
3687            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3688            .map(|entry| entry.to_lsp_diagnostic_stub())
3689            .collect();
3690        let buffer_id = buffer.remote_id();
3691        let worktree;
3692        let buffer_abs_path;
3693        if let Some(file) = File::from_dyn(buffer.file()) {
3694            worktree = file.worktree.clone();
3695            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3696        } else {
3697            return Task::ready(Ok(Default::default()));
3698        };
3699        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3700
3701        if worktree.read(cx).as_local().is_some() {
3702            let buffer_abs_path = buffer_abs_path.unwrap();
3703            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3704            {
3705                server.clone()
3706            } else {
3707                return Task::ready(Ok(Default::default()));
3708            };
3709
3710            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3711            cx.foreground().spawn(async move {
3712                if !lang_server.capabilities().code_action_provider.is_some() {
3713                    return Ok(Default::default());
3714                }
3715
3716                Ok(lang_server
3717                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3718                        text_document: lsp::TextDocumentIdentifier::new(
3719                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3720                        ),
3721                        range: lsp_range,
3722                        work_done_progress_params: Default::default(),
3723                        partial_result_params: Default::default(),
3724                        context: lsp::CodeActionContext {
3725                            diagnostics: relevant_diagnostics,
3726                            only: Some(vec![
3727                                lsp::CodeActionKind::QUICKFIX,
3728                                lsp::CodeActionKind::REFACTOR,
3729                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3730                                lsp::CodeActionKind::SOURCE,
3731                            ]),
3732                        },
3733                    })
3734                    .await?
3735                    .unwrap_or_default()
3736                    .into_iter()
3737                    .filter_map(|entry| {
3738                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3739                            Some(CodeAction {
3740                                range: range.clone(),
3741                                lsp_action,
3742                            })
3743                        } else {
3744                            None
3745                        }
3746                    })
3747                    .collect())
3748            })
3749        } else if let Some(project_id) = self.remote_id() {
3750            let rpc = self.client.clone();
3751            let version = buffer.version();
3752            cx.spawn_weak(|_, mut cx| async move {
3753                let response = rpc
3754                    .request(proto::GetCodeActions {
3755                        project_id,
3756                        buffer_id,
3757                        start: Some(language::proto::serialize_anchor(&range.start)),
3758                        end: Some(language::proto::serialize_anchor(&range.end)),
3759                        version: serialize_version(&version),
3760                    })
3761                    .await?;
3762
3763                buffer_handle
3764                    .update(&mut cx, |buffer, _| {
3765                        buffer.wait_for_version(deserialize_version(response.version))
3766                    })
3767                    .await;
3768
3769                response
3770                    .actions
3771                    .into_iter()
3772                    .map(language::proto::deserialize_code_action)
3773                    .collect()
3774            })
3775        } else {
3776            Task::ready(Ok(Default::default()))
3777        }
3778    }
3779
3780    pub fn apply_code_action(
3781        &self,
3782        buffer_handle: ModelHandle<Buffer>,
3783        mut action: CodeAction,
3784        push_to_history: bool,
3785        cx: &mut ModelContext<Self>,
3786    ) -> Task<Result<ProjectTransaction>> {
3787        if self.is_local() {
3788            let buffer = buffer_handle.read(cx);
3789            let (lsp_adapter, lang_server) =
3790                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3791                    (adapter.clone(), server.clone())
3792                } else {
3793                    return Task::ready(Ok(Default::default()));
3794                };
3795            let range = action.range.to_point_utf16(buffer);
3796
3797            cx.spawn(|this, mut cx| async move {
3798                if let Some(lsp_range) = action
3799                    .lsp_action
3800                    .data
3801                    .as_mut()
3802                    .and_then(|d| d.get_mut("codeActionParams"))
3803                    .and_then(|d| d.get_mut("range"))
3804                {
3805                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3806                    action.lsp_action = lang_server
3807                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3808                        .await?;
3809                } else {
3810                    let actions = this
3811                        .update(&mut cx, |this, cx| {
3812                            this.code_actions(&buffer_handle, action.range, cx)
3813                        })
3814                        .await?;
3815                    action.lsp_action = actions
3816                        .into_iter()
3817                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3818                        .ok_or_else(|| anyhow!("code action is outdated"))?
3819                        .lsp_action;
3820                }
3821
3822                if let Some(edit) = action.lsp_action.edit {
3823                    if edit.changes.is_some() || edit.document_changes.is_some() {
3824                        return Self::deserialize_workspace_edit(
3825                            this,
3826                            edit,
3827                            push_to_history,
3828                            lsp_adapter.clone(),
3829                            lang_server.clone(),
3830                            &mut cx,
3831                        )
3832                        .await;
3833                    }
3834                }
3835
3836                if let Some(command) = action.lsp_action.command {
3837                    this.update(&mut cx, |this, _| {
3838                        this.last_workspace_edits_by_language_server
3839                            .remove(&lang_server.server_id());
3840                    });
3841                    lang_server
3842                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3843                            command: command.command,
3844                            arguments: command.arguments.unwrap_or_default(),
3845                            ..Default::default()
3846                        })
3847                        .await?;
3848                    return Ok(this.update(&mut cx, |this, _| {
3849                        this.last_workspace_edits_by_language_server
3850                            .remove(&lang_server.server_id())
3851                            .unwrap_or_default()
3852                    }));
3853                }
3854
3855                Ok(ProjectTransaction::default())
3856            })
3857        } else if let Some(project_id) = self.remote_id() {
3858            let client = self.client.clone();
3859            let request = proto::ApplyCodeAction {
3860                project_id,
3861                buffer_id: buffer_handle.read(cx).remote_id(),
3862                action: Some(language::proto::serialize_code_action(&action)),
3863            };
3864            cx.spawn(|this, mut cx| async move {
3865                let response = client
3866                    .request(request)
3867                    .await?
3868                    .transaction
3869                    .ok_or_else(|| anyhow!("missing transaction"))?;
3870                this.update(&mut cx, |this, cx| {
3871                    this.deserialize_project_transaction(response, push_to_history, cx)
3872                })
3873                .await
3874            })
3875        } else {
3876            Task::ready(Err(anyhow!("project does not have a remote id")))
3877        }
3878    }
3879
3880    async fn deserialize_workspace_edit(
3881        this: ModelHandle<Self>,
3882        edit: lsp::WorkspaceEdit,
3883        push_to_history: bool,
3884        lsp_adapter: Arc<dyn LspAdapter>,
3885        language_server: Arc<LanguageServer>,
3886        cx: &mut AsyncAppContext,
3887    ) -> Result<ProjectTransaction> {
3888        let fs = this.read_with(cx, |this, _| this.fs.clone());
3889        let mut operations = Vec::new();
3890        if let Some(document_changes) = edit.document_changes {
3891            match document_changes {
3892                lsp::DocumentChanges::Edits(edits) => {
3893                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3894                }
3895                lsp::DocumentChanges::Operations(ops) => operations = ops,
3896            }
3897        } else if let Some(changes) = edit.changes {
3898            operations.extend(changes.into_iter().map(|(uri, edits)| {
3899                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3900                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3901                        uri,
3902                        version: None,
3903                    },
3904                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3905                })
3906            }));
3907        }
3908
3909        let mut project_transaction = ProjectTransaction::default();
3910        for operation in operations {
3911            match operation {
3912                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3913                    let abs_path = op
3914                        .uri
3915                        .to_file_path()
3916                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3917
3918                    if let Some(parent_path) = abs_path.parent() {
3919                        fs.create_dir(parent_path).await?;
3920                    }
3921                    if abs_path.ends_with("/") {
3922                        fs.create_dir(&abs_path).await?;
3923                    } else {
3924                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3925                            .await?;
3926                    }
3927                }
3928                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3929                    let source_abs_path = op
3930                        .old_uri
3931                        .to_file_path()
3932                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3933                    let target_abs_path = op
3934                        .new_uri
3935                        .to_file_path()
3936                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3937                    fs.rename(
3938                        &source_abs_path,
3939                        &target_abs_path,
3940                        op.options.map(Into::into).unwrap_or_default(),
3941                    )
3942                    .await?;
3943                }
3944                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3945                    let abs_path = op
3946                        .uri
3947                        .to_file_path()
3948                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3949                    let options = op.options.map(Into::into).unwrap_or_default();
3950                    if abs_path.ends_with("/") {
3951                        fs.remove_dir(&abs_path, options).await?;
3952                    } else {
3953                        fs.remove_file(&abs_path, options).await?;
3954                    }
3955                }
3956                lsp::DocumentChangeOperation::Edit(op) => {
3957                    let buffer_to_edit = this
3958                        .update(cx, |this, cx| {
3959                            this.open_local_buffer_via_lsp(
3960                                op.text_document.uri,
3961                                language_server.server_id(),
3962                                lsp_adapter.name(),
3963                                cx,
3964                            )
3965                        })
3966                        .await?;
3967
3968                    let edits = this
3969                        .update(cx, |this, cx| {
3970                            let edits = op.edits.into_iter().map(|edit| match edit {
3971                                lsp::OneOf::Left(edit) => edit,
3972                                lsp::OneOf::Right(edit) => edit.text_edit,
3973                            });
3974                            this.edits_from_lsp(
3975                                &buffer_to_edit,
3976                                edits,
3977                                op.text_document.version,
3978                                cx,
3979                            )
3980                        })
3981                        .await?;
3982
3983                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3984                        buffer.finalize_last_transaction();
3985                        buffer.start_transaction();
3986                        for (range, text) in edits {
3987                            buffer.edit([(range, text)], cx);
3988                        }
3989                        let transaction = if buffer.end_transaction(cx).is_some() {
3990                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3991                            if !push_to_history {
3992                                buffer.forget_transaction(transaction.id);
3993                            }
3994                            Some(transaction)
3995                        } else {
3996                            None
3997                        };
3998
3999                        transaction
4000                    });
4001                    if let Some(transaction) = transaction {
4002                        project_transaction.0.insert(buffer_to_edit, transaction);
4003                    }
4004                }
4005            }
4006        }
4007
4008        Ok(project_transaction)
4009    }
4010
4011    pub fn prepare_rename<T: ToPointUtf16>(
4012        &self,
4013        buffer: ModelHandle<Buffer>,
4014        position: T,
4015        cx: &mut ModelContext<Self>,
4016    ) -> Task<Result<Option<Range<Anchor>>>> {
4017        let position = position.to_point_utf16(buffer.read(cx));
4018        self.request_lsp(buffer, PrepareRename { position }, cx)
4019    }
4020
4021    pub fn perform_rename<T: ToPointUtf16>(
4022        &self,
4023        buffer: ModelHandle<Buffer>,
4024        position: T,
4025        new_name: String,
4026        push_to_history: bool,
4027        cx: &mut ModelContext<Self>,
4028    ) -> Task<Result<ProjectTransaction>> {
4029        let position = position.to_point_utf16(buffer.read(cx));
4030        self.request_lsp(
4031            buffer,
4032            PerformRename {
4033                position,
4034                new_name,
4035                push_to_history,
4036            },
4037            cx,
4038        )
4039    }
4040
4041    pub fn search(
4042        &self,
4043        query: SearchQuery,
4044        cx: &mut ModelContext<Self>,
4045    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4046        if self.is_local() {
4047            let snapshots = self
4048                .visible_worktrees(cx)
4049                .filter_map(|tree| {
4050                    let tree = tree.read(cx).as_local()?;
4051                    Some(tree.snapshot())
4052                })
4053                .collect::<Vec<_>>();
4054
4055            let background = cx.background().clone();
4056            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4057            if path_count == 0 {
4058                return Task::ready(Ok(Default::default()));
4059            }
4060            let workers = background.num_cpus().min(path_count);
4061            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4062            cx.background()
4063                .spawn({
4064                    let fs = self.fs.clone();
4065                    let background = cx.background().clone();
4066                    let query = query.clone();
4067                    async move {
4068                        let fs = &fs;
4069                        let query = &query;
4070                        let matching_paths_tx = &matching_paths_tx;
4071                        let paths_per_worker = (path_count + workers - 1) / workers;
4072                        let snapshots = &snapshots;
4073                        background
4074                            .scoped(|scope| {
4075                                for worker_ix in 0..workers {
4076                                    let worker_start_ix = worker_ix * paths_per_worker;
4077                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4078                                    scope.spawn(async move {
4079                                        let mut snapshot_start_ix = 0;
4080                                        let mut abs_path = PathBuf::new();
4081                                        for snapshot in snapshots {
4082                                            let snapshot_end_ix =
4083                                                snapshot_start_ix + snapshot.visible_file_count();
4084                                            if worker_end_ix <= snapshot_start_ix {
4085                                                break;
4086                                            } else if worker_start_ix > snapshot_end_ix {
4087                                                snapshot_start_ix = snapshot_end_ix;
4088                                                continue;
4089                                            } else {
4090                                                let start_in_snapshot = worker_start_ix
4091                                                    .saturating_sub(snapshot_start_ix);
4092                                                let end_in_snapshot =
4093                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4094                                                        - snapshot_start_ix;
4095
4096                                                for entry in snapshot
4097                                                    .files(false, start_in_snapshot)
4098                                                    .take(end_in_snapshot - start_in_snapshot)
4099                                                {
4100                                                    if matching_paths_tx.is_closed() {
4101                                                        break;
4102                                                    }
4103
4104                                                    abs_path.clear();
4105                                                    abs_path.push(&snapshot.abs_path());
4106                                                    abs_path.push(&entry.path);
4107                                                    let matches = if let Some(file) =
4108                                                        fs.open_sync(&abs_path).await.log_err()
4109                                                    {
4110                                                        query.detect(file).unwrap_or(false)
4111                                                    } else {
4112                                                        false
4113                                                    };
4114
4115                                                    if matches {
4116                                                        let project_path =
4117                                                            (snapshot.id(), entry.path.clone());
4118                                                        if matching_paths_tx
4119                                                            .send(project_path)
4120                                                            .await
4121                                                            .is_err()
4122                                                        {
4123                                                            break;
4124                                                        }
4125                                                    }
4126                                                }
4127
4128                                                snapshot_start_ix = snapshot_end_ix;
4129                                            }
4130                                        }
4131                                    });
4132                                }
4133                            })
4134                            .await;
4135                    }
4136                })
4137                .detach();
4138
4139            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4140            let open_buffers = self
4141                .opened_buffers
4142                .values()
4143                .filter_map(|b| b.upgrade(cx))
4144                .collect::<HashSet<_>>();
4145            cx.spawn(|this, cx| async move {
4146                for buffer in &open_buffers {
4147                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4148                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4149                }
4150
4151                let open_buffers = Rc::new(RefCell::new(open_buffers));
4152                while let Some(project_path) = matching_paths_rx.next().await {
4153                    if buffers_tx.is_closed() {
4154                        break;
4155                    }
4156
4157                    let this = this.clone();
4158                    let open_buffers = open_buffers.clone();
4159                    let buffers_tx = buffers_tx.clone();
4160                    cx.spawn(|mut cx| async move {
4161                        if let Some(buffer) = this
4162                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4163                            .await
4164                            .log_err()
4165                        {
4166                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4167                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4168                                buffers_tx.send((buffer, snapshot)).await?;
4169                            }
4170                        }
4171
4172                        Ok::<_, anyhow::Error>(())
4173                    })
4174                    .detach();
4175                }
4176
4177                Ok::<_, anyhow::Error>(())
4178            })
4179            .detach_and_log_err(cx);
4180
4181            let background = cx.background().clone();
4182            cx.background().spawn(async move {
4183                let query = &query;
4184                let mut matched_buffers = Vec::new();
4185                for _ in 0..workers {
4186                    matched_buffers.push(HashMap::default());
4187                }
4188                background
4189                    .scoped(|scope| {
4190                        for worker_matched_buffers in matched_buffers.iter_mut() {
4191                            let mut buffers_rx = buffers_rx.clone();
4192                            scope.spawn(async move {
4193                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4194                                    let buffer_matches = query
4195                                        .search(snapshot.as_rope())
4196                                        .await
4197                                        .iter()
4198                                        .map(|range| {
4199                                            snapshot.anchor_before(range.start)
4200                                                ..snapshot.anchor_after(range.end)
4201                                        })
4202                                        .collect::<Vec<_>>();
4203                                    if !buffer_matches.is_empty() {
4204                                        worker_matched_buffers
4205                                            .insert(buffer.clone(), buffer_matches);
4206                                    }
4207                                }
4208                            });
4209                        }
4210                    })
4211                    .await;
4212                Ok(matched_buffers.into_iter().flatten().collect())
4213            })
4214        } else if let Some(project_id) = self.remote_id() {
4215            let request = self.client.request(query.to_proto(project_id));
4216            cx.spawn(|this, mut cx| async move {
4217                let response = request.await?;
4218                let mut result = HashMap::default();
4219                for location in response.locations {
4220                    let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
4221                    let target_buffer = this
4222                        .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
4223                        .await?;
4224                    let start = location
4225                        .start
4226                        .and_then(deserialize_anchor)
4227                        .ok_or_else(|| anyhow!("missing target start"))?;
4228                    let end = location
4229                        .end
4230                        .and_then(deserialize_anchor)
4231                        .ok_or_else(|| anyhow!("missing target end"))?;
4232                    result
4233                        .entry(target_buffer)
4234                        .or_insert(Vec::new())
4235                        .push(start..end)
4236                }
4237                Ok(result)
4238            })
4239        } else {
4240            Task::ready(Ok(Default::default()))
4241        }
4242    }
4243
4244    fn request_lsp<R: LspCommand>(
4245        &self,
4246        buffer_handle: ModelHandle<Buffer>,
4247        request: R,
4248        cx: &mut ModelContext<Self>,
4249    ) -> Task<Result<R::Response>>
4250    where
4251        <R::LspRequest as lsp::request::Request>::Result: Send,
4252    {
4253        let buffer = buffer_handle.read(cx);
4254        if self.is_local() {
4255            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4256            if let Some((file, language_server)) = file.zip(
4257                self.language_server_for_buffer(buffer, cx)
4258                    .map(|(_, server)| server.clone()),
4259            ) {
4260                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4261                return cx.spawn(|this, cx| async move {
4262                    if !request.check_capabilities(&language_server.capabilities()) {
4263                        return Ok(Default::default());
4264                    }
4265
4266                    let response = language_server
4267                        .request::<R::LspRequest>(lsp_params)
4268                        .await
4269                        .context("lsp request failed")?;
4270                    request
4271                        .response_from_lsp(response, this, buffer_handle, cx)
4272                        .await
4273                });
4274            }
4275        } else if let Some(project_id) = self.remote_id() {
4276            let rpc = self.client.clone();
4277            let message = request.to_proto(project_id, buffer);
4278            return cx.spawn(|this, cx| async move {
4279                let response = rpc.request(message).await?;
4280                request
4281                    .response_from_proto(response, this, buffer_handle, cx)
4282                    .await
4283            });
4284        }
4285        Task::ready(Ok(Default::default()))
4286    }
4287
4288    pub fn find_or_create_local_worktree(
4289        &mut self,
4290        abs_path: impl AsRef<Path>,
4291        visible: bool,
4292        cx: &mut ModelContext<Self>,
4293    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4294        let abs_path = abs_path.as_ref();
4295        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4296            Task::ready(Ok((tree.clone(), relative_path.into())))
4297        } else {
4298            let worktree = self.create_local_worktree(abs_path, visible, cx);
4299            cx.foreground()
4300                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4301        }
4302    }
4303
4304    pub fn find_local_worktree(
4305        &self,
4306        abs_path: &Path,
4307        cx: &AppContext,
4308    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4309        for tree in &self.worktrees {
4310            if let Some(tree) = tree.upgrade(cx) {
4311                if let Some(relative_path) = tree
4312                    .read(cx)
4313                    .as_local()
4314                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4315                {
4316                    return Some((tree.clone(), relative_path.into()));
4317                }
4318            }
4319        }
4320        None
4321    }
4322
4323    pub fn is_shared(&self) -> bool {
4324        match &self.client_state {
4325            ProjectClientState::Local { is_shared, .. } => *is_shared,
4326            ProjectClientState::Remote { .. } => false,
4327        }
4328    }
4329
4330    fn create_local_worktree(
4331        &mut self,
4332        abs_path: impl AsRef<Path>,
4333        visible: bool,
4334        cx: &mut ModelContext<Self>,
4335    ) -> Task<Result<ModelHandle<Worktree>>> {
4336        let fs = self.fs.clone();
4337        let client = self.client.clone();
4338        let next_entry_id = self.next_entry_id.clone();
4339        let path: Arc<Path> = abs_path.as_ref().into();
4340        let task = self
4341            .loading_local_worktrees
4342            .entry(path.clone())
4343            .or_insert_with(|| {
4344                cx.spawn(|project, mut cx| {
4345                    async move {
4346                        let worktree = Worktree::local(
4347                            client.clone(),
4348                            path.clone(),
4349                            visible,
4350                            fs,
4351                            next_entry_id,
4352                            &mut cx,
4353                        )
4354                        .await;
4355                        project.update(&mut cx, |project, _| {
4356                            project.loading_local_worktrees.remove(&path);
4357                        });
4358                        let worktree = worktree?;
4359
4360                        let project_id = project.update(&mut cx, |project, cx| {
4361                            project.add_worktree(&worktree, cx);
4362                            project.shared_remote_id()
4363                        });
4364
4365                        if let Some(project_id) = project_id {
4366                            worktree
4367                                .update(&mut cx, |worktree, cx| {
4368                                    worktree.as_local_mut().unwrap().share(project_id, cx)
4369                                })
4370                                .await
4371                                .log_err();
4372                        }
4373
4374                        Ok(worktree)
4375                    }
4376                    .map_err(|err| Arc::new(err))
4377                })
4378                .shared()
4379            })
4380            .clone();
4381        cx.foreground().spawn(async move {
4382            match task.await {
4383                Ok(worktree) => Ok(worktree),
4384                Err(err) => Err(anyhow!("{}", err)),
4385            }
4386        })
4387    }
4388
4389    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4390        self.worktrees.retain(|worktree| {
4391            if let Some(worktree) = worktree.upgrade(cx) {
4392                let id = worktree.read(cx).id();
4393                if id == id_to_remove {
4394                    cx.emit(Event::WorktreeRemoved(id));
4395                    false
4396                } else {
4397                    true
4398                }
4399            } else {
4400                false
4401            }
4402        });
4403        self.metadata_changed(true, cx);
4404        cx.notify();
4405    }
4406
4407    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4408        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
4409        if worktree.read(cx).is_local() {
4410            cx.subscribe(&worktree, |this, worktree, _, cx| {
4411                this.update_local_worktree_buffers(worktree, cx);
4412            })
4413            .detach();
4414        }
4415
4416        let push_strong_handle = {
4417            let worktree = worktree.read(cx);
4418            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4419        };
4420        if push_strong_handle {
4421            self.worktrees
4422                .push(WorktreeHandle::Strong(worktree.clone()));
4423        } else {
4424            self.worktrees
4425                .push(WorktreeHandle::Weak(worktree.downgrade()));
4426        }
4427
4428        self.metadata_changed(true, cx);
4429        cx.observe_release(&worktree, |this, worktree, cx| {
4430            this.remove_worktree(worktree.id(), cx);
4431            cx.notify();
4432        })
4433        .detach();
4434
4435        cx.emit(Event::WorktreeAdded);
4436        cx.notify();
4437    }
4438
4439    fn update_local_worktree_buffers(
4440        &mut self,
4441        worktree_handle: ModelHandle<Worktree>,
4442        cx: &mut ModelContext<Self>,
4443    ) {
4444        let snapshot = worktree_handle.read(cx).snapshot();
4445        let mut buffers_to_delete = Vec::new();
4446        let mut renamed_buffers = Vec::new();
4447        for (buffer_id, buffer) in &self.opened_buffers {
4448            if let Some(buffer) = buffer.upgrade(cx) {
4449                buffer.update(cx, |buffer, cx| {
4450                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4451                        if old_file.worktree != worktree_handle {
4452                            return;
4453                        }
4454
4455                        let new_file = if let Some(entry) = old_file
4456                            .entry_id
4457                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4458                        {
4459                            File {
4460                                is_local: true,
4461                                entry_id: Some(entry.id),
4462                                mtime: entry.mtime,
4463                                path: entry.path.clone(),
4464                                worktree: worktree_handle.clone(),
4465                            }
4466                        } else if let Some(entry) =
4467                            snapshot.entry_for_path(old_file.path().as_ref())
4468                        {
4469                            File {
4470                                is_local: true,
4471                                entry_id: Some(entry.id),
4472                                mtime: entry.mtime,
4473                                path: entry.path.clone(),
4474                                worktree: worktree_handle.clone(),
4475                            }
4476                        } else {
4477                            File {
4478                                is_local: true,
4479                                entry_id: None,
4480                                path: old_file.path().clone(),
4481                                mtime: old_file.mtime(),
4482                                worktree: worktree_handle.clone(),
4483                            }
4484                        };
4485
4486                        let old_path = old_file.abs_path(cx);
4487                        if new_file.abs_path(cx) != old_path {
4488                            renamed_buffers.push((cx.handle(), old_path));
4489                        }
4490
4491                        if let Some(project_id) = self.shared_remote_id() {
4492                            self.client
4493                                .send(proto::UpdateBufferFile {
4494                                    project_id,
4495                                    buffer_id: *buffer_id as u64,
4496                                    file: Some(new_file.to_proto()),
4497                                })
4498                                .log_err();
4499                        }
4500                        buffer.file_updated(Arc::new(new_file), cx).detach();
4501                    }
4502                });
4503            } else {
4504                buffers_to_delete.push(*buffer_id);
4505            }
4506        }
4507
4508        for buffer_id in buffers_to_delete {
4509            self.opened_buffers.remove(&buffer_id);
4510        }
4511
4512        for (buffer, old_path) in renamed_buffers {
4513            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4514            self.assign_language_to_buffer(&buffer, cx);
4515            self.register_buffer_with_language_server(&buffer, cx);
4516        }
4517    }
4518
4519    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4520        let new_active_entry = entry.and_then(|project_path| {
4521            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4522            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4523            Some(entry.id)
4524        });
4525        if new_active_entry != self.active_entry {
4526            self.active_entry = new_active_entry;
4527            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4528        }
4529    }
4530
4531    pub fn language_servers_running_disk_based_diagnostics<'a>(
4532        &'a self,
4533    ) -> impl 'a + Iterator<Item = usize> {
4534        self.language_server_statuses
4535            .iter()
4536            .filter_map(|(id, status)| {
4537                if status.has_pending_diagnostic_updates {
4538                    Some(*id)
4539                } else {
4540                    None
4541                }
4542            })
4543    }
4544
4545    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4546        let mut summary = DiagnosticSummary::default();
4547        for (_, path_summary) in self.diagnostic_summaries(cx) {
4548            summary.error_count += path_summary.error_count;
4549            summary.warning_count += path_summary.warning_count;
4550        }
4551        summary
4552    }
4553
4554    pub fn diagnostic_summaries<'a>(
4555        &'a self,
4556        cx: &'a AppContext,
4557    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4558        self.visible_worktrees(cx).flat_map(move |worktree| {
4559            let worktree = worktree.read(cx);
4560            let worktree_id = worktree.id();
4561            worktree
4562                .diagnostic_summaries()
4563                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4564        })
4565    }
4566
4567    pub fn disk_based_diagnostics_started(
4568        &mut self,
4569        language_server_id: usize,
4570        cx: &mut ModelContext<Self>,
4571    ) {
4572        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4573    }
4574
4575    pub fn disk_based_diagnostics_finished(
4576        &mut self,
4577        language_server_id: usize,
4578        cx: &mut ModelContext<Self>,
4579    ) {
4580        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4581    }
4582
4583    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4584        self.active_entry
4585    }
4586
4587    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
4588        self.worktree_for_id(path.worktree_id, cx)?
4589            .read(cx)
4590            .entry_for_path(&path.path)
4591            .map(|entry| entry.id)
4592    }
4593
4594    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4595        let worktree = self.worktree_for_entry(entry_id, cx)?;
4596        let worktree = worktree.read(cx);
4597        let worktree_id = worktree.id();
4598        let path = worktree.entry_for_id(entry_id)?.path.clone();
4599        Some(ProjectPath { worktree_id, path })
4600    }
4601
4602    // RPC message handlers
4603
4604    async fn handle_request_join_project(
4605        this: ModelHandle<Self>,
4606        message: TypedEnvelope<proto::RequestJoinProject>,
4607        _: Arc<Client>,
4608        mut cx: AsyncAppContext,
4609    ) -> Result<()> {
4610        let user_id = message.payload.requester_id;
4611        if this.read_with(&cx, |project, _| {
4612            project.collaborators.values().any(|c| c.user.id == user_id)
4613        }) {
4614            this.update(&mut cx, |this, cx| {
4615                this.respond_to_join_request(user_id, true, cx)
4616            });
4617        } else {
4618            let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4619            let user = user_store
4620                .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4621                .await?;
4622            this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4623        }
4624        Ok(())
4625    }
4626
4627    async fn handle_unregister_project(
4628        this: ModelHandle<Self>,
4629        _: TypedEnvelope<proto::UnregisterProject>,
4630        _: Arc<Client>,
4631        mut cx: AsyncAppContext,
4632    ) -> Result<()> {
4633        this.update(&mut cx, |this, cx| this.disconnected_from_host(cx));
4634        Ok(())
4635    }
4636
4637    async fn handle_project_unshared(
4638        this: ModelHandle<Self>,
4639        _: TypedEnvelope<proto::ProjectUnshared>,
4640        _: Arc<Client>,
4641        mut cx: AsyncAppContext,
4642    ) -> Result<()> {
4643        this.update(&mut cx, |this, cx| this.unshared(cx));
4644        Ok(())
4645    }
4646
4647    async fn handle_add_collaborator(
4648        this: ModelHandle<Self>,
4649        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4650        _: Arc<Client>,
4651        mut cx: AsyncAppContext,
4652    ) -> Result<()> {
4653        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4654        let collaborator = envelope
4655            .payload
4656            .collaborator
4657            .take()
4658            .ok_or_else(|| anyhow!("empty collaborator"))?;
4659
4660        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4661        this.update(&mut cx, |this, cx| {
4662            this.collaborators
4663                .insert(collaborator.peer_id, collaborator);
4664            cx.notify();
4665        });
4666
4667        Ok(())
4668    }
4669
4670    async fn handle_remove_collaborator(
4671        this: ModelHandle<Self>,
4672        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4673        _: Arc<Client>,
4674        mut cx: AsyncAppContext,
4675    ) -> Result<()> {
4676        this.update(&mut cx, |this, cx| {
4677            let peer_id = PeerId(envelope.payload.peer_id);
4678            let replica_id = this
4679                .collaborators
4680                .remove(&peer_id)
4681                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4682                .replica_id;
4683            for (_, buffer) in &this.opened_buffers {
4684                if let Some(buffer) = buffer.upgrade(cx) {
4685                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4686                }
4687            }
4688
4689            cx.emit(Event::CollaboratorLeft(peer_id));
4690            cx.notify();
4691            Ok(())
4692        })
4693    }
4694
4695    async fn handle_join_project_request_cancelled(
4696        this: ModelHandle<Self>,
4697        envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4698        _: Arc<Client>,
4699        mut cx: AsyncAppContext,
4700    ) -> Result<()> {
4701        let user = this
4702            .update(&mut cx, |this, cx| {
4703                this.user_store.update(cx, |user_store, cx| {
4704                    user_store.fetch_user(envelope.payload.requester_id, cx)
4705                })
4706            })
4707            .await?;
4708
4709        this.update(&mut cx, |_, cx| {
4710            cx.emit(Event::ContactCancelledJoinRequest(user));
4711        });
4712
4713        Ok(())
4714    }
4715
4716    async fn handle_update_project(
4717        this: ModelHandle<Self>,
4718        envelope: TypedEnvelope<proto::UpdateProject>,
4719        client: Arc<Client>,
4720        mut cx: AsyncAppContext,
4721    ) -> Result<()> {
4722        this.update(&mut cx, |this, cx| {
4723            let replica_id = this.replica_id();
4724            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4725
4726            let mut old_worktrees_by_id = this
4727                .worktrees
4728                .drain(..)
4729                .filter_map(|worktree| {
4730                    let worktree = worktree.upgrade(cx)?;
4731                    Some((worktree.read(cx).id(), worktree))
4732                })
4733                .collect::<HashMap<_, _>>();
4734
4735            for worktree in envelope.payload.worktrees {
4736                if let Some(old_worktree) =
4737                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4738                {
4739                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4740                } else {
4741                    let worktree =
4742                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4743                    this.add_worktree(&worktree, cx);
4744                }
4745            }
4746
4747            this.metadata_changed(true, cx);
4748            for (id, _) in old_worktrees_by_id {
4749                cx.emit(Event::WorktreeRemoved(id));
4750            }
4751
4752            Ok(())
4753        })
4754    }
4755
4756    async fn handle_update_worktree(
4757        this: ModelHandle<Self>,
4758        envelope: TypedEnvelope<proto::UpdateWorktree>,
4759        _: Arc<Client>,
4760        mut cx: AsyncAppContext,
4761    ) -> Result<()> {
4762        this.update(&mut cx, |this, cx| {
4763            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4764            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4765                worktree.update(cx, |worktree, _| {
4766                    let worktree = worktree.as_remote_mut().unwrap();
4767                    worktree.update_from_remote(envelope.payload);
4768                });
4769            }
4770            Ok(())
4771        })
4772    }
4773
4774    async fn handle_create_project_entry(
4775        this: ModelHandle<Self>,
4776        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4777        _: Arc<Client>,
4778        mut cx: AsyncAppContext,
4779    ) -> Result<proto::ProjectEntryResponse> {
4780        let worktree = this.update(&mut cx, |this, cx| {
4781            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4782            this.worktree_for_id(worktree_id, cx)
4783                .ok_or_else(|| anyhow!("worktree not found"))
4784        })?;
4785        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4786        let entry = worktree
4787            .update(&mut cx, |worktree, cx| {
4788                let worktree = worktree.as_local_mut().unwrap();
4789                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4790                worktree.create_entry(path, envelope.payload.is_directory, cx)
4791            })
4792            .await?;
4793        Ok(proto::ProjectEntryResponse {
4794            entry: Some((&entry).into()),
4795            worktree_scan_id: worktree_scan_id as u64,
4796        })
4797    }
4798
4799    async fn handle_rename_project_entry(
4800        this: ModelHandle<Self>,
4801        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4802        _: Arc<Client>,
4803        mut cx: AsyncAppContext,
4804    ) -> Result<proto::ProjectEntryResponse> {
4805        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4806        let worktree = this.read_with(&cx, |this, cx| {
4807            this.worktree_for_entry(entry_id, cx)
4808                .ok_or_else(|| anyhow!("worktree not found"))
4809        })?;
4810        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4811        let entry = worktree
4812            .update(&mut cx, |worktree, cx| {
4813                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4814                worktree
4815                    .as_local_mut()
4816                    .unwrap()
4817                    .rename_entry(entry_id, new_path, cx)
4818                    .ok_or_else(|| anyhow!("invalid entry"))
4819            })?
4820            .await?;
4821        Ok(proto::ProjectEntryResponse {
4822            entry: Some((&entry).into()),
4823            worktree_scan_id: worktree_scan_id as u64,
4824        })
4825    }
4826
4827    async fn handle_copy_project_entry(
4828        this: ModelHandle<Self>,
4829        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4830        _: Arc<Client>,
4831        mut cx: AsyncAppContext,
4832    ) -> Result<proto::ProjectEntryResponse> {
4833        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4834        let worktree = this.read_with(&cx, |this, cx| {
4835            this.worktree_for_entry(entry_id, cx)
4836                .ok_or_else(|| anyhow!("worktree not found"))
4837        })?;
4838        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4839        let entry = worktree
4840            .update(&mut cx, |worktree, cx| {
4841                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4842                worktree
4843                    .as_local_mut()
4844                    .unwrap()
4845                    .copy_entry(entry_id, new_path, cx)
4846                    .ok_or_else(|| anyhow!("invalid entry"))
4847            })?
4848            .await?;
4849        Ok(proto::ProjectEntryResponse {
4850            entry: Some((&entry).into()),
4851            worktree_scan_id: worktree_scan_id as u64,
4852        })
4853    }
4854
4855    async fn handle_delete_project_entry(
4856        this: ModelHandle<Self>,
4857        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4858        _: Arc<Client>,
4859        mut cx: AsyncAppContext,
4860    ) -> Result<proto::ProjectEntryResponse> {
4861        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4862        let worktree = this.read_with(&cx, |this, cx| {
4863            this.worktree_for_entry(entry_id, cx)
4864                .ok_or_else(|| anyhow!("worktree not found"))
4865        })?;
4866        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4867        worktree
4868            .update(&mut cx, |worktree, cx| {
4869                worktree
4870                    .as_local_mut()
4871                    .unwrap()
4872                    .delete_entry(entry_id, cx)
4873                    .ok_or_else(|| anyhow!("invalid entry"))
4874            })?
4875            .await?;
4876        Ok(proto::ProjectEntryResponse {
4877            entry: None,
4878            worktree_scan_id: worktree_scan_id as u64,
4879        })
4880    }
4881
4882    async fn handle_update_diagnostic_summary(
4883        this: ModelHandle<Self>,
4884        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4885        _: Arc<Client>,
4886        mut cx: AsyncAppContext,
4887    ) -> Result<()> {
4888        this.update(&mut cx, |this, cx| {
4889            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4890            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4891                if let Some(summary) = envelope.payload.summary {
4892                    let project_path = ProjectPath {
4893                        worktree_id,
4894                        path: Path::new(&summary.path).into(),
4895                    };
4896                    worktree.update(cx, |worktree, _| {
4897                        worktree
4898                            .as_remote_mut()
4899                            .unwrap()
4900                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4901                    });
4902                    cx.emit(Event::DiagnosticsUpdated {
4903                        language_server_id: summary.language_server_id as usize,
4904                        path: project_path,
4905                    });
4906                }
4907            }
4908            Ok(())
4909        })
4910    }
4911
4912    async fn handle_start_language_server(
4913        this: ModelHandle<Self>,
4914        envelope: TypedEnvelope<proto::StartLanguageServer>,
4915        _: Arc<Client>,
4916        mut cx: AsyncAppContext,
4917    ) -> Result<()> {
4918        let server = envelope
4919            .payload
4920            .server
4921            .ok_or_else(|| anyhow!("invalid server"))?;
4922        this.update(&mut cx, |this, cx| {
4923            this.language_server_statuses.insert(
4924                server.id as usize,
4925                LanguageServerStatus {
4926                    name: server.name,
4927                    pending_work: Default::default(),
4928                    has_pending_diagnostic_updates: false,
4929                    progress_tokens: Default::default(),
4930                },
4931            );
4932            cx.notify();
4933        });
4934        Ok(())
4935    }
4936
4937    async fn handle_update_language_server(
4938        this: ModelHandle<Self>,
4939        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4940        _: Arc<Client>,
4941        mut cx: AsyncAppContext,
4942    ) -> Result<()> {
4943        let language_server_id = envelope.payload.language_server_id as usize;
4944        match envelope
4945            .payload
4946            .variant
4947            .ok_or_else(|| anyhow!("invalid variant"))?
4948        {
4949            proto::update_language_server::Variant::WorkStart(payload) => {
4950                this.update(&mut cx, |this, cx| {
4951                    this.on_lsp_work_start(
4952                        language_server_id,
4953                        payload.token,
4954                        LanguageServerProgress {
4955                            message: payload.message,
4956                            percentage: payload.percentage.map(|p| p as usize),
4957                            last_update_at: Instant::now(),
4958                        },
4959                        cx,
4960                    );
4961                })
4962            }
4963            proto::update_language_server::Variant::WorkProgress(payload) => {
4964                this.update(&mut cx, |this, cx| {
4965                    this.on_lsp_work_progress(
4966                        language_server_id,
4967                        payload.token,
4968                        LanguageServerProgress {
4969                            message: payload.message,
4970                            percentage: payload.percentage.map(|p| p as usize),
4971                            last_update_at: Instant::now(),
4972                        },
4973                        cx,
4974                    );
4975                })
4976            }
4977            proto::update_language_server::Variant::WorkEnd(payload) => {
4978                this.update(&mut cx, |this, cx| {
4979                    this.on_lsp_work_end(language_server_id, payload.token, cx);
4980                })
4981            }
4982            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4983                this.update(&mut cx, |this, cx| {
4984                    this.disk_based_diagnostics_started(language_server_id, cx);
4985                })
4986            }
4987            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4988                this.update(&mut cx, |this, cx| {
4989                    this.disk_based_diagnostics_finished(language_server_id, cx)
4990                });
4991            }
4992        }
4993
4994        Ok(())
4995    }
4996
4997    async fn handle_update_buffer(
4998        this: ModelHandle<Self>,
4999        envelope: TypedEnvelope<proto::UpdateBuffer>,
5000        _: Arc<Client>,
5001        mut cx: AsyncAppContext,
5002    ) -> Result<()> {
5003        this.update(&mut cx, |this, cx| {
5004            let payload = envelope.payload.clone();
5005            let buffer_id = payload.buffer_id;
5006            let ops = payload
5007                .operations
5008                .into_iter()
5009                .map(|op| language::proto::deserialize_operation(op))
5010                .collect::<Result<Vec<_>, _>>()?;
5011            let is_remote = this.is_remote();
5012            match this.opened_buffers.entry(buffer_id) {
5013                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5014                    OpenBuffer::Strong(buffer) => {
5015                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5016                    }
5017                    OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
5018                    OpenBuffer::Weak(_) => {}
5019                },
5020                hash_map::Entry::Vacant(e) => {
5021                    assert!(
5022                        is_remote,
5023                        "received buffer update from {:?}",
5024                        envelope.original_sender_id
5025                    );
5026                    e.insert(OpenBuffer::Loading(ops));
5027                }
5028            }
5029            Ok(())
5030        })
5031    }
5032
5033    async fn handle_update_buffer_file(
5034        this: ModelHandle<Self>,
5035        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5036        _: Arc<Client>,
5037        mut cx: AsyncAppContext,
5038    ) -> Result<()> {
5039        this.update(&mut cx, |this, cx| {
5040            let payload = envelope.payload.clone();
5041            let buffer_id = payload.buffer_id;
5042            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5043            let worktree = this
5044                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5045                .ok_or_else(|| anyhow!("no such worktree"))?;
5046            let file = File::from_proto(file, worktree.clone(), cx)?;
5047            let buffer = this
5048                .opened_buffers
5049                .get_mut(&buffer_id)
5050                .and_then(|b| b.upgrade(cx))
5051                .ok_or_else(|| anyhow!("no such buffer"))?;
5052            buffer.update(cx, |buffer, cx| {
5053                buffer.file_updated(Arc::new(file), cx).detach();
5054            });
5055            Ok(())
5056        })
5057    }
5058
5059    async fn handle_save_buffer(
5060        this: ModelHandle<Self>,
5061        envelope: TypedEnvelope<proto::SaveBuffer>,
5062        _: Arc<Client>,
5063        mut cx: AsyncAppContext,
5064    ) -> Result<proto::BufferSaved> {
5065        let buffer_id = envelope.payload.buffer_id;
5066        let requested_version = deserialize_version(envelope.payload.version);
5067
5068        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5069            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5070            let buffer = this
5071                .opened_buffers
5072                .get(&buffer_id)
5073                .and_then(|buffer| buffer.upgrade(cx))
5074                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5075            Ok::<_, anyhow::Error>((project_id, buffer))
5076        })?;
5077        buffer
5078            .update(&mut cx, |buffer, _| {
5079                buffer.wait_for_version(requested_version)
5080            })
5081            .await;
5082
5083        let (saved_version, fingerprint, mtime) =
5084            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5085        Ok(proto::BufferSaved {
5086            project_id,
5087            buffer_id,
5088            version: serialize_version(&saved_version),
5089            mtime: Some(mtime.into()),
5090            fingerprint,
5091        })
5092    }
5093
5094    async fn handle_reload_buffers(
5095        this: ModelHandle<Self>,
5096        envelope: TypedEnvelope<proto::ReloadBuffers>,
5097        _: Arc<Client>,
5098        mut cx: AsyncAppContext,
5099    ) -> Result<proto::ReloadBuffersResponse> {
5100        let sender_id = envelope.original_sender_id()?;
5101        let reload = this.update(&mut cx, |this, cx| {
5102            let mut buffers = HashSet::default();
5103            for buffer_id in &envelope.payload.buffer_ids {
5104                buffers.insert(
5105                    this.opened_buffers
5106                        .get(buffer_id)
5107                        .and_then(|buffer| buffer.upgrade(cx))
5108                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5109                );
5110            }
5111            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5112        })?;
5113
5114        let project_transaction = reload.await?;
5115        let project_transaction = this.update(&mut cx, |this, cx| {
5116            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5117        });
5118        Ok(proto::ReloadBuffersResponse {
5119            transaction: Some(project_transaction),
5120        })
5121    }
5122
5123    async fn handle_format_buffers(
5124        this: ModelHandle<Self>,
5125        envelope: TypedEnvelope<proto::FormatBuffers>,
5126        _: Arc<Client>,
5127        mut cx: AsyncAppContext,
5128    ) -> Result<proto::FormatBuffersResponse> {
5129        let sender_id = envelope.original_sender_id()?;
5130        let format = this.update(&mut cx, |this, cx| {
5131            let mut buffers = HashSet::default();
5132            for buffer_id in &envelope.payload.buffer_ids {
5133                buffers.insert(
5134                    this.opened_buffers
5135                        .get(buffer_id)
5136                        .and_then(|buffer| buffer.upgrade(cx))
5137                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5138                );
5139            }
5140            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
5141        })?;
5142
5143        let project_transaction = format.await?;
5144        let project_transaction = this.update(&mut cx, |this, cx| {
5145            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5146        });
5147        Ok(proto::FormatBuffersResponse {
5148            transaction: Some(project_transaction),
5149        })
5150    }
5151
5152    async fn handle_get_completions(
5153        this: ModelHandle<Self>,
5154        envelope: TypedEnvelope<proto::GetCompletions>,
5155        _: Arc<Client>,
5156        mut cx: AsyncAppContext,
5157    ) -> Result<proto::GetCompletionsResponse> {
5158        let position = envelope
5159            .payload
5160            .position
5161            .and_then(language::proto::deserialize_anchor)
5162            .ok_or_else(|| anyhow!("invalid position"))?;
5163        let version = deserialize_version(envelope.payload.version);
5164        let buffer = this.read_with(&cx, |this, cx| {
5165            this.opened_buffers
5166                .get(&envelope.payload.buffer_id)
5167                .and_then(|buffer| buffer.upgrade(cx))
5168                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5169        })?;
5170        buffer
5171            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5172            .await;
5173        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5174        let completions = this
5175            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5176            .await?;
5177
5178        Ok(proto::GetCompletionsResponse {
5179            completions: completions
5180                .iter()
5181                .map(language::proto::serialize_completion)
5182                .collect(),
5183            version: serialize_version(&version),
5184        })
5185    }
5186
5187    async fn handle_apply_additional_edits_for_completion(
5188        this: ModelHandle<Self>,
5189        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5190        _: Arc<Client>,
5191        mut cx: AsyncAppContext,
5192    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5193        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5194            let buffer = this
5195                .opened_buffers
5196                .get(&envelope.payload.buffer_id)
5197                .and_then(|buffer| buffer.upgrade(cx))
5198                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5199            let language = buffer.read(cx).language();
5200            let completion = language::proto::deserialize_completion(
5201                envelope
5202                    .payload
5203                    .completion
5204                    .ok_or_else(|| anyhow!("invalid completion"))?,
5205                language,
5206            )?;
5207            Ok::<_, anyhow::Error>(
5208                this.apply_additional_edits_for_completion(buffer, completion, false, cx),
5209            )
5210        })?;
5211
5212        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5213            transaction: apply_additional_edits
5214                .await?
5215                .as_ref()
5216                .map(language::proto::serialize_transaction),
5217        })
5218    }
5219
5220    async fn handle_get_code_actions(
5221        this: ModelHandle<Self>,
5222        envelope: TypedEnvelope<proto::GetCodeActions>,
5223        _: Arc<Client>,
5224        mut cx: AsyncAppContext,
5225    ) -> Result<proto::GetCodeActionsResponse> {
5226        let start = envelope
5227            .payload
5228            .start
5229            .and_then(language::proto::deserialize_anchor)
5230            .ok_or_else(|| anyhow!("invalid start"))?;
5231        let end = envelope
5232            .payload
5233            .end
5234            .and_then(language::proto::deserialize_anchor)
5235            .ok_or_else(|| anyhow!("invalid end"))?;
5236        let buffer = this.update(&mut cx, |this, cx| {
5237            this.opened_buffers
5238                .get(&envelope.payload.buffer_id)
5239                .and_then(|buffer| buffer.upgrade(cx))
5240                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5241        })?;
5242        buffer
5243            .update(&mut cx, |buffer, _| {
5244                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5245            })
5246            .await;
5247
5248        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5249        let code_actions = this.update(&mut cx, |this, cx| {
5250            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5251        })?;
5252
5253        Ok(proto::GetCodeActionsResponse {
5254            actions: code_actions
5255                .await?
5256                .iter()
5257                .map(language::proto::serialize_code_action)
5258                .collect(),
5259            version: serialize_version(&version),
5260        })
5261    }
5262
5263    async fn handle_apply_code_action(
5264        this: ModelHandle<Self>,
5265        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5266        _: Arc<Client>,
5267        mut cx: AsyncAppContext,
5268    ) -> Result<proto::ApplyCodeActionResponse> {
5269        let sender_id = envelope.original_sender_id()?;
5270        let action = language::proto::deserialize_code_action(
5271            envelope
5272                .payload
5273                .action
5274                .ok_or_else(|| anyhow!("invalid action"))?,
5275        )?;
5276        let apply_code_action = this.update(&mut cx, |this, cx| {
5277            let buffer = this
5278                .opened_buffers
5279                .get(&envelope.payload.buffer_id)
5280                .and_then(|buffer| buffer.upgrade(cx))
5281                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5282            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5283        })?;
5284
5285        let project_transaction = apply_code_action.await?;
5286        let project_transaction = this.update(&mut cx, |this, cx| {
5287            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5288        });
5289        Ok(proto::ApplyCodeActionResponse {
5290            transaction: Some(project_transaction),
5291        })
5292    }
5293
5294    async fn handle_lsp_command<T: LspCommand>(
5295        this: ModelHandle<Self>,
5296        envelope: TypedEnvelope<T::ProtoRequest>,
5297        _: Arc<Client>,
5298        mut cx: AsyncAppContext,
5299    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5300    where
5301        <T::LspRequest as lsp::request::Request>::Result: Send,
5302    {
5303        let sender_id = envelope.original_sender_id()?;
5304        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5305        let buffer_handle = this.read_with(&cx, |this, _| {
5306            this.opened_buffers
5307                .get(&buffer_id)
5308                .and_then(|buffer| buffer.upgrade(&cx))
5309                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5310        })?;
5311        let request = T::from_proto(
5312            envelope.payload,
5313            this.clone(),
5314            buffer_handle.clone(),
5315            cx.clone(),
5316        )
5317        .await?;
5318        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5319        let response = this
5320            .update(&mut cx, |this, cx| {
5321                this.request_lsp(buffer_handle, request, cx)
5322            })
5323            .await?;
5324        this.update(&mut cx, |this, cx| {
5325            Ok(T::response_to_proto(
5326                response,
5327                this,
5328                sender_id,
5329                &buffer_version,
5330                cx,
5331            ))
5332        })
5333    }
5334
5335    async fn handle_get_project_symbols(
5336        this: ModelHandle<Self>,
5337        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5338        _: Arc<Client>,
5339        mut cx: AsyncAppContext,
5340    ) -> Result<proto::GetProjectSymbolsResponse> {
5341        let symbols = this
5342            .update(&mut cx, |this, cx| {
5343                this.symbols(&envelope.payload.query, cx)
5344            })
5345            .await?;
5346
5347        Ok(proto::GetProjectSymbolsResponse {
5348            symbols: symbols.iter().map(serialize_symbol).collect(),
5349        })
5350    }
5351
5352    async fn handle_search_project(
5353        this: ModelHandle<Self>,
5354        envelope: TypedEnvelope<proto::SearchProject>,
5355        _: Arc<Client>,
5356        mut cx: AsyncAppContext,
5357    ) -> Result<proto::SearchProjectResponse> {
5358        let peer_id = envelope.original_sender_id()?;
5359        let query = SearchQuery::from_proto(envelope.payload)?;
5360        let result = this
5361            .update(&mut cx, |this, cx| this.search(query, cx))
5362            .await?;
5363
5364        this.update(&mut cx, |this, cx| {
5365            let mut locations = Vec::new();
5366            for (buffer, ranges) in result {
5367                for range in ranges {
5368                    let start = serialize_anchor(&range.start);
5369                    let end = serialize_anchor(&range.end);
5370                    let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
5371                    locations.push(proto::Location {
5372                        buffer: Some(buffer),
5373                        start: Some(start),
5374                        end: Some(end),
5375                    });
5376                }
5377            }
5378            Ok(proto::SearchProjectResponse { locations })
5379        })
5380    }
5381
5382    async fn handle_open_buffer_for_symbol(
5383        this: ModelHandle<Self>,
5384        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5385        _: Arc<Client>,
5386        mut cx: AsyncAppContext,
5387    ) -> Result<proto::OpenBufferForSymbolResponse> {
5388        let peer_id = envelope.original_sender_id()?;
5389        let symbol = envelope
5390            .payload
5391            .symbol
5392            .ok_or_else(|| anyhow!("invalid symbol"))?;
5393        let symbol = this.read_with(&cx, |this, _| {
5394            let symbol = this.deserialize_symbol(symbol)?;
5395            let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
5396            if signature == symbol.signature {
5397                Ok(symbol)
5398            } else {
5399                Err(anyhow!("invalid symbol signature"))
5400            }
5401        })?;
5402        let buffer = this
5403            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5404            .await?;
5405
5406        Ok(proto::OpenBufferForSymbolResponse {
5407            buffer: Some(this.update(&mut cx, |this, cx| {
5408                this.serialize_buffer_for_peer(&buffer, peer_id, cx)
5409            })),
5410        })
5411    }
5412
5413    fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
5414        let mut hasher = Sha256::new();
5415        hasher.update(worktree_id.to_proto().to_be_bytes());
5416        hasher.update(path.to_string_lossy().as_bytes());
5417        hasher.update(self.nonce.to_be_bytes());
5418        hasher.finalize().as_slice().try_into().unwrap()
5419    }
5420
5421    async fn handle_open_buffer_by_id(
5422        this: ModelHandle<Self>,
5423        envelope: TypedEnvelope<proto::OpenBufferById>,
5424        _: Arc<Client>,
5425        mut cx: AsyncAppContext,
5426    ) -> Result<proto::OpenBufferResponse> {
5427        let peer_id = envelope.original_sender_id()?;
5428        let buffer = this
5429            .update(&mut cx, |this, cx| {
5430                this.open_buffer_by_id(envelope.payload.id, cx)
5431            })
5432            .await?;
5433        this.update(&mut cx, |this, cx| {
5434            Ok(proto::OpenBufferResponse {
5435                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5436            })
5437        })
5438    }
5439
5440    async fn handle_open_buffer_by_path(
5441        this: ModelHandle<Self>,
5442        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5443        _: Arc<Client>,
5444        mut cx: AsyncAppContext,
5445    ) -> Result<proto::OpenBufferResponse> {
5446        let peer_id = envelope.original_sender_id()?;
5447        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5448        let open_buffer = this.update(&mut cx, |this, cx| {
5449            this.open_buffer(
5450                ProjectPath {
5451                    worktree_id,
5452                    path: PathBuf::from(envelope.payload.path).into(),
5453                },
5454                cx,
5455            )
5456        });
5457
5458        let buffer = open_buffer.await?;
5459        this.update(&mut cx, |this, cx| {
5460            Ok(proto::OpenBufferResponse {
5461                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5462            })
5463        })
5464    }
5465
5466    fn serialize_project_transaction_for_peer(
5467        &mut self,
5468        project_transaction: ProjectTransaction,
5469        peer_id: PeerId,
5470        cx: &AppContext,
5471    ) -> proto::ProjectTransaction {
5472        let mut serialized_transaction = proto::ProjectTransaction {
5473            buffers: Default::default(),
5474            transactions: Default::default(),
5475        };
5476        for (buffer, transaction) in project_transaction.0 {
5477            serialized_transaction
5478                .buffers
5479                .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
5480            serialized_transaction
5481                .transactions
5482                .push(language::proto::serialize_transaction(&transaction));
5483        }
5484        serialized_transaction
5485    }
5486
5487    fn deserialize_project_transaction(
5488        &mut self,
5489        message: proto::ProjectTransaction,
5490        push_to_history: bool,
5491        cx: &mut ModelContext<Self>,
5492    ) -> Task<Result<ProjectTransaction>> {
5493        cx.spawn(|this, mut cx| async move {
5494            let mut project_transaction = ProjectTransaction::default();
5495            for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
5496                let buffer = this
5497                    .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
5498                    .await?;
5499                let transaction = language::proto::deserialize_transaction(transaction)?;
5500                project_transaction.0.insert(buffer, transaction);
5501            }
5502
5503            for (buffer, transaction) in &project_transaction.0 {
5504                buffer
5505                    .update(&mut cx, |buffer, _| {
5506                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5507                    })
5508                    .await;
5509
5510                if push_to_history {
5511                    buffer.update(&mut cx, |buffer, _| {
5512                        buffer.push_transaction(transaction.clone(), Instant::now());
5513                    });
5514                }
5515            }
5516
5517            Ok(project_transaction)
5518        })
5519    }
5520
5521    fn serialize_buffer_for_peer(
5522        &mut self,
5523        buffer: &ModelHandle<Buffer>,
5524        peer_id: PeerId,
5525        cx: &AppContext,
5526    ) -> proto::Buffer {
5527        let buffer_id = buffer.read(cx).remote_id();
5528        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5529        if shared_buffers.insert(buffer_id) {
5530            proto::Buffer {
5531                variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
5532            }
5533        } else {
5534            proto::Buffer {
5535                variant: Some(proto::buffer::Variant::Id(buffer_id)),
5536            }
5537        }
5538    }
5539
5540    fn deserialize_buffer(
5541        &mut self,
5542        buffer: proto::Buffer,
5543        cx: &mut ModelContext<Self>,
5544    ) -> Task<Result<ModelHandle<Buffer>>> {
5545        let replica_id = self.replica_id();
5546
5547        let opened_buffer_tx = self.opened_buffer.0.clone();
5548        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5549        cx.spawn(|this, mut cx| async move {
5550            match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
5551                proto::buffer::Variant::Id(id) => {
5552                    let buffer = loop {
5553                        let buffer = this.read_with(&cx, |this, cx| {
5554                            this.opened_buffers
5555                                .get(&id)
5556                                .and_then(|buffer| buffer.upgrade(cx))
5557                        });
5558                        if let Some(buffer) = buffer {
5559                            break buffer;
5560                        }
5561                        opened_buffer_rx
5562                            .next()
5563                            .await
5564                            .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5565                    };
5566                    Ok(buffer)
5567                }
5568                proto::buffer::Variant::State(mut buffer) => {
5569                    let mut buffer_worktree = None;
5570                    let mut buffer_file = None;
5571                    if let Some(file) = buffer.file.take() {
5572                        this.read_with(&cx, |this, cx| {
5573                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
5574                            let worktree =
5575                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5576                                    anyhow!("no worktree found for id {}", file.worktree_id)
5577                                })?;
5578                            buffer_file =
5579                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5580                                    as Arc<dyn language::File>);
5581                            buffer_worktree = Some(worktree);
5582                            Ok::<_, anyhow::Error>(())
5583                        })?;
5584                    }
5585
5586                    let buffer = cx.add_model(|cx| {
5587                        Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
5588                    });
5589
5590                    this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
5591
5592                    *opened_buffer_tx.borrow_mut().borrow_mut() = ();
5593                    Ok(buffer)
5594                }
5595            }
5596        })
5597    }
5598
5599    fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
5600        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5601        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5602        let start = serialized_symbol
5603            .start
5604            .ok_or_else(|| anyhow!("invalid start"))?;
5605        let end = serialized_symbol
5606            .end
5607            .ok_or_else(|| anyhow!("invalid end"))?;
5608        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5609        let path = PathBuf::from(serialized_symbol.path);
5610        let language = self.languages.select_language(&path);
5611        Ok(Symbol {
5612            source_worktree_id,
5613            worktree_id,
5614            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
5615            label: language
5616                .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
5617                .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
5618            name: serialized_symbol.name,
5619            path,
5620            range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
5621            kind,
5622            signature: serialized_symbol
5623                .signature
5624                .try_into()
5625                .map_err(|_| anyhow!("invalid signature"))?,
5626        })
5627    }
5628
5629    async fn handle_buffer_saved(
5630        this: ModelHandle<Self>,
5631        envelope: TypedEnvelope<proto::BufferSaved>,
5632        _: Arc<Client>,
5633        mut cx: AsyncAppContext,
5634    ) -> Result<()> {
5635        let version = deserialize_version(envelope.payload.version);
5636        let mtime = envelope
5637            .payload
5638            .mtime
5639            .ok_or_else(|| anyhow!("missing mtime"))?
5640            .into();
5641
5642        this.update(&mut cx, |this, cx| {
5643            let buffer = this
5644                .opened_buffers
5645                .get(&envelope.payload.buffer_id)
5646                .and_then(|buffer| buffer.upgrade(cx));
5647            if let Some(buffer) = buffer {
5648                buffer.update(cx, |buffer, cx| {
5649                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5650                });
5651            }
5652            Ok(())
5653        })
5654    }
5655
5656    async fn handle_buffer_reloaded(
5657        this: ModelHandle<Self>,
5658        envelope: TypedEnvelope<proto::BufferReloaded>,
5659        _: Arc<Client>,
5660        mut cx: AsyncAppContext,
5661    ) -> Result<()> {
5662        let payload = envelope.payload;
5663        let version = deserialize_version(payload.version);
5664        let line_ending = deserialize_line_ending(
5665            proto::LineEnding::from_i32(payload.line_ending)
5666                .ok_or_else(|| anyhow!("missing line ending"))?,
5667        );
5668        let mtime = payload
5669            .mtime
5670            .ok_or_else(|| anyhow!("missing mtime"))?
5671            .into();
5672        this.update(&mut cx, |this, cx| {
5673            let buffer = this
5674                .opened_buffers
5675                .get(&payload.buffer_id)
5676                .and_then(|buffer| buffer.upgrade(cx));
5677            if let Some(buffer) = buffer {
5678                buffer.update(cx, |buffer, cx| {
5679                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5680                });
5681            }
5682            Ok(())
5683        })
5684    }
5685
5686    fn edits_from_lsp(
5687        &mut self,
5688        buffer: &ModelHandle<Buffer>,
5689        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5690        version: Option<i32>,
5691        cx: &mut ModelContext<Self>,
5692    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5693        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5694        cx.background().spawn(async move {
5695            let snapshot = snapshot?;
5696            let mut lsp_edits = lsp_edits
5697                .into_iter()
5698                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5699                .collect::<Vec<_>>();
5700            lsp_edits.sort_by_key(|(range, _)| range.start);
5701
5702            let mut lsp_edits = lsp_edits.into_iter().peekable();
5703            let mut edits = Vec::new();
5704            while let Some((mut range, mut new_text)) = lsp_edits.next() {
5705                // Combine any LSP edits that are adjacent.
5706                //
5707                // Also, combine LSP edits that are separated from each other by only
5708                // a newline. This is important because for some code actions,
5709                // Rust-analyzer rewrites the entire buffer via a series of edits that
5710                // are separated by unchanged newline characters.
5711                //
5712                // In order for the diffing logic below to work properly, any edits that
5713                // cancel each other out must be combined into one.
5714                while let Some((next_range, next_text)) = lsp_edits.peek() {
5715                    if next_range.start > range.end {
5716                        if next_range.start.row > range.end.row + 1
5717                            || next_range.start.column > 0
5718                            || snapshot.clip_point_utf16(
5719                                PointUtf16::new(range.end.row, u32::MAX),
5720                                Bias::Left,
5721                            ) > range.end
5722                        {
5723                            break;
5724                        }
5725                        new_text.push('\n');
5726                    }
5727                    range.end = next_range.end;
5728                    new_text.push_str(&next_text);
5729                    lsp_edits.next();
5730                }
5731
5732                if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
5733                    || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
5734                {
5735                    return Err(anyhow!("invalid edits received from language server"));
5736                }
5737
5738                // For multiline edits, perform a diff of the old and new text so that
5739                // we can identify the changes more precisely, preserving the locations
5740                // of any anchors positioned in the unchanged regions.
5741                if range.end.row > range.start.row {
5742                    let mut offset = range.start.to_offset(&snapshot);
5743                    let old_text = snapshot.text_for_range(range).collect::<String>();
5744
5745                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5746                    let mut moved_since_edit = true;
5747                    for change in diff.iter_all_changes() {
5748                        let tag = change.tag();
5749                        let value = change.value();
5750                        match tag {
5751                            ChangeTag::Equal => {
5752                                offset += value.len();
5753                                moved_since_edit = true;
5754                            }
5755                            ChangeTag::Delete => {
5756                                let start = snapshot.anchor_after(offset);
5757                                let end = snapshot.anchor_before(offset + value.len());
5758                                if moved_since_edit {
5759                                    edits.push((start..end, String::new()));
5760                                } else {
5761                                    edits.last_mut().unwrap().0.end = end;
5762                                }
5763                                offset += value.len();
5764                                moved_since_edit = false;
5765                            }
5766                            ChangeTag::Insert => {
5767                                if moved_since_edit {
5768                                    let anchor = snapshot.anchor_after(offset);
5769                                    edits.push((anchor.clone()..anchor, value.to_string()));
5770                                } else {
5771                                    edits.last_mut().unwrap().1.push_str(value);
5772                                }
5773                                moved_since_edit = false;
5774                            }
5775                        }
5776                    }
5777                } else if range.end == range.start {
5778                    let anchor = snapshot.anchor_after(range.start);
5779                    edits.push((anchor.clone()..anchor, new_text));
5780                } else {
5781                    let edit_start = snapshot.anchor_after(range.start);
5782                    let edit_end = snapshot.anchor_before(range.end);
5783                    edits.push((edit_start..edit_end, new_text));
5784                }
5785            }
5786
5787            Ok(edits)
5788        })
5789    }
5790
5791    fn buffer_snapshot_for_lsp_version(
5792        &mut self,
5793        buffer: &ModelHandle<Buffer>,
5794        version: Option<i32>,
5795        cx: &AppContext,
5796    ) -> Result<TextBufferSnapshot> {
5797        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5798
5799        if let Some(version) = version {
5800            let buffer_id = buffer.read(cx).remote_id();
5801            let snapshots = self
5802                .buffer_snapshots
5803                .get_mut(&buffer_id)
5804                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5805            let mut found_snapshot = None;
5806            snapshots.retain(|(snapshot_version, snapshot)| {
5807                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5808                    false
5809                } else {
5810                    if *snapshot_version == version {
5811                        found_snapshot = Some(snapshot.clone());
5812                    }
5813                    true
5814                }
5815            });
5816
5817            found_snapshot.ok_or_else(|| {
5818                anyhow!(
5819                    "snapshot not found for buffer {} at version {}",
5820                    buffer_id,
5821                    version
5822                )
5823            })
5824        } else {
5825            Ok((buffer.read(cx)).text_snapshot())
5826        }
5827    }
5828
5829    fn language_server_for_buffer(
5830        &self,
5831        buffer: &Buffer,
5832        cx: &AppContext,
5833    ) -> Option<(&Arc<dyn LspAdapter>, &Arc<LanguageServer>)> {
5834        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5835            let worktree_id = file.worktree_id(cx);
5836            let key = (worktree_id, language.lsp_adapter()?.name());
5837
5838            if let Some(server_id) = self.language_server_ids.get(&key) {
5839                if let Some(LanguageServerState::Running { adapter, server }) =
5840                    self.language_servers.get(&server_id)
5841                {
5842                    return Some((adapter, server));
5843                }
5844            }
5845        }
5846
5847        None
5848    }
5849}
5850
5851impl ProjectStore {
5852    pub fn new(db: Arc<Db>) -> Self {
5853        Self {
5854            db,
5855            projects: Default::default(),
5856        }
5857    }
5858
5859    pub fn projects<'a>(
5860        &'a self,
5861        cx: &'a AppContext,
5862    ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5863        self.projects
5864            .iter()
5865            .filter_map(|project| project.upgrade(cx))
5866    }
5867
5868    fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5869        if let Err(ix) = self
5870            .projects
5871            .binary_search_by_key(&project.id(), WeakModelHandle::id)
5872        {
5873            self.projects.insert(ix, project);
5874        }
5875        cx.notify();
5876    }
5877
5878    fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
5879        let mut did_change = false;
5880        self.projects.retain(|project| {
5881            if project.is_upgradable(cx) {
5882                true
5883            } else {
5884                did_change = true;
5885                false
5886            }
5887        });
5888        if did_change {
5889            cx.notify();
5890        }
5891    }
5892}
5893
5894impl WorktreeHandle {
5895    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5896        match self {
5897            WorktreeHandle::Strong(handle) => Some(handle.clone()),
5898            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5899        }
5900    }
5901}
5902
5903impl OpenBuffer {
5904    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5905        match self {
5906            OpenBuffer::Strong(handle) => Some(handle.clone()),
5907            OpenBuffer::Weak(handle) => handle.upgrade(cx),
5908            OpenBuffer::Loading(_) => None,
5909        }
5910    }
5911}
5912
5913pub struct PathMatchCandidateSet {
5914    pub snapshot: Snapshot,
5915    pub include_ignored: bool,
5916    pub include_root_name: bool,
5917}
5918
5919impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5920    type Candidates = PathMatchCandidateSetIter<'a>;
5921
5922    fn id(&self) -> usize {
5923        self.snapshot.id().to_usize()
5924    }
5925
5926    fn len(&self) -> usize {
5927        if self.include_ignored {
5928            self.snapshot.file_count()
5929        } else {
5930            self.snapshot.visible_file_count()
5931        }
5932    }
5933
5934    fn prefix(&self) -> Arc<str> {
5935        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5936            self.snapshot.root_name().into()
5937        } else if self.include_root_name {
5938            format!("{}/", self.snapshot.root_name()).into()
5939        } else {
5940            "".into()
5941        }
5942    }
5943
5944    fn candidates(&'a self, start: usize) -> Self::Candidates {
5945        PathMatchCandidateSetIter {
5946            traversal: self.snapshot.files(self.include_ignored, start),
5947        }
5948    }
5949}
5950
5951pub struct PathMatchCandidateSetIter<'a> {
5952    traversal: Traversal<'a>,
5953}
5954
5955impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5956    type Item = fuzzy::PathMatchCandidate<'a>;
5957
5958    fn next(&mut self) -> Option<Self::Item> {
5959        self.traversal.next().map(|entry| {
5960            if let EntryKind::File(char_bag) = entry.kind {
5961                fuzzy::PathMatchCandidate {
5962                    path: &entry.path,
5963                    char_bag,
5964                }
5965            } else {
5966                unreachable!()
5967            }
5968        })
5969    }
5970}
5971
5972impl Entity for ProjectStore {
5973    type Event = ();
5974}
5975
5976impl Entity for Project {
5977    type Event = Event;
5978
5979    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
5980        self.project_store.update(cx, ProjectStore::prune_projects);
5981
5982        match &self.client_state {
5983            ProjectClientState::Local { remote_id_rx, .. } => {
5984                if let Some(project_id) = *remote_id_rx.borrow() {
5985                    self.client
5986                        .send(proto::UnregisterProject { project_id })
5987                        .log_err();
5988                }
5989            }
5990            ProjectClientState::Remote { remote_id, .. } => {
5991                self.client
5992                    .send(proto::LeaveProject {
5993                        project_id: *remote_id,
5994                    })
5995                    .log_err();
5996            }
5997        }
5998    }
5999
6000    fn app_will_quit(
6001        &mut self,
6002        _: &mut MutableAppContext,
6003    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6004        let shutdown_futures = self
6005            .language_servers
6006            .drain()
6007            .map(|(_, server_state)| async {
6008                match server_state {
6009                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6010                    LanguageServerState::Starting(starting_server) => {
6011                        starting_server.await?.shutdown()?.await
6012                    }
6013                }
6014            })
6015            .collect::<Vec<_>>();
6016
6017        Some(
6018            async move {
6019                futures::future::join_all(shutdown_futures).await;
6020            }
6021            .boxed(),
6022        )
6023    }
6024}
6025
6026impl Collaborator {
6027    fn from_proto(
6028        message: proto::Collaborator,
6029        user_store: &ModelHandle<UserStore>,
6030        cx: &mut AsyncAppContext,
6031    ) -> impl Future<Output = Result<Self>> {
6032        let user = user_store.update(cx, |user_store, cx| {
6033            user_store.fetch_user(message.user_id, cx)
6034        });
6035
6036        async move {
6037            Ok(Self {
6038                peer_id: PeerId(message.peer_id),
6039                user: user.await?,
6040                replica_id: message.replica_id as ReplicaId,
6041            })
6042        }
6043    }
6044}
6045
6046impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6047    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6048        Self {
6049            worktree_id,
6050            path: path.as_ref().into(),
6051        }
6052    }
6053}
6054
6055impl From<lsp::CreateFileOptions> for fs::CreateOptions {
6056    fn from(options: lsp::CreateFileOptions) -> Self {
6057        Self {
6058            overwrite: options.overwrite.unwrap_or(false),
6059            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6060        }
6061    }
6062}
6063
6064impl From<lsp::RenameFileOptions> for fs::RenameOptions {
6065    fn from(options: lsp::RenameFileOptions) -> Self {
6066        Self {
6067            overwrite: options.overwrite.unwrap_or(false),
6068            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6069        }
6070    }
6071}
6072
6073impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6074    fn from(options: lsp::DeleteFileOptions) -> Self {
6075        Self {
6076            recursive: options.recursive.unwrap_or(false),
6077            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6078        }
6079    }
6080}
6081
6082fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6083    proto::Symbol {
6084        source_worktree_id: symbol.source_worktree_id.to_proto(),
6085        worktree_id: symbol.worktree_id.to_proto(),
6086        language_server_name: symbol.language_server_name.0.to_string(),
6087        name: symbol.name.clone(),
6088        kind: unsafe { mem::transmute(symbol.kind) },
6089        path: symbol.path.to_string_lossy().to_string(),
6090        start: Some(proto::Point {
6091            row: symbol.range.start.row,
6092            column: symbol.range.start.column,
6093        }),
6094        end: Some(proto::Point {
6095            row: symbol.range.end.row,
6096            column: symbol.range.end.column,
6097        }),
6098        signature: symbol.signature.to_vec(),
6099    }
6100}
6101
6102fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6103    let mut path_components = path.components();
6104    let mut base_components = base.components();
6105    let mut components: Vec<Component> = Vec::new();
6106    loop {
6107        match (path_components.next(), base_components.next()) {
6108            (None, None) => break,
6109            (Some(a), None) => {
6110                components.push(a);
6111                components.extend(path_components.by_ref());
6112                break;
6113            }
6114            (None, _) => components.push(Component::ParentDir),
6115            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6116            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6117            (Some(a), Some(_)) => {
6118                components.push(Component::ParentDir);
6119                for _ in base_components {
6120                    components.push(Component::ParentDir);
6121                }
6122                components.push(a);
6123                components.extend(path_components.by_ref());
6124                break;
6125            }
6126        }
6127    }
6128    components.iter().map(|c| c.as_os_str()).collect()
6129}
6130
6131impl Item for Buffer {
6132    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6133        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6134    }
6135}