project.rs

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