project.rs

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