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