project.rs

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