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(Some(language.clone()), cx);
2060        });
2061
2062        let file = File::from_dyn(buffer.read(cx).file())?;
2063        let worktree = file.worktree.read(cx).as_local()?;
2064        let worktree_id = worktree.id();
2065        let worktree_abs_path = worktree.abs_path().clone();
2066        self.start_language_server(worktree_id, worktree_abs_path, language, cx);
2067
2068        None
2069    }
2070
2071    fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
2072        use serde_json::Value;
2073
2074        match (source, target) {
2075            (Value::Object(source), Value::Object(target)) => {
2076                for (key, value) in source {
2077                    if let Some(target) = target.get_mut(&key) {
2078                        Self::merge_json_value_into(value, target);
2079                    } else {
2080                        target.insert(key.clone(), value);
2081                    }
2082                }
2083            }
2084
2085            (source, target) => *target = source,
2086        }
2087    }
2088
2089    fn start_language_server(
2090        &mut self,
2091        worktree_id: WorktreeId,
2092        worktree_path: Arc<Path>,
2093        language: Arc<Language>,
2094        cx: &mut ModelContext<Self>,
2095    ) {
2096        if !cx
2097            .global::<Settings>()
2098            .enable_language_server(Some(&language.name()))
2099        {
2100            return;
2101        }
2102
2103        let adapter = if let Some(adapter) = language.lsp_adapter() {
2104            adapter
2105        } else {
2106            return;
2107        };
2108        let key = (worktree_id, adapter.name.clone());
2109
2110        let mut initialization_options = adapter.initialization_options.clone();
2111
2112        let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
2113        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2114        match (&mut initialization_options, override_options) {
2115            (Some(initialization_options), Some(override_options)) => {
2116                Self::merge_json_value_into(override_options, initialization_options);
2117            }
2118
2119            (None, override_options) => initialization_options = override_options,
2120
2121            _ => {}
2122        }
2123
2124        self.language_server_ids
2125            .entry(key.clone())
2126            .or_insert_with(|| {
2127                let server_id = post_inc(&mut self.next_language_server_id);
2128                let language_server = self.languages.start_language_server(
2129                    server_id,
2130                    language.clone(),
2131                    worktree_path,
2132                    self.client.http_client(),
2133                    cx,
2134                );
2135                self.language_servers.insert(
2136                    server_id,
2137                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2138                        let language_server = language_server?.await.log_err()?;
2139                        let language_server = language_server
2140                            .initialize(initialization_options)
2141                            .await
2142                            .log_err()?;
2143                        let this = this.upgrade(&cx)?;
2144
2145                        language_server
2146                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
2147                                let this = this.downgrade();
2148                                let adapter = adapter.clone();
2149                                move |mut params, cx| {
2150                                    let this = this;
2151                                    let adapter = adapter.clone();
2152                                    cx.spawn(|mut cx| async move {
2153                                        adapter.process_diagnostics(&mut params).await;
2154                                        if let Some(this) = this.upgrade(&cx) {
2155                                            this.update(&mut cx, |this, cx| {
2156                                                this.update_diagnostics(
2157                                                    server_id,
2158                                                    params,
2159                                                    &adapter.disk_based_diagnostic_sources,
2160                                                    cx,
2161                                                )
2162                                                .log_err();
2163                                            });
2164                                        }
2165                                    })
2166                                    .detach();
2167                                }
2168                            })
2169                            .detach();
2170
2171                        language_server
2172                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2173                                let settings = this.read_with(&cx, |this, _| {
2174                                    this.language_server_settings.clone()
2175                                });
2176                                move |params, _| {
2177                                    let settings = settings.lock().clone();
2178                                    async move {
2179                                        Ok(params
2180                                            .items
2181                                            .into_iter()
2182                                            .map(|item| {
2183                                                if let Some(section) = &item.section {
2184                                                    settings
2185                                                        .get(section)
2186                                                        .cloned()
2187                                                        .unwrap_or(serde_json::Value::Null)
2188                                                } else {
2189                                                    settings.clone()
2190                                                }
2191                                            })
2192                                            .collect())
2193                                    }
2194                                }
2195                            })
2196                            .detach();
2197
2198                        // Even though we don't have handling for these requests, respond to them to
2199                        // avoid stalling any language server like `gopls` which waits for a response
2200                        // to these requests when initializing.
2201                        language_server
2202                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2203                                let this = this.downgrade();
2204                                move |params, mut cx| async move {
2205                                    if let Some(this) = this.upgrade(&cx) {
2206                                        this.update(&mut cx, |this, _| {
2207                                            if let Some(status) =
2208                                                this.language_server_statuses.get_mut(&server_id)
2209                                            {
2210                                                if let lsp::NumberOrString::String(token) =
2211                                                    params.token
2212                                                {
2213                                                    status.progress_tokens.insert(token);
2214                                                }
2215                                            }
2216                                        });
2217                                    }
2218                                    Ok(())
2219                                }
2220                            })
2221                            .detach();
2222                        language_server
2223                            .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2224                                Ok(())
2225                            })
2226                            .detach();
2227
2228                        language_server
2229                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2230                                let this = this.downgrade();
2231                                let adapter = adapter.clone();
2232                                let language_server = language_server.clone();
2233                                move |params, cx| {
2234                                    Self::on_lsp_workspace_edit(
2235                                        this,
2236                                        params,
2237                                        server_id,
2238                                        adapter.clone(),
2239                                        language_server.clone(),
2240                                        cx,
2241                                    )
2242                                }
2243                            })
2244                            .detach();
2245
2246                        let disk_based_diagnostics_progress_token =
2247                            adapter.disk_based_diagnostics_progress_token.clone();
2248
2249                        language_server
2250                            .on_notification::<lsp::notification::Progress, _>({
2251                                let this = this.downgrade();
2252                                move |params, mut cx| {
2253                                    if let Some(this) = this.upgrade(&cx) {
2254                                        this.update(&mut cx, |this, cx| {
2255                                            this.on_lsp_progress(
2256                                                params,
2257                                                server_id,
2258                                                disk_based_diagnostics_progress_token.clone(),
2259                                                cx,
2260                                            );
2261                                        });
2262                                    }
2263                                }
2264                            })
2265                            .detach();
2266
2267                        this.update(&mut cx, |this, cx| {
2268                            // If the language server for this key doesn't match the server id, don't store the
2269                            // server. Which will cause it to be dropped, killing the process
2270                            if this
2271                                .language_server_ids
2272                                .get(&key)
2273                                .map(|id| id != &server_id)
2274                                .unwrap_or(false)
2275                            {
2276                                return None;
2277                            }
2278
2279                            // Update language_servers collection with Running variant of LanguageServerState
2280                            // indicating that the server is up and running and ready
2281                            this.language_servers.insert(
2282                                server_id,
2283                                LanguageServerState::Running {
2284                                    adapter: adapter.clone(),
2285                                    server: language_server.clone(),
2286                                },
2287                            );
2288                            this.language_server_statuses.insert(
2289                                server_id,
2290                                LanguageServerStatus {
2291                                    name: language_server.name().to_string(),
2292                                    pending_work: Default::default(),
2293                                    has_pending_diagnostic_updates: false,
2294                                    progress_tokens: Default::default(),
2295                                },
2296                            );
2297                            language_server
2298                                .notify::<lsp::notification::DidChangeConfiguration>(
2299                                    lsp::DidChangeConfigurationParams {
2300                                        settings: this.language_server_settings.lock().clone(),
2301                                    },
2302                                )
2303                                .ok();
2304
2305                            if let Some(project_id) = this.shared_remote_id() {
2306                                this.client
2307                                    .send(proto::StartLanguageServer {
2308                                        project_id,
2309                                        server: Some(proto::LanguageServer {
2310                                            id: server_id as u64,
2311                                            name: language_server.name().to_string(),
2312                                        }),
2313                                    })
2314                                    .log_err();
2315                            }
2316
2317                            // Tell the language server about every open buffer in the worktree that matches the language.
2318                            for buffer in this.opened_buffers.values() {
2319                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2320                                    let buffer = buffer_handle.read(cx);
2321                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2322                                        file
2323                                    } else {
2324                                        continue;
2325                                    };
2326                                    let language = if let Some(language) = buffer.language() {
2327                                        language
2328                                    } else {
2329                                        continue;
2330                                    };
2331                                    if file.worktree.read(cx).id() != key.0
2332                                        || language.lsp_adapter().map(|a| a.name.clone())
2333                                            != Some(key.1.clone())
2334                                    {
2335                                        continue;
2336                                    }
2337
2338                                    let file = file.as_local()?;
2339                                    let versions = this
2340                                        .buffer_snapshots
2341                                        .entry(buffer.remote_id())
2342                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2343                                    let (version, initial_snapshot) = versions.last().unwrap();
2344                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2345                                    language_server
2346                                        .notify::<lsp::notification::DidOpenTextDocument>(
2347                                            lsp::DidOpenTextDocumentParams {
2348                                                text_document: lsp::TextDocumentItem::new(
2349                                                    uri,
2350                                                    adapter
2351                                                        .language_ids
2352                                                        .get(language.name().as_ref())
2353                                                        .cloned()
2354                                                        .unwrap_or_default(),
2355                                                    *version,
2356                                                    initial_snapshot.text(),
2357                                                ),
2358                                            },
2359                                        )
2360                                        .log_err()?;
2361                                    buffer_handle.update(cx, |buffer, cx| {
2362                                        buffer.set_completion_triggers(
2363                                            language_server
2364                                                .capabilities()
2365                                                .completion_provider
2366                                                .as_ref()
2367                                                .and_then(|provider| {
2368                                                    provider.trigger_characters.clone()
2369                                                })
2370                                                .unwrap_or_default(),
2371                                            cx,
2372                                        )
2373                                    });
2374                                }
2375                            }
2376
2377                            cx.notify();
2378                            Some(language_server)
2379                        })
2380                    })),
2381                );
2382
2383                server_id
2384            });
2385    }
2386
2387    // Returns a list of all of the worktrees which no longer have a language server and the root path
2388    // for the stopped server
2389    fn stop_language_server(
2390        &mut self,
2391        worktree_id: WorktreeId,
2392        adapter_name: LanguageServerName,
2393        cx: &mut ModelContext<Self>,
2394    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2395        let key = (worktree_id, adapter_name);
2396        if let Some(server_id) = self.language_server_ids.remove(&key) {
2397            // Remove other entries for this language server as well
2398            let mut orphaned_worktrees = vec![worktree_id];
2399            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2400            for other_key in other_keys {
2401                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2402                    self.language_server_ids.remove(&other_key);
2403                    orphaned_worktrees.push(other_key.0);
2404                }
2405            }
2406
2407            self.language_server_statuses.remove(&server_id);
2408            cx.notify();
2409
2410            let server_state = self.language_servers.remove(&server_id);
2411            cx.spawn_weak(|this, mut cx| async move {
2412                let mut root_path = None;
2413
2414                let server = match server_state {
2415                    Some(LanguageServerState::Starting(started_language_server)) => {
2416                        started_language_server.await
2417                    }
2418                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2419                    None => None,
2420                };
2421
2422                if let Some(server) = server {
2423                    root_path = Some(server.root_path().clone());
2424                    if let Some(shutdown) = server.shutdown() {
2425                        shutdown.await;
2426                    }
2427                }
2428
2429                if let Some(this) = this.upgrade(&cx) {
2430                    this.update(&mut cx, |this, cx| {
2431                        this.language_server_statuses.remove(&server_id);
2432                        cx.notify();
2433                    });
2434                }
2435
2436                (root_path, orphaned_worktrees)
2437            })
2438        } else {
2439            Task::ready((None, Vec::new()))
2440        }
2441    }
2442
2443    pub fn restart_language_servers_for_buffers(
2444        &mut self,
2445        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2446        cx: &mut ModelContext<Self>,
2447    ) -> Option<()> {
2448        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2449            .into_iter()
2450            .filter_map(|buffer| {
2451                let file = File::from_dyn(buffer.read(cx).file())?;
2452                let worktree = file.worktree.read(cx).as_local()?;
2453                let worktree_id = worktree.id();
2454                let worktree_abs_path = worktree.abs_path().clone();
2455                let full_path = file.full_path(cx);
2456                Some((worktree_id, worktree_abs_path, full_path))
2457            })
2458            .collect();
2459        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2460            let language = self.languages.select_language(&full_path)?;
2461            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2462        }
2463
2464        None
2465    }
2466
2467    fn restart_language_server(
2468        &mut self,
2469        worktree_id: WorktreeId,
2470        fallback_path: Arc<Path>,
2471        language: Arc<Language>,
2472        cx: &mut ModelContext<Self>,
2473    ) {
2474        let adapter = if let Some(adapter) = language.lsp_adapter() {
2475            adapter
2476        } else {
2477            return;
2478        };
2479
2480        let server_name = adapter.name.clone();
2481        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2482        cx.spawn_weak(|this, mut cx| async move {
2483            let (original_root_path, orphaned_worktrees) = stop.await;
2484            if let Some(this) = this.upgrade(&cx) {
2485                this.update(&mut cx, |this, cx| {
2486                    // Attempt to restart using original server path. Fallback to passed in
2487                    // path if we could not retrieve the root path
2488                    let root_path = original_root_path
2489                        .map(|path_buf| Arc::from(path_buf.as_path()))
2490                        .unwrap_or(fallback_path);
2491
2492                    this.start_language_server(worktree_id, root_path, language, cx);
2493
2494                    // Lookup new server id and set it for each of the orphaned worktrees
2495                    if let Some(new_server_id) = this
2496                        .language_server_ids
2497                        .get(&(worktree_id, server_name.clone()))
2498                        .cloned()
2499                    {
2500                        for orphaned_worktree in orphaned_worktrees {
2501                            this.language_server_ids
2502                                .insert((orphaned_worktree, server_name.clone()), new_server_id);
2503                        }
2504                    }
2505                });
2506            }
2507        })
2508        .detach();
2509    }
2510
2511    fn on_lsp_progress(
2512        &mut self,
2513        progress: lsp::ProgressParams,
2514        server_id: usize,
2515        disk_based_diagnostics_progress_token: Option<String>,
2516        cx: &mut ModelContext<Self>,
2517    ) {
2518        let token = match progress.token {
2519            lsp::NumberOrString::String(token) => token,
2520            lsp::NumberOrString::Number(token) => {
2521                log::info!("skipping numeric progress token {}", token);
2522                return;
2523            }
2524        };
2525        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2526        let language_server_status =
2527            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2528                status
2529            } else {
2530                return;
2531            };
2532
2533        if !language_server_status.progress_tokens.contains(&token) {
2534            return;
2535        }
2536
2537        let is_disk_based_diagnostics_progress =
2538            Some(token.as_ref()) == disk_based_diagnostics_progress_token.as_deref();
2539
2540        match progress {
2541            lsp::WorkDoneProgress::Begin(report) => {
2542                if is_disk_based_diagnostics_progress {
2543                    language_server_status.has_pending_diagnostic_updates = true;
2544                    self.disk_based_diagnostics_started(server_id, cx);
2545                    self.broadcast_language_server_update(
2546                        server_id,
2547                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2548                            proto::LspDiskBasedDiagnosticsUpdating {},
2549                        ),
2550                    );
2551                } else {
2552                    self.on_lsp_work_start(
2553                        server_id,
2554                        token.clone(),
2555                        LanguageServerProgress {
2556                            message: report.message.clone(),
2557                            percentage: report.percentage.map(|p| p as usize),
2558                            last_update_at: Instant::now(),
2559                        },
2560                        cx,
2561                    );
2562                    self.broadcast_language_server_update(
2563                        server_id,
2564                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2565                            token,
2566                            message: report.message,
2567                            percentage: report.percentage.map(|p| p as u32),
2568                        }),
2569                    );
2570                }
2571            }
2572            lsp::WorkDoneProgress::Report(report) => {
2573                if !is_disk_based_diagnostics_progress {
2574                    self.on_lsp_work_progress(
2575                        server_id,
2576                        token.clone(),
2577                        LanguageServerProgress {
2578                            message: report.message.clone(),
2579                            percentage: report.percentage.map(|p| p as usize),
2580                            last_update_at: Instant::now(),
2581                        },
2582                        cx,
2583                    );
2584                    self.broadcast_language_server_update(
2585                        server_id,
2586                        proto::update_language_server::Variant::WorkProgress(
2587                            proto::LspWorkProgress {
2588                                token,
2589                                message: report.message,
2590                                percentage: report.percentage.map(|p| p as u32),
2591                            },
2592                        ),
2593                    );
2594                }
2595            }
2596            lsp::WorkDoneProgress::End(_) => {
2597                language_server_status.progress_tokens.remove(&token);
2598
2599                if is_disk_based_diagnostics_progress {
2600                    language_server_status.has_pending_diagnostic_updates = false;
2601                    self.disk_based_diagnostics_finished(server_id, cx);
2602                    self.broadcast_language_server_update(
2603                        server_id,
2604                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2605                            proto::LspDiskBasedDiagnosticsUpdated {},
2606                        ),
2607                    );
2608                } else {
2609                    self.on_lsp_work_end(server_id, token.clone(), cx);
2610                    self.broadcast_language_server_update(
2611                        server_id,
2612                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2613                            token,
2614                        }),
2615                    );
2616                }
2617            }
2618        }
2619    }
2620
2621    fn on_lsp_work_start(
2622        &mut self,
2623        language_server_id: usize,
2624        token: String,
2625        progress: LanguageServerProgress,
2626        cx: &mut ModelContext<Self>,
2627    ) {
2628        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2629            status.pending_work.insert(token, progress);
2630            cx.notify();
2631        }
2632    }
2633
2634    fn on_lsp_work_progress(
2635        &mut self,
2636        language_server_id: usize,
2637        token: String,
2638        progress: LanguageServerProgress,
2639        cx: &mut ModelContext<Self>,
2640    ) {
2641        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2642            let entry = status
2643                .pending_work
2644                .entry(token)
2645                .or_insert(LanguageServerProgress {
2646                    message: Default::default(),
2647                    percentage: Default::default(),
2648                    last_update_at: progress.last_update_at,
2649                });
2650            if progress.message.is_some() {
2651                entry.message = progress.message;
2652            }
2653            if progress.percentage.is_some() {
2654                entry.percentage = progress.percentage;
2655            }
2656            entry.last_update_at = progress.last_update_at;
2657            cx.notify();
2658        }
2659    }
2660
2661    fn on_lsp_work_end(
2662        &mut self,
2663        language_server_id: usize,
2664        token: String,
2665        cx: &mut ModelContext<Self>,
2666    ) {
2667        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2668            status.pending_work.remove(&token);
2669            cx.notify();
2670        }
2671    }
2672
2673    async fn on_lsp_workspace_edit(
2674        this: WeakModelHandle<Self>,
2675        params: lsp::ApplyWorkspaceEditParams,
2676        server_id: usize,
2677        adapter: Arc<CachedLspAdapter>,
2678        language_server: Arc<LanguageServer>,
2679        mut cx: AsyncAppContext,
2680    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2681        let this = this
2682            .upgrade(&cx)
2683            .ok_or_else(|| anyhow!("project project closed"))?;
2684        let transaction = Self::deserialize_workspace_edit(
2685            this.clone(),
2686            params.edit,
2687            true,
2688            adapter.clone(),
2689            language_server.clone(),
2690            &mut cx,
2691        )
2692        .await
2693        .log_err();
2694        this.update(&mut cx, |this, _| {
2695            if let Some(transaction) = transaction {
2696                this.last_workspace_edits_by_language_server
2697                    .insert(server_id, transaction);
2698            }
2699        });
2700        Ok(lsp::ApplyWorkspaceEditResponse {
2701            applied: true,
2702            failed_change: None,
2703            failure_reason: None,
2704        })
2705    }
2706
2707    fn broadcast_language_server_update(
2708        &self,
2709        language_server_id: usize,
2710        event: proto::update_language_server::Variant,
2711    ) {
2712        if let Some(project_id) = self.shared_remote_id() {
2713            self.client
2714                .send(proto::UpdateLanguageServer {
2715                    project_id,
2716                    language_server_id: language_server_id as u64,
2717                    variant: Some(event),
2718                })
2719                .log_err();
2720        }
2721    }
2722
2723    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2724        for server_state in self.language_servers.values() {
2725            if let LanguageServerState::Running { server, .. } = server_state {
2726                server
2727                    .notify::<lsp::notification::DidChangeConfiguration>(
2728                        lsp::DidChangeConfigurationParams {
2729                            settings: settings.clone(),
2730                        },
2731                    )
2732                    .ok();
2733            }
2734        }
2735        *self.language_server_settings.lock() = settings;
2736    }
2737
2738    pub fn language_server_statuses(
2739        &self,
2740    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2741        self.language_server_statuses.values()
2742    }
2743
2744    pub fn update_diagnostics(
2745        &mut self,
2746        language_server_id: usize,
2747        params: lsp::PublishDiagnosticsParams,
2748        disk_based_sources: &[String],
2749        cx: &mut ModelContext<Self>,
2750    ) -> Result<()> {
2751        let abs_path = params
2752            .uri
2753            .to_file_path()
2754            .map_err(|_| anyhow!("URI is not a file"))?;
2755        let mut diagnostics = Vec::default();
2756        let mut primary_diagnostic_group_ids = HashMap::default();
2757        let mut sources_by_group_id = HashMap::default();
2758        let mut supporting_diagnostics = HashMap::default();
2759        for diagnostic in &params.diagnostics {
2760            let source = diagnostic.source.as_ref();
2761            let code = diagnostic.code.as_ref().map(|code| match code {
2762                lsp::NumberOrString::Number(code) => code.to_string(),
2763                lsp::NumberOrString::String(code) => code.clone(),
2764            });
2765            let range = range_from_lsp(diagnostic.range);
2766            let is_supporting = diagnostic
2767                .related_information
2768                .as_ref()
2769                .map_or(false, |infos| {
2770                    infos.iter().any(|info| {
2771                        primary_diagnostic_group_ids.contains_key(&(
2772                            source,
2773                            code.clone(),
2774                            range_from_lsp(info.location.range),
2775                        ))
2776                    })
2777                });
2778
2779            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2780                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2781            });
2782
2783            if is_supporting {
2784                supporting_diagnostics.insert(
2785                    (source, code.clone(), range),
2786                    (diagnostic.severity, is_unnecessary),
2787                );
2788            } else {
2789                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2790                let is_disk_based =
2791                    source.map_or(false, |source| disk_based_sources.contains(source));
2792
2793                sources_by_group_id.insert(group_id, source);
2794                primary_diagnostic_group_ids
2795                    .insert((source, code.clone(), range.clone()), group_id);
2796
2797                diagnostics.push(DiagnosticEntry {
2798                    range,
2799                    diagnostic: Diagnostic {
2800                        code: code.clone(),
2801                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2802                        message: diagnostic.message.clone(),
2803                        group_id,
2804                        is_primary: true,
2805                        is_valid: true,
2806                        is_disk_based,
2807                        is_unnecessary,
2808                    },
2809                });
2810                if let Some(infos) = &diagnostic.related_information {
2811                    for info in infos {
2812                        if info.location.uri == params.uri && !info.message.is_empty() {
2813                            let range = range_from_lsp(info.location.range);
2814                            diagnostics.push(DiagnosticEntry {
2815                                range,
2816                                diagnostic: Diagnostic {
2817                                    code: code.clone(),
2818                                    severity: DiagnosticSeverity::INFORMATION,
2819                                    message: info.message.clone(),
2820                                    group_id,
2821                                    is_primary: false,
2822                                    is_valid: true,
2823                                    is_disk_based,
2824                                    is_unnecessary: false,
2825                                },
2826                            });
2827                        }
2828                    }
2829                }
2830            }
2831        }
2832
2833        for entry in &mut diagnostics {
2834            let diagnostic = &mut entry.diagnostic;
2835            if !diagnostic.is_primary {
2836                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2837                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2838                    source,
2839                    diagnostic.code.clone(),
2840                    entry.range.clone(),
2841                )) {
2842                    if let Some(severity) = severity {
2843                        diagnostic.severity = severity;
2844                    }
2845                    diagnostic.is_unnecessary = is_unnecessary;
2846                }
2847            }
2848        }
2849
2850        self.update_diagnostic_entries(
2851            language_server_id,
2852            abs_path,
2853            params.version,
2854            diagnostics,
2855            cx,
2856        )?;
2857        Ok(())
2858    }
2859
2860    pub fn update_diagnostic_entries(
2861        &mut self,
2862        language_server_id: usize,
2863        abs_path: PathBuf,
2864        version: Option<i32>,
2865        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2866        cx: &mut ModelContext<Project>,
2867    ) -> Result<(), anyhow::Error> {
2868        let (worktree, relative_path) = self
2869            .find_local_worktree(&abs_path, cx)
2870            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2871
2872        let project_path = ProjectPath {
2873            worktree_id: worktree.read(cx).id(),
2874            path: relative_path.into(),
2875        };
2876        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2877            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2878        }
2879
2880        let updated = worktree.update(cx, |worktree, cx| {
2881            worktree
2882                .as_local_mut()
2883                .ok_or_else(|| anyhow!("not a local worktree"))?
2884                .update_diagnostics(
2885                    language_server_id,
2886                    project_path.path.clone(),
2887                    diagnostics,
2888                    cx,
2889                )
2890        })?;
2891        if updated {
2892            cx.emit(Event::DiagnosticsUpdated {
2893                language_server_id,
2894                path: project_path,
2895            });
2896        }
2897        Ok(())
2898    }
2899
2900    fn update_buffer_diagnostics(
2901        &mut self,
2902        buffer: &ModelHandle<Buffer>,
2903        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2904        version: Option<i32>,
2905        cx: &mut ModelContext<Self>,
2906    ) -> Result<()> {
2907        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2908            Ordering::Equal
2909                .then_with(|| b.is_primary.cmp(&a.is_primary))
2910                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2911                .then_with(|| a.severity.cmp(&b.severity))
2912                .then_with(|| a.message.cmp(&b.message))
2913        }
2914
2915        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2916
2917        diagnostics.sort_unstable_by(|a, b| {
2918            Ordering::Equal
2919                .then_with(|| a.range.start.cmp(&b.range.start))
2920                .then_with(|| b.range.end.cmp(&a.range.end))
2921                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2922        });
2923
2924        let mut sanitized_diagnostics = Vec::new();
2925        let edits_since_save = Patch::new(
2926            snapshot
2927                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2928                .collect(),
2929        );
2930        for entry in diagnostics {
2931            let start;
2932            let end;
2933            if entry.diagnostic.is_disk_based {
2934                // Some diagnostics are based on files on disk instead of buffers'
2935                // current contents. Adjust these diagnostics' ranges to reflect
2936                // any unsaved edits.
2937                start = edits_since_save.old_to_new(entry.range.start);
2938                end = edits_since_save.old_to_new(entry.range.end);
2939            } else {
2940                start = entry.range.start;
2941                end = entry.range.end;
2942            }
2943
2944            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2945                ..snapshot.clip_point_utf16(end, Bias::Right);
2946
2947            // Expand empty ranges by one character
2948            if range.start == range.end {
2949                range.end.column += 1;
2950                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2951                if range.start == range.end && range.end.column > 0 {
2952                    range.start.column -= 1;
2953                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2954                }
2955            }
2956
2957            sanitized_diagnostics.push(DiagnosticEntry {
2958                range,
2959                diagnostic: entry.diagnostic,
2960            });
2961        }
2962        drop(edits_since_save);
2963
2964        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2965        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2966        Ok(())
2967    }
2968
2969    pub fn reload_buffers(
2970        &self,
2971        buffers: HashSet<ModelHandle<Buffer>>,
2972        push_to_history: bool,
2973        cx: &mut ModelContext<Self>,
2974    ) -> Task<Result<ProjectTransaction>> {
2975        let mut local_buffers = Vec::new();
2976        let mut remote_buffers = None;
2977        for buffer_handle in buffers {
2978            let buffer = buffer_handle.read(cx);
2979            if buffer.is_dirty() {
2980                if let Some(file) = File::from_dyn(buffer.file()) {
2981                    if file.is_local() {
2982                        local_buffers.push(buffer_handle);
2983                    } else {
2984                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2985                    }
2986                }
2987            }
2988        }
2989
2990        let remote_buffers = self.remote_id().zip(remote_buffers);
2991        let client = self.client.clone();
2992
2993        cx.spawn(|this, mut cx| async move {
2994            let mut project_transaction = ProjectTransaction::default();
2995
2996            if let Some((project_id, remote_buffers)) = remote_buffers {
2997                let response = client
2998                    .request(proto::ReloadBuffers {
2999                        project_id,
3000                        buffer_ids: remote_buffers
3001                            .iter()
3002                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3003                            .collect(),
3004                    })
3005                    .await?
3006                    .transaction
3007                    .ok_or_else(|| anyhow!("missing transaction"))?;
3008                project_transaction = this
3009                    .update(&mut cx, |this, cx| {
3010                        this.deserialize_project_transaction(response, push_to_history, cx)
3011                    })
3012                    .await?;
3013            }
3014
3015            for buffer in local_buffers {
3016                let transaction = buffer
3017                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
3018                    .await?;
3019                buffer.update(&mut cx, |buffer, cx| {
3020                    if let Some(transaction) = transaction {
3021                        if !push_to_history {
3022                            buffer.forget_transaction(transaction.id);
3023                        }
3024                        project_transaction.0.insert(cx.handle(), transaction);
3025                    }
3026                });
3027            }
3028
3029            Ok(project_transaction)
3030        })
3031    }
3032
3033    pub fn format(
3034        &self,
3035        buffers: HashSet<ModelHandle<Buffer>>,
3036        push_to_history: bool,
3037        cx: &mut ModelContext<Project>,
3038    ) -> Task<Result<ProjectTransaction>> {
3039        let mut local_buffers = Vec::new();
3040        let mut remote_buffers = None;
3041        for buffer_handle in buffers {
3042            let buffer = buffer_handle.read(cx);
3043            if let Some(file) = File::from_dyn(buffer.file()) {
3044                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
3045                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
3046                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
3047                    }
3048                } else {
3049                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3050                }
3051            } else {
3052                return Task::ready(Ok(Default::default()));
3053            }
3054        }
3055
3056        let remote_buffers = self.remote_id().zip(remote_buffers);
3057        let client = self.client.clone();
3058
3059        cx.spawn(|this, mut cx| async move {
3060            let mut project_transaction = ProjectTransaction::default();
3061
3062            if let Some((project_id, remote_buffers)) = remote_buffers {
3063                let response = client
3064                    .request(proto::FormatBuffers {
3065                        project_id,
3066                        buffer_ids: remote_buffers
3067                            .iter()
3068                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3069                            .collect(),
3070                    })
3071                    .await?
3072                    .transaction
3073                    .ok_or_else(|| anyhow!("missing transaction"))?;
3074                project_transaction = this
3075                    .update(&mut cx, |this, cx| {
3076                        this.deserialize_project_transaction(response, push_to_history, cx)
3077                    })
3078                    .await?;
3079            }
3080
3081            for (buffer, buffer_abs_path, language_server) in local_buffers {
3082                let (format_on_save, tab_size) = buffer.read_with(&cx, |buffer, cx| {
3083                    let settings = cx.global::<Settings>();
3084                    let language_name = buffer.language().map(|language| language.name());
3085                    (
3086                        settings.format_on_save(language_name.as_deref()),
3087                        settings.tab_size(language_name.as_deref()),
3088                    )
3089                });
3090
3091                let transaction = match format_on_save {
3092                    settings::FormatOnSave::Off => continue,
3093                    settings::FormatOnSave::LanguageServer => Self::format_via_lsp(
3094                        &this,
3095                        &buffer,
3096                        &buffer_abs_path,
3097                        &language_server,
3098                        tab_size,
3099                        &mut cx,
3100                    )
3101                    .await
3102                    .context("failed to format via language server")?,
3103                    settings::FormatOnSave::External { command, arguments } => {
3104                        Self::format_via_external_command(
3105                            &buffer,
3106                            &buffer_abs_path,
3107                            &command,
3108                            &arguments,
3109                            &mut cx,
3110                        )
3111                        .await
3112                        .context(format!(
3113                            "failed to format via external command {:?}",
3114                            command
3115                        ))?
3116                    }
3117                };
3118
3119                if let Some(transaction) = transaction {
3120                    if !push_to_history {
3121                        buffer.update(&mut cx, |buffer, _| {
3122                            buffer.forget_transaction(transaction.id)
3123                        });
3124                    }
3125                    project_transaction.0.insert(buffer, transaction);
3126                }
3127            }
3128
3129            Ok(project_transaction)
3130        })
3131    }
3132
3133    async fn format_via_lsp(
3134        this: &ModelHandle<Self>,
3135        buffer: &ModelHandle<Buffer>,
3136        abs_path: &Path,
3137        language_server: &Arc<LanguageServer>,
3138        tab_size: NonZeroU32,
3139        cx: &mut AsyncAppContext,
3140    ) -> Result<Option<Transaction>> {
3141        let text_document =
3142            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3143        let capabilities = &language_server.capabilities();
3144        let lsp_edits = if capabilities
3145            .document_formatting_provider
3146            .as_ref()
3147            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3148        {
3149            language_server
3150                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3151                    text_document,
3152                    options: lsp::FormattingOptions {
3153                        tab_size: tab_size.into(),
3154                        insert_spaces: true,
3155                        insert_final_newline: Some(true),
3156                        ..Default::default()
3157                    },
3158                    work_done_progress_params: Default::default(),
3159                })
3160                .await?
3161        } else if capabilities
3162            .document_range_formatting_provider
3163            .as_ref()
3164            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3165        {
3166            let buffer_start = lsp::Position::new(0, 0);
3167            let buffer_end =
3168                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3169            language_server
3170                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3171                    text_document,
3172                    range: lsp::Range::new(buffer_start, buffer_end),
3173                    options: lsp::FormattingOptions {
3174                        tab_size: tab_size.into(),
3175                        insert_spaces: true,
3176                        insert_final_newline: Some(true),
3177                        ..Default::default()
3178                    },
3179                    work_done_progress_params: Default::default(),
3180                })
3181                .await?
3182        } else {
3183            None
3184        };
3185
3186        if let Some(lsp_edits) = lsp_edits {
3187            let edits = this
3188                .update(cx, |this, cx| {
3189                    this.edits_from_lsp(buffer, lsp_edits, None, cx)
3190                })
3191                .await?;
3192            buffer.update(cx, |buffer, cx| {
3193                buffer.finalize_last_transaction();
3194                buffer.start_transaction();
3195                for (range, text) in edits {
3196                    buffer.edit([(range, text)], None, cx);
3197                }
3198                if buffer.end_transaction(cx).is_some() {
3199                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
3200                    Ok(Some(transaction))
3201                } else {
3202                    Ok(None)
3203                }
3204            })
3205        } else {
3206            Ok(None)
3207        }
3208    }
3209
3210    async fn format_via_external_command(
3211        buffer: &ModelHandle<Buffer>,
3212        buffer_abs_path: &Path,
3213        command: &str,
3214        arguments: &[String],
3215        cx: &mut AsyncAppContext,
3216    ) -> Result<Option<Transaction>> {
3217        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3218            let file = File::from_dyn(buffer.file())?;
3219            let worktree = file.worktree.read(cx).as_local()?;
3220            let mut worktree_path = worktree.abs_path().to_path_buf();
3221            if worktree.root_entry()?.is_file() {
3222                worktree_path.pop();
3223            }
3224            Some(worktree_path)
3225        });
3226
3227        if let Some(working_dir_path) = working_dir_path {
3228            let mut child =
3229                smol::process::Command::new(command)
3230                    .args(arguments.iter().map(|arg| {
3231                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3232                    }))
3233                    .current_dir(&working_dir_path)
3234                    .stdin(smol::process::Stdio::piped())
3235                    .stdout(smol::process::Stdio::piped())
3236                    .stderr(smol::process::Stdio::piped())
3237                    .spawn()?;
3238            let stdin = child
3239                .stdin
3240                .as_mut()
3241                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3242            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3243            for chunk in text.chunks() {
3244                stdin.write_all(chunk.as_bytes()).await?;
3245            }
3246            stdin.flush().await?;
3247
3248            let output = child.output().await?;
3249            if !output.status.success() {
3250                return Err(anyhow!(
3251                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3252                    output.status.code(),
3253                    String::from_utf8_lossy(&output.stdout),
3254                    String::from_utf8_lossy(&output.stderr),
3255                ));
3256            }
3257
3258            let stdout = String::from_utf8(output.stdout)?;
3259            let diff = buffer
3260                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3261                .await;
3262            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3263        } else {
3264            Ok(None)
3265        }
3266    }
3267
3268    pub fn definition<T: ToPointUtf16>(
3269        &self,
3270        buffer: &ModelHandle<Buffer>,
3271        position: T,
3272        cx: &mut ModelContext<Self>,
3273    ) -> Task<Result<Vec<LocationLink>>> {
3274        let position = position.to_point_utf16(buffer.read(cx));
3275        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3276    }
3277
3278    pub fn type_definition<T: ToPointUtf16>(
3279        &self,
3280        buffer: &ModelHandle<Buffer>,
3281        position: T,
3282        cx: &mut ModelContext<Self>,
3283    ) -> Task<Result<Vec<LocationLink>>> {
3284        let position = position.to_point_utf16(buffer.read(cx));
3285        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3286    }
3287
3288    pub fn references<T: ToPointUtf16>(
3289        &self,
3290        buffer: &ModelHandle<Buffer>,
3291        position: T,
3292        cx: &mut ModelContext<Self>,
3293    ) -> Task<Result<Vec<Location>>> {
3294        let position = position.to_point_utf16(buffer.read(cx));
3295        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3296    }
3297
3298    pub fn document_highlights<T: ToPointUtf16>(
3299        &self,
3300        buffer: &ModelHandle<Buffer>,
3301        position: T,
3302        cx: &mut ModelContext<Self>,
3303    ) -> Task<Result<Vec<DocumentHighlight>>> {
3304        let position = position.to_point_utf16(buffer.read(cx));
3305        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3306    }
3307
3308    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3309        if self.is_local() {
3310            let mut requests = Vec::new();
3311            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3312                let worktree_id = *worktree_id;
3313                if let Some(worktree) = self
3314                    .worktree_for_id(worktree_id, cx)
3315                    .and_then(|worktree| worktree.read(cx).as_local())
3316                {
3317                    if let Some(LanguageServerState::Running { adapter, server }) =
3318                        self.language_servers.get(server_id)
3319                    {
3320                        let adapter = adapter.clone();
3321                        let worktree_abs_path = worktree.abs_path().clone();
3322                        requests.push(
3323                            server
3324                                .request::<lsp::request::WorkspaceSymbol>(
3325                                    lsp::WorkspaceSymbolParams {
3326                                        query: query.to_string(),
3327                                        ..Default::default()
3328                                    },
3329                                )
3330                                .log_err()
3331                                .map(move |response| {
3332                                    (
3333                                        adapter,
3334                                        worktree_id,
3335                                        worktree_abs_path,
3336                                        response.unwrap_or_default(),
3337                                    )
3338                                }),
3339                        );
3340                    }
3341                }
3342            }
3343
3344            cx.spawn_weak(|this, cx| async move {
3345                let responses = futures::future::join_all(requests).await;
3346                let this = if let Some(this) = this.upgrade(&cx) {
3347                    this
3348                } else {
3349                    return Ok(Default::default());
3350                };
3351                let symbols = this.read_with(&cx, |this, cx| {
3352                    let mut symbols = Vec::new();
3353                    for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
3354                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3355                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3356                            let mut worktree_id = source_worktree_id;
3357                            let path;
3358                            if let Some((worktree, rel_path)) =
3359                                this.find_local_worktree(&abs_path, cx)
3360                            {
3361                                worktree_id = worktree.read(cx).id();
3362                                path = rel_path;
3363                            } else {
3364                                path = relativize_path(&worktree_abs_path, &abs_path);
3365                            }
3366
3367                            let project_path = ProjectPath {
3368                                worktree_id,
3369                                path: path.into(),
3370                            };
3371                            let signature = this.symbol_signature(&project_path);
3372                            let language = this.languages.select_language(&project_path.path);
3373                            let language_server_name = adapter.name.clone();
3374                            Some(async move {
3375                                let label = if let Some(language) = language {
3376                                    language
3377                                        .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3378                                        .await
3379                                } else {
3380                                    None
3381                                };
3382
3383                                Symbol {
3384                                    language_server_name,
3385                                    source_worktree_id,
3386                                    path: project_path,
3387                                    label: label.unwrap_or_else(|| {
3388                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3389                                    }),
3390                                    kind: lsp_symbol.kind,
3391                                    name: lsp_symbol.name,
3392                                    range: range_from_lsp(lsp_symbol.location.range),
3393                                    signature,
3394                                }
3395                            })
3396                        }));
3397                    }
3398                    symbols
3399                });
3400                Ok(futures::future::join_all(symbols).await)
3401            })
3402        } else if let Some(project_id) = self.remote_id() {
3403            let request = self.client.request(proto::GetProjectSymbols {
3404                project_id,
3405                query: query.to_string(),
3406            });
3407            cx.spawn_weak(|this, cx| async move {
3408                let response = request.await?;
3409                let mut symbols = Vec::new();
3410                if let Some(this) = this.upgrade(&cx) {
3411                    let new_symbols = this.read_with(&cx, |this, _| {
3412                        response
3413                            .symbols
3414                            .into_iter()
3415                            .map(|symbol| this.deserialize_symbol(symbol))
3416                            .collect::<Vec<_>>()
3417                    });
3418                    symbols = futures::future::join_all(new_symbols)
3419                        .await
3420                        .into_iter()
3421                        .filter_map(|symbol| symbol.log_err())
3422                        .collect::<Vec<_>>();
3423                }
3424                Ok(symbols)
3425            })
3426        } else {
3427            Task::ready(Ok(Default::default()))
3428        }
3429    }
3430
3431    pub fn open_buffer_for_symbol(
3432        &mut self,
3433        symbol: &Symbol,
3434        cx: &mut ModelContext<Self>,
3435    ) -> Task<Result<ModelHandle<Buffer>>> {
3436        if self.is_local() {
3437            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3438                symbol.source_worktree_id,
3439                symbol.language_server_name.clone(),
3440            )) {
3441                *id
3442            } else {
3443                return Task::ready(Err(anyhow!(
3444                    "language server for worktree and language not found"
3445                )));
3446            };
3447
3448            let worktree_abs_path = if let Some(worktree_abs_path) = self
3449                .worktree_for_id(symbol.path.worktree_id, cx)
3450                .and_then(|worktree| worktree.read(cx).as_local())
3451                .map(|local_worktree| local_worktree.abs_path())
3452            {
3453                worktree_abs_path
3454            } else {
3455                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3456            };
3457            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3458            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3459                uri
3460            } else {
3461                return Task::ready(Err(anyhow!("invalid symbol path")));
3462            };
3463
3464            self.open_local_buffer_via_lsp(
3465                symbol_uri,
3466                language_server_id,
3467                symbol.language_server_name.clone(),
3468                cx,
3469            )
3470        } else if let Some(project_id) = self.remote_id() {
3471            let request = self.client.request(proto::OpenBufferForSymbol {
3472                project_id,
3473                symbol: Some(serialize_symbol(symbol)),
3474            });
3475            cx.spawn(|this, mut cx| async move {
3476                let response = request.await?;
3477                this.update(&mut cx, |this, cx| {
3478                    this.wait_for_buffer(response.buffer_id, cx)
3479                })
3480                .await
3481            })
3482        } else {
3483            Task::ready(Err(anyhow!("project does not have a remote id")))
3484        }
3485    }
3486
3487    pub fn hover<T: ToPointUtf16>(
3488        &self,
3489        buffer: &ModelHandle<Buffer>,
3490        position: T,
3491        cx: &mut ModelContext<Self>,
3492    ) -> Task<Result<Option<Hover>>> {
3493        let position = position.to_point_utf16(buffer.read(cx));
3494        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3495    }
3496
3497    pub fn completions<T: ToPointUtf16>(
3498        &self,
3499        source_buffer_handle: &ModelHandle<Buffer>,
3500        position: T,
3501        cx: &mut ModelContext<Self>,
3502    ) -> Task<Result<Vec<Completion>>> {
3503        let source_buffer_handle = source_buffer_handle.clone();
3504        let source_buffer = source_buffer_handle.read(cx);
3505        let buffer_id = source_buffer.remote_id();
3506        let language = source_buffer.language().cloned();
3507        let worktree;
3508        let buffer_abs_path;
3509        if let Some(file) = File::from_dyn(source_buffer.file()) {
3510            worktree = file.worktree.clone();
3511            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3512        } else {
3513            return Task::ready(Ok(Default::default()));
3514        };
3515
3516        let position = position.to_point_utf16(source_buffer);
3517        let anchor = source_buffer.anchor_after(position);
3518
3519        if worktree.read(cx).as_local().is_some() {
3520            let buffer_abs_path = buffer_abs_path.unwrap();
3521            let lang_server =
3522                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3523                    server.clone()
3524                } else {
3525                    return Task::ready(Ok(Default::default()));
3526                };
3527
3528            cx.spawn(|_, cx| async move {
3529                let completions = lang_server
3530                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3531                        text_document_position: lsp::TextDocumentPositionParams::new(
3532                            lsp::TextDocumentIdentifier::new(
3533                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3534                            ),
3535                            point_to_lsp(position),
3536                        ),
3537                        context: Default::default(),
3538                        work_done_progress_params: Default::default(),
3539                        partial_result_params: Default::default(),
3540                    })
3541                    .await
3542                    .context("lsp completion request failed")?;
3543
3544                let completions = if let Some(completions) = completions {
3545                    match completions {
3546                        lsp::CompletionResponse::Array(completions) => completions,
3547                        lsp::CompletionResponse::List(list) => list.items,
3548                    }
3549                } else {
3550                    Default::default()
3551                };
3552
3553                let completions = source_buffer_handle.read_with(&cx, |this, _| {
3554                    let snapshot = this.snapshot();
3555                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3556                    let mut range_for_token = None;
3557                    completions.into_iter().filter_map(move |lsp_completion| {
3558                        // For now, we can only handle additional edits if they are returned
3559                        // when resolving the completion, not if they are present initially.
3560                        if lsp_completion
3561                            .additional_text_edits
3562                            .as_ref()
3563                            .map_or(false, |edits| !edits.is_empty())
3564                        {
3565                            return None;
3566                        }
3567
3568                        let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref() {
3569                            // If the language server provides a range to overwrite, then
3570                            // check that the range is valid.
3571                            Some(lsp::CompletionTextEdit::Edit(edit)) => {
3572                                let range = range_from_lsp(edit.range);
3573                                let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3574                                let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3575                                if start != range.start || end != range.end {
3576                                    log::info!("completion out of expected range");
3577                                    return None;
3578                                }
3579                                (
3580                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3581                                    edit.new_text.clone(),
3582                                )
3583                            }
3584                            // If the language server does not provide a range, then infer
3585                            // the range based on the syntax tree.
3586                            None => {
3587                                if position != clipped_position {
3588                                    log::info!("completion out of expected range");
3589                                    return None;
3590                                }
3591                                let Range { start, end } = range_for_token
3592                                    .get_or_insert_with(|| {
3593                                        let offset = position.to_offset(&snapshot);
3594                                        let (range, kind) = snapshot.surrounding_word(offset);
3595                                        if kind == Some(CharKind::Word) {
3596                                            range
3597                                        } else {
3598                                            offset..offset
3599                                        }
3600                                    })
3601                                    .clone();
3602                                let text = lsp_completion
3603                                    .insert_text
3604                                    .as_ref()
3605                                    .unwrap_or(&lsp_completion.label)
3606                                    .clone();
3607                                (
3608                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3609                                    text,
3610                                )
3611                            }
3612                            Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3613                                log::info!("unsupported insert/replace completion");
3614                                return None;
3615                            }
3616                        };
3617
3618                        LineEnding::normalize(&mut new_text);
3619                        let language = language.clone();
3620                        Some(async move {
3621                            let label = if let Some(language) = language {
3622                                language.label_for_completion(&lsp_completion).await
3623                            } else {
3624                                None
3625                            };
3626                            Completion {
3627                                old_range,
3628                                new_text,
3629                                label: label.unwrap_or_else(|| {
3630                                    CodeLabel::plain(
3631                                        lsp_completion.label.clone(),
3632                                        lsp_completion.filter_text.as_deref(),
3633                                    )
3634                                }),
3635                                lsp_completion,
3636                            }
3637                        })
3638                    })
3639                });
3640
3641                Ok(futures::future::join_all(completions).await)
3642            })
3643        } else if let Some(project_id) = self.remote_id() {
3644            let rpc = self.client.clone();
3645            let message = proto::GetCompletions {
3646                project_id,
3647                buffer_id,
3648                position: Some(language::proto::serialize_anchor(&anchor)),
3649                version: serialize_version(&source_buffer.version()),
3650            };
3651            cx.spawn_weak(|_, mut cx| async move {
3652                let response = rpc.request(message).await?;
3653
3654                source_buffer_handle
3655                    .update(&mut cx, |buffer, _| {
3656                        buffer.wait_for_version(deserialize_version(response.version))
3657                    })
3658                    .await;
3659
3660                let completions = response.completions.into_iter().map(|completion| {
3661                    language::proto::deserialize_completion(completion, language.clone())
3662                });
3663                futures::future::try_join_all(completions).await
3664            })
3665        } else {
3666            Task::ready(Ok(Default::default()))
3667        }
3668    }
3669
3670    pub fn apply_additional_edits_for_completion(
3671        &self,
3672        buffer_handle: ModelHandle<Buffer>,
3673        completion: Completion,
3674        push_to_history: bool,
3675        cx: &mut ModelContext<Self>,
3676    ) -> Task<Result<Option<Transaction>>> {
3677        let buffer = buffer_handle.read(cx);
3678        let buffer_id = buffer.remote_id();
3679
3680        if self.is_local() {
3681            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3682            {
3683                server.clone()
3684            } else {
3685                return Task::ready(Ok(Default::default()));
3686            };
3687
3688            cx.spawn(|this, mut cx| async move {
3689                let resolved_completion = lang_server
3690                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3691                    .await?;
3692                if let Some(edits) = resolved_completion.additional_text_edits {
3693                    let edits = this
3694                        .update(&mut cx, |this, cx| {
3695                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3696                        })
3697                        .await?;
3698                    buffer_handle.update(&mut cx, |buffer, cx| {
3699                        buffer.finalize_last_transaction();
3700                        buffer.start_transaction();
3701                        for (range, text) in edits {
3702                            buffer.edit([(range, text)], None, cx);
3703                        }
3704                        let transaction = if buffer.end_transaction(cx).is_some() {
3705                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3706                            if !push_to_history {
3707                                buffer.forget_transaction(transaction.id);
3708                            }
3709                            Some(transaction)
3710                        } else {
3711                            None
3712                        };
3713                        Ok(transaction)
3714                    })
3715                } else {
3716                    Ok(None)
3717                }
3718            })
3719        } else if let Some(project_id) = self.remote_id() {
3720            let client = self.client.clone();
3721            cx.spawn(|_, mut cx| async move {
3722                let response = client
3723                    .request(proto::ApplyCompletionAdditionalEdits {
3724                        project_id,
3725                        buffer_id,
3726                        completion: Some(language::proto::serialize_completion(&completion)),
3727                    })
3728                    .await?;
3729
3730                if let Some(transaction) = response.transaction {
3731                    let transaction = language::proto::deserialize_transaction(transaction)?;
3732                    buffer_handle
3733                        .update(&mut cx, |buffer, _| {
3734                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3735                        })
3736                        .await;
3737                    if push_to_history {
3738                        buffer_handle.update(&mut cx, |buffer, _| {
3739                            buffer.push_transaction(transaction.clone(), Instant::now());
3740                        });
3741                    }
3742                    Ok(Some(transaction))
3743                } else {
3744                    Ok(None)
3745                }
3746            })
3747        } else {
3748            Task::ready(Err(anyhow!("project does not have a remote id")))
3749        }
3750    }
3751
3752    pub fn code_actions<T: Clone + ToOffset>(
3753        &self,
3754        buffer_handle: &ModelHandle<Buffer>,
3755        range: Range<T>,
3756        cx: &mut ModelContext<Self>,
3757    ) -> Task<Result<Vec<CodeAction>>> {
3758        let buffer_handle = buffer_handle.clone();
3759        let buffer = buffer_handle.read(cx);
3760        let snapshot = buffer.snapshot();
3761        let relevant_diagnostics = snapshot
3762            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3763            .map(|entry| entry.to_lsp_diagnostic_stub())
3764            .collect();
3765        let buffer_id = buffer.remote_id();
3766        let worktree;
3767        let buffer_abs_path;
3768        if let Some(file) = File::from_dyn(buffer.file()) {
3769            worktree = file.worktree.clone();
3770            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3771        } else {
3772            return Task::ready(Ok(Default::default()));
3773        };
3774        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3775
3776        if worktree.read(cx).as_local().is_some() {
3777            let buffer_abs_path = buffer_abs_path.unwrap();
3778            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3779            {
3780                server.clone()
3781            } else {
3782                return Task::ready(Ok(Default::default()));
3783            };
3784
3785            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3786            cx.foreground().spawn(async move {
3787                if lang_server.capabilities().code_action_provider.is_none() {
3788                    return Ok(Default::default());
3789                }
3790
3791                Ok(lang_server
3792                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3793                        text_document: lsp::TextDocumentIdentifier::new(
3794                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3795                        ),
3796                        range: lsp_range,
3797                        work_done_progress_params: Default::default(),
3798                        partial_result_params: Default::default(),
3799                        context: lsp::CodeActionContext {
3800                            diagnostics: relevant_diagnostics,
3801                            only: Some(vec![
3802                                lsp::CodeActionKind::QUICKFIX,
3803                                lsp::CodeActionKind::REFACTOR,
3804                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3805                                lsp::CodeActionKind::SOURCE,
3806                            ]),
3807                        },
3808                    })
3809                    .await?
3810                    .unwrap_or_default()
3811                    .into_iter()
3812                    .filter_map(|entry| {
3813                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3814                            Some(CodeAction {
3815                                range: range.clone(),
3816                                lsp_action,
3817                            })
3818                        } else {
3819                            None
3820                        }
3821                    })
3822                    .collect())
3823            })
3824        } else if let Some(project_id) = self.remote_id() {
3825            let rpc = self.client.clone();
3826            let version = buffer.version();
3827            cx.spawn_weak(|_, mut cx| async move {
3828                let response = rpc
3829                    .request(proto::GetCodeActions {
3830                        project_id,
3831                        buffer_id,
3832                        start: Some(language::proto::serialize_anchor(&range.start)),
3833                        end: Some(language::proto::serialize_anchor(&range.end)),
3834                        version: serialize_version(&version),
3835                    })
3836                    .await?;
3837
3838                buffer_handle
3839                    .update(&mut cx, |buffer, _| {
3840                        buffer.wait_for_version(deserialize_version(response.version))
3841                    })
3842                    .await;
3843
3844                response
3845                    .actions
3846                    .into_iter()
3847                    .map(language::proto::deserialize_code_action)
3848                    .collect()
3849            })
3850        } else {
3851            Task::ready(Ok(Default::default()))
3852        }
3853    }
3854
3855    pub fn apply_code_action(
3856        &self,
3857        buffer_handle: ModelHandle<Buffer>,
3858        mut action: CodeAction,
3859        push_to_history: bool,
3860        cx: &mut ModelContext<Self>,
3861    ) -> Task<Result<ProjectTransaction>> {
3862        if self.is_local() {
3863            let buffer = buffer_handle.read(cx);
3864            let (lsp_adapter, lang_server) =
3865                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3866                    (adapter.clone(), server.clone())
3867                } else {
3868                    return Task::ready(Ok(Default::default()));
3869                };
3870            let range = action.range.to_point_utf16(buffer);
3871
3872            cx.spawn(|this, mut cx| async move {
3873                if let Some(lsp_range) = action
3874                    .lsp_action
3875                    .data
3876                    .as_mut()
3877                    .and_then(|d| d.get_mut("codeActionParams"))
3878                    .and_then(|d| d.get_mut("range"))
3879                {
3880                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3881                    action.lsp_action = lang_server
3882                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3883                        .await?;
3884                } else {
3885                    let actions = this
3886                        .update(&mut cx, |this, cx| {
3887                            this.code_actions(&buffer_handle, action.range, cx)
3888                        })
3889                        .await?;
3890                    action.lsp_action = actions
3891                        .into_iter()
3892                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3893                        .ok_or_else(|| anyhow!("code action is outdated"))?
3894                        .lsp_action;
3895                }
3896
3897                if let Some(edit) = action.lsp_action.edit {
3898                    if edit.changes.is_some() || edit.document_changes.is_some() {
3899                        return Self::deserialize_workspace_edit(
3900                            this,
3901                            edit,
3902                            push_to_history,
3903                            lsp_adapter.clone(),
3904                            lang_server.clone(),
3905                            &mut cx,
3906                        )
3907                        .await;
3908                    }
3909                }
3910
3911                if let Some(command) = action.lsp_action.command {
3912                    this.update(&mut cx, |this, _| {
3913                        this.last_workspace_edits_by_language_server
3914                            .remove(&lang_server.server_id());
3915                    });
3916                    lang_server
3917                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3918                            command: command.command,
3919                            arguments: command.arguments.unwrap_or_default(),
3920                            ..Default::default()
3921                        })
3922                        .await?;
3923                    return Ok(this.update(&mut cx, |this, _| {
3924                        this.last_workspace_edits_by_language_server
3925                            .remove(&lang_server.server_id())
3926                            .unwrap_or_default()
3927                    }));
3928                }
3929
3930                Ok(ProjectTransaction::default())
3931            })
3932        } else if let Some(project_id) = self.remote_id() {
3933            let client = self.client.clone();
3934            let request = proto::ApplyCodeAction {
3935                project_id,
3936                buffer_id: buffer_handle.read(cx).remote_id(),
3937                action: Some(language::proto::serialize_code_action(&action)),
3938            };
3939            cx.spawn(|this, mut cx| async move {
3940                let response = client
3941                    .request(request)
3942                    .await?
3943                    .transaction
3944                    .ok_or_else(|| anyhow!("missing transaction"))?;
3945                this.update(&mut cx, |this, cx| {
3946                    this.deserialize_project_transaction(response, push_to_history, cx)
3947                })
3948                .await
3949            })
3950        } else {
3951            Task::ready(Err(anyhow!("project does not have a remote id")))
3952        }
3953    }
3954
3955    async fn deserialize_workspace_edit(
3956        this: ModelHandle<Self>,
3957        edit: lsp::WorkspaceEdit,
3958        push_to_history: bool,
3959        lsp_adapter: Arc<CachedLspAdapter>,
3960        language_server: Arc<LanguageServer>,
3961        cx: &mut AsyncAppContext,
3962    ) -> Result<ProjectTransaction> {
3963        let fs = this.read_with(cx, |this, _| this.fs.clone());
3964        let mut operations = Vec::new();
3965        if let Some(document_changes) = edit.document_changes {
3966            match document_changes {
3967                lsp::DocumentChanges::Edits(edits) => {
3968                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3969                }
3970                lsp::DocumentChanges::Operations(ops) => operations = ops,
3971            }
3972        } else if let Some(changes) = edit.changes {
3973            operations.extend(changes.into_iter().map(|(uri, edits)| {
3974                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3975                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3976                        uri,
3977                        version: None,
3978                    },
3979                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3980                })
3981            }));
3982        }
3983
3984        let mut project_transaction = ProjectTransaction::default();
3985        for operation in operations {
3986            match operation {
3987                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3988                    let abs_path = op
3989                        .uri
3990                        .to_file_path()
3991                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3992
3993                    if let Some(parent_path) = abs_path.parent() {
3994                        fs.create_dir(parent_path).await?;
3995                    }
3996                    if abs_path.ends_with("/") {
3997                        fs.create_dir(&abs_path).await?;
3998                    } else {
3999                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4000                            .await?;
4001                    }
4002                }
4003                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4004                    let source_abs_path = op
4005                        .old_uri
4006                        .to_file_path()
4007                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4008                    let target_abs_path = op
4009                        .new_uri
4010                        .to_file_path()
4011                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4012                    fs.rename(
4013                        &source_abs_path,
4014                        &target_abs_path,
4015                        op.options.map(Into::into).unwrap_or_default(),
4016                    )
4017                    .await?;
4018                }
4019                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4020                    let abs_path = op
4021                        .uri
4022                        .to_file_path()
4023                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4024                    let options = op.options.map(Into::into).unwrap_or_default();
4025                    if abs_path.ends_with("/") {
4026                        fs.remove_dir(&abs_path, options).await?;
4027                    } else {
4028                        fs.remove_file(&abs_path, options).await?;
4029                    }
4030                }
4031                lsp::DocumentChangeOperation::Edit(op) => {
4032                    let buffer_to_edit = this
4033                        .update(cx, |this, cx| {
4034                            this.open_local_buffer_via_lsp(
4035                                op.text_document.uri,
4036                                language_server.server_id(),
4037                                lsp_adapter.name.clone(),
4038                                cx,
4039                            )
4040                        })
4041                        .await?;
4042
4043                    let edits = this
4044                        .update(cx, |this, cx| {
4045                            let edits = op.edits.into_iter().map(|edit| match edit {
4046                                lsp::OneOf::Left(edit) => edit,
4047                                lsp::OneOf::Right(edit) => edit.text_edit,
4048                            });
4049                            this.edits_from_lsp(
4050                                &buffer_to_edit,
4051                                edits,
4052                                op.text_document.version,
4053                                cx,
4054                            )
4055                        })
4056                        .await?;
4057
4058                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4059                        buffer.finalize_last_transaction();
4060                        buffer.start_transaction();
4061                        for (range, text) in edits {
4062                            buffer.edit([(range, text)], None, cx);
4063                        }
4064                        let transaction = if buffer.end_transaction(cx).is_some() {
4065                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4066                            if !push_to_history {
4067                                buffer.forget_transaction(transaction.id);
4068                            }
4069                            Some(transaction)
4070                        } else {
4071                            None
4072                        };
4073
4074                        transaction
4075                    });
4076                    if let Some(transaction) = transaction {
4077                        project_transaction.0.insert(buffer_to_edit, transaction);
4078                    }
4079                }
4080            }
4081        }
4082
4083        Ok(project_transaction)
4084    }
4085
4086    pub fn prepare_rename<T: ToPointUtf16>(
4087        &self,
4088        buffer: ModelHandle<Buffer>,
4089        position: T,
4090        cx: &mut ModelContext<Self>,
4091    ) -> Task<Result<Option<Range<Anchor>>>> {
4092        let position = position.to_point_utf16(buffer.read(cx));
4093        self.request_lsp(buffer, PrepareRename { position }, cx)
4094    }
4095
4096    pub fn perform_rename<T: ToPointUtf16>(
4097        &self,
4098        buffer: ModelHandle<Buffer>,
4099        position: T,
4100        new_name: String,
4101        push_to_history: bool,
4102        cx: &mut ModelContext<Self>,
4103    ) -> Task<Result<ProjectTransaction>> {
4104        let position = position.to_point_utf16(buffer.read(cx));
4105        self.request_lsp(
4106            buffer,
4107            PerformRename {
4108                position,
4109                new_name,
4110                push_to_history,
4111            },
4112            cx,
4113        )
4114    }
4115
4116    #[allow(clippy::type_complexity)]
4117    pub fn search(
4118        &self,
4119        query: SearchQuery,
4120        cx: &mut ModelContext<Self>,
4121    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4122        if self.is_local() {
4123            let snapshots = self
4124                .visible_worktrees(cx)
4125                .filter_map(|tree| {
4126                    let tree = tree.read(cx).as_local()?;
4127                    Some(tree.snapshot())
4128                })
4129                .collect::<Vec<_>>();
4130
4131            let background = cx.background().clone();
4132            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4133            if path_count == 0 {
4134                return Task::ready(Ok(Default::default()));
4135            }
4136            let workers = background.num_cpus().min(path_count);
4137            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4138            cx.background()
4139                .spawn({
4140                    let fs = self.fs.clone();
4141                    let background = cx.background().clone();
4142                    let query = query.clone();
4143                    async move {
4144                        let fs = &fs;
4145                        let query = &query;
4146                        let matching_paths_tx = &matching_paths_tx;
4147                        let paths_per_worker = (path_count + workers - 1) / workers;
4148                        let snapshots = &snapshots;
4149                        background
4150                            .scoped(|scope| {
4151                                for worker_ix in 0..workers {
4152                                    let worker_start_ix = worker_ix * paths_per_worker;
4153                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4154                                    scope.spawn(async move {
4155                                        let mut snapshot_start_ix = 0;
4156                                        let mut abs_path = PathBuf::new();
4157                                        for snapshot in snapshots {
4158                                            let snapshot_end_ix =
4159                                                snapshot_start_ix + snapshot.visible_file_count();
4160                                            if worker_end_ix <= snapshot_start_ix {
4161                                                break;
4162                                            } else if worker_start_ix > snapshot_end_ix {
4163                                                snapshot_start_ix = snapshot_end_ix;
4164                                                continue;
4165                                            } else {
4166                                                let start_in_snapshot = worker_start_ix
4167                                                    .saturating_sub(snapshot_start_ix);
4168                                                let end_in_snapshot =
4169                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4170                                                        - snapshot_start_ix;
4171
4172                                                for entry in snapshot
4173                                                    .files(false, start_in_snapshot)
4174                                                    .take(end_in_snapshot - start_in_snapshot)
4175                                                {
4176                                                    if matching_paths_tx.is_closed() {
4177                                                        break;
4178                                                    }
4179
4180                                                    abs_path.clear();
4181                                                    abs_path.push(&snapshot.abs_path());
4182                                                    abs_path.push(&entry.path);
4183                                                    let matches = if let Some(file) =
4184                                                        fs.open_sync(&abs_path).await.log_err()
4185                                                    {
4186                                                        query.detect(file).unwrap_or(false)
4187                                                    } else {
4188                                                        false
4189                                                    };
4190
4191                                                    if matches {
4192                                                        let project_path =
4193                                                            (snapshot.id(), entry.path.clone());
4194                                                        if matching_paths_tx
4195                                                            .send(project_path)
4196                                                            .await
4197                                                            .is_err()
4198                                                        {
4199                                                            break;
4200                                                        }
4201                                                    }
4202                                                }
4203
4204                                                snapshot_start_ix = snapshot_end_ix;
4205                                            }
4206                                        }
4207                                    });
4208                                }
4209                            })
4210                            .await;
4211                    }
4212                })
4213                .detach();
4214
4215            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4216            let open_buffers = self
4217                .opened_buffers
4218                .values()
4219                .filter_map(|b| b.upgrade(cx))
4220                .collect::<HashSet<_>>();
4221            cx.spawn(|this, cx| async move {
4222                for buffer in &open_buffers {
4223                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4224                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4225                }
4226
4227                let open_buffers = Rc::new(RefCell::new(open_buffers));
4228                while let Some(project_path) = matching_paths_rx.next().await {
4229                    if buffers_tx.is_closed() {
4230                        break;
4231                    }
4232
4233                    let this = this.clone();
4234                    let open_buffers = open_buffers.clone();
4235                    let buffers_tx = buffers_tx.clone();
4236                    cx.spawn(|mut cx| async move {
4237                        if let Some(buffer) = this
4238                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4239                            .await
4240                            .log_err()
4241                        {
4242                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4243                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4244                                buffers_tx.send((buffer, snapshot)).await?;
4245                            }
4246                        }
4247
4248                        Ok::<_, anyhow::Error>(())
4249                    })
4250                    .detach();
4251                }
4252
4253                Ok::<_, anyhow::Error>(())
4254            })
4255            .detach_and_log_err(cx);
4256
4257            let background = cx.background().clone();
4258            cx.background().spawn(async move {
4259                let query = &query;
4260                let mut matched_buffers = Vec::new();
4261                for _ in 0..workers {
4262                    matched_buffers.push(HashMap::default());
4263                }
4264                background
4265                    .scoped(|scope| {
4266                        for worker_matched_buffers in matched_buffers.iter_mut() {
4267                            let mut buffers_rx = buffers_rx.clone();
4268                            scope.spawn(async move {
4269                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4270                                    let buffer_matches = query
4271                                        .search(snapshot.as_rope())
4272                                        .await
4273                                        .iter()
4274                                        .map(|range| {
4275                                            snapshot.anchor_before(range.start)
4276                                                ..snapshot.anchor_after(range.end)
4277                                        })
4278                                        .collect::<Vec<_>>();
4279                                    if !buffer_matches.is_empty() {
4280                                        worker_matched_buffers
4281                                            .insert(buffer.clone(), buffer_matches);
4282                                    }
4283                                }
4284                            });
4285                        }
4286                    })
4287                    .await;
4288                Ok(matched_buffers.into_iter().flatten().collect())
4289            })
4290        } else if let Some(project_id) = self.remote_id() {
4291            let request = self.client.request(query.to_proto(project_id));
4292            cx.spawn(|this, mut cx| async move {
4293                let response = request.await?;
4294                let mut result = HashMap::default();
4295                for location in response.locations {
4296                    let target_buffer = this
4297                        .update(&mut cx, |this, cx| {
4298                            this.wait_for_buffer(location.buffer_id, cx)
4299                        })
4300                        .await?;
4301                    let start = location
4302                        .start
4303                        .and_then(deserialize_anchor)
4304                        .ok_or_else(|| anyhow!("missing target start"))?;
4305                    let end = location
4306                        .end
4307                        .and_then(deserialize_anchor)
4308                        .ok_or_else(|| anyhow!("missing target end"))?;
4309                    result
4310                        .entry(target_buffer)
4311                        .or_insert(Vec::new())
4312                        .push(start..end)
4313                }
4314                Ok(result)
4315            })
4316        } else {
4317            Task::ready(Ok(Default::default()))
4318        }
4319    }
4320
4321    fn request_lsp<R: LspCommand>(
4322        &self,
4323        buffer_handle: ModelHandle<Buffer>,
4324        request: R,
4325        cx: &mut ModelContext<Self>,
4326    ) -> Task<Result<R::Response>>
4327    where
4328        <R::LspRequest as lsp::request::Request>::Result: Send,
4329    {
4330        let buffer = buffer_handle.read(cx);
4331        if self.is_local() {
4332            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4333            if let Some((file, language_server)) = file.zip(
4334                self.language_server_for_buffer(buffer, cx)
4335                    .map(|(_, server)| server.clone()),
4336            ) {
4337                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4338                return cx.spawn(|this, cx| async move {
4339                    if !request.check_capabilities(language_server.capabilities()) {
4340                        return Ok(Default::default());
4341                    }
4342
4343                    let response = language_server
4344                        .request::<R::LspRequest>(lsp_params)
4345                        .await
4346                        .context("lsp request failed")?;
4347                    request
4348                        .response_from_lsp(response, this, buffer_handle, cx)
4349                        .await
4350                });
4351            }
4352        } else if let Some(project_id) = self.remote_id() {
4353            let rpc = self.client.clone();
4354            let message = request.to_proto(project_id, buffer);
4355            return cx.spawn(|this, cx| async move {
4356                let response = rpc.request(message).await?;
4357                request
4358                    .response_from_proto(response, this, buffer_handle, cx)
4359                    .await
4360            });
4361        }
4362        Task::ready(Ok(Default::default()))
4363    }
4364
4365    pub fn find_or_create_local_worktree(
4366        &mut self,
4367        abs_path: impl AsRef<Path>,
4368        visible: bool,
4369        cx: &mut ModelContext<Self>,
4370    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4371        let abs_path = abs_path.as_ref();
4372        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4373            Task::ready(Ok((tree, relative_path)))
4374        } else {
4375            let worktree = self.create_local_worktree(abs_path, visible, cx);
4376            cx.foreground()
4377                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4378        }
4379    }
4380
4381    pub fn find_local_worktree(
4382        &self,
4383        abs_path: &Path,
4384        cx: &AppContext,
4385    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4386        for tree in &self.worktrees {
4387            if let Some(tree) = tree.upgrade(cx) {
4388                if let Some(relative_path) = tree
4389                    .read(cx)
4390                    .as_local()
4391                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4392                {
4393                    return Some((tree.clone(), relative_path.into()));
4394                }
4395            }
4396        }
4397        None
4398    }
4399
4400    pub fn is_shared(&self) -> bool {
4401        match &self.client_state {
4402            ProjectClientState::Local { is_shared, .. } => *is_shared,
4403            ProjectClientState::Remote { .. } => false,
4404        }
4405    }
4406
4407    fn create_local_worktree(
4408        &mut self,
4409        abs_path: impl AsRef<Path>,
4410        visible: bool,
4411        cx: &mut ModelContext<Self>,
4412    ) -> Task<Result<ModelHandle<Worktree>>> {
4413        let fs = self.fs.clone();
4414        let client = self.client.clone();
4415        let next_entry_id = self.next_entry_id.clone();
4416        let path: Arc<Path> = abs_path.as_ref().into();
4417        let task = self
4418            .loading_local_worktrees
4419            .entry(path.clone())
4420            .or_insert_with(|| {
4421                cx.spawn(|project, mut cx| {
4422                    async move {
4423                        let worktree = Worktree::local(
4424                            client.clone(),
4425                            path.clone(),
4426                            visible,
4427                            fs,
4428                            next_entry_id,
4429                            &mut cx,
4430                        )
4431                        .await;
4432                        project.update(&mut cx, |project, _| {
4433                            project.loading_local_worktrees.remove(&path);
4434                        });
4435                        let worktree = worktree?;
4436
4437                        let project_id = project.update(&mut cx, |project, cx| {
4438                            project.add_worktree(&worktree, cx);
4439                            project.shared_remote_id()
4440                        });
4441
4442                        if let Some(project_id) = project_id {
4443                            worktree
4444                                .update(&mut cx, |worktree, cx| {
4445                                    worktree.as_local_mut().unwrap().share(project_id, cx)
4446                                })
4447                                .await
4448                                .log_err();
4449                        }
4450
4451                        Ok(worktree)
4452                    }
4453                    .map_err(Arc::new)
4454                })
4455                .shared()
4456            })
4457            .clone();
4458        cx.foreground().spawn(async move {
4459            match task.await {
4460                Ok(worktree) => Ok(worktree),
4461                Err(err) => Err(anyhow!("{}", err)),
4462            }
4463        })
4464    }
4465
4466    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4467        self.worktrees.retain(|worktree| {
4468            if let Some(worktree) = worktree.upgrade(cx) {
4469                let id = worktree.read(cx).id();
4470                if id == id_to_remove {
4471                    cx.emit(Event::WorktreeRemoved(id));
4472                    false
4473                } else {
4474                    true
4475                }
4476            } else {
4477                false
4478            }
4479        });
4480        self.metadata_changed(true, cx);
4481        cx.notify();
4482    }
4483
4484    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4485        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4486        if worktree.read(cx).is_local() {
4487            cx.subscribe(worktree, |this, worktree, _, cx| {
4488                this.update_local_worktree_buffers(worktree, cx);
4489            })
4490            .detach();
4491        }
4492
4493        let push_strong_handle = {
4494            let worktree = worktree.read(cx);
4495            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4496        };
4497        if push_strong_handle {
4498            self.worktrees
4499                .push(WorktreeHandle::Strong(worktree.clone()));
4500        } else {
4501            self.worktrees
4502                .push(WorktreeHandle::Weak(worktree.downgrade()));
4503        }
4504
4505        self.metadata_changed(true, cx);
4506        cx.observe_release(worktree, |this, worktree, cx| {
4507            this.remove_worktree(worktree.id(), cx);
4508            cx.notify();
4509        })
4510        .detach();
4511
4512        cx.emit(Event::WorktreeAdded);
4513        cx.notify();
4514    }
4515
4516    fn update_local_worktree_buffers(
4517        &mut self,
4518        worktree_handle: ModelHandle<Worktree>,
4519        cx: &mut ModelContext<Self>,
4520    ) {
4521        let snapshot = worktree_handle.read(cx).snapshot();
4522        let mut buffers_to_delete = Vec::new();
4523        let mut renamed_buffers = Vec::new();
4524        for (buffer_id, buffer) in &self.opened_buffers {
4525            if let Some(buffer) = buffer.upgrade(cx) {
4526                buffer.update(cx, |buffer, cx| {
4527                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4528                        if old_file.worktree != worktree_handle {
4529                            return;
4530                        }
4531
4532                        let new_file = if let Some(entry) = old_file
4533                            .entry_id
4534                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4535                        {
4536                            File {
4537                                is_local: true,
4538                                entry_id: Some(entry.id),
4539                                mtime: entry.mtime,
4540                                path: entry.path.clone(),
4541                                worktree: worktree_handle.clone(),
4542                            }
4543                        } else if let Some(entry) =
4544                            snapshot.entry_for_path(old_file.path().as_ref())
4545                        {
4546                            File {
4547                                is_local: true,
4548                                entry_id: Some(entry.id),
4549                                mtime: entry.mtime,
4550                                path: entry.path.clone(),
4551                                worktree: worktree_handle.clone(),
4552                            }
4553                        } else {
4554                            File {
4555                                is_local: true,
4556                                entry_id: None,
4557                                path: old_file.path().clone(),
4558                                mtime: old_file.mtime(),
4559                                worktree: worktree_handle.clone(),
4560                            }
4561                        };
4562
4563                        let old_path = old_file.abs_path(cx);
4564                        if new_file.abs_path(cx) != old_path {
4565                            renamed_buffers.push((cx.handle(), old_path));
4566                        }
4567
4568                        if let Some(project_id) = self.shared_remote_id() {
4569                            self.client
4570                                .send(proto::UpdateBufferFile {
4571                                    project_id,
4572                                    buffer_id: *buffer_id as u64,
4573                                    file: Some(new_file.to_proto()),
4574                                })
4575                                .log_err();
4576                        }
4577                        buffer.file_updated(Arc::new(new_file), cx).detach();
4578                    }
4579                });
4580            } else {
4581                buffers_to_delete.push(*buffer_id);
4582            }
4583        }
4584
4585        for buffer_id in buffers_to_delete {
4586            self.opened_buffers.remove(&buffer_id);
4587        }
4588
4589        for (buffer, old_path) in renamed_buffers {
4590            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4591            self.assign_language_to_buffer(&buffer, cx);
4592            self.register_buffer_with_language_server(&buffer, cx);
4593        }
4594    }
4595
4596    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4597        let new_active_entry = entry.and_then(|project_path| {
4598            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4599            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4600            Some(entry.id)
4601        });
4602        if new_active_entry != self.active_entry {
4603            self.active_entry = new_active_entry;
4604            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4605        }
4606    }
4607
4608    pub fn language_servers_running_disk_based_diagnostics(
4609        &self,
4610    ) -> impl Iterator<Item = usize> + '_ {
4611        self.language_server_statuses
4612            .iter()
4613            .filter_map(|(id, status)| {
4614                if status.has_pending_diagnostic_updates {
4615                    Some(*id)
4616                } else {
4617                    None
4618                }
4619            })
4620    }
4621
4622    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4623        let mut summary = DiagnosticSummary::default();
4624        for (_, path_summary) in self.diagnostic_summaries(cx) {
4625            summary.error_count += path_summary.error_count;
4626            summary.warning_count += path_summary.warning_count;
4627        }
4628        summary
4629    }
4630
4631    pub fn diagnostic_summaries<'a>(
4632        &'a self,
4633        cx: &'a AppContext,
4634    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4635        self.visible_worktrees(cx).flat_map(move |worktree| {
4636            let worktree = worktree.read(cx);
4637            let worktree_id = worktree.id();
4638            worktree
4639                .diagnostic_summaries()
4640                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4641        })
4642    }
4643
4644    pub fn disk_based_diagnostics_started(
4645        &mut self,
4646        language_server_id: usize,
4647        cx: &mut ModelContext<Self>,
4648    ) {
4649        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4650    }
4651
4652    pub fn disk_based_diagnostics_finished(
4653        &mut self,
4654        language_server_id: usize,
4655        cx: &mut ModelContext<Self>,
4656    ) {
4657        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4658    }
4659
4660    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4661        self.active_entry
4662    }
4663
4664    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4665        self.worktree_for_id(path.worktree_id, cx)?
4666            .read(cx)
4667            .entry_for_path(&path.path)
4668            .cloned()
4669    }
4670
4671    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4672        let worktree = self.worktree_for_entry(entry_id, cx)?;
4673        let worktree = worktree.read(cx);
4674        let worktree_id = worktree.id();
4675        let path = worktree.entry_for_id(entry_id)?.path.clone();
4676        Some(ProjectPath { worktree_id, path })
4677    }
4678
4679    // RPC message handlers
4680
4681    async fn handle_request_join_project(
4682        this: ModelHandle<Self>,
4683        message: TypedEnvelope<proto::RequestJoinProject>,
4684        _: Arc<Client>,
4685        mut cx: AsyncAppContext,
4686    ) -> Result<()> {
4687        let user_id = message.payload.requester_id;
4688        if this.read_with(&cx, |project, _| {
4689            project.collaborators.values().any(|c| c.user.id == user_id)
4690        }) {
4691            this.update(&mut cx, |this, cx| {
4692                this.respond_to_join_request(user_id, true, cx)
4693            });
4694        } else {
4695            let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4696            let user = user_store
4697                .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4698                .await?;
4699            this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4700        }
4701        Ok(())
4702    }
4703
4704    async fn handle_unregister_project(
4705        this: ModelHandle<Self>,
4706        _: TypedEnvelope<proto::UnregisterProject>,
4707        _: Arc<Client>,
4708        mut cx: AsyncAppContext,
4709    ) -> Result<()> {
4710        this.update(&mut cx, |this, cx| this.disconnected_from_host(cx));
4711        Ok(())
4712    }
4713
4714    async fn handle_project_unshared(
4715        this: ModelHandle<Self>,
4716        _: TypedEnvelope<proto::ProjectUnshared>,
4717        _: Arc<Client>,
4718        mut cx: AsyncAppContext,
4719    ) -> Result<()> {
4720        this.update(&mut cx, |this, cx| this.unshared(cx));
4721        Ok(())
4722    }
4723
4724    async fn handle_add_collaborator(
4725        this: ModelHandle<Self>,
4726        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4727        _: Arc<Client>,
4728        mut cx: AsyncAppContext,
4729    ) -> Result<()> {
4730        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4731        let collaborator = envelope
4732            .payload
4733            .collaborator
4734            .take()
4735            .ok_or_else(|| anyhow!("empty collaborator"))?;
4736
4737        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4738        this.update(&mut cx, |this, cx| {
4739            this.collaborators
4740                .insert(collaborator.peer_id, collaborator);
4741            cx.notify();
4742        });
4743
4744        Ok(())
4745    }
4746
4747    async fn handle_remove_collaborator(
4748        this: ModelHandle<Self>,
4749        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4750        _: Arc<Client>,
4751        mut cx: AsyncAppContext,
4752    ) -> Result<()> {
4753        this.update(&mut cx, |this, cx| {
4754            let peer_id = PeerId(envelope.payload.peer_id);
4755            let replica_id = this
4756                .collaborators
4757                .remove(&peer_id)
4758                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4759                .replica_id;
4760            for buffer in this.opened_buffers.values() {
4761                if let Some(buffer) = buffer.upgrade(cx) {
4762                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4763                }
4764            }
4765
4766            cx.emit(Event::CollaboratorLeft(peer_id));
4767            cx.notify();
4768            Ok(())
4769        })
4770    }
4771
4772    async fn handle_join_project_request_cancelled(
4773        this: ModelHandle<Self>,
4774        envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4775        _: Arc<Client>,
4776        mut cx: AsyncAppContext,
4777    ) -> Result<()> {
4778        let user = this
4779            .update(&mut cx, |this, cx| {
4780                this.user_store.update(cx, |user_store, cx| {
4781                    user_store.fetch_user(envelope.payload.requester_id, cx)
4782                })
4783            })
4784            .await?;
4785
4786        this.update(&mut cx, |_, cx| {
4787            cx.emit(Event::ContactCancelledJoinRequest(user));
4788        });
4789
4790        Ok(())
4791    }
4792
4793    async fn handle_update_project(
4794        this: ModelHandle<Self>,
4795        envelope: TypedEnvelope<proto::UpdateProject>,
4796        client: Arc<Client>,
4797        mut cx: AsyncAppContext,
4798    ) -> Result<()> {
4799        this.update(&mut cx, |this, cx| {
4800            let replica_id = this.replica_id();
4801            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4802
4803            let mut old_worktrees_by_id = this
4804                .worktrees
4805                .drain(..)
4806                .filter_map(|worktree| {
4807                    let worktree = worktree.upgrade(cx)?;
4808                    Some((worktree.read(cx).id(), worktree))
4809                })
4810                .collect::<HashMap<_, _>>();
4811
4812            for worktree in envelope.payload.worktrees {
4813                if let Some(old_worktree) =
4814                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4815                {
4816                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4817                } else {
4818                    let worktree =
4819                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4820                    this.add_worktree(&worktree, cx);
4821                }
4822            }
4823
4824            this.metadata_changed(true, cx);
4825            for (id, _) in old_worktrees_by_id {
4826                cx.emit(Event::WorktreeRemoved(id));
4827            }
4828
4829            Ok(())
4830        })
4831    }
4832
4833    async fn handle_update_worktree(
4834        this: ModelHandle<Self>,
4835        envelope: TypedEnvelope<proto::UpdateWorktree>,
4836        _: Arc<Client>,
4837        mut cx: AsyncAppContext,
4838    ) -> Result<()> {
4839        this.update(&mut cx, |this, cx| {
4840            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4841            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4842                worktree.update(cx, |worktree, _| {
4843                    let worktree = worktree.as_remote_mut().unwrap();
4844                    worktree.update_from_remote(envelope.payload);
4845                });
4846            }
4847            Ok(())
4848        })
4849    }
4850
4851    async fn handle_create_project_entry(
4852        this: ModelHandle<Self>,
4853        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4854        _: Arc<Client>,
4855        mut cx: AsyncAppContext,
4856    ) -> Result<proto::ProjectEntryResponse> {
4857        let worktree = this.update(&mut cx, |this, cx| {
4858            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4859            this.worktree_for_id(worktree_id, cx)
4860                .ok_or_else(|| anyhow!("worktree not found"))
4861        })?;
4862        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4863        let entry = worktree
4864            .update(&mut cx, |worktree, cx| {
4865                let worktree = worktree.as_local_mut().unwrap();
4866                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4867                worktree.create_entry(path, envelope.payload.is_directory, cx)
4868            })
4869            .await?;
4870        Ok(proto::ProjectEntryResponse {
4871            entry: Some((&entry).into()),
4872            worktree_scan_id: worktree_scan_id as u64,
4873        })
4874    }
4875
4876    async fn handle_rename_project_entry(
4877        this: ModelHandle<Self>,
4878        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4879        _: Arc<Client>,
4880        mut cx: AsyncAppContext,
4881    ) -> Result<proto::ProjectEntryResponse> {
4882        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4883        let worktree = this.read_with(&cx, |this, cx| {
4884            this.worktree_for_entry(entry_id, cx)
4885                .ok_or_else(|| anyhow!("worktree not found"))
4886        })?;
4887        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4888        let entry = worktree
4889            .update(&mut cx, |worktree, cx| {
4890                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4891                worktree
4892                    .as_local_mut()
4893                    .unwrap()
4894                    .rename_entry(entry_id, new_path, cx)
4895                    .ok_or_else(|| anyhow!("invalid entry"))
4896            })?
4897            .await?;
4898        Ok(proto::ProjectEntryResponse {
4899            entry: Some((&entry).into()),
4900            worktree_scan_id: worktree_scan_id as u64,
4901        })
4902    }
4903
4904    async fn handle_copy_project_entry(
4905        this: ModelHandle<Self>,
4906        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4907        _: Arc<Client>,
4908        mut cx: AsyncAppContext,
4909    ) -> Result<proto::ProjectEntryResponse> {
4910        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4911        let worktree = this.read_with(&cx, |this, cx| {
4912            this.worktree_for_entry(entry_id, cx)
4913                .ok_or_else(|| anyhow!("worktree not found"))
4914        })?;
4915        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4916        let entry = worktree
4917            .update(&mut cx, |worktree, cx| {
4918                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4919                worktree
4920                    .as_local_mut()
4921                    .unwrap()
4922                    .copy_entry(entry_id, new_path, cx)
4923                    .ok_or_else(|| anyhow!("invalid entry"))
4924            })?
4925            .await?;
4926        Ok(proto::ProjectEntryResponse {
4927            entry: Some((&entry).into()),
4928            worktree_scan_id: worktree_scan_id as u64,
4929        })
4930    }
4931
4932    async fn handle_delete_project_entry(
4933        this: ModelHandle<Self>,
4934        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4935        _: Arc<Client>,
4936        mut cx: AsyncAppContext,
4937    ) -> Result<proto::ProjectEntryResponse> {
4938        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4939        let worktree = this.read_with(&cx, |this, cx| {
4940            this.worktree_for_entry(entry_id, cx)
4941                .ok_or_else(|| anyhow!("worktree not found"))
4942        })?;
4943        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4944        worktree
4945            .update(&mut cx, |worktree, cx| {
4946                worktree
4947                    .as_local_mut()
4948                    .unwrap()
4949                    .delete_entry(entry_id, cx)
4950                    .ok_or_else(|| anyhow!("invalid entry"))
4951            })?
4952            .await?;
4953        Ok(proto::ProjectEntryResponse {
4954            entry: None,
4955            worktree_scan_id: worktree_scan_id as u64,
4956        })
4957    }
4958
4959    async fn handle_update_diagnostic_summary(
4960        this: ModelHandle<Self>,
4961        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4962        _: Arc<Client>,
4963        mut cx: AsyncAppContext,
4964    ) -> Result<()> {
4965        this.update(&mut cx, |this, cx| {
4966            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4967            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4968                if let Some(summary) = envelope.payload.summary {
4969                    let project_path = ProjectPath {
4970                        worktree_id,
4971                        path: Path::new(&summary.path).into(),
4972                    };
4973                    worktree.update(cx, |worktree, _| {
4974                        worktree
4975                            .as_remote_mut()
4976                            .unwrap()
4977                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4978                    });
4979                    cx.emit(Event::DiagnosticsUpdated {
4980                        language_server_id: summary.language_server_id as usize,
4981                        path: project_path,
4982                    });
4983                }
4984            }
4985            Ok(())
4986        })
4987    }
4988
4989    async fn handle_start_language_server(
4990        this: ModelHandle<Self>,
4991        envelope: TypedEnvelope<proto::StartLanguageServer>,
4992        _: Arc<Client>,
4993        mut cx: AsyncAppContext,
4994    ) -> Result<()> {
4995        let server = envelope
4996            .payload
4997            .server
4998            .ok_or_else(|| anyhow!("invalid server"))?;
4999        this.update(&mut cx, |this, cx| {
5000            this.language_server_statuses.insert(
5001                server.id as usize,
5002                LanguageServerStatus {
5003                    name: server.name,
5004                    pending_work: Default::default(),
5005                    has_pending_diagnostic_updates: false,
5006                    progress_tokens: Default::default(),
5007                },
5008            );
5009            cx.notify();
5010        });
5011        Ok(())
5012    }
5013
5014    async fn handle_update_language_server(
5015        this: ModelHandle<Self>,
5016        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5017        _: Arc<Client>,
5018        mut cx: AsyncAppContext,
5019    ) -> Result<()> {
5020        let language_server_id = envelope.payload.language_server_id as usize;
5021        match envelope
5022            .payload
5023            .variant
5024            .ok_or_else(|| anyhow!("invalid variant"))?
5025        {
5026            proto::update_language_server::Variant::WorkStart(payload) => {
5027                this.update(&mut cx, |this, cx| {
5028                    this.on_lsp_work_start(
5029                        language_server_id,
5030                        payload.token,
5031                        LanguageServerProgress {
5032                            message: payload.message,
5033                            percentage: payload.percentage.map(|p| p as usize),
5034                            last_update_at: Instant::now(),
5035                        },
5036                        cx,
5037                    );
5038                })
5039            }
5040            proto::update_language_server::Variant::WorkProgress(payload) => {
5041                this.update(&mut cx, |this, cx| {
5042                    this.on_lsp_work_progress(
5043                        language_server_id,
5044                        payload.token,
5045                        LanguageServerProgress {
5046                            message: payload.message,
5047                            percentage: payload.percentage.map(|p| p as usize),
5048                            last_update_at: Instant::now(),
5049                        },
5050                        cx,
5051                    );
5052                })
5053            }
5054            proto::update_language_server::Variant::WorkEnd(payload) => {
5055                this.update(&mut cx, |this, cx| {
5056                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5057                })
5058            }
5059            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5060                this.update(&mut cx, |this, cx| {
5061                    this.disk_based_diagnostics_started(language_server_id, cx);
5062                })
5063            }
5064            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5065                this.update(&mut cx, |this, cx| {
5066                    this.disk_based_diagnostics_finished(language_server_id, cx)
5067                });
5068            }
5069        }
5070
5071        Ok(())
5072    }
5073
5074    async fn handle_update_buffer(
5075        this: ModelHandle<Self>,
5076        envelope: TypedEnvelope<proto::UpdateBuffer>,
5077        _: Arc<Client>,
5078        mut cx: AsyncAppContext,
5079    ) -> Result<()> {
5080        this.update(&mut cx, |this, cx| {
5081            let payload = envelope.payload.clone();
5082            let buffer_id = payload.buffer_id;
5083            let ops = payload
5084                .operations
5085                .into_iter()
5086                .map(language::proto::deserialize_operation)
5087                .collect::<Result<Vec<_>, _>>()?;
5088            let is_remote = this.is_remote();
5089            match this.opened_buffers.entry(buffer_id) {
5090                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5091                    OpenBuffer::Strong(buffer) => {
5092                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5093                    }
5094                    OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
5095                    OpenBuffer::Weak(_) => {}
5096                },
5097                hash_map::Entry::Vacant(e) => {
5098                    assert!(
5099                        is_remote,
5100                        "received buffer update from {:?}",
5101                        envelope.original_sender_id
5102                    );
5103                    e.insert(OpenBuffer::Loading(ops));
5104                }
5105            }
5106            Ok(())
5107        })
5108    }
5109
5110    async fn handle_create_buffer_for_peer(
5111        this: ModelHandle<Self>,
5112        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5113        _: Arc<Client>,
5114        mut cx: AsyncAppContext,
5115    ) -> Result<()> {
5116        this.update(&mut cx, |this, cx| {
5117            let mut buffer = envelope
5118                .payload
5119                .buffer
5120                .ok_or_else(|| anyhow!("invalid buffer"))?;
5121            let mut buffer_file = None;
5122            if let Some(file) = buffer.file.take() {
5123                let worktree_id = WorktreeId::from_proto(file.worktree_id);
5124                let worktree = this
5125                    .worktree_for_id(worktree_id, cx)
5126                    .ok_or_else(|| anyhow!("no worktree found for id {}", file.worktree_id))?;
5127                buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5128                    as Arc<dyn language::File>);
5129            }
5130
5131            let buffer = cx.add_model(|cx| {
5132                Buffer::from_proto(this.replica_id(), buffer, buffer_file, cx).unwrap()
5133            });
5134            this.register_buffer(&buffer, cx)?;
5135
5136            Ok(())
5137        })
5138    }
5139
5140    async fn handle_update_buffer_file(
5141        this: ModelHandle<Self>,
5142        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5143        _: Arc<Client>,
5144        mut cx: AsyncAppContext,
5145    ) -> Result<()> {
5146        this.update(&mut cx, |this, cx| {
5147            let payload = envelope.payload.clone();
5148            let buffer_id = payload.buffer_id;
5149            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5150            let worktree = this
5151                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5152                .ok_or_else(|| anyhow!("no such worktree"))?;
5153            let file = File::from_proto(file, worktree, cx)?;
5154            let buffer = this
5155                .opened_buffers
5156                .get_mut(&buffer_id)
5157                .and_then(|b| b.upgrade(cx))
5158                .ok_or_else(|| anyhow!("no such buffer"))?;
5159            buffer.update(cx, |buffer, cx| {
5160                buffer.file_updated(Arc::new(file), cx).detach();
5161            });
5162            Ok(())
5163        })
5164    }
5165
5166    async fn handle_save_buffer(
5167        this: ModelHandle<Self>,
5168        envelope: TypedEnvelope<proto::SaveBuffer>,
5169        _: Arc<Client>,
5170        mut cx: AsyncAppContext,
5171    ) -> Result<proto::BufferSaved> {
5172        let buffer_id = envelope.payload.buffer_id;
5173        let requested_version = deserialize_version(envelope.payload.version);
5174
5175        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5176            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5177            let buffer = this
5178                .opened_buffers
5179                .get(&buffer_id)
5180                .and_then(|buffer| buffer.upgrade(cx))
5181                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5182            Ok::<_, anyhow::Error>((project_id, buffer))
5183        })?;
5184        buffer
5185            .update(&mut cx, |buffer, _| {
5186                buffer.wait_for_version(requested_version)
5187            })
5188            .await;
5189
5190        let (saved_version, fingerprint, mtime) =
5191            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5192        Ok(proto::BufferSaved {
5193            project_id,
5194            buffer_id,
5195            version: serialize_version(&saved_version),
5196            mtime: Some(mtime.into()),
5197            fingerprint,
5198        })
5199    }
5200
5201    async fn handle_reload_buffers(
5202        this: ModelHandle<Self>,
5203        envelope: TypedEnvelope<proto::ReloadBuffers>,
5204        _: Arc<Client>,
5205        mut cx: AsyncAppContext,
5206    ) -> Result<proto::ReloadBuffersResponse> {
5207        let sender_id = envelope.original_sender_id()?;
5208        let reload = this.update(&mut cx, |this, cx| {
5209            let mut buffers = HashSet::default();
5210            for buffer_id in &envelope.payload.buffer_ids {
5211                buffers.insert(
5212                    this.opened_buffers
5213                        .get(buffer_id)
5214                        .and_then(|buffer| buffer.upgrade(cx))
5215                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5216                );
5217            }
5218            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5219        })?;
5220
5221        let project_transaction = reload.await?;
5222        let project_transaction = this.update(&mut cx, |this, cx| {
5223            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5224        });
5225        Ok(proto::ReloadBuffersResponse {
5226            transaction: Some(project_transaction),
5227        })
5228    }
5229
5230    async fn handle_format_buffers(
5231        this: ModelHandle<Self>,
5232        envelope: TypedEnvelope<proto::FormatBuffers>,
5233        _: Arc<Client>,
5234        mut cx: AsyncAppContext,
5235    ) -> Result<proto::FormatBuffersResponse> {
5236        let sender_id = envelope.original_sender_id()?;
5237        let format = this.update(&mut cx, |this, cx| {
5238            let mut buffers = HashSet::default();
5239            for buffer_id in &envelope.payload.buffer_ids {
5240                buffers.insert(
5241                    this.opened_buffers
5242                        .get(buffer_id)
5243                        .and_then(|buffer| buffer.upgrade(cx))
5244                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5245                );
5246            }
5247            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
5248        })?;
5249
5250        let project_transaction = format.await?;
5251        let project_transaction = this.update(&mut cx, |this, cx| {
5252            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5253        });
5254        Ok(proto::FormatBuffersResponse {
5255            transaction: Some(project_transaction),
5256        })
5257    }
5258
5259    async fn handle_get_completions(
5260        this: ModelHandle<Self>,
5261        envelope: TypedEnvelope<proto::GetCompletions>,
5262        _: Arc<Client>,
5263        mut cx: AsyncAppContext,
5264    ) -> Result<proto::GetCompletionsResponse> {
5265        let position = envelope
5266            .payload
5267            .position
5268            .and_then(language::proto::deserialize_anchor)
5269            .ok_or_else(|| anyhow!("invalid position"))?;
5270        let version = deserialize_version(envelope.payload.version);
5271        let buffer = this.read_with(&cx, |this, cx| {
5272            this.opened_buffers
5273                .get(&envelope.payload.buffer_id)
5274                .and_then(|buffer| buffer.upgrade(cx))
5275                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5276        })?;
5277        buffer
5278            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5279            .await;
5280        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5281        let completions = this
5282            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5283            .await?;
5284
5285        Ok(proto::GetCompletionsResponse {
5286            completions: completions
5287                .iter()
5288                .map(language::proto::serialize_completion)
5289                .collect(),
5290            version: serialize_version(&version),
5291        })
5292    }
5293
5294    async fn handle_apply_additional_edits_for_completion(
5295        this: ModelHandle<Self>,
5296        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5297        _: Arc<Client>,
5298        mut cx: AsyncAppContext,
5299    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5300        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5301            let buffer = this
5302                .opened_buffers
5303                .get(&envelope.payload.buffer_id)
5304                .and_then(|buffer| buffer.upgrade(cx))
5305                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5306            let language = buffer.read(cx).language();
5307            let completion = language::proto::deserialize_completion(
5308                envelope
5309                    .payload
5310                    .completion
5311                    .ok_or_else(|| anyhow!("invalid completion"))?,
5312                language.cloned(),
5313            );
5314            Ok::<_, anyhow::Error>((buffer, completion))
5315        })?;
5316
5317        let completion = completion.await?;
5318
5319        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5320            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5321        });
5322
5323        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5324            transaction: apply_additional_edits
5325                .await?
5326                .as_ref()
5327                .map(language::proto::serialize_transaction),
5328        })
5329    }
5330
5331    async fn handle_get_code_actions(
5332        this: ModelHandle<Self>,
5333        envelope: TypedEnvelope<proto::GetCodeActions>,
5334        _: Arc<Client>,
5335        mut cx: AsyncAppContext,
5336    ) -> Result<proto::GetCodeActionsResponse> {
5337        let start = envelope
5338            .payload
5339            .start
5340            .and_then(language::proto::deserialize_anchor)
5341            .ok_or_else(|| anyhow!("invalid start"))?;
5342        let end = envelope
5343            .payload
5344            .end
5345            .and_then(language::proto::deserialize_anchor)
5346            .ok_or_else(|| anyhow!("invalid end"))?;
5347        let buffer = this.update(&mut cx, |this, cx| {
5348            this.opened_buffers
5349                .get(&envelope.payload.buffer_id)
5350                .and_then(|buffer| buffer.upgrade(cx))
5351                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5352        })?;
5353        buffer
5354            .update(&mut cx, |buffer, _| {
5355                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5356            })
5357            .await;
5358
5359        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5360        let code_actions = this.update(&mut cx, |this, cx| {
5361            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5362        })?;
5363
5364        Ok(proto::GetCodeActionsResponse {
5365            actions: code_actions
5366                .await?
5367                .iter()
5368                .map(language::proto::serialize_code_action)
5369                .collect(),
5370            version: serialize_version(&version),
5371        })
5372    }
5373
5374    async fn handle_apply_code_action(
5375        this: ModelHandle<Self>,
5376        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5377        _: Arc<Client>,
5378        mut cx: AsyncAppContext,
5379    ) -> Result<proto::ApplyCodeActionResponse> {
5380        let sender_id = envelope.original_sender_id()?;
5381        let action = language::proto::deserialize_code_action(
5382            envelope
5383                .payload
5384                .action
5385                .ok_or_else(|| anyhow!("invalid action"))?,
5386        )?;
5387        let apply_code_action = this.update(&mut cx, |this, cx| {
5388            let buffer = this
5389                .opened_buffers
5390                .get(&envelope.payload.buffer_id)
5391                .and_then(|buffer| buffer.upgrade(cx))
5392                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5393            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5394        })?;
5395
5396        let project_transaction = apply_code_action.await?;
5397        let project_transaction = this.update(&mut cx, |this, cx| {
5398            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5399        });
5400        Ok(proto::ApplyCodeActionResponse {
5401            transaction: Some(project_transaction),
5402        })
5403    }
5404
5405    async fn handle_lsp_command<T: LspCommand>(
5406        this: ModelHandle<Self>,
5407        envelope: TypedEnvelope<T::ProtoRequest>,
5408        _: Arc<Client>,
5409        mut cx: AsyncAppContext,
5410    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5411    where
5412        <T::LspRequest as lsp::request::Request>::Result: Send,
5413    {
5414        let sender_id = envelope.original_sender_id()?;
5415        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5416        let buffer_handle = this.read_with(&cx, |this, _| {
5417            this.opened_buffers
5418                .get(&buffer_id)
5419                .and_then(|buffer| buffer.upgrade(&cx))
5420                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5421        })?;
5422        let request = T::from_proto(
5423            envelope.payload,
5424            this.clone(),
5425            buffer_handle.clone(),
5426            cx.clone(),
5427        )
5428        .await?;
5429        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5430        let response = this
5431            .update(&mut cx, |this, cx| {
5432                this.request_lsp(buffer_handle, request, cx)
5433            })
5434            .await?;
5435        this.update(&mut cx, |this, cx| {
5436            Ok(T::response_to_proto(
5437                response,
5438                this,
5439                sender_id,
5440                &buffer_version,
5441                cx,
5442            ))
5443        })
5444    }
5445
5446    async fn handle_get_project_symbols(
5447        this: ModelHandle<Self>,
5448        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5449        _: Arc<Client>,
5450        mut cx: AsyncAppContext,
5451    ) -> Result<proto::GetProjectSymbolsResponse> {
5452        let symbols = this
5453            .update(&mut cx, |this, cx| {
5454                this.symbols(&envelope.payload.query, cx)
5455            })
5456            .await?;
5457
5458        Ok(proto::GetProjectSymbolsResponse {
5459            symbols: symbols.iter().map(serialize_symbol).collect(),
5460        })
5461    }
5462
5463    async fn handle_search_project(
5464        this: ModelHandle<Self>,
5465        envelope: TypedEnvelope<proto::SearchProject>,
5466        _: Arc<Client>,
5467        mut cx: AsyncAppContext,
5468    ) -> Result<proto::SearchProjectResponse> {
5469        let peer_id = envelope.original_sender_id()?;
5470        let query = SearchQuery::from_proto(envelope.payload)?;
5471        let result = this
5472            .update(&mut cx, |this, cx| this.search(query, cx))
5473            .await?;
5474
5475        this.update(&mut cx, |this, cx| {
5476            let mut locations = Vec::new();
5477            for (buffer, ranges) in result {
5478                for range in ranges {
5479                    let start = serialize_anchor(&range.start);
5480                    let end = serialize_anchor(&range.end);
5481                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5482                    locations.push(proto::Location {
5483                        buffer_id,
5484                        start: Some(start),
5485                        end: Some(end),
5486                    });
5487                }
5488            }
5489            Ok(proto::SearchProjectResponse { locations })
5490        })
5491    }
5492
5493    async fn handle_open_buffer_for_symbol(
5494        this: ModelHandle<Self>,
5495        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5496        _: Arc<Client>,
5497        mut cx: AsyncAppContext,
5498    ) -> Result<proto::OpenBufferForSymbolResponse> {
5499        let peer_id = envelope.original_sender_id()?;
5500        let symbol = envelope
5501            .payload
5502            .symbol
5503            .ok_or_else(|| anyhow!("invalid symbol"))?;
5504        let symbol = this
5505            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5506            .await?;
5507        let symbol = this.read_with(&cx, |this, _| {
5508            let signature = this.symbol_signature(&symbol.path);
5509            if signature == symbol.signature {
5510                Ok(symbol)
5511            } else {
5512                Err(anyhow!("invalid symbol signature"))
5513            }
5514        })?;
5515        let buffer = this
5516            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5517            .await?;
5518
5519        Ok(proto::OpenBufferForSymbolResponse {
5520            buffer_id: this.update(&mut cx, |this, cx| {
5521                this.create_buffer_for_peer(&buffer, peer_id, cx)
5522            }),
5523        })
5524    }
5525
5526    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5527        let mut hasher = Sha256::new();
5528        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5529        hasher.update(project_path.path.to_string_lossy().as_bytes());
5530        hasher.update(self.nonce.to_be_bytes());
5531        hasher.finalize().as_slice().try_into().unwrap()
5532    }
5533
5534    async fn handle_open_buffer_by_id(
5535        this: ModelHandle<Self>,
5536        envelope: TypedEnvelope<proto::OpenBufferById>,
5537        _: Arc<Client>,
5538        mut cx: AsyncAppContext,
5539    ) -> Result<proto::OpenBufferResponse> {
5540        let peer_id = envelope.original_sender_id()?;
5541        let buffer = this
5542            .update(&mut cx, |this, cx| {
5543                this.open_buffer_by_id(envelope.payload.id, cx)
5544            })
5545            .await?;
5546        this.update(&mut cx, |this, cx| {
5547            Ok(proto::OpenBufferResponse {
5548                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5549            })
5550        })
5551    }
5552
5553    async fn handle_open_buffer_by_path(
5554        this: ModelHandle<Self>,
5555        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5556        _: Arc<Client>,
5557        mut cx: AsyncAppContext,
5558    ) -> Result<proto::OpenBufferResponse> {
5559        let peer_id = envelope.original_sender_id()?;
5560        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5561        let open_buffer = this.update(&mut cx, |this, cx| {
5562            this.open_buffer(
5563                ProjectPath {
5564                    worktree_id,
5565                    path: PathBuf::from(envelope.payload.path).into(),
5566                },
5567                cx,
5568            )
5569        });
5570
5571        let buffer = open_buffer.await?;
5572        this.update(&mut cx, |this, cx| {
5573            Ok(proto::OpenBufferResponse {
5574                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5575            })
5576        })
5577    }
5578
5579    fn serialize_project_transaction_for_peer(
5580        &mut self,
5581        project_transaction: ProjectTransaction,
5582        peer_id: PeerId,
5583        cx: &AppContext,
5584    ) -> proto::ProjectTransaction {
5585        let mut serialized_transaction = proto::ProjectTransaction {
5586            buffer_ids: Default::default(),
5587            transactions: Default::default(),
5588        };
5589        for (buffer, transaction) in project_transaction.0 {
5590            serialized_transaction
5591                .buffer_ids
5592                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5593            serialized_transaction
5594                .transactions
5595                .push(language::proto::serialize_transaction(&transaction));
5596        }
5597        serialized_transaction
5598    }
5599
5600    fn deserialize_project_transaction(
5601        &mut self,
5602        message: proto::ProjectTransaction,
5603        push_to_history: bool,
5604        cx: &mut ModelContext<Self>,
5605    ) -> Task<Result<ProjectTransaction>> {
5606        cx.spawn(|this, mut cx| async move {
5607            let mut project_transaction = ProjectTransaction::default();
5608            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5609            {
5610                let buffer = this
5611                    .update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
5612                    .await?;
5613                let transaction = language::proto::deserialize_transaction(transaction)?;
5614                project_transaction.0.insert(buffer, transaction);
5615            }
5616
5617            for (buffer, transaction) in &project_transaction.0 {
5618                buffer
5619                    .update(&mut cx, |buffer, _| {
5620                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5621                    })
5622                    .await;
5623
5624                if push_to_history {
5625                    buffer.update(&mut cx, |buffer, _| {
5626                        buffer.push_transaction(transaction.clone(), Instant::now());
5627                    });
5628                }
5629            }
5630
5631            Ok(project_transaction)
5632        })
5633    }
5634
5635    fn create_buffer_for_peer(
5636        &mut self,
5637        buffer: &ModelHandle<Buffer>,
5638        peer_id: PeerId,
5639        cx: &AppContext,
5640    ) -> u64 {
5641        let buffer_id = buffer.read(cx).remote_id();
5642        if let Some(project_id) = self.remote_id() {
5643            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5644            if shared_buffers.insert(buffer_id) {
5645                self.client
5646                    .send(proto::CreateBufferForPeer {
5647                        project_id,
5648                        peer_id: peer_id.0,
5649                        buffer: Some(buffer.read(cx).to_proto()),
5650                    })
5651                    .log_err();
5652            }
5653        }
5654
5655        buffer_id
5656    }
5657
5658    fn wait_for_buffer(
5659        &self,
5660        id: u64,
5661        cx: &mut ModelContext<Self>,
5662    ) -> Task<Result<ModelHandle<Buffer>>> {
5663        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5664        cx.spawn(|this, cx| async move {
5665            let buffer = loop {
5666                let buffer = this.read_with(&cx, |this, cx| {
5667                    this.opened_buffers
5668                        .get(&id)
5669                        .and_then(|buffer| buffer.upgrade(cx))
5670                });
5671                if let Some(buffer) = buffer {
5672                    break buffer;
5673                }
5674                opened_buffer_rx
5675                    .next()
5676                    .await
5677                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5678            };
5679            Ok(buffer)
5680        })
5681    }
5682
5683    fn deserialize_symbol(
5684        &self,
5685        serialized_symbol: proto::Symbol,
5686    ) -> impl Future<Output = Result<Symbol>> {
5687        let languages = self.languages.clone();
5688        async move {
5689            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5690            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5691            let start = serialized_symbol
5692                .start
5693                .ok_or_else(|| anyhow!("invalid start"))?;
5694            let end = serialized_symbol
5695                .end
5696                .ok_or_else(|| anyhow!("invalid end"))?;
5697            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5698            let path = ProjectPath {
5699                worktree_id,
5700                path: PathBuf::from(serialized_symbol.path).into(),
5701            };
5702            let language = languages.select_language(&path.path);
5703            Ok(Symbol {
5704                language_server_name: LanguageServerName(
5705                    serialized_symbol.language_server_name.into(),
5706                ),
5707                source_worktree_id,
5708                path,
5709                label: {
5710                    match language {
5711                        Some(language) => {
5712                            language
5713                                .label_for_symbol(&serialized_symbol.name, kind)
5714                                .await
5715                        }
5716                        None => None,
5717                    }
5718                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5719                },
5720
5721                name: serialized_symbol.name,
5722                range: PointUtf16::new(start.row, start.column)
5723                    ..PointUtf16::new(end.row, end.column),
5724                kind,
5725                signature: serialized_symbol
5726                    .signature
5727                    .try_into()
5728                    .map_err(|_| anyhow!("invalid signature"))?,
5729            })
5730        }
5731    }
5732
5733    async fn handle_buffer_saved(
5734        this: ModelHandle<Self>,
5735        envelope: TypedEnvelope<proto::BufferSaved>,
5736        _: Arc<Client>,
5737        mut cx: AsyncAppContext,
5738    ) -> Result<()> {
5739        let version = deserialize_version(envelope.payload.version);
5740        let mtime = envelope
5741            .payload
5742            .mtime
5743            .ok_or_else(|| anyhow!("missing mtime"))?
5744            .into();
5745
5746        this.update(&mut cx, |this, cx| {
5747            let buffer = this
5748                .opened_buffers
5749                .get(&envelope.payload.buffer_id)
5750                .and_then(|buffer| buffer.upgrade(cx));
5751            if let Some(buffer) = buffer {
5752                buffer.update(cx, |buffer, cx| {
5753                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5754                });
5755            }
5756            Ok(())
5757        })
5758    }
5759
5760    async fn handle_buffer_reloaded(
5761        this: ModelHandle<Self>,
5762        envelope: TypedEnvelope<proto::BufferReloaded>,
5763        _: Arc<Client>,
5764        mut cx: AsyncAppContext,
5765    ) -> Result<()> {
5766        let payload = envelope.payload;
5767        let version = deserialize_version(payload.version);
5768        let line_ending = deserialize_line_ending(
5769            proto::LineEnding::from_i32(payload.line_ending)
5770                .ok_or_else(|| anyhow!("missing line ending"))?,
5771        );
5772        let mtime = payload
5773            .mtime
5774            .ok_or_else(|| anyhow!("missing mtime"))?
5775            .into();
5776        this.update(&mut cx, |this, cx| {
5777            let buffer = this
5778                .opened_buffers
5779                .get(&payload.buffer_id)
5780                .and_then(|buffer| buffer.upgrade(cx));
5781            if let Some(buffer) = buffer {
5782                buffer.update(cx, |buffer, cx| {
5783                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5784                });
5785            }
5786            Ok(())
5787        })
5788    }
5789
5790    #[allow(clippy::type_complexity)]
5791    fn edits_from_lsp(
5792        &mut self,
5793        buffer: &ModelHandle<Buffer>,
5794        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5795        version: Option<i32>,
5796        cx: &mut ModelContext<Self>,
5797    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5798        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5799        cx.background().spawn(async move {
5800            let snapshot = snapshot?;
5801            let mut lsp_edits = lsp_edits
5802                .into_iter()
5803                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5804                .collect::<Vec<_>>();
5805            lsp_edits.sort_by_key(|(range, _)| range.start);
5806
5807            let mut lsp_edits = lsp_edits.into_iter().peekable();
5808            let mut edits = Vec::new();
5809            while let Some((mut range, mut new_text)) = lsp_edits.next() {
5810                // Clip invalid ranges provided by the language server.
5811                range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
5812                range.end = snapshot.clip_point_utf16(range.end, Bias::Left);
5813
5814                // Combine any LSP edits that are adjacent.
5815                //
5816                // Also, combine LSP edits that are separated from each other by only
5817                // a newline. This is important because for some code actions,
5818                // Rust-analyzer rewrites the entire buffer via a series of edits that
5819                // are separated by unchanged newline characters.
5820                //
5821                // In order for the diffing logic below to work properly, any edits that
5822                // cancel each other out must be combined into one.
5823                while let Some((next_range, next_text)) = lsp_edits.peek() {
5824                    if next_range.start > range.end {
5825                        if next_range.start.row > range.end.row + 1
5826                            || next_range.start.column > 0
5827                            || snapshot.clip_point_utf16(
5828                                PointUtf16::new(range.end.row, u32::MAX),
5829                                Bias::Left,
5830                            ) > range.end
5831                        {
5832                            break;
5833                        }
5834                        new_text.push('\n');
5835                    }
5836                    range.end = next_range.end;
5837                    new_text.push_str(next_text);
5838                    lsp_edits.next();
5839                }
5840
5841                // For multiline edits, perform a diff of the old and new text so that
5842                // we can identify the changes more precisely, preserving the locations
5843                // of any anchors positioned in the unchanged regions.
5844                if range.end.row > range.start.row {
5845                    let mut offset = range.start.to_offset(&snapshot);
5846                    let old_text = snapshot.text_for_range(range).collect::<String>();
5847
5848                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5849                    let mut moved_since_edit = true;
5850                    for change in diff.iter_all_changes() {
5851                        let tag = change.tag();
5852                        let value = change.value();
5853                        match tag {
5854                            ChangeTag::Equal => {
5855                                offset += value.len();
5856                                moved_since_edit = true;
5857                            }
5858                            ChangeTag::Delete => {
5859                                let start = snapshot.anchor_after(offset);
5860                                let end = snapshot.anchor_before(offset + value.len());
5861                                if moved_since_edit {
5862                                    edits.push((start..end, String::new()));
5863                                } else {
5864                                    edits.last_mut().unwrap().0.end = end;
5865                                }
5866                                offset += value.len();
5867                                moved_since_edit = false;
5868                            }
5869                            ChangeTag::Insert => {
5870                                if moved_since_edit {
5871                                    let anchor = snapshot.anchor_after(offset);
5872                                    edits.push((anchor..anchor, value.to_string()));
5873                                } else {
5874                                    edits.last_mut().unwrap().1.push_str(value);
5875                                }
5876                                moved_since_edit = false;
5877                            }
5878                        }
5879                    }
5880                } else if range.end == range.start {
5881                    let anchor = snapshot.anchor_after(range.start);
5882                    edits.push((anchor..anchor, new_text));
5883                } else {
5884                    let edit_start = snapshot.anchor_after(range.start);
5885                    let edit_end = snapshot.anchor_before(range.end);
5886                    edits.push((edit_start..edit_end, new_text));
5887                }
5888            }
5889
5890            Ok(edits)
5891        })
5892    }
5893
5894    fn buffer_snapshot_for_lsp_version(
5895        &mut self,
5896        buffer: &ModelHandle<Buffer>,
5897        version: Option<i32>,
5898        cx: &AppContext,
5899    ) -> Result<TextBufferSnapshot> {
5900        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5901
5902        if let Some(version) = version {
5903            let buffer_id = buffer.read(cx).remote_id();
5904            let snapshots = self
5905                .buffer_snapshots
5906                .get_mut(&buffer_id)
5907                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5908            let mut found_snapshot = None;
5909            snapshots.retain(|(snapshot_version, snapshot)| {
5910                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5911                    false
5912                } else {
5913                    if *snapshot_version == version {
5914                        found_snapshot = Some(snapshot.clone());
5915                    }
5916                    true
5917                }
5918            });
5919
5920            found_snapshot.ok_or_else(|| {
5921                anyhow!(
5922                    "snapshot not found for buffer {} at version {}",
5923                    buffer_id,
5924                    version
5925                )
5926            })
5927        } else {
5928            Ok((buffer.read(cx)).text_snapshot())
5929        }
5930    }
5931
5932    fn language_server_for_buffer(
5933        &self,
5934        buffer: &Buffer,
5935        cx: &AppContext,
5936    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
5937        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5938            let name = language.lsp_adapter()?.name.clone();
5939            let worktree_id = file.worktree_id(cx);
5940            let key = (worktree_id, name);
5941
5942            if let Some(server_id) = self.language_server_ids.get(&key) {
5943                if let Some(LanguageServerState::Running { adapter, server }) =
5944                    self.language_servers.get(server_id)
5945                {
5946                    return Some((adapter, server));
5947                }
5948            }
5949        }
5950
5951        None
5952    }
5953}
5954
5955impl ProjectStore {
5956    pub fn new(db: Arc<Db>) -> Self {
5957        Self {
5958            db,
5959            projects: Default::default(),
5960        }
5961    }
5962
5963    pub fn projects<'a>(
5964        &'a self,
5965        cx: &'a AppContext,
5966    ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5967        self.projects
5968            .iter()
5969            .filter_map(|project| project.upgrade(cx))
5970    }
5971
5972    fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5973        if let Err(ix) = self
5974            .projects
5975            .binary_search_by_key(&project.id(), WeakModelHandle::id)
5976        {
5977            self.projects.insert(ix, project);
5978        }
5979        cx.notify();
5980    }
5981
5982    fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
5983        let mut did_change = false;
5984        self.projects.retain(|project| {
5985            if project.is_upgradable(cx) {
5986                true
5987            } else {
5988                did_change = true;
5989                false
5990            }
5991        });
5992        if did_change {
5993            cx.notify();
5994        }
5995    }
5996}
5997
5998impl WorktreeHandle {
5999    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6000        match self {
6001            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6002            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6003        }
6004    }
6005}
6006
6007impl OpenBuffer {
6008    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6009        match self {
6010            OpenBuffer::Strong(handle) => Some(handle.clone()),
6011            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6012            OpenBuffer::Loading(_) => None,
6013        }
6014    }
6015}
6016
6017pub struct PathMatchCandidateSet {
6018    pub snapshot: Snapshot,
6019    pub include_ignored: bool,
6020    pub include_root_name: bool,
6021}
6022
6023impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6024    type Candidates = PathMatchCandidateSetIter<'a>;
6025
6026    fn id(&self) -> usize {
6027        self.snapshot.id().to_usize()
6028    }
6029
6030    fn len(&self) -> usize {
6031        if self.include_ignored {
6032            self.snapshot.file_count()
6033        } else {
6034            self.snapshot.visible_file_count()
6035        }
6036    }
6037
6038    fn prefix(&self) -> Arc<str> {
6039        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6040            self.snapshot.root_name().into()
6041        } else if self.include_root_name {
6042            format!("{}/", self.snapshot.root_name()).into()
6043        } else {
6044            "".into()
6045        }
6046    }
6047
6048    fn candidates(&'a self, start: usize) -> Self::Candidates {
6049        PathMatchCandidateSetIter {
6050            traversal: self.snapshot.files(self.include_ignored, start),
6051        }
6052    }
6053}
6054
6055pub struct PathMatchCandidateSetIter<'a> {
6056    traversal: Traversal<'a>,
6057}
6058
6059impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6060    type Item = fuzzy::PathMatchCandidate<'a>;
6061
6062    fn next(&mut self) -> Option<Self::Item> {
6063        self.traversal.next().map(|entry| {
6064            if let EntryKind::File(char_bag) = entry.kind {
6065                fuzzy::PathMatchCandidate {
6066                    path: &entry.path,
6067                    char_bag,
6068                }
6069            } else {
6070                unreachable!()
6071            }
6072        })
6073    }
6074}
6075
6076impl Entity for ProjectStore {
6077    type Event = ();
6078}
6079
6080impl Entity for Project {
6081    type Event = Event;
6082
6083    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
6084        self.project_store.update(cx, ProjectStore::prune_projects);
6085
6086        match &self.client_state {
6087            ProjectClientState::Local { remote_id_rx, .. } => {
6088                if let Some(project_id) = *remote_id_rx.borrow() {
6089                    self.client
6090                        .send(proto::UnregisterProject { project_id })
6091                        .log_err();
6092                }
6093            }
6094            ProjectClientState::Remote { remote_id, .. } => {
6095                self.client
6096                    .send(proto::LeaveProject {
6097                        project_id: *remote_id,
6098                    })
6099                    .log_err();
6100            }
6101        }
6102    }
6103
6104    fn app_will_quit(
6105        &mut self,
6106        _: &mut MutableAppContext,
6107    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6108        let shutdown_futures = self
6109            .language_servers
6110            .drain()
6111            .map(|(_, server_state)| async {
6112                match server_state {
6113                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6114                    LanguageServerState::Starting(starting_server) => {
6115                        starting_server.await?.shutdown()?.await
6116                    }
6117                }
6118            })
6119            .collect::<Vec<_>>();
6120
6121        Some(
6122            async move {
6123                futures::future::join_all(shutdown_futures).await;
6124            }
6125            .boxed(),
6126        )
6127    }
6128}
6129
6130impl Collaborator {
6131    fn from_proto(
6132        message: proto::Collaborator,
6133        user_store: &ModelHandle<UserStore>,
6134        cx: &mut AsyncAppContext,
6135    ) -> impl Future<Output = Result<Self>> {
6136        let user = user_store.update(cx, |user_store, cx| {
6137            user_store.fetch_user(message.user_id, cx)
6138        });
6139
6140        async move {
6141            Ok(Self {
6142                peer_id: PeerId(message.peer_id),
6143                user: user.await?,
6144                replica_id: message.replica_id as ReplicaId,
6145            })
6146        }
6147    }
6148}
6149
6150impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6151    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6152        Self {
6153            worktree_id,
6154            path: path.as_ref().into(),
6155        }
6156    }
6157}
6158
6159impl From<lsp::CreateFileOptions> for fs::CreateOptions {
6160    fn from(options: lsp::CreateFileOptions) -> Self {
6161        Self {
6162            overwrite: options.overwrite.unwrap_or(false),
6163            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6164        }
6165    }
6166}
6167
6168impl From<lsp::RenameFileOptions> for fs::RenameOptions {
6169    fn from(options: lsp::RenameFileOptions) -> Self {
6170        Self {
6171            overwrite: options.overwrite.unwrap_or(false),
6172            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6173        }
6174    }
6175}
6176
6177impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6178    fn from(options: lsp::DeleteFileOptions) -> Self {
6179        Self {
6180            recursive: options.recursive.unwrap_or(false),
6181            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6182        }
6183    }
6184}
6185
6186fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6187    proto::Symbol {
6188        language_server_name: symbol.language_server_name.0.to_string(),
6189        source_worktree_id: symbol.source_worktree_id.to_proto(),
6190        worktree_id: symbol.path.worktree_id.to_proto(),
6191        path: symbol.path.path.to_string_lossy().to_string(),
6192        name: symbol.name.clone(),
6193        kind: unsafe { mem::transmute(symbol.kind) },
6194        start: Some(proto::Point {
6195            row: symbol.range.start.row,
6196            column: symbol.range.start.column,
6197        }),
6198        end: Some(proto::Point {
6199            row: symbol.range.end.row,
6200            column: symbol.range.end.column,
6201        }),
6202        signature: symbol.signature.to_vec(),
6203    }
6204}
6205
6206fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6207    let mut path_components = path.components();
6208    let mut base_components = base.components();
6209    let mut components: Vec<Component> = Vec::new();
6210    loop {
6211        match (path_components.next(), base_components.next()) {
6212            (None, None) => break,
6213            (Some(a), None) => {
6214                components.push(a);
6215                components.extend(path_components.by_ref());
6216                break;
6217            }
6218            (None, _) => components.push(Component::ParentDir),
6219            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6220            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6221            (Some(a), Some(_)) => {
6222                components.push(Component::ParentDir);
6223                for _ in base_components {
6224                    components.push(Component::ParentDir);
6225                }
6226                components.push(a);
6227                components.extend(path_components.by_ref());
6228                break;
6229            }
6230        }
6231    }
6232    components.iter().map(|c| c.as_os_str()).collect()
6233}
6234
6235impl Item for Buffer {
6236    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6237        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6238    }
6239}