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_head_text);
 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(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        repos: &[GitRepositoryEntry],
4656        cx: &mut ModelContext<Self>,
4657    ) {
4658        //TODO: Produce protos
4659
4660        for (_, buffer) in &self.opened_buffers {
4661            if let Some(buffer) = buffer.upgrade(cx) {
4662                let file = match buffer.read(cx).file().and_then(|file| file.as_local()) {
4663                    Some(file) => file,
4664                    None => return,
4665                };
4666                let path = file.path().clone();
4667                let abs_path = file.abs_path(cx);
4668
4669                let repo = match repos.iter().find(|repo| repo.manages(&abs_path)) {
4670                    Some(repo) => repo.clone(),
4671                    None => return,
4672                };
4673
4674                let shared_remote_id = self.shared_remote_id();
4675                let client = self.client.clone();
4676
4677                cx.spawn(|_, mut cx| async move {
4678                    let head_text = cx
4679                        .background()
4680                        .spawn(async move { repo.repo.lock().load_head_text(&path) })
4681                        .await;
4682
4683                    let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4684                        buffer.update_head_text(head_text.clone(), cx);
4685                        buffer.remote_id()
4686                    });
4687
4688                    if let Some(project_id) = shared_remote_id {
4689                        client
4690                            .send(proto::UpdateHeadText {
4691                                project_id,
4692                                buffer_id: buffer_id as u64,
4693                                head_text,
4694                            })
4695                            .log_err();
4696                    }
4697                })
4698                .detach();
4699            }
4700        }
4701    }
4702
4703    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4704        let new_active_entry = entry.and_then(|project_path| {
4705            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4706            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4707            Some(entry.id)
4708        });
4709        if new_active_entry != self.active_entry {
4710            self.active_entry = new_active_entry;
4711            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4712        }
4713    }
4714
4715    pub fn language_servers_running_disk_based_diagnostics(
4716        &self,
4717    ) -> impl Iterator<Item = usize> + '_ {
4718        self.language_server_statuses
4719            .iter()
4720            .filter_map(|(id, status)| {
4721                if status.has_pending_diagnostic_updates {
4722                    Some(*id)
4723                } else {
4724                    None
4725                }
4726            })
4727    }
4728
4729    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4730        let mut summary = DiagnosticSummary::default();
4731        for (_, path_summary) in self.diagnostic_summaries(cx) {
4732            summary.error_count += path_summary.error_count;
4733            summary.warning_count += path_summary.warning_count;
4734        }
4735        summary
4736    }
4737
4738    pub fn diagnostic_summaries<'a>(
4739        &'a self,
4740        cx: &'a AppContext,
4741    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4742        self.visible_worktrees(cx).flat_map(move |worktree| {
4743            let worktree = worktree.read(cx);
4744            let worktree_id = worktree.id();
4745            worktree
4746                .diagnostic_summaries()
4747                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4748        })
4749    }
4750
4751    pub fn disk_based_diagnostics_started(
4752        &mut self,
4753        language_server_id: usize,
4754        cx: &mut ModelContext<Self>,
4755    ) {
4756        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4757    }
4758
4759    pub fn disk_based_diagnostics_finished(
4760        &mut self,
4761        language_server_id: usize,
4762        cx: &mut ModelContext<Self>,
4763    ) {
4764        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4765    }
4766
4767    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4768        self.active_entry
4769    }
4770
4771    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4772        self.worktree_for_id(path.worktree_id, cx)?
4773            .read(cx)
4774            .entry_for_path(&path.path)
4775            .cloned()
4776    }
4777
4778    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4779        let worktree = self.worktree_for_entry(entry_id, cx)?;
4780        let worktree = worktree.read(cx);
4781        let worktree_id = worktree.id();
4782        let path = worktree.entry_for_id(entry_id)?.path.clone();
4783        Some(ProjectPath { worktree_id, path })
4784    }
4785
4786    // RPC message handlers
4787
4788    async fn handle_request_join_project(
4789        this: ModelHandle<Self>,
4790        message: TypedEnvelope<proto::RequestJoinProject>,
4791        _: Arc<Client>,
4792        mut cx: AsyncAppContext,
4793    ) -> Result<()> {
4794        let user_id = message.payload.requester_id;
4795        if this.read_with(&cx, |project, _| {
4796            project.collaborators.values().any(|c| c.user.id == user_id)
4797        }) {
4798            this.update(&mut cx, |this, cx| {
4799                this.respond_to_join_request(user_id, true, cx)
4800            });
4801        } else {
4802            let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4803            let user = user_store
4804                .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4805                .await?;
4806            this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4807        }
4808        Ok(())
4809    }
4810
4811    async fn handle_unregister_project(
4812        this: ModelHandle<Self>,
4813        _: TypedEnvelope<proto::UnregisterProject>,
4814        _: Arc<Client>,
4815        mut cx: AsyncAppContext,
4816    ) -> Result<()> {
4817        this.update(&mut cx, |this, cx| this.disconnected_from_host(cx));
4818        Ok(())
4819    }
4820
4821    async fn handle_project_unshared(
4822        this: ModelHandle<Self>,
4823        _: TypedEnvelope<proto::ProjectUnshared>,
4824        _: Arc<Client>,
4825        mut cx: AsyncAppContext,
4826    ) -> Result<()> {
4827        this.update(&mut cx, |this, cx| this.unshared(cx));
4828        Ok(())
4829    }
4830
4831    async fn handle_add_collaborator(
4832        this: ModelHandle<Self>,
4833        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4834        _: Arc<Client>,
4835        mut cx: AsyncAppContext,
4836    ) -> Result<()> {
4837        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4838        let collaborator = envelope
4839            .payload
4840            .collaborator
4841            .take()
4842            .ok_or_else(|| anyhow!("empty collaborator"))?;
4843
4844        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4845        this.update(&mut cx, |this, cx| {
4846            this.collaborators
4847                .insert(collaborator.peer_id, collaborator);
4848            cx.notify();
4849        });
4850
4851        Ok(())
4852    }
4853
4854    async fn handle_remove_collaborator(
4855        this: ModelHandle<Self>,
4856        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4857        _: Arc<Client>,
4858        mut cx: AsyncAppContext,
4859    ) -> Result<()> {
4860        this.update(&mut cx, |this, cx| {
4861            let peer_id = PeerId(envelope.payload.peer_id);
4862            let replica_id = this
4863                .collaborators
4864                .remove(&peer_id)
4865                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4866                .replica_id;
4867            for buffer in this.opened_buffers.values() {
4868                if let Some(buffer) = buffer.upgrade(cx) {
4869                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4870                }
4871            }
4872
4873            cx.emit(Event::CollaboratorLeft(peer_id));
4874            cx.notify();
4875            Ok(())
4876        })
4877    }
4878
4879    async fn handle_join_project_request_cancelled(
4880        this: ModelHandle<Self>,
4881        envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4882        _: Arc<Client>,
4883        mut cx: AsyncAppContext,
4884    ) -> Result<()> {
4885        let user = this
4886            .update(&mut cx, |this, cx| {
4887                this.user_store.update(cx, |user_store, cx| {
4888                    user_store.fetch_user(envelope.payload.requester_id, cx)
4889                })
4890            })
4891            .await?;
4892
4893        this.update(&mut cx, |_, cx| {
4894            cx.emit(Event::ContactCancelledJoinRequest(user));
4895        });
4896
4897        Ok(())
4898    }
4899
4900    async fn handle_update_project(
4901        this: ModelHandle<Self>,
4902        envelope: TypedEnvelope<proto::UpdateProject>,
4903        client: Arc<Client>,
4904        mut cx: AsyncAppContext,
4905    ) -> Result<()> {
4906        this.update(&mut cx, |this, cx| {
4907            let replica_id = this.replica_id();
4908            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4909
4910            let mut old_worktrees_by_id = this
4911                .worktrees
4912                .drain(..)
4913                .filter_map(|worktree| {
4914                    let worktree = worktree.upgrade(cx)?;
4915                    Some((worktree.read(cx).id(), worktree))
4916                })
4917                .collect::<HashMap<_, _>>();
4918
4919            for worktree in envelope.payload.worktrees {
4920                if let Some(old_worktree) =
4921                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4922                {
4923                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4924                } else {
4925                    let worktree =
4926                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4927                    this.add_worktree(&worktree, cx);
4928                }
4929            }
4930
4931            this.metadata_changed(true, cx);
4932            for (id, _) in old_worktrees_by_id {
4933                cx.emit(Event::WorktreeRemoved(id));
4934            }
4935
4936            Ok(())
4937        })
4938    }
4939
4940    async fn handle_update_worktree(
4941        this: ModelHandle<Self>,
4942        envelope: TypedEnvelope<proto::UpdateWorktree>,
4943        _: Arc<Client>,
4944        mut cx: AsyncAppContext,
4945    ) -> Result<()> {
4946        this.update(&mut cx, |this, cx| {
4947            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4948            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4949                worktree.update(cx, |worktree, _| {
4950                    let worktree = worktree.as_remote_mut().unwrap();
4951                    worktree.update_from_remote(envelope.payload);
4952                });
4953            }
4954            Ok(())
4955        })
4956    }
4957
4958    async fn handle_create_project_entry(
4959        this: ModelHandle<Self>,
4960        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4961        _: Arc<Client>,
4962        mut cx: AsyncAppContext,
4963    ) -> Result<proto::ProjectEntryResponse> {
4964        let worktree = this.update(&mut cx, |this, cx| {
4965            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4966            this.worktree_for_id(worktree_id, cx)
4967                .ok_or_else(|| anyhow!("worktree not found"))
4968        })?;
4969        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4970        let entry = worktree
4971            .update(&mut cx, |worktree, cx| {
4972                let worktree = worktree.as_local_mut().unwrap();
4973                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4974                worktree.create_entry(path, envelope.payload.is_directory, cx)
4975            })
4976            .await?;
4977        Ok(proto::ProjectEntryResponse {
4978            entry: Some((&entry).into()),
4979            worktree_scan_id: worktree_scan_id as u64,
4980        })
4981    }
4982
4983    async fn handle_rename_project_entry(
4984        this: ModelHandle<Self>,
4985        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4986        _: Arc<Client>,
4987        mut cx: AsyncAppContext,
4988    ) -> Result<proto::ProjectEntryResponse> {
4989        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4990        let worktree = this.read_with(&cx, |this, cx| {
4991            this.worktree_for_entry(entry_id, cx)
4992                .ok_or_else(|| anyhow!("worktree not found"))
4993        })?;
4994        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4995        let entry = worktree
4996            .update(&mut cx, |worktree, cx| {
4997                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4998                worktree
4999                    .as_local_mut()
5000                    .unwrap()
5001                    .rename_entry(entry_id, new_path, cx)
5002                    .ok_or_else(|| anyhow!("invalid entry"))
5003            })?
5004            .await?;
5005        Ok(proto::ProjectEntryResponse {
5006            entry: Some((&entry).into()),
5007            worktree_scan_id: worktree_scan_id as u64,
5008        })
5009    }
5010
5011    async fn handle_copy_project_entry(
5012        this: ModelHandle<Self>,
5013        envelope: TypedEnvelope<proto::CopyProjectEntry>,
5014        _: Arc<Client>,
5015        mut cx: AsyncAppContext,
5016    ) -> Result<proto::ProjectEntryResponse> {
5017        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5018        let worktree = this.read_with(&cx, |this, cx| {
5019            this.worktree_for_entry(entry_id, cx)
5020                .ok_or_else(|| anyhow!("worktree not found"))
5021        })?;
5022        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5023        let entry = worktree
5024            .update(&mut cx, |worktree, cx| {
5025                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
5026                worktree
5027                    .as_local_mut()
5028                    .unwrap()
5029                    .copy_entry(entry_id, new_path, cx)
5030                    .ok_or_else(|| anyhow!("invalid entry"))
5031            })?
5032            .await?;
5033        Ok(proto::ProjectEntryResponse {
5034            entry: Some((&entry).into()),
5035            worktree_scan_id: worktree_scan_id as u64,
5036        })
5037    }
5038
5039    async fn handle_delete_project_entry(
5040        this: ModelHandle<Self>,
5041        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5042        _: Arc<Client>,
5043        mut cx: AsyncAppContext,
5044    ) -> Result<proto::ProjectEntryResponse> {
5045        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5046        let worktree = this.read_with(&cx, |this, cx| {
5047            this.worktree_for_entry(entry_id, cx)
5048                .ok_or_else(|| anyhow!("worktree not found"))
5049        })?;
5050        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5051        worktree
5052            .update(&mut cx, |worktree, cx| {
5053                worktree
5054                    .as_local_mut()
5055                    .unwrap()
5056                    .delete_entry(entry_id, cx)
5057                    .ok_or_else(|| anyhow!("invalid entry"))
5058            })?
5059            .await?;
5060        Ok(proto::ProjectEntryResponse {
5061            entry: None,
5062            worktree_scan_id: worktree_scan_id as u64,
5063        })
5064    }
5065
5066    async fn handle_update_diagnostic_summary(
5067        this: ModelHandle<Self>,
5068        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5069        _: Arc<Client>,
5070        mut cx: AsyncAppContext,
5071    ) -> Result<()> {
5072        this.update(&mut cx, |this, cx| {
5073            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5074            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5075                if let Some(summary) = envelope.payload.summary {
5076                    let project_path = ProjectPath {
5077                        worktree_id,
5078                        path: Path::new(&summary.path).into(),
5079                    };
5080                    worktree.update(cx, |worktree, _| {
5081                        worktree
5082                            .as_remote_mut()
5083                            .unwrap()
5084                            .update_diagnostic_summary(project_path.path.clone(), &summary);
5085                    });
5086                    cx.emit(Event::DiagnosticsUpdated {
5087                        language_server_id: summary.language_server_id as usize,
5088                        path: project_path,
5089                    });
5090                }
5091            }
5092            Ok(())
5093        })
5094    }
5095
5096    async fn handle_start_language_server(
5097        this: ModelHandle<Self>,
5098        envelope: TypedEnvelope<proto::StartLanguageServer>,
5099        _: Arc<Client>,
5100        mut cx: AsyncAppContext,
5101    ) -> Result<()> {
5102        let server = envelope
5103            .payload
5104            .server
5105            .ok_or_else(|| anyhow!("invalid server"))?;
5106        this.update(&mut cx, |this, cx| {
5107            this.language_server_statuses.insert(
5108                server.id as usize,
5109                LanguageServerStatus {
5110                    name: server.name,
5111                    pending_work: Default::default(),
5112                    has_pending_diagnostic_updates: false,
5113                    progress_tokens: Default::default(),
5114                },
5115            );
5116            cx.notify();
5117        });
5118        Ok(())
5119    }
5120
5121    async fn handle_update_language_server(
5122        this: ModelHandle<Self>,
5123        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5124        _: Arc<Client>,
5125        mut cx: AsyncAppContext,
5126    ) -> Result<()> {
5127        let language_server_id = envelope.payload.language_server_id as usize;
5128        match envelope
5129            .payload
5130            .variant
5131            .ok_or_else(|| anyhow!("invalid variant"))?
5132        {
5133            proto::update_language_server::Variant::WorkStart(payload) => {
5134                this.update(&mut cx, |this, cx| {
5135                    this.on_lsp_work_start(
5136                        language_server_id,
5137                        payload.token,
5138                        LanguageServerProgress {
5139                            message: payload.message,
5140                            percentage: payload.percentage.map(|p| p as usize),
5141                            last_update_at: Instant::now(),
5142                        },
5143                        cx,
5144                    );
5145                })
5146            }
5147            proto::update_language_server::Variant::WorkProgress(payload) => {
5148                this.update(&mut cx, |this, cx| {
5149                    this.on_lsp_work_progress(
5150                        language_server_id,
5151                        payload.token,
5152                        LanguageServerProgress {
5153                            message: payload.message,
5154                            percentage: payload.percentage.map(|p| p as usize),
5155                            last_update_at: Instant::now(),
5156                        },
5157                        cx,
5158                    );
5159                })
5160            }
5161            proto::update_language_server::Variant::WorkEnd(payload) => {
5162                this.update(&mut cx, |this, cx| {
5163                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5164                })
5165            }
5166            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5167                this.update(&mut cx, |this, cx| {
5168                    this.disk_based_diagnostics_started(language_server_id, cx);
5169                })
5170            }
5171            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5172                this.update(&mut cx, |this, cx| {
5173                    this.disk_based_diagnostics_finished(language_server_id, cx)
5174                });
5175            }
5176        }
5177
5178        Ok(())
5179    }
5180
5181    async fn handle_update_buffer(
5182        this: ModelHandle<Self>,
5183        envelope: TypedEnvelope<proto::UpdateBuffer>,
5184        _: Arc<Client>,
5185        mut cx: AsyncAppContext,
5186    ) -> Result<()> {
5187        this.update(&mut cx, |this, cx| {
5188            let payload = envelope.payload.clone();
5189            let buffer_id = payload.buffer_id;
5190            let ops = payload
5191                .operations
5192                .into_iter()
5193                .map(language::proto::deserialize_operation)
5194                .collect::<Result<Vec<_>, _>>()?;
5195            let is_remote = this.is_remote();
5196            match this.opened_buffers.entry(buffer_id) {
5197                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5198                    OpenBuffer::Strong(buffer) => {
5199                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5200                    }
5201                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5202                    OpenBuffer::Weak(_) => {}
5203                },
5204                hash_map::Entry::Vacant(e) => {
5205                    assert!(
5206                        is_remote,
5207                        "received buffer update from {:?}",
5208                        envelope.original_sender_id
5209                    );
5210                    e.insert(OpenBuffer::Operations(ops));
5211                }
5212            }
5213            Ok(())
5214        })
5215    }
5216
5217    async fn handle_create_buffer_for_peer(
5218        this: ModelHandle<Self>,
5219        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5220        _: Arc<Client>,
5221        mut cx: AsyncAppContext,
5222    ) -> Result<()> {
5223        this.update(&mut cx, |this, cx| {
5224            match envelope
5225                .payload
5226                .variant
5227                .ok_or_else(|| anyhow!("missing variant"))?
5228            {
5229                proto::create_buffer_for_peer::Variant::State(mut state) => {
5230                    let mut buffer_file = None;
5231                    if let Some(file) = state.file.take() {
5232                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5233                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5234                            anyhow!("no worktree found for id {}", file.worktree_id)
5235                        })?;
5236                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5237                            as Arc<dyn language::File>);
5238                    }
5239
5240                    let buffer_id = state.id;
5241                    let buffer = cx.add_model(|_| {
5242                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5243                    });
5244                    this.incomplete_buffers.insert(buffer_id, buffer);
5245                }
5246                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5247                    let buffer = this
5248                        .incomplete_buffers
5249                        .get(&chunk.buffer_id)
5250                        .ok_or_else(|| {
5251                            anyhow!(
5252                                "received chunk for buffer {} without initial state",
5253                                chunk.buffer_id
5254                            )
5255                        })?
5256                        .clone();
5257                    let operations = chunk
5258                        .operations
5259                        .into_iter()
5260                        .map(language::proto::deserialize_operation)
5261                        .collect::<Result<Vec<_>>>()?;
5262                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5263
5264                    if chunk.is_last {
5265                        this.incomplete_buffers.remove(&chunk.buffer_id);
5266                        this.register_buffer(&buffer, cx)?;
5267                    }
5268                }
5269            }
5270
5271            Ok(())
5272        })
5273    }
5274
5275    async fn handle_update_head_text(
5276        this: ModelHandle<Self>,
5277        envelope: TypedEnvelope<proto::UpdateHeadText>,
5278        _: Arc<Client>,
5279        mut cx: AsyncAppContext,
5280    ) -> Result<()> {
5281        this.update(&mut cx, |this, cx| {
5282            let buffer_id = envelope.payload.buffer_id;
5283            let head_text = envelope.payload.head_text;
5284            let buffer = this
5285                .opened_buffers
5286                .get_mut(&buffer_id)
5287                .and_then(|b| b.upgrade(cx))
5288                .ok_or_else(|| anyhow!("No such buffer {}", buffer_id))?;
5289
5290            buffer.update(cx, |buffer, cx| buffer.update_head_text(head_text, cx));
5291
5292            Ok(())
5293        })
5294    }
5295
5296    async fn handle_update_buffer_file(
5297        this: ModelHandle<Self>,
5298        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5299        _: Arc<Client>,
5300        mut cx: AsyncAppContext,
5301    ) -> Result<()> {
5302        this.update(&mut cx, |this, cx| {
5303            let payload = envelope.payload.clone();
5304            let buffer_id = payload.buffer_id;
5305            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5306            let worktree = this
5307                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5308                .ok_or_else(|| anyhow!("no such worktree"))?;
5309            let file = File::from_proto(file, worktree, cx)?;
5310            let buffer = this
5311                .opened_buffers
5312                .get_mut(&buffer_id)
5313                .and_then(|b| b.upgrade(cx))
5314                .ok_or_else(|| anyhow!("no such buffer"))?;
5315            buffer.update(cx, |buffer, cx| {
5316                buffer.file_updated(Arc::new(file), cx).detach();
5317            });
5318            Ok(())
5319        })
5320    }
5321
5322    async fn handle_save_buffer(
5323        this: ModelHandle<Self>,
5324        envelope: TypedEnvelope<proto::SaveBuffer>,
5325        _: Arc<Client>,
5326        mut cx: AsyncAppContext,
5327    ) -> Result<proto::BufferSaved> {
5328        let buffer_id = envelope.payload.buffer_id;
5329        let requested_version = deserialize_version(envelope.payload.version);
5330
5331        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5332            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5333            let buffer = this
5334                .opened_buffers
5335                .get(&buffer_id)
5336                .and_then(|buffer| buffer.upgrade(cx))
5337                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5338            Ok::<_, anyhow::Error>((project_id, buffer))
5339        })?;
5340        buffer
5341            .update(&mut cx, |buffer, _| {
5342                buffer.wait_for_version(requested_version)
5343            })
5344            .await;
5345
5346        let (saved_version, fingerprint, mtime) =
5347            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5348        Ok(proto::BufferSaved {
5349            project_id,
5350            buffer_id,
5351            version: serialize_version(&saved_version),
5352            mtime: Some(mtime.into()),
5353            fingerprint,
5354        })
5355    }
5356
5357    async fn handle_reload_buffers(
5358        this: ModelHandle<Self>,
5359        envelope: TypedEnvelope<proto::ReloadBuffers>,
5360        _: Arc<Client>,
5361        mut cx: AsyncAppContext,
5362    ) -> Result<proto::ReloadBuffersResponse> {
5363        let sender_id = envelope.original_sender_id()?;
5364        let reload = this.update(&mut cx, |this, cx| {
5365            let mut buffers = HashSet::default();
5366            for buffer_id in &envelope.payload.buffer_ids {
5367                buffers.insert(
5368                    this.opened_buffers
5369                        .get(buffer_id)
5370                        .and_then(|buffer| buffer.upgrade(cx))
5371                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5372                );
5373            }
5374            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5375        })?;
5376
5377        let project_transaction = reload.await?;
5378        let project_transaction = this.update(&mut cx, |this, cx| {
5379            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5380        });
5381        Ok(proto::ReloadBuffersResponse {
5382            transaction: Some(project_transaction),
5383        })
5384    }
5385
5386    async fn handle_format_buffers(
5387        this: ModelHandle<Self>,
5388        envelope: TypedEnvelope<proto::FormatBuffers>,
5389        _: Arc<Client>,
5390        mut cx: AsyncAppContext,
5391    ) -> Result<proto::FormatBuffersResponse> {
5392        let sender_id = envelope.original_sender_id()?;
5393        let format = this.update(&mut cx, |this, cx| {
5394            let mut buffers = HashSet::default();
5395            for buffer_id in &envelope.payload.buffer_ids {
5396                buffers.insert(
5397                    this.opened_buffers
5398                        .get(buffer_id)
5399                        .and_then(|buffer| buffer.upgrade(cx))
5400                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5401                );
5402            }
5403            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5404            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5405        })?;
5406
5407        let project_transaction = format.await?;
5408        let project_transaction = this.update(&mut cx, |this, cx| {
5409            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5410        });
5411        Ok(proto::FormatBuffersResponse {
5412            transaction: Some(project_transaction),
5413        })
5414    }
5415
5416    async fn handle_get_completions(
5417        this: ModelHandle<Self>,
5418        envelope: TypedEnvelope<proto::GetCompletions>,
5419        _: Arc<Client>,
5420        mut cx: AsyncAppContext,
5421    ) -> Result<proto::GetCompletionsResponse> {
5422        let position = envelope
5423            .payload
5424            .position
5425            .and_then(language::proto::deserialize_anchor)
5426            .ok_or_else(|| anyhow!("invalid position"))?;
5427        let version = deserialize_version(envelope.payload.version);
5428        let buffer = this.read_with(&cx, |this, cx| {
5429            this.opened_buffers
5430                .get(&envelope.payload.buffer_id)
5431                .and_then(|buffer| buffer.upgrade(cx))
5432                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5433        })?;
5434        buffer
5435            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5436            .await;
5437        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5438        let completions = this
5439            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5440            .await?;
5441
5442        Ok(proto::GetCompletionsResponse {
5443            completions: completions
5444                .iter()
5445                .map(language::proto::serialize_completion)
5446                .collect(),
5447            version: serialize_version(&version),
5448        })
5449    }
5450
5451    async fn handle_apply_additional_edits_for_completion(
5452        this: ModelHandle<Self>,
5453        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5454        _: Arc<Client>,
5455        mut cx: AsyncAppContext,
5456    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5457        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5458            let buffer = this
5459                .opened_buffers
5460                .get(&envelope.payload.buffer_id)
5461                .and_then(|buffer| buffer.upgrade(cx))
5462                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5463            let language = buffer.read(cx).language();
5464            let completion = language::proto::deserialize_completion(
5465                envelope
5466                    .payload
5467                    .completion
5468                    .ok_or_else(|| anyhow!("invalid completion"))?,
5469                language.cloned(),
5470            );
5471            Ok::<_, anyhow::Error>((buffer, completion))
5472        })?;
5473
5474        let completion = completion.await?;
5475
5476        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5477            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5478        });
5479
5480        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5481            transaction: apply_additional_edits
5482                .await?
5483                .as_ref()
5484                .map(language::proto::serialize_transaction),
5485        })
5486    }
5487
5488    async fn handle_get_code_actions(
5489        this: ModelHandle<Self>,
5490        envelope: TypedEnvelope<proto::GetCodeActions>,
5491        _: Arc<Client>,
5492        mut cx: AsyncAppContext,
5493    ) -> Result<proto::GetCodeActionsResponse> {
5494        let start = envelope
5495            .payload
5496            .start
5497            .and_then(language::proto::deserialize_anchor)
5498            .ok_or_else(|| anyhow!("invalid start"))?;
5499        let end = envelope
5500            .payload
5501            .end
5502            .and_then(language::proto::deserialize_anchor)
5503            .ok_or_else(|| anyhow!("invalid end"))?;
5504        let buffer = this.update(&mut cx, |this, cx| {
5505            this.opened_buffers
5506                .get(&envelope.payload.buffer_id)
5507                .and_then(|buffer| buffer.upgrade(cx))
5508                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5509        })?;
5510        buffer
5511            .update(&mut cx, |buffer, _| {
5512                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5513            })
5514            .await;
5515
5516        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5517        let code_actions = this.update(&mut cx, |this, cx| {
5518            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5519        })?;
5520
5521        Ok(proto::GetCodeActionsResponse {
5522            actions: code_actions
5523                .await?
5524                .iter()
5525                .map(language::proto::serialize_code_action)
5526                .collect(),
5527            version: serialize_version(&version),
5528        })
5529    }
5530
5531    async fn handle_apply_code_action(
5532        this: ModelHandle<Self>,
5533        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5534        _: Arc<Client>,
5535        mut cx: AsyncAppContext,
5536    ) -> Result<proto::ApplyCodeActionResponse> {
5537        let sender_id = envelope.original_sender_id()?;
5538        let action = language::proto::deserialize_code_action(
5539            envelope
5540                .payload
5541                .action
5542                .ok_or_else(|| anyhow!("invalid action"))?,
5543        )?;
5544        let apply_code_action = this.update(&mut cx, |this, cx| {
5545            let buffer = this
5546                .opened_buffers
5547                .get(&envelope.payload.buffer_id)
5548                .and_then(|buffer| buffer.upgrade(cx))
5549                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5550            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5551        })?;
5552
5553        let project_transaction = apply_code_action.await?;
5554        let project_transaction = this.update(&mut cx, |this, cx| {
5555            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5556        });
5557        Ok(proto::ApplyCodeActionResponse {
5558            transaction: Some(project_transaction),
5559        })
5560    }
5561
5562    async fn handle_lsp_command<T: LspCommand>(
5563        this: ModelHandle<Self>,
5564        envelope: TypedEnvelope<T::ProtoRequest>,
5565        _: Arc<Client>,
5566        mut cx: AsyncAppContext,
5567    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5568    where
5569        <T::LspRequest as lsp::request::Request>::Result: Send,
5570    {
5571        let sender_id = envelope.original_sender_id()?;
5572        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5573        let buffer_handle = this.read_with(&cx, |this, _| {
5574            this.opened_buffers
5575                .get(&buffer_id)
5576                .and_then(|buffer| buffer.upgrade(&cx))
5577                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5578        })?;
5579        let request = T::from_proto(
5580            envelope.payload,
5581            this.clone(),
5582            buffer_handle.clone(),
5583            cx.clone(),
5584        )
5585        .await?;
5586        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5587        let response = this
5588            .update(&mut cx, |this, cx| {
5589                this.request_lsp(buffer_handle, request, cx)
5590            })
5591            .await?;
5592        this.update(&mut cx, |this, cx| {
5593            Ok(T::response_to_proto(
5594                response,
5595                this,
5596                sender_id,
5597                &buffer_version,
5598                cx,
5599            ))
5600        })
5601    }
5602
5603    async fn handle_get_project_symbols(
5604        this: ModelHandle<Self>,
5605        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5606        _: Arc<Client>,
5607        mut cx: AsyncAppContext,
5608    ) -> Result<proto::GetProjectSymbolsResponse> {
5609        let symbols = this
5610            .update(&mut cx, |this, cx| {
5611                this.symbols(&envelope.payload.query, cx)
5612            })
5613            .await?;
5614
5615        Ok(proto::GetProjectSymbolsResponse {
5616            symbols: symbols.iter().map(serialize_symbol).collect(),
5617        })
5618    }
5619
5620    async fn handle_search_project(
5621        this: ModelHandle<Self>,
5622        envelope: TypedEnvelope<proto::SearchProject>,
5623        _: Arc<Client>,
5624        mut cx: AsyncAppContext,
5625    ) -> Result<proto::SearchProjectResponse> {
5626        let peer_id = envelope.original_sender_id()?;
5627        let query = SearchQuery::from_proto(envelope.payload)?;
5628        let result = this
5629            .update(&mut cx, |this, cx| this.search(query, cx))
5630            .await?;
5631
5632        this.update(&mut cx, |this, cx| {
5633            let mut locations = Vec::new();
5634            for (buffer, ranges) in result {
5635                for range in ranges {
5636                    let start = serialize_anchor(&range.start);
5637                    let end = serialize_anchor(&range.end);
5638                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5639                    locations.push(proto::Location {
5640                        buffer_id,
5641                        start: Some(start),
5642                        end: Some(end),
5643                    });
5644                }
5645            }
5646            Ok(proto::SearchProjectResponse { locations })
5647        })
5648    }
5649
5650    async fn handle_open_buffer_for_symbol(
5651        this: ModelHandle<Self>,
5652        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5653        _: Arc<Client>,
5654        mut cx: AsyncAppContext,
5655    ) -> Result<proto::OpenBufferForSymbolResponse> {
5656        let peer_id = envelope.original_sender_id()?;
5657        let symbol = envelope
5658            .payload
5659            .symbol
5660            .ok_or_else(|| anyhow!("invalid symbol"))?;
5661        let symbol = this
5662            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5663            .await?;
5664        let symbol = this.read_with(&cx, |this, _| {
5665            let signature = this.symbol_signature(&symbol.path);
5666            if signature == symbol.signature {
5667                Ok(symbol)
5668            } else {
5669                Err(anyhow!("invalid symbol signature"))
5670            }
5671        })?;
5672        let buffer = this
5673            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5674            .await?;
5675
5676        Ok(proto::OpenBufferForSymbolResponse {
5677            buffer_id: this.update(&mut cx, |this, cx| {
5678                this.create_buffer_for_peer(&buffer, peer_id, cx)
5679            }),
5680        })
5681    }
5682
5683    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5684        let mut hasher = Sha256::new();
5685        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5686        hasher.update(project_path.path.to_string_lossy().as_bytes());
5687        hasher.update(self.nonce.to_be_bytes());
5688        hasher.finalize().as_slice().try_into().unwrap()
5689    }
5690
5691    async fn handle_open_buffer_by_id(
5692        this: ModelHandle<Self>,
5693        envelope: TypedEnvelope<proto::OpenBufferById>,
5694        _: Arc<Client>,
5695        mut cx: AsyncAppContext,
5696    ) -> Result<proto::OpenBufferResponse> {
5697        let peer_id = envelope.original_sender_id()?;
5698        let buffer = this
5699            .update(&mut cx, |this, cx| {
5700                this.open_buffer_by_id(envelope.payload.id, cx)
5701            })
5702            .await?;
5703        this.update(&mut cx, |this, cx| {
5704            Ok(proto::OpenBufferResponse {
5705                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5706            })
5707        })
5708    }
5709
5710    async fn handle_open_buffer_by_path(
5711        this: ModelHandle<Self>,
5712        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5713        _: Arc<Client>,
5714        mut cx: AsyncAppContext,
5715    ) -> Result<proto::OpenBufferResponse> {
5716        let peer_id = envelope.original_sender_id()?;
5717        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5718        let open_buffer = this.update(&mut cx, |this, cx| {
5719            this.open_buffer(
5720                ProjectPath {
5721                    worktree_id,
5722                    path: PathBuf::from(envelope.payload.path).into(),
5723                },
5724                cx,
5725            )
5726        });
5727
5728        let buffer = open_buffer.await?;
5729        this.update(&mut cx, |this, cx| {
5730            Ok(proto::OpenBufferResponse {
5731                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5732            })
5733        })
5734    }
5735
5736    fn serialize_project_transaction_for_peer(
5737        &mut self,
5738        project_transaction: ProjectTransaction,
5739        peer_id: PeerId,
5740        cx: &AppContext,
5741    ) -> proto::ProjectTransaction {
5742        let mut serialized_transaction = proto::ProjectTransaction {
5743            buffer_ids: Default::default(),
5744            transactions: Default::default(),
5745        };
5746        for (buffer, transaction) in project_transaction.0 {
5747            serialized_transaction
5748                .buffer_ids
5749                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5750            serialized_transaction
5751                .transactions
5752                .push(language::proto::serialize_transaction(&transaction));
5753        }
5754        serialized_transaction
5755    }
5756
5757    fn deserialize_project_transaction(
5758        &mut self,
5759        message: proto::ProjectTransaction,
5760        push_to_history: bool,
5761        cx: &mut ModelContext<Self>,
5762    ) -> Task<Result<ProjectTransaction>> {
5763        cx.spawn(|this, mut cx| async move {
5764            let mut project_transaction = ProjectTransaction::default();
5765            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5766            {
5767                let buffer = this
5768                    .update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
5769                    .await?;
5770                let transaction = language::proto::deserialize_transaction(transaction)?;
5771                project_transaction.0.insert(buffer, transaction);
5772            }
5773
5774            for (buffer, transaction) in &project_transaction.0 {
5775                buffer
5776                    .update(&mut cx, |buffer, _| {
5777                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5778                    })
5779                    .await;
5780
5781                if push_to_history {
5782                    buffer.update(&mut cx, |buffer, _| {
5783                        buffer.push_transaction(transaction.clone(), Instant::now());
5784                    });
5785                }
5786            }
5787
5788            Ok(project_transaction)
5789        })
5790    }
5791
5792    fn create_buffer_for_peer(
5793        &mut self,
5794        buffer: &ModelHandle<Buffer>,
5795        peer_id: PeerId,
5796        cx: &AppContext,
5797    ) -> u64 {
5798        let buffer_id = buffer.read(cx).remote_id();
5799        if let Some(project_id) = self.remote_id() {
5800            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5801            if shared_buffers.insert(buffer_id) {
5802                let buffer = buffer.read(cx);
5803                let state = buffer.to_proto();
5804                let operations = buffer.serialize_ops(cx);
5805                let client = self.client.clone();
5806                cx.background()
5807                    .spawn(
5808                        async move {
5809                            let mut operations = operations.await;
5810
5811                            client.send(proto::CreateBufferForPeer {
5812                                project_id,
5813                                peer_id: peer_id.0,
5814                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5815                            })?;
5816
5817                            loop {
5818                                #[cfg(any(test, feature = "test-support"))]
5819                                const CHUNK_SIZE: usize = 5;
5820
5821                                #[cfg(not(any(test, feature = "test-support")))]
5822                                const CHUNK_SIZE: usize = 100;
5823
5824                                let chunk = operations
5825                                    .drain(..cmp::min(CHUNK_SIZE, operations.len()))
5826                                    .collect();
5827                                let is_last = operations.is_empty();
5828                                client.send(proto::CreateBufferForPeer {
5829                                    project_id,
5830                                    peer_id: peer_id.0,
5831                                    variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5832                                        proto::BufferChunk {
5833                                            buffer_id,
5834                                            operations: chunk,
5835                                            is_last,
5836                                        },
5837                                    )),
5838                                })?;
5839
5840                                if is_last {
5841                                    break;
5842                                }
5843                            }
5844
5845                            Ok(())
5846                        }
5847                        .log_err(),
5848                    )
5849                    .detach();
5850            }
5851        }
5852
5853        buffer_id
5854    }
5855
5856    fn wait_for_buffer(
5857        &self,
5858        id: u64,
5859        cx: &mut ModelContext<Self>,
5860    ) -> Task<Result<ModelHandle<Buffer>>> {
5861        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5862        cx.spawn(|this, mut cx| async move {
5863            let buffer = loop {
5864                let buffer = this.read_with(&cx, |this, cx| {
5865                    this.opened_buffers
5866                        .get(&id)
5867                        .and_then(|buffer| buffer.upgrade(cx))
5868                });
5869                if let Some(buffer) = buffer {
5870                    break buffer;
5871                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5872                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5873                }
5874
5875                opened_buffer_rx
5876                    .next()
5877                    .await
5878                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5879            };
5880            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5881            Ok(buffer)
5882        })
5883    }
5884
5885    fn deserialize_symbol(
5886        &self,
5887        serialized_symbol: proto::Symbol,
5888    ) -> impl Future<Output = Result<Symbol>> {
5889        let languages = self.languages.clone();
5890        async move {
5891            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5892            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5893            let start = serialized_symbol
5894                .start
5895                .ok_or_else(|| anyhow!("invalid start"))?;
5896            let end = serialized_symbol
5897                .end
5898                .ok_or_else(|| anyhow!("invalid end"))?;
5899            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5900            let path = ProjectPath {
5901                worktree_id,
5902                path: PathBuf::from(serialized_symbol.path).into(),
5903            };
5904            let language = languages.select_language(&path.path);
5905            Ok(Symbol {
5906                language_server_name: LanguageServerName(
5907                    serialized_symbol.language_server_name.into(),
5908                ),
5909                source_worktree_id,
5910                path,
5911                label: {
5912                    match language {
5913                        Some(language) => {
5914                            language
5915                                .label_for_symbol(&serialized_symbol.name, kind)
5916                                .await
5917                        }
5918                        None => None,
5919                    }
5920                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5921                },
5922
5923                name: serialized_symbol.name,
5924                range: PointUtf16::new(start.row, start.column)
5925                    ..PointUtf16::new(end.row, end.column),
5926                kind,
5927                signature: serialized_symbol
5928                    .signature
5929                    .try_into()
5930                    .map_err(|_| anyhow!("invalid signature"))?,
5931            })
5932        }
5933    }
5934
5935    async fn handle_buffer_saved(
5936        this: ModelHandle<Self>,
5937        envelope: TypedEnvelope<proto::BufferSaved>,
5938        _: Arc<Client>,
5939        mut cx: AsyncAppContext,
5940    ) -> Result<()> {
5941        let version = deserialize_version(envelope.payload.version);
5942        let mtime = envelope
5943            .payload
5944            .mtime
5945            .ok_or_else(|| anyhow!("missing mtime"))?
5946            .into();
5947
5948        this.update(&mut cx, |this, cx| {
5949            let buffer = this
5950                .opened_buffers
5951                .get(&envelope.payload.buffer_id)
5952                .and_then(|buffer| buffer.upgrade(cx));
5953            if let Some(buffer) = buffer {
5954                buffer.update(cx, |buffer, cx| {
5955                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5956                });
5957            }
5958            Ok(())
5959        })
5960    }
5961
5962    async fn handle_buffer_reloaded(
5963        this: ModelHandle<Self>,
5964        envelope: TypedEnvelope<proto::BufferReloaded>,
5965        _: Arc<Client>,
5966        mut cx: AsyncAppContext,
5967    ) -> Result<()> {
5968        let payload = envelope.payload;
5969        let version = deserialize_version(payload.version);
5970        let line_ending = deserialize_line_ending(
5971            proto::LineEnding::from_i32(payload.line_ending)
5972                .ok_or_else(|| anyhow!("missing line ending"))?,
5973        );
5974        let mtime = payload
5975            .mtime
5976            .ok_or_else(|| anyhow!("missing mtime"))?
5977            .into();
5978        this.update(&mut cx, |this, cx| {
5979            let buffer = this
5980                .opened_buffers
5981                .get(&payload.buffer_id)
5982                .and_then(|buffer| buffer.upgrade(cx));
5983            if let Some(buffer) = buffer {
5984                buffer.update(cx, |buffer, cx| {
5985                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5986                });
5987            }
5988            Ok(())
5989        })
5990    }
5991
5992    #[allow(clippy::type_complexity)]
5993    fn edits_from_lsp(
5994        &mut self,
5995        buffer: &ModelHandle<Buffer>,
5996        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5997        version: Option<i32>,
5998        cx: &mut ModelContext<Self>,
5999    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6000        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
6001        cx.background().spawn(async move {
6002            let snapshot = snapshot?;
6003            let mut lsp_edits = lsp_edits
6004                .into_iter()
6005                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6006                .collect::<Vec<_>>();
6007            lsp_edits.sort_by_key(|(range, _)| range.start);
6008
6009            let mut lsp_edits = lsp_edits.into_iter().peekable();
6010            let mut edits = Vec::new();
6011            while let Some((mut range, mut new_text)) = lsp_edits.next() {
6012                // Clip invalid ranges provided by the language server.
6013                range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
6014                range.end = snapshot.clip_point_utf16(range.end, Bias::Left);
6015
6016                // Combine any LSP edits that are adjacent.
6017                //
6018                // Also, combine LSP edits that are separated from each other by only
6019                // a newline. This is important because for some code actions,
6020                // Rust-analyzer rewrites the entire buffer via a series of edits that
6021                // are separated by unchanged newline characters.
6022                //
6023                // In order for the diffing logic below to work properly, any edits that
6024                // cancel each other out must be combined into one.
6025                while let Some((next_range, next_text)) = lsp_edits.peek() {
6026                    if next_range.start > range.end {
6027                        if next_range.start.row > range.end.row + 1
6028                            || next_range.start.column > 0
6029                            || snapshot.clip_point_utf16(
6030                                PointUtf16::new(range.end.row, u32::MAX),
6031                                Bias::Left,
6032                            ) > range.end
6033                        {
6034                            break;
6035                        }
6036                        new_text.push('\n');
6037                    }
6038                    range.end = next_range.end;
6039                    new_text.push_str(next_text);
6040                    lsp_edits.next();
6041                }
6042
6043                // For multiline edits, perform a diff of the old and new text so that
6044                // we can identify the changes more precisely, preserving the locations
6045                // of any anchors positioned in the unchanged regions.
6046                if range.end.row > range.start.row {
6047                    let mut offset = range.start.to_offset(&snapshot);
6048                    let old_text = snapshot.text_for_range(range).collect::<String>();
6049
6050                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6051                    let mut moved_since_edit = true;
6052                    for change in diff.iter_all_changes() {
6053                        let tag = change.tag();
6054                        let value = change.value();
6055                        match tag {
6056                            ChangeTag::Equal => {
6057                                offset += value.len();
6058                                moved_since_edit = true;
6059                            }
6060                            ChangeTag::Delete => {
6061                                let start = snapshot.anchor_after(offset);
6062                                let end = snapshot.anchor_before(offset + value.len());
6063                                if moved_since_edit {
6064                                    edits.push((start..end, String::new()));
6065                                } else {
6066                                    edits.last_mut().unwrap().0.end = end;
6067                                }
6068                                offset += value.len();
6069                                moved_since_edit = false;
6070                            }
6071                            ChangeTag::Insert => {
6072                                if moved_since_edit {
6073                                    let anchor = snapshot.anchor_after(offset);
6074                                    edits.push((anchor..anchor, value.to_string()));
6075                                } else {
6076                                    edits.last_mut().unwrap().1.push_str(value);
6077                                }
6078                                moved_since_edit = false;
6079                            }
6080                        }
6081                    }
6082                } else if range.end == range.start {
6083                    let anchor = snapshot.anchor_after(range.start);
6084                    edits.push((anchor..anchor, new_text));
6085                } else {
6086                    let edit_start = snapshot.anchor_after(range.start);
6087                    let edit_end = snapshot.anchor_before(range.end);
6088                    edits.push((edit_start..edit_end, new_text));
6089                }
6090            }
6091
6092            Ok(edits)
6093        })
6094    }
6095
6096    fn buffer_snapshot_for_lsp_version(
6097        &mut self,
6098        buffer: &ModelHandle<Buffer>,
6099        version: Option<i32>,
6100        cx: &AppContext,
6101    ) -> Result<TextBufferSnapshot> {
6102        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6103
6104        if let Some(version) = version {
6105            let buffer_id = buffer.read(cx).remote_id();
6106            let snapshots = self
6107                .buffer_snapshots
6108                .get_mut(&buffer_id)
6109                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6110            let mut found_snapshot = None;
6111            snapshots.retain(|(snapshot_version, snapshot)| {
6112                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
6113                    false
6114                } else {
6115                    if *snapshot_version == version {
6116                        found_snapshot = Some(snapshot.clone());
6117                    }
6118                    true
6119                }
6120            });
6121
6122            found_snapshot.ok_or_else(|| {
6123                anyhow!(
6124                    "snapshot not found for buffer {} at version {}",
6125                    buffer_id,
6126                    version
6127                )
6128            })
6129        } else {
6130            Ok((buffer.read(cx)).text_snapshot())
6131        }
6132    }
6133
6134    fn language_server_for_buffer(
6135        &self,
6136        buffer: &Buffer,
6137        cx: &AppContext,
6138    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6139        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6140            let name = language.lsp_adapter()?.name.clone();
6141            let worktree_id = file.worktree_id(cx);
6142            let key = (worktree_id, name);
6143
6144            if let Some(server_id) = self.language_server_ids.get(&key) {
6145                if let Some(LanguageServerState::Running {
6146                    adapter, server, ..
6147                }) = self.language_servers.get(server_id)
6148                {
6149                    return Some((adapter, server));
6150                }
6151            }
6152        }
6153
6154        None
6155    }
6156}
6157
6158impl ProjectStore {
6159    pub fn new(db: Arc<Db>) -> Self {
6160        Self {
6161            db,
6162            projects: Default::default(),
6163        }
6164    }
6165
6166    pub fn projects<'a>(
6167        &'a self,
6168        cx: &'a AppContext,
6169    ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
6170        self.projects
6171            .iter()
6172            .filter_map(|project| project.upgrade(cx))
6173    }
6174
6175    fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
6176        if let Err(ix) = self
6177            .projects
6178            .binary_search_by_key(&project.id(), WeakModelHandle::id)
6179        {
6180            self.projects.insert(ix, project);
6181        }
6182        cx.notify();
6183    }
6184
6185    fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
6186        let mut did_change = false;
6187        self.projects.retain(|project| {
6188            if project.is_upgradable(cx) {
6189                true
6190            } else {
6191                did_change = true;
6192                false
6193            }
6194        });
6195        if did_change {
6196            cx.notify();
6197        }
6198    }
6199}
6200
6201impl WorktreeHandle {
6202    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6203        match self {
6204            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6205            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6206        }
6207    }
6208}
6209
6210impl OpenBuffer {
6211    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6212        match self {
6213            OpenBuffer::Strong(handle) => Some(handle.clone()),
6214            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6215            OpenBuffer::Operations(_) => None,
6216        }
6217    }
6218}
6219
6220pub struct PathMatchCandidateSet {
6221    pub snapshot: Snapshot,
6222    pub include_ignored: bool,
6223    pub include_root_name: bool,
6224}
6225
6226impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6227    type Candidates = PathMatchCandidateSetIter<'a>;
6228
6229    fn id(&self) -> usize {
6230        self.snapshot.id().to_usize()
6231    }
6232
6233    fn len(&self) -> usize {
6234        if self.include_ignored {
6235            self.snapshot.file_count()
6236        } else {
6237            self.snapshot.visible_file_count()
6238        }
6239    }
6240
6241    fn prefix(&self) -> Arc<str> {
6242        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6243            self.snapshot.root_name().into()
6244        } else if self.include_root_name {
6245            format!("{}/", self.snapshot.root_name()).into()
6246        } else {
6247            "".into()
6248        }
6249    }
6250
6251    fn candidates(&'a self, start: usize) -> Self::Candidates {
6252        PathMatchCandidateSetIter {
6253            traversal: self.snapshot.files(self.include_ignored, start),
6254        }
6255    }
6256}
6257
6258pub struct PathMatchCandidateSetIter<'a> {
6259    traversal: Traversal<'a>,
6260}
6261
6262impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6263    type Item = fuzzy::PathMatchCandidate<'a>;
6264
6265    fn next(&mut self) -> Option<Self::Item> {
6266        self.traversal.next().map(|entry| {
6267            if let EntryKind::File(char_bag) = entry.kind {
6268                fuzzy::PathMatchCandidate {
6269                    path: &entry.path,
6270                    char_bag,
6271                }
6272            } else {
6273                unreachable!()
6274            }
6275        })
6276    }
6277}
6278
6279impl Entity for ProjectStore {
6280    type Event = ();
6281}
6282
6283impl Entity for Project {
6284    type Event = Event;
6285
6286    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
6287        self.project_store.update(cx, ProjectStore::prune_projects);
6288
6289        match &self.client_state {
6290            ProjectClientState::Local { remote_id_rx, .. } => {
6291                if let Some(project_id) = *remote_id_rx.borrow() {
6292                    self.client
6293                        .send(proto::UnregisterProject { project_id })
6294                        .log_err();
6295                }
6296            }
6297            ProjectClientState::Remote { remote_id, .. } => {
6298                self.client
6299                    .send(proto::LeaveProject {
6300                        project_id: *remote_id,
6301                    })
6302                    .log_err();
6303            }
6304        }
6305    }
6306
6307    fn app_will_quit(
6308        &mut self,
6309        _: &mut MutableAppContext,
6310    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6311        let shutdown_futures = self
6312            .language_servers
6313            .drain()
6314            .map(|(_, server_state)| async {
6315                match server_state {
6316                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6317                    LanguageServerState::Starting(starting_server) => {
6318                        starting_server.await?.shutdown()?.await
6319                    }
6320                }
6321            })
6322            .collect::<Vec<_>>();
6323
6324        Some(
6325            async move {
6326                futures::future::join_all(shutdown_futures).await;
6327            }
6328            .boxed(),
6329        )
6330    }
6331}
6332
6333impl Collaborator {
6334    fn from_proto(
6335        message: proto::Collaborator,
6336        user_store: &ModelHandle<UserStore>,
6337        cx: &mut AsyncAppContext,
6338    ) -> impl Future<Output = Result<Self>> {
6339        let user = user_store.update(cx, |user_store, cx| {
6340            user_store.fetch_user(message.user_id, cx)
6341        });
6342
6343        async move {
6344            Ok(Self {
6345                peer_id: PeerId(message.peer_id),
6346                user: user.await?,
6347                replica_id: message.replica_id as ReplicaId,
6348            })
6349        }
6350    }
6351}
6352
6353impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6354    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6355        Self {
6356            worktree_id,
6357            path: path.as_ref().into(),
6358        }
6359    }
6360}
6361
6362impl From<lsp::CreateFileOptions> for fs::CreateOptions {
6363    fn from(options: lsp::CreateFileOptions) -> Self {
6364        Self {
6365            overwrite: options.overwrite.unwrap_or(false),
6366            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6367        }
6368    }
6369}
6370
6371impl From<lsp::RenameFileOptions> for fs::RenameOptions {
6372    fn from(options: lsp::RenameFileOptions) -> Self {
6373        Self {
6374            overwrite: options.overwrite.unwrap_or(false),
6375            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6376        }
6377    }
6378}
6379
6380impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6381    fn from(options: lsp::DeleteFileOptions) -> Self {
6382        Self {
6383            recursive: options.recursive.unwrap_or(false),
6384            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6385        }
6386    }
6387}
6388
6389fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6390    proto::Symbol {
6391        language_server_name: symbol.language_server_name.0.to_string(),
6392        source_worktree_id: symbol.source_worktree_id.to_proto(),
6393        worktree_id: symbol.path.worktree_id.to_proto(),
6394        path: symbol.path.path.to_string_lossy().to_string(),
6395        name: symbol.name.clone(),
6396        kind: unsafe { mem::transmute(symbol.kind) },
6397        start: Some(proto::Point {
6398            row: symbol.range.start.row,
6399            column: symbol.range.start.column,
6400        }),
6401        end: Some(proto::Point {
6402            row: symbol.range.end.row,
6403            column: symbol.range.end.column,
6404        }),
6405        signature: symbol.signature.to_vec(),
6406    }
6407}
6408
6409fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6410    let mut path_components = path.components();
6411    let mut base_components = base.components();
6412    let mut components: Vec<Component> = Vec::new();
6413    loop {
6414        match (path_components.next(), base_components.next()) {
6415            (None, None) => break,
6416            (Some(a), None) => {
6417                components.push(a);
6418                components.extend(path_components.by_ref());
6419                break;
6420            }
6421            (None, _) => components.push(Component::ParentDir),
6422            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6423            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6424            (Some(a), Some(_)) => {
6425                components.push(Component::ParentDir);
6426                for _ in base_components {
6427                    components.push(Component::ParentDir);
6428                }
6429                components.push(a);
6430                components.extend(path_components.by_ref());
6431                break;
6432            }
6433        }
6434    }
6435    components.iter().map(|c| c.as_os_str()).collect()
6436}
6437
6438impl Item for Buffer {
6439    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6440        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6441    }
6442}