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