project.rs

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