project.rs

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