project.rs

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