project.rs

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