project.rs

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