project.rs

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