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, split_operations,
  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    supplementary_language_servers:
 112        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
 113    language_servers: HashMap<LanguageServerId, LanguageServerState>,
 114    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
 115    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
 116    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
 117    client: Arc<client::Client>,
 118    next_entry_id: Arc<AtomicUsize>,
 119    join_project_response_message_id: u32,
 120    next_diagnostic_group_id: usize,
 121    user_store: ModelHandle<UserStore>,
 122    fs: Arc<dyn Fs>,
 123    client_state: Option<ProjectClientState>,
 124    collaborators: HashMap<proto::PeerId, Collaborator>,
 125    client_subscriptions: Vec<client::Subscription>,
 126    _subscriptions: Vec<gpui::Subscription>,
 127    next_buffer_id: u64,
 128    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 129    shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
 130    #[allow(clippy::type_complexity)]
 131    loading_buffers_by_path: HashMap<
 132        ProjectPath,
 133        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 134    >,
 135    #[allow(clippy::type_complexity)]
 136    loading_local_worktrees:
 137        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 138    opened_buffers: HashMap<u64, OpenBuffer>,
 139    local_buffer_ids_by_path: HashMap<ProjectPath, u64>,
 140    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, u64>,
 141    /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
 142    /// Used for re-issuing buffer requests when peers temporarily disconnect
 143    incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
 144    buffer_snapshots: HashMap<u64, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
 145    buffers_being_formatted: HashSet<u64>,
 146    buffers_needing_diff: HashSet<WeakModelHandle<Buffer>>,
 147    git_diff_debouncer: DelayedDebounced,
 148    nonce: u128,
 149    _maintain_buffer_languages: Task<()>,
 150    _maintain_workspace_config: Task<()>,
 151    terminals: Terminals,
 152    copilot_lsp_subscription: Option<gpui::Subscription>,
 153    copilot_log_subscription: Option<lsp::Subscription>,
 154    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
 155}
 156
 157struct DelayedDebounced {
 158    task: Option<Task<()>>,
 159    cancel_channel: Option<oneshot::Sender<()>>,
 160}
 161
 162enum LanguageServerToQuery {
 163    Primary,
 164    Other(LanguageServerId),
 165}
 166
 167impl DelayedDebounced {
 168    fn new() -> DelayedDebounced {
 169        DelayedDebounced {
 170            task: None,
 171            cancel_channel: None,
 172        }
 173    }
 174
 175    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ModelContext<Project>, func: F)
 176    where
 177        F: 'static + FnOnce(&mut Project, &mut ModelContext<Project>) -> Task<()>,
 178    {
 179        if let Some(channel) = self.cancel_channel.take() {
 180            _ = channel.send(());
 181        }
 182
 183        let (sender, mut receiver) = oneshot::channel::<()>();
 184        self.cancel_channel = Some(sender);
 185
 186        let previous_task = self.task.take();
 187        self.task = Some(cx.spawn(|workspace, mut cx| async move {
 188            let mut timer = cx.background().timer(delay).fuse();
 189            if let Some(previous_task) = previous_task {
 190                previous_task.await;
 191            }
 192
 193            futures::select_biased! {
 194                _ = receiver => return,
 195                    _ = timer => {}
 196            }
 197
 198            workspace
 199                .update(&mut cx, |workspace, cx| (func)(workspace, cx))
 200                .await;
 201        }));
 202    }
 203}
 204
 205struct LspBufferSnapshot {
 206    version: i32,
 207    snapshot: TextBufferSnapshot,
 208}
 209
 210/// Message ordered with respect to buffer operations
 211enum BufferOrderedMessage {
 212    Operation {
 213        buffer_id: u64,
 214        operation: proto::Operation,
 215    },
 216    LanguageServerUpdate {
 217        language_server_id: LanguageServerId,
 218        message: proto::update_language_server::Variant,
 219    },
 220    Resync,
 221}
 222
 223enum LocalProjectUpdate {
 224    WorktreesChanged,
 225    CreateBufferForPeer {
 226        peer_id: proto::PeerId,
 227        buffer_id: u64,
 228    },
 229}
 230
 231enum OpenBuffer {
 232    Strong(ModelHandle<Buffer>),
 233    Weak(WeakModelHandle<Buffer>),
 234    Operations(Vec<Operation>),
 235}
 236
 237#[derive(Clone)]
 238enum WorktreeHandle {
 239    Strong(ModelHandle<Worktree>),
 240    Weak(WeakModelHandle<Worktree>),
 241}
 242
 243enum ProjectClientState {
 244    Local {
 245        remote_id: u64,
 246        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
 247        _send_updates: Task<()>,
 248    },
 249    Remote {
 250        sharing_has_stopped: bool,
 251        remote_id: u64,
 252        replica_id: ReplicaId,
 253    },
 254}
 255
 256#[derive(Clone, Debug)]
 257pub struct Collaborator {
 258    pub peer_id: proto::PeerId,
 259    pub replica_id: ReplicaId,
 260    pub user_id: UserId,
 261}
 262
 263#[derive(Clone, Debug, PartialEq)]
 264pub enum Event {
 265    LanguageServerAdded(LanguageServerId),
 266    LanguageServerRemoved(LanguageServerId),
 267    LanguageServerLog(LanguageServerId, String),
 268    Notification(String),
 269    ActiveEntryChanged(Option<ProjectEntryId>),
 270    ActivateProjectPanel,
 271    WorktreeAdded,
 272    WorktreeRemoved(WorktreeId),
 273    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 274    DiskBasedDiagnosticsStarted {
 275        language_server_id: LanguageServerId,
 276    },
 277    DiskBasedDiagnosticsFinished {
 278        language_server_id: LanguageServerId,
 279    },
 280    DiagnosticsUpdated {
 281        path: ProjectPath,
 282        language_server_id: LanguageServerId,
 283    },
 284    RemoteIdChanged(Option<u64>),
 285    DisconnectedFromHost,
 286    Closed,
 287    DeletedEntry(ProjectEntryId),
 288    CollaboratorUpdated {
 289        old_peer_id: proto::PeerId,
 290        new_peer_id: proto::PeerId,
 291    },
 292    CollaboratorJoined(proto::PeerId),
 293    CollaboratorLeft(proto::PeerId),
 294    RefreshInlayHints,
 295}
 296
 297pub enum LanguageServerState {
 298    Starting(Task<Option<Arc<LanguageServer>>>),
 299
 300    Running {
 301        language: Arc<Language>,
 302        adapter: Arc<CachedLspAdapter>,
 303        server: Arc<LanguageServer>,
 304        watched_paths: HashMap<WorktreeId, GlobSet>,
 305        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 306    },
 307}
 308
 309#[derive(Serialize)]
 310pub struct LanguageServerStatus {
 311    pub name: String,
 312    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 313    pub has_pending_diagnostic_updates: bool,
 314    progress_tokens: HashSet<String>,
 315}
 316
 317#[derive(Clone, Debug, Serialize)]
 318pub struct LanguageServerProgress {
 319    pub message: Option<String>,
 320    pub percentage: Option<usize>,
 321    #[serde(skip_serializing)]
 322    pub last_update_at: Instant,
 323}
 324
 325#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 326pub struct ProjectPath {
 327    pub worktree_id: WorktreeId,
 328    pub path: Arc<Path>,
 329}
 330
 331#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 332pub struct DiagnosticSummary {
 333    pub error_count: usize,
 334    pub warning_count: usize,
 335}
 336
 337#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 338pub struct Location {
 339    pub buffer: ModelHandle<Buffer>,
 340    pub range: Range<language::Anchor>,
 341}
 342
 343#[derive(Debug, Clone, PartialEq, Eq)]
 344pub struct InlayHint {
 345    pub position: language::Anchor,
 346    pub label: InlayHintLabel,
 347    pub kind: Option<InlayHintKind>,
 348    pub padding_left: bool,
 349    pub padding_right: bool,
 350    pub tooltip: Option<InlayHintTooltip>,
 351    pub resolve_state: ResolveState,
 352}
 353
 354#[derive(Debug, Clone, PartialEq, Eq)]
 355pub enum ResolveState {
 356    Resolved,
 357    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 358    Resolving,
 359}
 360
 361impl InlayHint {
 362    pub fn text(&self) -> String {
 363        match &self.label {
 364            InlayHintLabel::String(s) => s.to_owned(),
 365            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 366        }
 367    }
 368}
 369
 370#[derive(Debug, Clone, PartialEq, Eq)]
 371pub enum InlayHintLabel {
 372    String(String),
 373    LabelParts(Vec<InlayHintLabelPart>),
 374}
 375
 376#[derive(Debug, Clone, PartialEq, Eq)]
 377pub struct InlayHintLabelPart {
 378    pub value: String,
 379    pub tooltip: Option<InlayHintLabelPartTooltip>,
 380    pub location: Option<(LanguageServerId, lsp::Location)>,
 381}
 382
 383#[derive(Debug, Clone, PartialEq, Eq)]
 384pub enum InlayHintTooltip {
 385    String(String),
 386    MarkupContent(MarkupContent),
 387}
 388
 389#[derive(Debug, Clone, PartialEq, Eq)]
 390pub enum InlayHintLabelPartTooltip {
 391    String(String),
 392    MarkupContent(MarkupContent),
 393}
 394
 395#[derive(Debug, Clone, PartialEq, Eq)]
 396pub struct MarkupContent {
 397    pub kind: HoverBlockKind,
 398    pub value: String,
 399}
 400
 401#[derive(Debug, Clone)]
 402pub struct LocationLink {
 403    pub origin: Option<Location>,
 404    pub target: Location,
 405}
 406
 407#[derive(Debug)]
 408pub struct DocumentHighlight {
 409    pub range: Range<language::Anchor>,
 410    pub kind: DocumentHighlightKind,
 411}
 412
 413#[derive(Clone, Debug)]
 414pub struct Symbol {
 415    pub language_server_name: LanguageServerName,
 416    pub source_worktree_id: WorktreeId,
 417    pub path: ProjectPath,
 418    pub label: CodeLabel,
 419    pub name: String,
 420    pub kind: lsp::SymbolKind,
 421    pub range: Range<Unclipped<PointUtf16>>,
 422    pub signature: [u8; 32],
 423}
 424
 425#[derive(Clone, Debug, PartialEq)]
 426pub struct HoverBlock {
 427    pub text: String,
 428    pub kind: HoverBlockKind,
 429}
 430
 431#[derive(Clone, Debug, PartialEq, Eq)]
 432pub enum HoverBlockKind {
 433    PlainText,
 434    Markdown,
 435    Code { language: String },
 436}
 437
 438#[derive(Debug)]
 439pub struct Hover {
 440    pub contents: Vec<HoverBlock>,
 441    pub range: Option<Range<language::Anchor>>,
 442    pub language: Option<Arc<Language>>,
 443}
 444
 445impl Hover {
 446    pub fn is_empty(&self) -> bool {
 447        self.contents.iter().all(|block| block.text.is_empty())
 448    }
 449}
 450
 451#[derive(Default)]
 452pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 453
 454impl DiagnosticSummary {
 455    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 456        let mut this = Self {
 457            error_count: 0,
 458            warning_count: 0,
 459        };
 460
 461        for entry in diagnostics {
 462            if entry.diagnostic.is_primary {
 463                match entry.diagnostic.severity {
 464                    DiagnosticSeverity::ERROR => this.error_count += 1,
 465                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 466                    _ => {}
 467                }
 468            }
 469        }
 470
 471        this
 472    }
 473
 474    pub fn is_empty(&self) -> bool {
 475        self.error_count == 0 && self.warning_count == 0
 476    }
 477
 478    pub fn to_proto(
 479        &self,
 480        language_server_id: LanguageServerId,
 481        path: &Path,
 482    ) -> proto::DiagnosticSummary {
 483        proto::DiagnosticSummary {
 484            path: path.to_string_lossy().to_string(),
 485            language_server_id: language_server_id.0 as u64,
 486            error_count: self.error_count as u32,
 487            warning_count: self.warning_count as u32,
 488        }
 489    }
 490}
 491
 492#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 493pub struct ProjectEntryId(usize);
 494
 495impl ProjectEntryId {
 496    pub const MAX: Self = Self(usize::MAX);
 497
 498    pub fn new(counter: &AtomicUsize) -> Self {
 499        Self(counter.fetch_add(1, SeqCst))
 500    }
 501
 502    pub fn from_proto(id: u64) -> Self {
 503        Self(id as usize)
 504    }
 505
 506    pub fn to_proto(&self) -> u64 {
 507        self.0 as u64
 508    }
 509
 510    pub fn to_usize(&self) -> usize {
 511        self.0
 512    }
 513}
 514
 515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 516pub enum FormatTrigger {
 517    Save,
 518    Manual,
 519}
 520
 521struct ProjectLspAdapterDelegate {
 522    project: ModelHandle<Project>,
 523    http_client: Arc<dyn HttpClient>,
 524}
 525
 526impl FormatTrigger {
 527    fn from_proto(value: i32) -> FormatTrigger {
 528        match value {
 529            0 => FormatTrigger::Save,
 530            1 => FormatTrigger::Manual,
 531            _ => FormatTrigger::Save,
 532        }
 533    }
 534}
 535#[derive(Clone, Debug, PartialEq)]
 536enum SearchMatchCandidate {
 537    OpenBuffer {
 538        buffer: ModelHandle<Buffer>,
 539        // This might be an unnamed file without representation on filesystem
 540        path: Option<Arc<Path>>,
 541    },
 542    Path {
 543        worktree_id: WorktreeId,
 544        path: Arc<Path>,
 545    },
 546}
 547
 548type SearchMatchCandidateIndex = usize;
 549impl SearchMatchCandidate {
 550    fn path(&self) -> Option<Arc<Path>> {
 551        match self {
 552            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
 553            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
 554        }
 555    }
 556}
 557
 558impl Project {
 559    pub fn init_settings(cx: &mut AppContext) {
 560        settings::register::<ProjectSettings>(cx);
 561    }
 562
 563    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 564        Self::init_settings(cx);
 565
 566        client.add_model_message_handler(Self::handle_add_collaborator);
 567        client.add_model_message_handler(Self::handle_update_project_collaborator);
 568        client.add_model_message_handler(Self::handle_remove_collaborator);
 569        client.add_model_message_handler(Self::handle_buffer_reloaded);
 570        client.add_model_message_handler(Self::handle_buffer_saved);
 571        client.add_model_message_handler(Self::handle_start_language_server);
 572        client.add_model_message_handler(Self::handle_update_language_server);
 573        client.add_model_message_handler(Self::handle_update_project);
 574        client.add_model_message_handler(Self::handle_unshare_project);
 575        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 576        client.add_model_message_handler(Self::handle_update_buffer_file);
 577        client.add_model_request_handler(Self::handle_update_buffer);
 578        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 579        client.add_model_message_handler(Self::handle_update_worktree);
 580        client.add_model_message_handler(Self::handle_update_worktree_settings);
 581        client.add_model_request_handler(Self::handle_create_project_entry);
 582        client.add_model_request_handler(Self::handle_rename_project_entry);
 583        client.add_model_request_handler(Self::handle_copy_project_entry);
 584        client.add_model_request_handler(Self::handle_delete_project_entry);
 585        client.add_model_request_handler(Self::handle_expand_project_entry);
 586        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 587        client.add_model_request_handler(Self::handle_apply_code_action);
 588        client.add_model_request_handler(Self::handle_on_type_formatting);
 589        client.add_model_request_handler(Self::handle_inlay_hints);
 590        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
 591        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
 592        client.add_model_request_handler(Self::handle_reload_buffers);
 593        client.add_model_request_handler(Self::handle_synchronize_buffers);
 594        client.add_model_request_handler(Self::handle_format_buffers);
 595        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
 596        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
 597        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 598        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 599        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 600        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 601        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 602        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 603        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 604        client.add_model_request_handler(Self::handle_search_project);
 605        client.add_model_request_handler(Self::handle_get_project_symbols);
 606        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 607        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 608        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 609        client.add_model_request_handler(Self::handle_save_buffer);
 610        client.add_model_message_handler(Self::handle_update_diff_base);
 611    }
 612
 613    pub fn local(
 614        client: Arc<Client>,
 615        user_store: ModelHandle<UserStore>,
 616        languages: Arc<LanguageRegistry>,
 617        fs: Arc<dyn Fs>,
 618        cx: &mut AppContext,
 619    ) -> ModelHandle<Self> {
 620        cx.add_model(|cx: &mut ModelContext<Self>| {
 621            let (tx, rx) = mpsc::unbounded();
 622            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 623                .detach();
 624            let copilot_lsp_subscription =
 625                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 626            Self {
 627                worktrees: Default::default(),
 628                buffer_ordered_messages_tx: tx,
 629                collaborators: Default::default(),
 630                next_buffer_id: 0,
 631                opened_buffers: Default::default(),
 632                shared_buffers: Default::default(),
 633                incomplete_remote_buffers: Default::default(),
 634                loading_buffers_by_path: Default::default(),
 635                loading_local_worktrees: Default::default(),
 636                local_buffer_ids_by_path: Default::default(),
 637                local_buffer_ids_by_entry_id: Default::default(),
 638                buffer_snapshots: Default::default(),
 639                join_project_response_message_id: 0,
 640                client_state: None,
 641                opened_buffer: watch::channel(),
 642                client_subscriptions: Vec::new(),
 643                _subscriptions: vec![
 644                    cx.observe_global::<SettingsStore, _>(Self::on_settings_changed)
 645                ],
 646                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 647                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 648                active_entry: None,
 649                languages,
 650                client,
 651                user_store,
 652                fs,
 653                next_entry_id: Default::default(),
 654                next_diagnostic_group_id: Default::default(),
 655                supplementary_language_servers: HashMap::default(),
 656                language_servers: Default::default(),
 657                language_server_ids: Default::default(),
 658                language_server_statuses: Default::default(),
 659                last_workspace_edits_by_language_server: Default::default(),
 660                buffers_being_formatted: Default::default(),
 661                buffers_needing_diff: Default::default(),
 662                git_diff_debouncer: DelayedDebounced::new(),
 663                nonce: StdRng::from_entropy().gen(),
 664                terminals: Terminals {
 665                    local_handles: Vec::new(),
 666                },
 667                copilot_lsp_subscription,
 668                copilot_log_subscription: None,
 669                current_lsp_settings: settings::get::<ProjectSettings>(cx).lsp.clone(),
 670            }
 671        })
 672    }
 673
 674    pub async fn remote(
 675        remote_id: u64,
 676        client: Arc<Client>,
 677        user_store: ModelHandle<UserStore>,
 678        languages: Arc<LanguageRegistry>,
 679        fs: Arc<dyn Fs>,
 680        mut cx: AsyncAppContext,
 681    ) -> Result<ModelHandle<Self>> {
 682        client.authenticate_and_connect(true, &cx).await?;
 683
 684        let subscription = client.subscribe_to_entity(remote_id)?;
 685        let response = client
 686            .request_envelope(proto::JoinProject {
 687                project_id: remote_id,
 688            })
 689            .await?;
 690        let this = cx.add_model(|cx| {
 691            let replica_id = response.payload.replica_id as ReplicaId;
 692
 693            let mut worktrees = Vec::new();
 694            for worktree in response.payload.worktrees {
 695                let worktree = cx.update(|cx| {
 696                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
 697                });
 698                worktrees.push(worktree);
 699            }
 700
 701            let (tx, rx) = mpsc::unbounded();
 702            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 703                .detach();
 704            let copilot_lsp_subscription =
 705                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 706            let mut this = Self {
 707                worktrees: Vec::new(),
 708                buffer_ordered_messages_tx: tx,
 709                loading_buffers_by_path: Default::default(),
 710                next_buffer_id: 0,
 711                opened_buffer: watch::channel(),
 712                shared_buffers: Default::default(),
 713                incomplete_remote_buffers: Default::default(),
 714                loading_local_worktrees: Default::default(),
 715                local_buffer_ids_by_path: Default::default(),
 716                local_buffer_ids_by_entry_id: Default::default(),
 717                active_entry: None,
 718                collaborators: Default::default(),
 719                join_project_response_message_id: response.message_id,
 720                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 721                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 722                languages,
 723                user_store: user_store.clone(),
 724                fs,
 725                next_entry_id: Default::default(),
 726                next_diagnostic_group_id: Default::default(),
 727                client_subscriptions: Default::default(),
 728                _subscriptions: Default::default(),
 729                client: client.clone(),
 730                client_state: Some(ProjectClientState::Remote {
 731                    sharing_has_stopped: false,
 732                    remote_id,
 733                    replica_id,
 734                }),
 735                supplementary_language_servers: HashMap::default(),
 736                language_servers: Default::default(),
 737                language_server_ids: Default::default(),
 738                language_server_statuses: response
 739                    .payload
 740                    .language_servers
 741                    .into_iter()
 742                    .map(|server| {
 743                        (
 744                            LanguageServerId(server.id as usize),
 745                            LanguageServerStatus {
 746                                name: server.name,
 747                                pending_work: Default::default(),
 748                                has_pending_diagnostic_updates: false,
 749                                progress_tokens: Default::default(),
 750                            },
 751                        )
 752                    })
 753                    .collect(),
 754                last_workspace_edits_by_language_server: Default::default(),
 755                opened_buffers: Default::default(),
 756                buffers_being_formatted: Default::default(),
 757                buffers_needing_diff: Default::default(),
 758                git_diff_debouncer: DelayedDebounced::new(),
 759                buffer_snapshots: Default::default(),
 760                nonce: StdRng::from_entropy().gen(),
 761                terminals: Terminals {
 762                    local_handles: Vec::new(),
 763                },
 764                copilot_lsp_subscription,
 765                copilot_log_subscription: None,
 766                current_lsp_settings: settings::get::<ProjectSettings>(cx).lsp.clone(),
 767            };
 768            for worktree in worktrees {
 769                let _ = this.add_worktree(&worktree, cx);
 770            }
 771            this
 772        });
 773        let subscription = subscription.set_model(&this, &mut cx);
 774
 775        let user_ids = response
 776            .payload
 777            .collaborators
 778            .iter()
 779            .map(|peer| peer.user_id)
 780            .collect();
 781        user_store
 782            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 783            .await?;
 784
 785        this.update(&mut cx, |this, cx| {
 786            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
 787            this.client_subscriptions.push(subscription);
 788            anyhow::Ok(())
 789        })?;
 790
 791        Ok(this)
 792    }
 793
 794    #[cfg(any(test, feature = "test-support"))]
 795    pub async fn test(
 796        fs: Arc<dyn Fs>,
 797        root_paths: impl IntoIterator<Item = &Path>,
 798        cx: &mut gpui::TestAppContext,
 799    ) -> ModelHandle<Project> {
 800        let mut languages = LanguageRegistry::test();
 801        languages.set_executor(cx.background());
 802        let http_client = util::http::FakeHttpClient::with_404_response();
 803        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 804        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 805        let project =
 806            cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
 807        for path in root_paths {
 808            let (tree, _) = project
 809                .update(cx, |project, cx| {
 810                    project.find_or_create_local_worktree(path, true, cx)
 811                })
 812                .await
 813                .unwrap();
 814            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 815                .await;
 816        }
 817        project
 818    }
 819
 820    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 821        let mut language_servers_to_start = Vec::new();
 822        for buffer in self.opened_buffers.values() {
 823            if let Some(buffer) = buffer.upgrade(cx) {
 824                let buffer = buffer.read(cx);
 825                if let Some((file, language)) = buffer.file().zip(buffer.language()) {
 826                    let settings = language_settings(Some(language), Some(file), cx);
 827                    if settings.enable_language_server {
 828                        if let Some(file) = File::from_dyn(Some(file)) {
 829                            language_servers_to_start
 830                                .push((file.worktree.clone(), language.clone()));
 831                        }
 832                    }
 833                }
 834            }
 835        }
 836
 837        let mut language_servers_to_stop = Vec::new();
 838        let mut language_servers_to_restart = Vec::new();
 839        let languages = self.languages.to_vec();
 840
 841        let new_lsp_settings = settings::get::<ProjectSettings>(cx).lsp.clone();
 842        let current_lsp_settings = &self.current_lsp_settings;
 843        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 844            let language = languages.iter().find_map(|l| {
 845                let adapter = l
 846                    .lsp_adapters()
 847                    .iter()
 848                    .find(|adapter| &adapter.name == started_lsp_name)?;
 849                Some((l, adapter))
 850            });
 851            if let Some((language, adapter)) = language {
 852                let worktree = self.worktree_for_id(*worktree_id, cx);
 853                let file = worktree.as_ref().and_then(|tree| {
 854                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 855                });
 856                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 857                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 858                } else if let Some(worktree) = worktree {
 859                    let server_name = &adapter.name.0;
 860                    match (
 861                        current_lsp_settings.get(server_name),
 862                        new_lsp_settings.get(server_name),
 863                    ) {
 864                        (None, None) => {}
 865                        (Some(_), None) | (None, Some(_)) => {
 866                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 867                        }
 868                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 869                            if current_lsp_settings != new_lsp_settings {
 870                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 871                            }
 872                        }
 873                    }
 874                }
 875            }
 876        }
 877        self.current_lsp_settings = new_lsp_settings;
 878
 879        // Stop all newly-disabled language servers.
 880        for (worktree_id, adapter_name) in language_servers_to_stop {
 881            self.stop_language_server(worktree_id, adapter_name, cx)
 882                .detach();
 883        }
 884
 885        // Start all the newly-enabled language servers.
 886        for (worktree, language) in language_servers_to_start {
 887            let worktree_path = worktree.read(cx).abs_path();
 888            self.start_language_servers(&worktree, worktree_path, language, cx);
 889        }
 890
 891        // Restart all language servers with changed initialization options.
 892        for (worktree, language) in language_servers_to_restart {
 893            self.restart_language_servers(worktree, language, cx);
 894        }
 895
 896        if self.copilot_lsp_subscription.is_none() {
 897            if let Some(copilot) = Copilot::global(cx) {
 898                for buffer in self.opened_buffers.values() {
 899                    if let Some(buffer) = buffer.upgrade(cx) {
 900                        self.register_buffer_with_copilot(&buffer, cx);
 901                    }
 902                }
 903                self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
 904            }
 905        }
 906
 907        cx.notify();
 908    }
 909
 910    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 911        self.opened_buffers
 912            .get(&remote_id)
 913            .and_then(|buffer| buffer.upgrade(cx))
 914    }
 915
 916    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 917        &self.languages
 918    }
 919
 920    pub fn client(&self) -> Arc<Client> {
 921        self.client.clone()
 922    }
 923
 924    pub fn user_store(&self) -> ModelHandle<UserStore> {
 925        self.user_store.clone()
 926    }
 927
 928    pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
 929        self.opened_buffers
 930            .values()
 931            .filter_map(|b| b.upgrade(cx))
 932            .collect()
 933    }
 934
 935    #[cfg(any(test, feature = "test-support"))]
 936    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 937        let path = path.into();
 938        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 939            self.opened_buffers.iter().any(|(_, buffer)| {
 940                if let Some(buffer) = buffer.upgrade(cx) {
 941                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 942                        if file.worktree == worktree && file.path() == &path.path {
 943                            return true;
 944                        }
 945                    }
 946                }
 947                false
 948            })
 949        } else {
 950            false
 951        }
 952    }
 953
 954    pub fn fs(&self) -> &Arc<dyn Fs> {
 955        &self.fs
 956    }
 957
 958    pub fn remote_id(&self) -> Option<u64> {
 959        match self.client_state.as_ref()? {
 960            ProjectClientState::Local { remote_id, .. }
 961            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 962        }
 963    }
 964
 965    pub fn replica_id(&self) -> ReplicaId {
 966        match &self.client_state {
 967            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
 968            _ => 0,
 969        }
 970    }
 971
 972    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
 973        if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
 974            updates_tx
 975                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
 976                .ok();
 977        }
 978        cx.notify();
 979    }
 980
 981    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 982        &self.collaborators
 983    }
 984
 985    /// Collect all worktrees, including ones that don't appear in the project panel
 986    pub fn worktrees<'a>(
 987        &'a self,
 988        cx: &'a AppContext,
 989    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 990        self.worktrees
 991            .iter()
 992            .filter_map(move |worktree| worktree.upgrade(cx))
 993    }
 994
 995    /// Collect all user-visible worktrees, the ones that appear in the project panel
 996    pub fn visible_worktrees<'a>(
 997        &'a self,
 998        cx: &'a AppContext,
 999    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1000        self.worktrees.iter().filter_map(|worktree| {
1001            worktree.upgrade(cx).and_then(|worktree| {
1002                if worktree.read(cx).is_visible() {
1003                    Some(worktree)
1004                } else {
1005                    None
1006                }
1007            })
1008        })
1009    }
1010
1011    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1012        self.visible_worktrees(cx)
1013            .map(|tree| tree.read(cx).root_name())
1014    }
1015
1016    pub fn worktree_for_id(
1017        &self,
1018        id: WorktreeId,
1019        cx: &AppContext,
1020    ) -> Option<ModelHandle<Worktree>> {
1021        self.worktrees(cx)
1022            .find(|worktree| worktree.read(cx).id() == id)
1023    }
1024
1025    pub fn worktree_for_entry(
1026        &self,
1027        entry_id: ProjectEntryId,
1028        cx: &AppContext,
1029    ) -> Option<ModelHandle<Worktree>> {
1030        self.worktrees(cx)
1031            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1032    }
1033
1034    pub fn worktree_id_for_entry(
1035        &self,
1036        entry_id: ProjectEntryId,
1037        cx: &AppContext,
1038    ) -> Option<WorktreeId> {
1039        self.worktree_for_entry(entry_id, cx)
1040            .map(|worktree| worktree.read(cx).id())
1041    }
1042
1043    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1044        paths.iter().all(|path| self.contains_path(path, cx))
1045    }
1046
1047    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1048        for worktree in self.worktrees(cx) {
1049            let worktree = worktree.read(cx).as_local();
1050            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1051                return true;
1052            }
1053        }
1054        false
1055    }
1056
1057    pub fn create_entry(
1058        &mut self,
1059        project_path: impl Into<ProjectPath>,
1060        is_directory: bool,
1061        cx: &mut ModelContext<Self>,
1062    ) -> Option<Task<Result<Entry>>> {
1063        let project_path = project_path.into();
1064        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1065        if self.is_local() {
1066            Some(worktree.update(cx, |worktree, cx| {
1067                worktree
1068                    .as_local_mut()
1069                    .unwrap()
1070                    .create_entry(project_path.path, is_directory, cx)
1071            }))
1072        } else {
1073            let client = self.client.clone();
1074            let project_id = self.remote_id().unwrap();
1075            Some(cx.spawn_weak(|_, mut cx| async move {
1076                let response = client
1077                    .request(proto::CreateProjectEntry {
1078                        worktree_id: project_path.worktree_id.to_proto(),
1079                        project_id,
1080                        path: project_path.path.to_string_lossy().into(),
1081                        is_directory,
1082                    })
1083                    .await?;
1084                let entry = response
1085                    .entry
1086                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1087                worktree
1088                    .update(&mut cx, |worktree, cx| {
1089                        worktree.as_remote_mut().unwrap().insert_entry(
1090                            entry,
1091                            response.worktree_scan_id as usize,
1092                            cx,
1093                        )
1094                    })
1095                    .await
1096            }))
1097        }
1098    }
1099
1100    pub fn copy_entry(
1101        &mut self,
1102        entry_id: ProjectEntryId,
1103        new_path: impl Into<Arc<Path>>,
1104        cx: &mut ModelContext<Self>,
1105    ) -> Option<Task<Result<Entry>>> {
1106        let worktree = self.worktree_for_entry(entry_id, cx)?;
1107        let new_path = new_path.into();
1108        if self.is_local() {
1109            worktree.update(cx, |worktree, cx| {
1110                worktree
1111                    .as_local_mut()
1112                    .unwrap()
1113                    .copy_entry(entry_id, new_path, cx)
1114            })
1115        } else {
1116            let client = self.client.clone();
1117            let project_id = self.remote_id().unwrap();
1118
1119            Some(cx.spawn_weak(|_, mut cx| async move {
1120                let response = client
1121                    .request(proto::CopyProjectEntry {
1122                        project_id,
1123                        entry_id: entry_id.to_proto(),
1124                        new_path: new_path.to_string_lossy().into(),
1125                    })
1126                    .await?;
1127                let entry = response
1128                    .entry
1129                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1130                worktree
1131                    .update(&mut cx, |worktree, cx| {
1132                        worktree.as_remote_mut().unwrap().insert_entry(
1133                            entry,
1134                            response.worktree_scan_id as usize,
1135                            cx,
1136                        )
1137                    })
1138                    .await
1139            }))
1140        }
1141    }
1142
1143    pub fn rename_entry(
1144        &mut self,
1145        entry_id: ProjectEntryId,
1146        new_path: impl Into<Arc<Path>>,
1147        cx: &mut ModelContext<Self>,
1148    ) -> Option<Task<Result<Entry>>> {
1149        let worktree = self.worktree_for_entry(entry_id, cx)?;
1150        let new_path = new_path.into();
1151        if self.is_local() {
1152            worktree.update(cx, |worktree, cx| {
1153                worktree
1154                    .as_local_mut()
1155                    .unwrap()
1156                    .rename_entry(entry_id, new_path, cx)
1157            })
1158        } else {
1159            let client = self.client.clone();
1160            let project_id = self.remote_id().unwrap();
1161
1162            Some(cx.spawn_weak(|_, mut cx| async move {
1163                let response = client
1164                    .request(proto::RenameProjectEntry {
1165                        project_id,
1166                        entry_id: entry_id.to_proto(),
1167                        new_path: new_path.to_string_lossy().into(),
1168                    })
1169                    .await?;
1170                let entry = response
1171                    .entry
1172                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1173                worktree
1174                    .update(&mut cx, |worktree, cx| {
1175                        worktree.as_remote_mut().unwrap().insert_entry(
1176                            entry,
1177                            response.worktree_scan_id as usize,
1178                            cx,
1179                        )
1180                    })
1181                    .await
1182            }))
1183        }
1184    }
1185
1186    pub fn delete_entry(
1187        &mut self,
1188        entry_id: ProjectEntryId,
1189        cx: &mut ModelContext<Self>,
1190    ) -> Option<Task<Result<()>>> {
1191        let worktree = self.worktree_for_entry(entry_id, cx)?;
1192
1193        cx.emit(Event::DeletedEntry(entry_id));
1194
1195        if self.is_local() {
1196            worktree.update(cx, |worktree, cx| {
1197                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1198            })
1199        } else {
1200            let client = self.client.clone();
1201            let project_id = self.remote_id().unwrap();
1202            Some(cx.spawn_weak(|_, mut cx| async move {
1203                let response = client
1204                    .request(proto::DeleteProjectEntry {
1205                        project_id,
1206                        entry_id: entry_id.to_proto(),
1207                    })
1208                    .await?;
1209                worktree
1210                    .update(&mut cx, move |worktree, cx| {
1211                        worktree.as_remote_mut().unwrap().delete_entry(
1212                            entry_id,
1213                            response.worktree_scan_id as usize,
1214                            cx,
1215                        )
1216                    })
1217                    .await
1218            }))
1219        }
1220    }
1221
1222    pub fn expand_entry(
1223        &mut self,
1224        worktree_id: WorktreeId,
1225        entry_id: ProjectEntryId,
1226        cx: &mut ModelContext<Self>,
1227    ) -> Option<Task<Result<()>>> {
1228        let worktree = self.worktree_for_id(worktree_id, cx)?;
1229        if self.is_local() {
1230            worktree.update(cx, |worktree, cx| {
1231                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
1232            })
1233        } else {
1234            let worktree = worktree.downgrade();
1235            let request = self.client.request(proto::ExpandProjectEntry {
1236                project_id: self.remote_id().unwrap(),
1237                entry_id: entry_id.to_proto(),
1238            });
1239            Some(cx.spawn_weak(|_, mut cx| async move {
1240                let response = request.await?;
1241                if let Some(worktree) = worktree.upgrade(&cx) {
1242                    worktree
1243                        .update(&mut cx, |worktree, _| {
1244                            worktree
1245                                .as_remote_mut()
1246                                .unwrap()
1247                                .wait_for_snapshot(response.worktree_scan_id as usize)
1248                        })
1249                        .await?;
1250                }
1251                Ok(())
1252            }))
1253        }
1254    }
1255
1256    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1257        if self.client_state.is_some() {
1258            return Err(anyhow!("project was already shared"));
1259        }
1260        self.client_subscriptions.push(
1261            self.client
1262                .subscribe_to_entity(project_id)?
1263                .set_model(&cx.handle(), &mut cx.to_async()),
1264        );
1265
1266        for open_buffer in self.opened_buffers.values_mut() {
1267            match open_buffer {
1268                OpenBuffer::Strong(_) => {}
1269                OpenBuffer::Weak(buffer) => {
1270                    if let Some(buffer) = buffer.upgrade(cx) {
1271                        *open_buffer = OpenBuffer::Strong(buffer);
1272                    }
1273                }
1274                OpenBuffer::Operations(_) => unreachable!(),
1275            }
1276        }
1277
1278        for worktree_handle in self.worktrees.iter_mut() {
1279            match worktree_handle {
1280                WorktreeHandle::Strong(_) => {}
1281                WorktreeHandle::Weak(worktree) => {
1282                    if let Some(worktree) = worktree.upgrade(cx) {
1283                        *worktree_handle = WorktreeHandle::Strong(worktree);
1284                    }
1285                }
1286            }
1287        }
1288
1289        for (server_id, status) in &self.language_server_statuses {
1290            self.client
1291                .send(proto::StartLanguageServer {
1292                    project_id,
1293                    server: Some(proto::LanguageServer {
1294                        id: server_id.0 as u64,
1295                        name: status.name.clone(),
1296                    }),
1297                })
1298                .log_err();
1299        }
1300
1301        let store = cx.global::<SettingsStore>();
1302        for worktree in self.worktrees(cx) {
1303            let worktree_id = worktree.read(cx).id().to_proto();
1304            for (path, content) in store.local_settings(worktree.id()) {
1305                self.client
1306                    .send(proto::UpdateWorktreeSettings {
1307                        project_id,
1308                        worktree_id,
1309                        path: path.to_string_lossy().into(),
1310                        content: Some(content),
1311                    })
1312                    .log_err();
1313            }
1314        }
1315
1316        let (updates_tx, mut updates_rx) = mpsc::unbounded();
1317        let client = self.client.clone();
1318        self.client_state = Some(ProjectClientState::Local {
1319            remote_id: project_id,
1320            updates_tx,
1321            _send_updates: cx.spawn_weak(move |this, mut cx| async move {
1322                while let Some(update) = updates_rx.next().await {
1323                    let Some(this) = this.upgrade(&cx) else { break };
1324
1325                    match update {
1326                        LocalProjectUpdate::WorktreesChanged => {
1327                            let worktrees = this
1328                                .read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1329                            let update_project = this
1330                                .read_with(&cx, |this, cx| {
1331                                    this.client.request(proto::UpdateProject {
1332                                        project_id,
1333                                        worktrees: this.worktree_metadata_protos(cx),
1334                                    })
1335                                })
1336                                .await;
1337                            if update_project.is_ok() {
1338                                for worktree in worktrees {
1339                                    worktree.update(&mut cx, |worktree, cx| {
1340                                        let worktree = worktree.as_local_mut().unwrap();
1341                                        worktree.share(project_id, cx).detach_and_log_err(cx)
1342                                    });
1343                                }
1344                            }
1345                        }
1346                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1347                            let buffer = this.update(&mut cx, |this, _| {
1348                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1349                                let shared_buffers =
1350                                    this.shared_buffers.entry(peer_id).or_default();
1351                                if shared_buffers.insert(buffer_id) {
1352                                    if let OpenBuffer::Strong(buffer) = buffer {
1353                                        Some(buffer.clone())
1354                                    } else {
1355                                        None
1356                                    }
1357                                } else {
1358                                    None
1359                                }
1360                            });
1361
1362                            let Some(buffer) = buffer else { continue };
1363                            let operations =
1364                                buffer.read_with(&cx, |b, cx| b.serialize_ops(None, cx));
1365                            let operations = operations.await;
1366                            let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1367
1368                            let initial_state = proto::CreateBufferForPeer {
1369                                project_id,
1370                                peer_id: Some(peer_id),
1371                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1372                            };
1373                            if client.send(initial_state).log_err().is_some() {
1374                                let client = client.clone();
1375                                cx.background()
1376                                    .spawn(async move {
1377                                        let mut chunks = split_operations(operations).peekable();
1378                                        while let Some(chunk) = chunks.next() {
1379                                            let is_last = chunks.peek().is_none();
1380                                            client.send(proto::CreateBufferForPeer {
1381                                                project_id,
1382                                                peer_id: Some(peer_id),
1383                                                variant: Some(
1384                                                    proto::create_buffer_for_peer::Variant::Chunk(
1385                                                        proto::BufferChunk {
1386                                                            buffer_id,
1387                                                            operations: chunk,
1388                                                            is_last,
1389                                                        },
1390                                                    ),
1391                                                ),
1392                                            })?;
1393                                        }
1394                                        anyhow::Ok(())
1395                                    })
1396                                    .await
1397                                    .log_err();
1398                            }
1399                        }
1400                    }
1401                }
1402            }),
1403        });
1404
1405        self.metadata_changed(cx);
1406        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1407        cx.notify();
1408        Ok(())
1409    }
1410
1411    pub fn reshared(
1412        &mut self,
1413        message: proto::ResharedProject,
1414        cx: &mut ModelContext<Self>,
1415    ) -> Result<()> {
1416        self.shared_buffers.clear();
1417        self.set_collaborators_from_proto(message.collaborators, cx)?;
1418        self.metadata_changed(cx);
1419        Ok(())
1420    }
1421
1422    pub fn rejoined(
1423        &mut self,
1424        message: proto::RejoinedProject,
1425        message_id: u32,
1426        cx: &mut ModelContext<Self>,
1427    ) -> Result<()> {
1428        cx.update_global::<SettingsStore, _, _>(|store, cx| {
1429            for worktree in &self.worktrees {
1430                store
1431                    .clear_local_settings(worktree.handle_id(), cx)
1432                    .log_err();
1433            }
1434        });
1435
1436        self.join_project_response_message_id = message_id;
1437        self.set_worktrees_from_proto(message.worktrees, cx)?;
1438        self.set_collaborators_from_proto(message.collaborators, cx)?;
1439        self.language_server_statuses = message
1440            .language_servers
1441            .into_iter()
1442            .map(|server| {
1443                (
1444                    LanguageServerId(server.id as usize),
1445                    LanguageServerStatus {
1446                        name: server.name,
1447                        pending_work: Default::default(),
1448                        has_pending_diagnostic_updates: false,
1449                        progress_tokens: Default::default(),
1450                    },
1451                )
1452            })
1453            .collect();
1454        self.buffer_ordered_messages_tx
1455            .unbounded_send(BufferOrderedMessage::Resync)
1456            .unwrap();
1457        cx.notify();
1458        Ok(())
1459    }
1460
1461    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1462        self.unshare_internal(cx)?;
1463        self.metadata_changed(cx);
1464        cx.notify();
1465        Ok(())
1466    }
1467
1468    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1469        if self.is_remote() {
1470            return Err(anyhow!("attempted to unshare a remote project"));
1471        }
1472
1473        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1474            self.collaborators.clear();
1475            self.shared_buffers.clear();
1476            self.client_subscriptions.clear();
1477
1478            for worktree_handle in self.worktrees.iter_mut() {
1479                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1480                    let is_visible = worktree.update(cx, |worktree, _| {
1481                        worktree.as_local_mut().unwrap().unshare();
1482                        worktree.is_visible()
1483                    });
1484                    if !is_visible {
1485                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1486                    }
1487                }
1488            }
1489
1490            for open_buffer in self.opened_buffers.values_mut() {
1491                // Wake up any tasks waiting for peers' edits to this buffer.
1492                if let Some(buffer) = open_buffer.upgrade(cx) {
1493                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1494                }
1495
1496                if let OpenBuffer::Strong(buffer) = open_buffer {
1497                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1498                }
1499            }
1500
1501            self.client.send(proto::UnshareProject {
1502                project_id: remote_id,
1503            })?;
1504
1505            Ok(())
1506        } else {
1507            Err(anyhow!("attempted to unshare an unshared project"))
1508        }
1509    }
1510
1511    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1512        self.disconnected_from_host_internal(cx);
1513        cx.emit(Event::DisconnectedFromHost);
1514        cx.notify();
1515    }
1516
1517    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1518        if let Some(ProjectClientState::Remote {
1519            sharing_has_stopped,
1520            ..
1521        }) = &mut self.client_state
1522        {
1523            *sharing_has_stopped = true;
1524
1525            self.collaborators.clear();
1526
1527            for worktree in &self.worktrees {
1528                if let Some(worktree) = worktree.upgrade(cx) {
1529                    worktree.update(cx, |worktree, _| {
1530                        if let Some(worktree) = worktree.as_remote_mut() {
1531                            worktree.disconnected_from_host();
1532                        }
1533                    });
1534                }
1535            }
1536
1537            for open_buffer in self.opened_buffers.values_mut() {
1538                // Wake up any tasks waiting for peers' edits to this buffer.
1539                if let Some(buffer) = open_buffer.upgrade(cx) {
1540                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1541                }
1542
1543                if let OpenBuffer::Strong(buffer) = open_buffer {
1544                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1545                }
1546            }
1547
1548            // Wake up all futures currently waiting on a buffer to get opened,
1549            // to give them a chance to fail now that we've disconnected.
1550            *self.opened_buffer.0.borrow_mut() = ();
1551        }
1552    }
1553
1554    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1555        cx.emit(Event::Closed);
1556    }
1557
1558    pub fn is_read_only(&self) -> bool {
1559        match &self.client_state {
1560            Some(ProjectClientState::Remote {
1561                sharing_has_stopped,
1562                ..
1563            }) => *sharing_has_stopped,
1564            _ => false,
1565        }
1566    }
1567
1568    pub fn is_local(&self) -> bool {
1569        match &self.client_state {
1570            Some(ProjectClientState::Remote { .. }) => false,
1571            _ => true,
1572        }
1573    }
1574
1575    pub fn is_remote(&self) -> bool {
1576        !self.is_local()
1577    }
1578
1579    pub fn create_buffer(
1580        &mut self,
1581        text: &str,
1582        language: Option<Arc<Language>>,
1583        cx: &mut ModelContext<Self>,
1584    ) -> Result<ModelHandle<Buffer>> {
1585        if self.is_remote() {
1586            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1587        }
1588        let id = post_inc(&mut self.next_buffer_id);
1589        let buffer = cx.add_model(|cx| {
1590            Buffer::new(self.replica_id(), id, text)
1591                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1592        });
1593        self.register_buffer(&buffer, cx)?;
1594        Ok(buffer)
1595    }
1596
1597    pub fn open_path(
1598        &mut self,
1599        path: impl Into<ProjectPath>,
1600        cx: &mut ModelContext<Self>,
1601    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1602        let task = self.open_buffer(path, cx);
1603        cx.spawn_weak(|_, cx| async move {
1604            let buffer = task.await?;
1605            let project_entry_id = buffer
1606                .read_with(&cx, |buffer, cx| {
1607                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1608                })
1609                .ok_or_else(|| anyhow!("no project entry"))?;
1610
1611            let buffer: &AnyModelHandle = &buffer;
1612            Ok((project_entry_id, buffer.clone()))
1613        })
1614    }
1615
1616    pub fn open_local_buffer(
1617        &mut self,
1618        abs_path: impl AsRef<Path>,
1619        cx: &mut ModelContext<Self>,
1620    ) -> Task<Result<ModelHandle<Buffer>>> {
1621        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1622            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1623        } else {
1624            Task::ready(Err(anyhow!("no such path")))
1625        }
1626    }
1627
1628    pub fn open_buffer(
1629        &mut self,
1630        path: impl Into<ProjectPath>,
1631        cx: &mut ModelContext<Self>,
1632    ) -> Task<Result<ModelHandle<Buffer>>> {
1633        let project_path = path.into();
1634        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1635            worktree
1636        } else {
1637            return Task::ready(Err(anyhow!("no such worktree")));
1638        };
1639
1640        // If there is already a buffer for the given path, then return it.
1641        let existing_buffer = self.get_open_buffer(&project_path, cx);
1642        if let Some(existing_buffer) = existing_buffer {
1643            return Task::ready(Ok(existing_buffer));
1644        }
1645
1646        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1647            // If the given path is already being loaded, then wait for that existing
1648            // task to complete and return the same buffer.
1649            hash_map::Entry::Occupied(e) => e.get().clone(),
1650
1651            // Otherwise, record the fact that this path is now being loaded.
1652            hash_map::Entry::Vacant(entry) => {
1653                let (mut tx, rx) = postage::watch::channel();
1654                entry.insert(rx.clone());
1655
1656                let load_buffer = if worktree.read(cx).is_local() {
1657                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1658                } else {
1659                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1660                };
1661
1662                cx.spawn(move |this, mut cx| async move {
1663                    let load_result = load_buffer.await;
1664                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1665                        // Record the fact that the buffer is no longer loading.
1666                        this.loading_buffers_by_path.remove(&project_path);
1667                        let buffer = load_result.map_err(Arc::new)?;
1668                        Ok(buffer)
1669                    }));
1670                })
1671                .detach();
1672                rx
1673            }
1674        };
1675
1676        cx.foreground().spawn(async move {
1677            wait_for_loading_buffer(loading_watch)
1678                .await
1679                .map_err(|error| anyhow!("{}", error))
1680        })
1681    }
1682
1683    fn open_local_buffer_internal(
1684        &mut self,
1685        path: &Arc<Path>,
1686        worktree: &ModelHandle<Worktree>,
1687        cx: &mut ModelContext<Self>,
1688    ) -> Task<Result<ModelHandle<Buffer>>> {
1689        let buffer_id = post_inc(&mut self.next_buffer_id);
1690        let load_buffer = worktree.update(cx, |worktree, cx| {
1691            let worktree = worktree.as_local_mut().unwrap();
1692            worktree.load_buffer(buffer_id, path, cx)
1693        });
1694        cx.spawn(|this, mut cx| async move {
1695            let buffer = load_buffer.await?;
1696            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1697            Ok(buffer)
1698        })
1699    }
1700
1701    fn open_remote_buffer_internal(
1702        &mut self,
1703        path: &Arc<Path>,
1704        worktree: &ModelHandle<Worktree>,
1705        cx: &mut ModelContext<Self>,
1706    ) -> Task<Result<ModelHandle<Buffer>>> {
1707        let rpc = self.client.clone();
1708        let project_id = self.remote_id().unwrap();
1709        let remote_worktree_id = worktree.read(cx).id();
1710        let path = path.clone();
1711        let path_string = path.to_string_lossy().to_string();
1712        cx.spawn(|this, mut cx| async move {
1713            let response = rpc
1714                .request(proto::OpenBufferByPath {
1715                    project_id,
1716                    worktree_id: remote_worktree_id.to_proto(),
1717                    path: path_string,
1718                })
1719                .await?;
1720            this.update(&mut cx, |this, cx| {
1721                this.wait_for_remote_buffer(response.buffer_id, cx)
1722            })
1723            .await
1724        })
1725    }
1726
1727    /// LanguageServerName is owned, because it is inserted into a map
1728    pub fn open_local_buffer_via_lsp(
1729        &mut self,
1730        abs_path: lsp::Url,
1731        language_server_id: LanguageServerId,
1732        language_server_name: LanguageServerName,
1733        cx: &mut ModelContext<Self>,
1734    ) -> Task<Result<ModelHandle<Buffer>>> {
1735        cx.spawn(|this, mut cx| async move {
1736            let abs_path = abs_path
1737                .to_file_path()
1738                .map_err(|_| anyhow!("can't convert URI to path"))?;
1739            let (worktree, relative_path) = if let Some(result) =
1740                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1741            {
1742                result
1743            } else {
1744                let worktree = this
1745                    .update(&mut cx, |this, cx| {
1746                        this.create_local_worktree(&abs_path, false, cx)
1747                    })
1748                    .await?;
1749                this.update(&mut cx, |this, cx| {
1750                    this.language_server_ids.insert(
1751                        (worktree.read(cx).id(), language_server_name),
1752                        language_server_id,
1753                    );
1754                });
1755                (worktree, PathBuf::new())
1756            };
1757
1758            let project_path = ProjectPath {
1759                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1760                path: relative_path.into(),
1761            };
1762            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1763                .await
1764        })
1765    }
1766
1767    pub fn open_buffer_by_id(
1768        &mut self,
1769        id: u64,
1770        cx: &mut ModelContext<Self>,
1771    ) -> Task<Result<ModelHandle<Buffer>>> {
1772        if let Some(buffer) = self.buffer_for_id(id, cx) {
1773            Task::ready(Ok(buffer))
1774        } else if self.is_local() {
1775            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1776        } else if let Some(project_id) = self.remote_id() {
1777            let request = self
1778                .client
1779                .request(proto::OpenBufferById { project_id, id });
1780            cx.spawn(|this, mut cx| async move {
1781                let buffer_id = request.await?.buffer_id;
1782                this.update(&mut cx, |this, cx| {
1783                    this.wait_for_remote_buffer(buffer_id, cx)
1784                })
1785                .await
1786            })
1787        } else {
1788            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1789        }
1790    }
1791
1792    pub fn save_buffers(
1793        &self,
1794        buffers: HashSet<ModelHandle<Buffer>>,
1795        cx: &mut ModelContext<Self>,
1796    ) -> Task<Result<()>> {
1797        cx.spawn(|this, mut cx| async move {
1798            let save_tasks = buffers
1799                .into_iter()
1800                .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1801            try_join_all(save_tasks).await?;
1802            Ok(())
1803        })
1804    }
1805
1806    pub fn save_buffer(
1807        &self,
1808        buffer: ModelHandle<Buffer>,
1809        cx: &mut ModelContext<Self>,
1810    ) -> Task<Result<()>> {
1811        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1812            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1813        };
1814        let worktree = file.worktree.clone();
1815        let path = file.path.clone();
1816        worktree.update(cx, |worktree, cx| match worktree {
1817            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1818            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1819        })
1820    }
1821
1822    pub fn save_buffer_as(
1823        &mut self,
1824        buffer: ModelHandle<Buffer>,
1825        abs_path: PathBuf,
1826        cx: &mut ModelContext<Self>,
1827    ) -> Task<Result<()>> {
1828        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1829        let old_file = File::from_dyn(buffer.read(cx).file())
1830            .filter(|f| f.is_local())
1831            .cloned();
1832        cx.spawn(|this, mut cx| async move {
1833            if let Some(old_file) = &old_file {
1834                this.update(&mut cx, |this, cx| {
1835                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1836                });
1837            }
1838            let (worktree, path) = worktree_task.await?;
1839            worktree
1840                .update(&mut cx, |worktree, cx| match worktree {
1841                    Worktree::Local(worktree) => {
1842                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1843                    }
1844                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1845                })
1846                .await?;
1847            this.update(&mut cx, |this, cx| {
1848                this.detect_language_for_buffer(&buffer, cx);
1849                this.register_buffer_with_language_servers(&buffer, cx);
1850            });
1851            Ok(())
1852        })
1853    }
1854
1855    pub fn get_open_buffer(
1856        &mut self,
1857        path: &ProjectPath,
1858        cx: &mut ModelContext<Self>,
1859    ) -> Option<ModelHandle<Buffer>> {
1860        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1861        self.opened_buffers.values().find_map(|buffer| {
1862            let buffer = buffer.upgrade(cx)?;
1863            let file = File::from_dyn(buffer.read(cx).file())?;
1864            if file.worktree == worktree && file.path() == &path.path {
1865                Some(buffer)
1866            } else {
1867                None
1868            }
1869        })
1870    }
1871
1872    fn register_buffer(
1873        &mut self,
1874        buffer: &ModelHandle<Buffer>,
1875        cx: &mut ModelContext<Self>,
1876    ) -> Result<()> {
1877        self.request_buffer_diff_recalculation(buffer, cx);
1878        buffer.update(cx, |buffer, _| {
1879            buffer.set_language_registry(self.languages.clone())
1880        });
1881
1882        let remote_id = buffer.read(cx).remote_id();
1883        let is_remote = self.is_remote();
1884        let open_buffer = if is_remote || self.is_shared() {
1885            OpenBuffer::Strong(buffer.clone())
1886        } else {
1887            OpenBuffer::Weak(buffer.downgrade())
1888        };
1889
1890        match self.opened_buffers.entry(remote_id) {
1891            hash_map::Entry::Vacant(entry) => {
1892                entry.insert(open_buffer);
1893            }
1894            hash_map::Entry::Occupied(mut entry) => {
1895                if let OpenBuffer::Operations(operations) = entry.get_mut() {
1896                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1897                } else if entry.get().upgrade(cx).is_some() {
1898                    if is_remote {
1899                        return Ok(());
1900                    } else {
1901                        debug_panic!("buffer {} was already registered", remote_id);
1902                        Err(anyhow!("buffer {} was already registered", remote_id))?;
1903                    }
1904                }
1905                entry.insert(open_buffer);
1906            }
1907        }
1908        cx.subscribe(buffer, |this, buffer, event, cx| {
1909            this.on_buffer_event(buffer, event, cx);
1910        })
1911        .detach();
1912
1913        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1914            if file.is_local {
1915                self.local_buffer_ids_by_path.insert(
1916                    ProjectPath {
1917                        worktree_id: file.worktree_id(cx),
1918                        path: file.path.clone(),
1919                    },
1920                    remote_id,
1921                );
1922
1923                self.local_buffer_ids_by_entry_id
1924                    .insert(file.entry_id, remote_id);
1925            }
1926        }
1927
1928        self.detect_language_for_buffer(buffer, cx);
1929        self.register_buffer_with_language_servers(buffer, cx);
1930        self.register_buffer_with_copilot(buffer, cx);
1931        cx.observe_release(buffer, |this, buffer, cx| {
1932            if let Some(file) = File::from_dyn(buffer.file()) {
1933                if file.is_local() {
1934                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1935                    for server in this.language_servers_for_buffer(buffer, cx) {
1936                        server
1937                            .1
1938                            .notify::<lsp::notification::DidCloseTextDocument>(
1939                                lsp::DidCloseTextDocumentParams {
1940                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1941                                },
1942                            )
1943                            .log_err();
1944                    }
1945                }
1946            }
1947        })
1948        .detach();
1949
1950        *self.opened_buffer.0.borrow_mut() = ();
1951        Ok(())
1952    }
1953
1954    fn register_buffer_with_language_servers(
1955        &mut self,
1956        buffer_handle: &ModelHandle<Buffer>,
1957        cx: &mut ModelContext<Self>,
1958    ) {
1959        let buffer = buffer_handle.read(cx);
1960        let buffer_id = buffer.remote_id();
1961
1962        if let Some(file) = File::from_dyn(buffer.file()) {
1963            if !file.is_local() {
1964                return;
1965            }
1966
1967            let abs_path = file.abs_path(cx);
1968            let uri = lsp::Url::from_file_path(&abs_path)
1969                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
1970            let initial_snapshot = buffer.text_snapshot();
1971            let language = buffer.language().cloned();
1972            let worktree_id = file.worktree_id(cx);
1973
1974            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1975                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
1976                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
1977                        .log_err();
1978                }
1979            }
1980
1981            if let Some(language) = language {
1982                for adapter in language.lsp_adapters() {
1983                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1984                    let server = self
1985                        .language_server_ids
1986                        .get(&(worktree_id, adapter.name.clone()))
1987                        .and_then(|id| self.language_servers.get(id))
1988                        .and_then(|server_state| {
1989                            if let LanguageServerState::Running { server, .. } = server_state {
1990                                Some(server.clone())
1991                            } else {
1992                                None
1993                            }
1994                        });
1995                    let server = match server {
1996                        Some(server) => server,
1997                        None => continue,
1998                    };
1999
2000                    server
2001                        .notify::<lsp::notification::DidOpenTextDocument>(
2002                            lsp::DidOpenTextDocumentParams {
2003                                text_document: lsp::TextDocumentItem::new(
2004                                    uri.clone(),
2005                                    language_id.unwrap_or_default(),
2006                                    0,
2007                                    initial_snapshot.text(),
2008                                ),
2009                            },
2010                        )
2011                        .log_err();
2012
2013                    buffer_handle.update(cx, |buffer, cx| {
2014                        buffer.set_completion_triggers(
2015                            server
2016                                .capabilities()
2017                                .completion_provider
2018                                .as_ref()
2019                                .and_then(|provider| provider.trigger_characters.clone())
2020                                .unwrap_or_default(),
2021                            cx,
2022                        );
2023                    });
2024
2025                    let snapshot = LspBufferSnapshot {
2026                        version: 0,
2027                        snapshot: initial_snapshot.clone(),
2028                    };
2029                    self.buffer_snapshots
2030                        .entry(buffer_id)
2031                        .or_default()
2032                        .insert(server.server_id(), vec![snapshot]);
2033                }
2034            }
2035        }
2036    }
2037
2038    fn unregister_buffer_from_language_servers(
2039        &mut self,
2040        buffer: &ModelHandle<Buffer>,
2041        old_file: &File,
2042        cx: &mut ModelContext<Self>,
2043    ) {
2044        let old_path = match old_file.as_local() {
2045            Some(local) => local.abs_path(cx),
2046            None => return,
2047        };
2048
2049        buffer.update(cx, |buffer, cx| {
2050            let worktree_id = old_file.worktree_id(cx);
2051            let ids = &self.language_server_ids;
2052
2053            let language = buffer.language().cloned();
2054            let adapters = language.iter().flat_map(|language| language.lsp_adapters());
2055            for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
2056                buffer.update_diagnostics(server_id, Default::default(), cx);
2057            }
2058
2059            self.buffer_snapshots.remove(&buffer.remote_id());
2060            let file_url = lsp::Url::from_file_path(old_path).unwrap();
2061            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2062                language_server
2063                    .notify::<lsp::notification::DidCloseTextDocument>(
2064                        lsp::DidCloseTextDocumentParams {
2065                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
2066                        },
2067                    )
2068                    .log_err();
2069            }
2070        });
2071    }
2072
2073    fn register_buffer_with_copilot(
2074        &self,
2075        buffer_handle: &ModelHandle<Buffer>,
2076        cx: &mut ModelContext<Self>,
2077    ) {
2078        if let Some(copilot) = Copilot::global(cx) {
2079            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
2080        }
2081    }
2082
2083    async fn send_buffer_ordered_messages(
2084        this: WeakModelHandle<Self>,
2085        rx: UnboundedReceiver<BufferOrderedMessage>,
2086        mut cx: AsyncAppContext,
2087    ) -> Option<()> {
2088        const MAX_BATCH_SIZE: usize = 128;
2089
2090        let mut operations_by_buffer_id = HashMap::default();
2091        async fn flush_operations(
2092            this: &ModelHandle<Project>,
2093            operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
2094            needs_resync_with_host: &mut bool,
2095            is_local: bool,
2096            cx: &AsyncAppContext,
2097        ) {
2098            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2099                let request = this.read_with(cx, |this, _| {
2100                    let project_id = this.remote_id()?;
2101                    Some(this.client.request(proto::UpdateBuffer {
2102                        buffer_id,
2103                        project_id,
2104                        operations,
2105                    }))
2106                });
2107                if let Some(request) = request {
2108                    if request.await.is_err() && !is_local {
2109                        *needs_resync_with_host = true;
2110                        break;
2111                    }
2112                }
2113            }
2114        }
2115
2116        let mut needs_resync_with_host = false;
2117        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2118
2119        while let Some(changes) = changes.next().await {
2120            let this = this.upgrade(&mut cx)?;
2121            let is_local = this.read_with(&cx, |this, _| this.is_local());
2122
2123            for change in changes {
2124                match change {
2125                    BufferOrderedMessage::Operation {
2126                        buffer_id,
2127                        operation,
2128                    } => {
2129                        if needs_resync_with_host {
2130                            continue;
2131                        }
2132
2133                        operations_by_buffer_id
2134                            .entry(buffer_id)
2135                            .or_insert(Vec::new())
2136                            .push(operation);
2137                    }
2138
2139                    BufferOrderedMessage::Resync => {
2140                        operations_by_buffer_id.clear();
2141                        if this
2142                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
2143                            .await
2144                            .is_ok()
2145                        {
2146                            needs_resync_with_host = false;
2147                        }
2148                    }
2149
2150                    BufferOrderedMessage::LanguageServerUpdate {
2151                        language_server_id,
2152                        message,
2153                    } => {
2154                        flush_operations(
2155                            &this,
2156                            &mut operations_by_buffer_id,
2157                            &mut needs_resync_with_host,
2158                            is_local,
2159                            &cx,
2160                        )
2161                        .await;
2162
2163                        this.read_with(&cx, |this, _| {
2164                            if let Some(project_id) = this.remote_id() {
2165                                this.client
2166                                    .send(proto::UpdateLanguageServer {
2167                                        project_id,
2168                                        language_server_id: language_server_id.0 as u64,
2169                                        variant: Some(message),
2170                                    })
2171                                    .log_err();
2172                            }
2173                        });
2174                    }
2175                }
2176            }
2177
2178            flush_operations(
2179                &this,
2180                &mut operations_by_buffer_id,
2181                &mut needs_resync_with_host,
2182                is_local,
2183                &cx,
2184            )
2185            .await;
2186        }
2187
2188        None
2189    }
2190
2191    fn on_buffer_event(
2192        &mut self,
2193        buffer: ModelHandle<Buffer>,
2194        event: &BufferEvent,
2195        cx: &mut ModelContext<Self>,
2196    ) -> Option<()> {
2197        if matches!(
2198            event,
2199            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2200        ) {
2201            self.request_buffer_diff_recalculation(&buffer, cx);
2202        }
2203
2204        match event {
2205            BufferEvent::Operation(operation) => {
2206                self.buffer_ordered_messages_tx
2207                    .unbounded_send(BufferOrderedMessage::Operation {
2208                        buffer_id: buffer.read(cx).remote_id(),
2209                        operation: language::proto::serialize_operation(operation),
2210                    })
2211                    .ok();
2212            }
2213
2214            BufferEvent::Edited { .. } => {
2215                let buffer = buffer.read(cx);
2216                let file = File::from_dyn(buffer.file())?;
2217                let abs_path = file.as_local()?.abs_path(cx);
2218                let uri = lsp::Url::from_file_path(abs_path).unwrap();
2219                let next_snapshot = buffer.text_snapshot();
2220
2221                let language_servers: Vec<_> = self
2222                    .language_servers_for_buffer(buffer, cx)
2223                    .map(|i| i.1.clone())
2224                    .collect();
2225
2226                for language_server in language_servers {
2227                    let language_server = language_server.clone();
2228
2229                    let buffer_snapshots = self
2230                        .buffer_snapshots
2231                        .get_mut(&buffer.remote_id())
2232                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
2233                    let previous_snapshot = buffer_snapshots.last()?;
2234                    let next_version = previous_snapshot.version + 1;
2235
2236                    let content_changes = buffer
2237                        .edits_since::<(PointUtf16, usize)>(previous_snapshot.snapshot.version())
2238                        .map(|edit| {
2239                            let edit_start = edit.new.start.0;
2240                            let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2241                            let new_text = next_snapshot
2242                                .text_for_range(edit.new.start.1..edit.new.end.1)
2243                                .collect();
2244                            lsp::TextDocumentContentChangeEvent {
2245                                range: Some(lsp::Range::new(
2246                                    point_to_lsp(edit_start),
2247                                    point_to_lsp(edit_end),
2248                                )),
2249                                range_length: None,
2250                                text: new_text,
2251                            }
2252                        })
2253                        .collect();
2254
2255                    buffer_snapshots.push(LspBufferSnapshot {
2256                        version: next_version,
2257                        snapshot: next_snapshot.clone(),
2258                    });
2259
2260                    language_server
2261                        .notify::<lsp::notification::DidChangeTextDocument>(
2262                            lsp::DidChangeTextDocumentParams {
2263                                text_document: lsp::VersionedTextDocumentIdentifier::new(
2264                                    uri.clone(),
2265                                    next_version,
2266                                ),
2267                                content_changes,
2268                            },
2269                        )
2270                        .log_err();
2271                }
2272            }
2273
2274            BufferEvent::Saved => {
2275                let file = File::from_dyn(buffer.read(cx).file())?;
2276                let worktree_id = file.worktree_id(cx);
2277                let abs_path = file.as_local()?.abs_path(cx);
2278                let text_document = lsp::TextDocumentIdentifier {
2279                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
2280                };
2281
2282                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2283                    server
2284                        .notify::<lsp::notification::DidSaveTextDocument>(
2285                            lsp::DidSaveTextDocumentParams {
2286                                text_document: text_document.clone(),
2287                                text: None,
2288                            },
2289                        )
2290                        .log_err();
2291                }
2292
2293                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2294                for language_server_id in language_server_ids {
2295                    if let Some(LanguageServerState::Running {
2296                        adapter,
2297                        simulate_disk_based_diagnostics_completion,
2298                        ..
2299                    }) = self.language_servers.get_mut(&language_server_id)
2300                    {
2301                        // After saving a buffer using a language server that doesn't provide
2302                        // a disk-based progress token, kick off a timer that will reset every
2303                        // time the buffer is saved. If the timer eventually fires, simulate
2304                        // disk-based diagnostics being finished so that other pieces of UI
2305                        // (e.g., project diagnostics view, diagnostic status bar) can update.
2306                        // We don't emit an event right away because the language server might take
2307                        // some time to publish diagnostics.
2308                        if adapter.disk_based_diagnostics_progress_token.is_none() {
2309                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2310                                Duration::from_secs(1);
2311
2312                            let task = cx.spawn_weak(|this, mut cx| async move {
2313                                cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2314                                if let Some(this) = this.upgrade(&cx) {
2315                                    this.update(&mut cx, |this, cx| {
2316                                        this.disk_based_diagnostics_finished(
2317                                            language_server_id,
2318                                            cx,
2319                                        );
2320                                        this.buffer_ordered_messages_tx
2321                                            .unbounded_send(
2322                                                BufferOrderedMessage::LanguageServerUpdate {
2323                                                    language_server_id,
2324                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2325                                                },
2326                                            )
2327                                            .ok();
2328                                    });
2329                                }
2330                            });
2331                            *simulate_disk_based_diagnostics_completion = Some(task);
2332                        }
2333                    }
2334                }
2335            }
2336
2337            _ => {}
2338        }
2339
2340        None
2341    }
2342
2343    fn request_buffer_diff_recalculation(
2344        &mut self,
2345        buffer: &ModelHandle<Buffer>,
2346        cx: &mut ModelContext<Self>,
2347    ) {
2348        self.buffers_needing_diff.insert(buffer.downgrade());
2349        let first_insertion = self.buffers_needing_diff.len() == 1;
2350
2351        let settings = settings::get::<ProjectSettings>(cx);
2352        let delay = if let Some(delay) = settings.git.gutter_debounce {
2353            delay
2354        } else {
2355            if first_insertion {
2356                let this = cx.weak_handle();
2357                cx.defer(move |cx| {
2358                    if let Some(this) = this.upgrade(cx) {
2359                        this.update(cx, |this, cx| {
2360                            this.recalculate_buffer_diffs(cx).detach();
2361                        });
2362                    }
2363                });
2364            }
2365            return;
2366        };
2367
2368        const MIN_DELAY: u64 = 50;
2369        let delay = delay.max(MIN_DELAY);
2370        let duration = Duration::from_millis(delay);
2371
2372        self.git_diff_debouncer
2373            .fire_new(duration, cx, move |this, cx| {
2374                this.recalculate_buffer_diffs(cx)
2375            });
2376    }
2377
2378    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2379        cx.spawn(|this, mut cx| async move {
2380            let buffers: Vec<_> = this.update(&mut cx, |this, _| {
2381                this.buffers_needing_diff.drain().collect()
2382            });
2383
2384            let tasks: Vec<_> = this.update(&mut cx, |_, cx| {
2385                buffers
2386                    .iter()
2387                    .filter_map(|buffer| {
2388                        let buffer = buffer.upgrade(cx)?;
2389                        buffer.update(cx, |buffer, cx| buffer.git_diff_recalc(cx))
2390                    })
2391                    .collect()
2392            });
2393
2394            futures::future::join_all(tasks).await;
2395
2396            this.update(&mut cx, |this, cx| {
2397                if !this.buffers_needing_diff.is_empty() {
2398                    this.recalculate_buffer_diffs(cx).detach();
2399                } else {
2400                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2401                    for buffer in buffers {
2402                        if let Some(buffer) = buffer.upgrade(cx) {
2403                            buffer.update(cx, |_, cx| cx.notify());
2404                        }
2405                    }
2406                }
2407            });
2408        })
2409    }
2410
2411    fn language_servers_for_worktree(
2412        &self,
2413        worktree_id: WorktreeId,
2414    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2415        self.language_server_ids
2416            .iter()
2417            .filter_map(move |((language_server_worktree_id, _), id)| {
2418                if *language_server_worktree_id == worktree_id {
2419                    if let Some(LanguageServerState::Running {
2420                        adapter,
2421                        language,
2422                        server,
2423                        ..
2424                    }) = self.language_servers.get(id)
2425                    {
2426                        return Some((adapter, language, server));
2427                    }
2428                }
2429                None
2430            })
2431    }
2432
2433    fn maintain_buffer_languages(
2434        languages: Arc<LanguageRegistry>,
2435        cx: &mut ModelContext<Project>,
2436    ) -> Task<()> {
2437        let mut subscription = languages.subscribe();
2438        let mut prev_reload_count = languages.reload_count();
2439        cx.spawn_weak(|project, mut cx| async move {
2440            while let Some(()) = subscription.next().await {
2441                if let Some(project) = project.upgrade(&cx) {
2442                    // If the language registry has been reloaded, then remove and
2443                    // re-assign the languages on all open buffers.
2444                    let reload_count = languages.reload_count();
2445                    if reload_count > prev_reload_count {
2446                        prev_reload_count = reload_count;
2447                        project.update(&mut cx, |this, cx| {
2448                            let buffers = this
2449                                .opened_buffers
2450                                .values()
2451                                .filter_map(|b| b.upgrade(cx))
2452                                .collect::<Vec<_>>();
2453                            for buffer in buffers {
2454                                if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned() {
2455                                    this.unregister_buffer_from_language_servers(&buffer, &f, cx);
2456                                    buffer.update(cx, |buffer, cx| buffer.set_language(None, cx));
2457                                }
2458                            }
2459                        });
2460                    }
2461
2462                    project.update(&mut cx, |project, cx| {
2463                        let mut plain_text_buffers = Vec::new();
2464                        let mut buffers_with_unknown_injections = Vec::new();
2465                        for buffer in project.opened_buffers.values() {
2466                            if let Some(handle) = buffer.upgrade(cx) {
2467                                let buffer = &handle.read(cx);
2468                                if buffer.language().is_none()
2469                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
2470                                {
2471                                    plain_text_buffers.push(handle);
2472                                } else if buffer.contains_unknown_injections() {
2473                                    buffers_with_unknown_injections.push(handle);
2474                                }
2475                            }
2476                        }
2477
2478                        for buffer in plain_text_buffers {
2479                            project.detect_language_for_buffer(&buffer, cx);
2480                            project.register_buffer_with_language_servers(&buffer, cx);
2481                        }
2482
2483                        for buffer in buffers_with_unknown_injections {
2484                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2485                        }
2486                    });
2487                }
2488            }
2489        })
2490    }
2491
2492    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<()> {
2493        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2494        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2495
2496        let settings_observation = cx.observe_global::<SettingsStore, _>(move |_, _| {
2497            *settings_changed_tx.borrow_mut() = ();
2498        });
2499
2500        cx.spawn_weak(|this, mut cx| async move {
2501            while let Some(_) = settings_changed_rx.next().await {
2502                let Some(this) = this.upgrade(&cx) else {
2503                    break;
2504                };
2505
2506                let servers: Vec<_> = this.read_with(&cx, |this, _| {
2507                    this.language_servers
2508                        .values()
2509                        .filter_map(|state| match state {
2510                            LanguageServerState::Starting(_) => None,
2511                            LanguageServerState::Running {
2512                                adapter, server, ..
2513                            } => Some((adapter.clone(), server.clone())),
2514                        })
2515                        .collect()
2516                });
2517
2518                for (adapter, server) in servers {
2519                    let workspace_config =
2520                        cx.update(|cx| adapter.workspace_configuration(cx)).await;
2521                    server
2522                        .notify::<lsp::notification::DidChangeConfiguration>(
2523                            lsp::DidChangeConfigurationParams {
2524                                settings: workspace_config.clone(),
2525                            },
2526                        )
2527                        .ok();
2528                }
2529            }
2530
2531            drop(settings_observation);
2532        })
2533    }
2534
2535    fn detect_language_for_buffer(
2536        &mut self,
2537        buffer_handle: &ModelHandle<Buffer>,
2538        cx: &mut ModelContext<Self>,
2539    ) -> Option<()> {
2540        // If the buffer has a language, set it and start the language server if we haven't already.
2541        let buffer = buffer_handle.read(cx);
2542        let full_path = buffer.file()?.full_path(cx);
2543        let content = buffer.as_rope();
2544        let new_language = self
2545            .languages
2546            .language_for_file(&full_path, Some(content))
2547            .now_or_never()?
2548            .ok()?;
2549        self.set_language_for_buffer(buffer_handle, new_language, cx);
2550        None
2551    }
2552
2553    pub fn set_language_for_buffer(
2554        &mut self,
2555        buffer: &ModelHandle<Buffer>,
2556        new_language: Arc<Language>,
2557        cx: &mut ModelContext<Self>,
2558    ) {
2559        buffer.update(cx, |buffer, cx| {
2560            if buffer.language().map_or(true, |old_language| {
2561                !Arc::ptr_eq(old_language, &new_language)
2562            }) {
2563                buffer.set_language(Some(new_language.clone()), cx);
2564            }
2565        });
2566
2567        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2568            let worktree = file.worktree.clone();
2569            if let Some(tree) = worktree.read(cx).as_local() {
2570                self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2571            }
2572        }
2573    }
2574
2575    fn start_language_servers(
2576        &mut self,
2577        worktree: &ModelHandle<Worktree>,
2578        worktree_path: Arc<Path>,
2579        language: Arc<Language>,
2580        cx: &mut ModelContext<Self>,
2581    ) {
2582        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2583        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2584        if !settings.enable_language_server {
2585            return;
2586        }
2587
2588        let worktree_id = worktree.read(cx).id();
2589        for adapter in language.lsp_adapters() {
2590            self.start_language_server(
2591                worktree_id,
2592                worktree_path.clone(),
2593                adapter.clone(),
2594                language.clone(),
2595                cx,
2596            );
2597        }
2598    }
2599
2600    fn start_language_server(
2601        &mut self,
2602        worktree_id: WorktreeId,
2603        worktree_path: Arc<Path>,
2604        adapter: Arc<CachedLspAdapter>,
2605        language: Arc<Language>,
2606        cx: &mut ModelContext<Self>,
2607    ) {
2608        let key = (worktree_id, adapter.name.clone());
2609        if self.language_server_ids.contains_key(&key) {
2610            return;
2611        }
2612
2613        let pending_server = match self.languages.create_pending_language_server(
2614            language.clone(),
2615            adapter.clone(),
2616            worktree_path,
2617            ProjectLspAdapterDelegate::new(self, cx),
2618            cx,
2619        ) {
2620            Some(pending_server) => pending_server,
2621            None => return,
2622        };
2623
2624        let project_settings = settings::get::<ProjectSettings>(cx);
2625        let lsp = project_settings.lsp.get(&adapter.name.0);
2626        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2627
2628        let mut initialization_options = adapter.initialization_options.clone();
2629        match (&mut initialization_options, override_options) {
2630            (Some(initialization_options), Some(override_options)) => {
2631                merge_json_value_into(override_options, initialization_options);
2632            }
2633            (None, override_options) => initialization_options = override_options,
2634            _ => {}
2635        }
2636
2637        let server_id = pending_server.server_id;
2638        let container_dir = pending_server.container_dir.clone();
2639        let state = LanguageServerState::Starting({
2640            let adapter = adapter.clone();
2641            let server_name = adapter.name.0.clone();
2642            let language = language.clone();
2643            let key = key.clone();
2644
2645            cx.spawn_weak(|this, mut cx| async move {
2646                let result = Self::setup_and_insert_language_server(
2647                    this,
2648                    initialization_options,
2649                    pending_server,
2650                    adapter.clone(),
2651                    language.clone(),
2652                    server_id,
2653                    key,
2654                    &mut cx,
2655                )
2656                .await;
2657
2658                match result {
2659                    Ok(server) => server,
2660
2661                    Err(err) => {
2662                        log::error!("failed to start language server {:?}: {}", server_name, err);
2663
2664                        if let Some(this) = this.upgrade(&cx) {
2665                            if let Some(container_dir) = container_dir {
2666                                let installation_test_binary = adapter
2667                                    .installation_test_binary(container_dir.to_path_buf())
2668                                    .await;
2669
2670                                this.update(&mut cx, |_, cx| {
2671                                    Self::check_errored_server(
2672                                        language,
2673                                        adapter,
2674                                        server_id,
2675                                        installation_test_binary,
2676                                        cx,
2677                                    )
2678                                });
2679                            }
2680                        }
2681
2682                        None
2683                    }
2684                }
2685            })
2686        });
2687
2688        self.language_servers.insert(server_id, state);
2689        self.language_server_ids.insert(key, server_id);
2690    }
2691
2692    fn reinstall_language_server(
2693        &mut self,
2694        language: Arc<Language>,
2695        adapter: Arc<CachedLspAdapter>,
2696        server_id: LanguageServerId,
2697        cx: &mut ModelContext<Self>,
2698    ) -> Option<Task<()>> {
2699        log::info!("beginning to reinstall server");
2700
2701        let existing_server = match self.language_servers.remove(&server_id) {
2702            Some(LanguageServerState::Running { server, .. }) => Some(server),
2703            _ => None,
2704        };
2705
2706        for worktree in &self.worktrees {
2707            if let Some(worktree) = worktree.upgrade(cx) {
2708                let key = (worktree.read(cx).id(), adapter.name.clone());
2709                self.language_server_ids.remove(&key);
2710            }
2711        }
2712
2713        Some(cx.spawn(move |this, mut cx| async move {
2714            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2715                log::info!("shutting down existing server");
2716                task.await;
2717            }
2718
2719            // TODO: This is race-safe with regards to preventing new instances from
2720            // starting while deleting, but existing instances in other projects are going
2721            // to be very confused and messed up
2722            this.update(&mut cx, |this, cx| {
2723                this.languages.delete_server_container(adapter.clone(), cx)
2724            })
2725            .await;
2726
2727            this.update(&mut cx, |this, mut cx| {
2728                let worktrees = this.worktrees.clone();
2729                for worktree in worktrees {
2730                    let worktree = match worktree.upgrade(cx) {
2731                        Some(worktree) => worktree.read(cx),
2732                        None => continue,
2733                    };
2734                    let worktree_id = worktree.id();
2735                    let root_path = worktree.abs_path();
2736
2737                    this.start_language_server(
2738                        worktree_id,
2739                        root_path,
2740                        adapter.clone(),
2741                        language.clone(),
2742                        &mut cx,
2743                    );
2744                }
2745            })
2746        }))
2747    }
2748
2749    async fn setup_and_insert_language_server(
2750        this: WeakModelHandle<Self>,
2751        initialization_options: Option<serde_json::Value>,
2752        pending_server: PendingLanguageServer,
2753        adapter: Arc<CachedLspAdapter>,
2754        language: Arc<Language>,
2755        server_id: LanguageServerId,
2756        key: (WorktreeId, LanguageServerName),
2757        cx: &mut AsyncAppContext,
2758    ) -> Result<Option<Arc<LanguageServer>>> {
2759        let setup = Self::setup_pending_language_server(
2760            this,
2761            initialization_options,
2762            pending_server,
2763            adapter.clone(),
2764            server_id,
2765            cx,
2766        );
2767
2768        let language_server = match setup.await? {
2769            Some(language_server) => language_server,
2770            None => return Ok(None),
2771        };
2772        let this = match this.upgrade(cx) {
2773            Some(this) => this,
2774            None => return Err(anyhow!("failed to upgrade project handle")),
2775        };
2776
2777        this.update(cx, |this, cx| {
2778            this.insert_newly_running_language_server(
2779                language,
2780                adapter,
2781                language_server.clone(),
2782                server_id,
2783                key,
2784                cx,
2785            )
2786        })?;
2787
2788        Ok(Some(language_server))
2789    }
2790
2791    async fn setup_pending_language_server(
2792        this: WeakModelHandle<Self>,
2793        initialization_options: Option<serde_json::Value>,
2794        pending_server: PendingLanguageServer,
2795        adapter: Arc<CachedLspAdapter>,
2796        server_id: LanguageServerId,
2797        cx: &mut AsyncAppContext,
2798    ) -> Result<Option<Arc<LanguageServer>>> {
2799        let workspace_config = cx.update(|cx| adapter.workspace_configuration(cx)).await;
2800        let language_server = match pending_server.task.await? {
2801            Some(server) => server,
2802            None => return Ok(None),
2803        };
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 position = position.to_point_utf16(buffer.read(cx));
4500        if self.is_local() {
4501            let snapshot = buffer.read(cx).snapshot();
4502            let offset = position.to_offset(&snapshot);
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        } else if let Some(project_id) = self.remote_id() {
4541            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4542        } else {
4543            Task::ready(Ok(Default::default()))
4544        }
4545    }
4546
4547    pub fn apply_additional_edits_for_completion(
4548        &self,
4549        buffer_handle: ModelHandle<Buffer>,
4550        completion: Completion,
4551        push_to_history: bool,
4552        cx: &mut ModelContext<Self>,
4553    ) -> Task<Result<Option<Transaction>>> {
4554        let buffer = buffer_handle.read(cx);
4555        let buffer_id = buffer.remote_id();
4556
4557        if self.is_local() {
4558            let server_id = completion.server_id;
4559            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4560                Some((_, server)) => server.clone(),
4561                _ => return Task::ready(Ok(Default::default())),
4562            };
4563
4564            cx.spawn(|this, mut cx| async move {
4565                let can_resolve = lang_server
4566                    .capabilities()
4567                    .completion_provider
4568                    .as_ref()
4569                    .and_then(|options| options.resolve_provider)
4570                    .unwrap_or(false);
4571                let additional_text_edits = if can_resolve {
4572                    lang_server
4573                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4574                        .await?
4575                        .additional_text_edits
4576                } else {
4577                    completion.lsp_completion.additional_text_edits
4578                };
4579                if let Some(edits) = additional_text_edits {
4580                    let edits = this
4581                        .update(&mut cx, |this, cx| {
4582                            this.edits_from_lsp(
4583                                &buffer_handle,
4584                                edits,
4585                                lang_server.server_id(),
4586                                None,
4587                                cx,
4588                            )
4589                        })
4590                        .await?;
4591
4592                    buffer_handle.update(&mut cx, |buffer, cx| {
4593                        buffer.finalize_last_transaction();
4594                        buffer.start_transaction();
4595
4596                        for (range, text) in edits {
4597                            let primary = &completion.old_range;
4598                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4599                                && primary.end.cmp(&range.start, buffer).is_ge();
4600                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4601                                && range.end.cmp(&primary.end, buffer).is_ge();
4602
4603                            //Skip additional edits which overlap with the primary completion edit
4604                            //https://github.com/zed-industries/zed/pull/1871
4605                            if !start_within && !end_within {
4606                                buffer.edit([(range, text)], None, cx);
4607                            }
4608                        }
4609
4610                        let transaction = if buffer.end_transaction(cx).is_some() {
4611                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4612                            if !push_to_history {
4613                                buffer.forget_transaction(transaction.id);
4614                            }
4615                            Some(transaction)
4616                        } else {
4617                            None
4618                        };
4619                        Ok(transaction)
4620                    })
4621                } else {
4622                    Ok(None)
4623                }
4624            })
4625        } else if let Some(project_id) = self.remote_id() {
4626            let client = self.client.clone();
4627            cx.spawn(|_, mut cx| async move {
4628                let response = client
4629                    .request(proto::ApplyCompletionAdditionalEdits {
4630                        project_id,
4631                        buffer_id,
4632                        completion: Some(language::proto::serialize_completion(&completion)),
4633                    })
4634                    .await?;
4635
4636                if let Some(transaction) = response.transaction {
4637                    let transaction = language::proto::deserialize_transaction(transaction)?;
4638                    buffer_handle
4639                        .update(&mut cx, |buffer, _| {
4640                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4641                        })
4642                        .await?;
4643                    if push_to_history {
4644                        buffer_handle.update(&mut cx, |buffer, _| {
4645                            buffer.push_transaction(transaction.clone(), Instant::now());
4646                        });
4647                    }
4648                    Ok(Some(transaction))
4649                } else {
4650                    Ok(None)
4651                }
4652            })
4653        } else {
4654            Task::ready(Err(anyhow!("project does not have a remote id")))
4655        }
4656    }
4657
4658    pub fn code_actions<T: Clone + ToOffset>(
4659        &self,
4660        buffer_handle: &ModelHandle<Buffer>,
4661        range: Range<T>,
4662        cx: &mut ModelContext<Self>,
4663    ) -> Task<Result<Vec<CodeAction>>> {
4664        let buffer = buffer_handle.read(cx);
4665        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4666        self.request_lsp(
4667            buffer_handle.clone(),
4668            LanguageServerToQuery::Primary,
4669            GetCodeActions { range },
4670            cx,
4671        )
4672    }
4673
4674    pub fn apply_code_action(
4675        &self,
4676        buffer_handle: ModelHandle<Buffer>,
4677        mut action: CodeAction,
4678        push_to_history: bool,
4679        cx: &mut ModelContext<Self>,
4680    ) -> Task<Result<ProjectTransaction>> {
4681        if self.is_local() {
4682            let buffer = buffer_handle.read(cx);
4683            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4684                self.language_server_for_buffer(buffer, action.server_id, cx)
4685            {
4686                (adapter.clone(), server.clone())
4687            } else {
4688                return Task::ready(Ok(Default::default()));
4689            };
4690            let range = action.range.to_point_utf16(buffer);
4691
4692            cx.spawn(|this, mut cx| async move {
4693                if let Some(lsp_range) = action
4694                    .lsp_action
4695                    .data
4696                    .as_mut()
4697                    .and_then(|d| d.get_mut("codeActionParams"))
4698                    .and_then(|d| d.get_mut("range"))
4699                {
4700                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4701                    action.lsp_action = lang_server
4702                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4703                        .await?;
4704                } else {
4705                    let actions = this
4706                        .update(&mut cx, |this, cx| {
4707                            this.code_actions(&buffer_handle, action.range, cx)
4708                        })
4709                        .await?;
4710                    action.lsp_action = actions
4711                        .into_iter()
4712                        .find(|a| a.lsp_action.title == action.lsp_action.title)
4713                        .ok_or_else(|| anyhow!("code action is outdated"))?
4714                        .lsp_action;
4715                }
4716
4717                if let Some(edit) = action.lsp_action.edit {
4718                    if edit.changes.is_some() || edit.document_changes.is_some() {
4719                        return Self::deserialize_workspace_edit(
4720                            this,
4721                            edit,
4722                            push_to_history,
4723                            lsp_adapter.clone(),
4724                            lang_server.clone(),
4725                            &mut cx,
4726                        )
4727                        .await;
4728                    }
4729                }
4730
4731                if let Some(command) = action.lsp_action.command {
4732                    this.update(&mut cx, |this, _| {
4733                        this.last_workspace_edits_by_language_server
4734                            .remove(&lang_server.server_id());
4735                    });
4736
4737                    let result = lang_server
4738                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4739                            command: command.command,
4740                            arguments: command.arguments.unwrap_or_default(),
4741                            ..Default::default()
4742                        })
4743                        .await;
4744
4745                    if let Err(err) = result {
4746                        // TODO: LSP ERROR
4747                        return Err(err);
4748                    }
4749
4750                    return Ok(this.update(&mut cx, |this, _| {
4751                        this.last_workspace_edits_by_language_server
4752                            .remove(&lang_server.server_id())
4753                            .unwrap_or_default()
4754                    }));
4755                }
4756
4757                Ok(ProjectTransaction::default())
4758            })
4759        } else if let Some(project_id) = self.remote_id() {
4760            let client = self.client.clone();
4761            let request = proto::ApplyCodeAction {
4762                project_id,
4763                buffer_id: buffer_handle.read(cx).remote_id(),
4764                action: Some(language::proto::serialize_code_action(&action)),
4765            };
4766            cx.spawn(|this, mut cx| async move {
4767                let response = client
4768                    .request(request)
4769                    .await?
4770                    .transaction
4771                    .ok_or_else(|| anyhow!("missing transaction"))?;
4772                this.update(&mut cx, |this, cx| {
4773                    this.deserialize_project_transaction(response, push_to_history, cx)
4774                })
4775                .await
4776            })
4777        } else {
4778            Task::ready(Err(anyhow!("project does not have a remote id")))
4779        }
4780    }
4781
4782    fn apply_on_type_formatting(
4783        &self,
4784        buffer: ModelHandle<Buffer>,
4785        position: Anchor,
4786        trigger: String,
4787        cx: &mut ModelContext<Self>,
4788    ) -> Task<Result<Option<Transaction>>> {
4789        if self.is_local() {
4790            cx.spawn(|this, mut cx| async move {
4791                // Do not allow multiple concurrent formatting requests for the
4792                // same buffer.
4793                this.update(&mut cx, |this, cx| {
4794                    this.buffers_being_formatted
4795                        .insert(buffer.read(cx).remote_id())
4796                });
4797
4798                let _cleanup = defer({
4799                    let this = this.clone();
4800                    let mut cx = cx.clone();
4801                    let closure_buffer = buffer.clone();
4802                    move || {
4803                        this.update(&mut cx, |this, cx| {
4804                            this.buffers_being_formatted
4805                                .remove(&closure_buffer.read(cx).remote_id());
4806                        });
4807                    }
4808                });
4809
4810                buffer
4811                    .update(&mut cx, |buffer, _| {
4812                        buffer.wait_for_edits(Some(position.timestamp))
4813                    })
4814                    .await?;
4815                this.update(&mut cx, |this, cx| {
4816                    let position = position.to_point_utf16(buffer.read(cx));
4817                    this.on_type_format(buffer, position, trigger, false, cx)
4818                })
4819                .await
4820            })
4821        } else if let Some(project_id) = self.remote_id() {
4822            let client = self.client.clone();
4823            let request = proto::OnTypeFormatting {
4824                project_id,
4825                buffer_id: buffer.read(cx).remote_id(),
4826                position: Some(serialize_anchor(&position)),
4827                trigger,
4828                version: serialize_version(&buffer.read(cx).version()),
4829            };
4830            cx.spawn(|_, _| async move {
4831                client
4832                    .request(request)
4833                    .await?
4834                    .transaction
4835                    .map(language::proto::deserialize_transaction)
4836                    .transpose()
4837            })
4838        } else {
4839            Task::ready(Err(anyhow!("project does not have a remote id")))
4840        }
4841    }
4842
4843    async fn deserialize_edits(
4844        this: ModelHandle<Self>,
4845        buffer_to_edit: ModelHandle<Buffer>,
4846        edits: Vec<lsp::TextEdit>,
4847        push_to_history: bool,
4848        _: Arc<CachedLspAdapter>,
4849        language_server: Arc<LanguageServer>,
4850        cx: &mut AsyncAppContext,
4851    ) -> Result<Option<Transaction>> {
4852        let edits = this
4853            .update(cx, |this, cx| {
4854                this.edits_from_lsp(
4855                    &buffer_to_edit,
4856                    edits,
4857                    language_server.server_id(),
4858                    None,
4859                    cx,
4860                )
4861            })
4862            .await?;
4863
4864        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4865            buffer.finalize_last_transaction();
4866            buffer.start_transaction();
4867            for (range, text) in edits {
4868                buffer.edit([(range, text)], None, cx);
4869            }
4870
4871            if buffer.end_transaction(cx).is_some() {
4872                let transaction = buffer.finalize_last_transaction().unwrap().clone();
4873                if !push_to_history {
4874                    buffer.forget_transaction(transaction.id);
4875                }
4876                Some(transaction)
4877            } else {
4878                None
4879            }
4880        });
4881
4882        Ok(transaction)
4883    }
4884
4885    async fn deserialize_workspace_edit(
4886        this: ModelHandle<Self>,
4887        edit: lsp::WorkspaceEdit,
4888        push_to_history: bool,
4889        lsp_adapter: Arc<CachedLspAdapter>,
4890        language_server: Arc<LanguageServer>,
4891        cx: &mut AsyncAppContext,
4892    ) -> Result<ProjectTransaction> {
4893        let fs = this.read_with(cx, |this, _| this.fs.clone());
4894        let mut operations = Vec::new();
4895        if let Some(document_changes) = edit.document_changes {
4896            match document_changes {
4897                lsp::DocumentChanges::Edits(edits) => {
4898                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4899                }
4900                lsp::DocumentChanges::Operations(ops) => operations = ops,
4901            }
4902        } else if let Some(changes) = edit.changes {
4903            operations.extend(changes.into_iter().map(|(uri, edits)| {
4904                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4905                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4906                        uri,
4907                        version: None,
4908                    },
4909                    edits: edits.into_iter().map(OneOf::Left).collect(),
4910                })
4911            }));
4912        }
4913
4914        let mut project_transaction = ProjectTransaction::default();
4915        for operation in operations {
4916            match operation {
4917                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4918                    let abs_path = op
4919                        .uri
4920                        .to_file_path()
4921                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4922
4923                    if let Some(parent_path) = abs_path.parent() {
4924                        fs.create_dir(parent_path).await?;
4925                    }
4926                    if abs_path.ends_with("/") {
4927                        fs.create_dir(&abs_path).await?;
4928                    } else {
4929                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4930                            .await?;
4931                    }
4932                }
4933
4934                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4935                    let source_abs_path = op
4936                        .old_uri
4937                        .to_file_path()
4938                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4939                    let target_abs_path = op
4940                        .new_uri
4941                        .to_file_path()
4942                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4943                    fs.rename(
4944                        &source_abs_path,
4945                        &target_abs_path,
4946                        op.options.map(Into::into).unwrap_or_default(),
4947                    )
4948                    .await?;
4949                }
4950
4951                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4952                    let abs_path = op
4953                        .uri
4954                        .to_file_path()
4955                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4956                    let options = op.options.map(Into::into).unwrap_or_default();
4957                    if abs_path.ends_with("/") {
4958                        fs.remove_dir(&abs_path, options).await?;
4959                    } else {
4960                        fs.remove_file(&abs_path, options).await?;
4961                    }
4962                }
4963
4964                lsp::DocumentChangeOperation::Edit(op) => {
4965                    let buffer_to_edit = this
4966                        .update(cx, |this, cx| {
4967                            this.open_local_buffer_via_lsp(
4968                                op.text_document.uri,
4969                                language_server.server_id(),
4970                                lsp_adapter.name.clone(),
4971                                cx,
4972                            )
4973                        })
4974                        .await?;
4975
4976                    let edits = this
4977                        .update(cx, |this, cx| {
4978                            let edits = op.edits.into_iter().map(|edit| match edit {
4979                                OneOf::Left(edit) => edit,
4980                                OneOf::Right(edit) => edit.text_edit,
4981                            });
4982                            this.edits_from_lsp(
4983                                &buffer_to_edit,
4984                                edits,
4985                                language_server.server_id(),
4986                                op.text_document.version,
4987                                cx,
4988                            )
4989                        })
4990                        .await?;
4991
4992                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4993                        buffer.finalize_last_transaction();
4994                        buffer.start_transaction();
4995                        for (range, text) in edits {
4996                            buffer.edit([(range, text)], None, cx);
4997                        }
4998                        let transaction = if buffer.end_transaction(cx).is_some() {
4999                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5000                            if !push_to_history {
5001                                buffer.forget_transaction(transaction.id);
5002                            }
5003                            Some(transaction)
5004                        } else {
5005                            None
5006                        };
5007
5008                        transaction
5009                    });
5010                    if let Some(transaction) = transaction {
5011                        project_transaction.0.insert(buffer_to_edit, transaction);
5012                    }
5013                }
5014            }
5015        }
5016
5017        Ok(project_transaction)
5018    }
5019
5020    pub fn prepare_rename<T: ToPointUtf16>(
5021        &self,
5022        buffer: ModelHandle<Buffer>,
5023        position: T,
5024        cx: &mut ModelContext<Self>,
5025    ) -> Task<Result<Option<Range<Anchor>>>> {
5026        let position = position.to_point_utf16(buffer.read(cx));
5027        self.request_lsp(
5028            buffer,
5029            LanguageServerToQuery::Primary,
5030            PrepareRename { position },
5031            cx,
5032        )
5033    }
5034
5035    pub fn perform_rename<T: ToPointUtf16>(
5036        &self,
5037        buffer: ModelHandle<Buffer>,
5038        position: T,
5039        new_name: String,
5040        push_to_history: bool,
5041        cx: &mut ModelContext<Self>,
5042    ) -> Task<Result<ProjectTransaction>> {
5043        let position = position.to_point_utf16(buffer.read(cx));
5044        self.request_lsp(
5045            buffer,
5046            LanguageServerToQuery::Primary,
5047            PerformRename {
5048                position,
5049                new_name,
5050                push_to_history,
5051            },
5052            cx,
5053        )
5054    }
5055
5056    pub fn on_type_format<T: ToPointUtf16>(
5057        &self,
5058        buffer: ModelHandle<Buffer>,
5059        position: T,
5060        trigger: String,
5061        push_to_history: bool,
5062        cx: &mut ModelContext<Self>,
5063    ) -> Task<Result<Option<Transaction>>> {
5064        let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
5065            let position = position.to_point_utf16(buffer);
5066            (
5067                position,
5068                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5069                    .tab_size,
5070            )
5071        });
5072        self.request_lsp(
5073            buffer.clone(),
5074            LanguageServerToQuery::Primary,
5075            OnTypeFormatting {
5076                position,
5077                trigger,
5078                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5079                push_to_history,
5080            },
5081            cx,
5082        )
5083    }
5084
5085    pub fn inlay_hints<T: ToOffset>(
5086        &self,
5087        buffer_handle: ModelHandle<Buffer>,
5088        range: Range<T>,
5089        cx: &mut ModelContext<Self>,
5090    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5091        let buffer = buffer_handle.read(cx);
5092        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5093        let range_start = range.start;
5094        let range_end = range.end;
5095        let buffer_id = buffer.remote_id();
5096        let buffer_version = buffer.version().clone();
5097        let lsp_request = InlayHints { range };
5098
5099        if self.is_local() {
5100            let lsp_request_task = self.request_lsp(
5101                buffer_handle.clone(),
5102                LanguageServerToQuery::Primary,
5103                lsp_request,
5104                cx,
5105            );
5106            cx.spawn(|_, mut cx| async move {
5107                buffer_handle
5108                    .update(&mut cx, |buffer, _| {
5109                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5110                    })
5111                    .await
5112                    .context("waiting for inlay hint request range edits")?;
5113                lsp_request_task.await.context("inlay hints LSP request")
5114            })
5115        } else if let Some(project_id) = self.remote_id() {
5116            let client = self.client.clone();
5117            let request = proto::InlayHints {
5118                project_id,
5119                buffer_id,
5120                start: Some(serialize_anchor(&range_start)),
5121                end: Some(serialize_anchor(&range_end)),
5122                version: serialize_version(&buffer_version),
5123            };
5124            cx.spawn(|project, cx| async move {
5125                let response = client
5126                    .request(request)
5127                    .await
5128                    .context("inlay hints proto request")?;
5129                let hints_request_result = LspCommand::response_from_proto(
5130                    lsp_request,
5131                    response,
5132                    project,
5133                    buffer_handle.clone(),
5134                    cx,
5135                )
5136                .await;
5137
5138                hints_request_result.context("inlay hints proto response conversion")
5139            })
5140        } else {
5141            Task::ready(Err(anyhow!("project does not have a remote id")))
5142        }
5143    }
5144
5145    pub fn resolve_inlay_hint(
5146        &self,
5147        hint: InlayHint,
5148        buffer_handle: ModelHandle<Buffer>,
5149        server_id: LanguageServerId,
5150        cx: &mut ModelContext<Self>,
5151    ) -> Task<anyhow::Result<InlayHint>> {
5152        if self.is_local() {
5153            let buffer = buffer_handle.read(cx);
5154            let (_, lang_server) = if let Some((adapter, server)) =
5155                self.language_server_for_buffer(buffer, server_id, cx)
5156            {
5157                (adapter.clone(), server.clone())
5158            } else {
5159                return Task::ready(Ok(hint));
5160            };
5161            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5162                return Task::ready(Ok(hint));
5163            }
5164
5165            let buffer_snapshot = buffer.snapshot();
5166            cx.spawn(|_, mut cx| async move {
5167                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5168                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5169                );
5170                let resolved_hint = resolve_task
5171                    .await
5172                    .context("inlay hint resolve LSP request")?;
5173                let resolved_hint = InlayHints::lsp_to_project_hint(
5174                    resolved_hint,
5175                    &buffer_handle,
5176                    server_id,
5177                    ResolveState::Resolved,
5178                    false,
5179                    &mut cx,
5180                )
5181                .await?;
5182                Ok(resolved_hint)
5183            })
5184        } else if let Some(project_id) = self.remote_id() {
5185            let client = self.client.clone();
5186            let request = proto::ResolveInlayHint {
5187                project_id,
5188                buffer_id: buffer_handle.read(cx).remote_id(),
5189                language_server_id: server_id.0 as u64,
5190                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5191            };
5192            cx.spawn(|_, _| async move {
5193                let response = client
5194                    .request(request)
5195                    .await
5196                    .context("inlay hints proto request")?;
5197                match response.hint {
5198                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5199                        .context("inlay hints proto resolve response conversion"),
5200                    None => Ok(hint),
5201                }
5202            })
5203        } else {
5204            Task::ready(Err(anyhow!("project does not have a remote id")))
5205        }
5206    }
5207
5208    #[allow(clippy::type_complexity)]
5209    pub fn search(
5210        &self,
5211        query: SearchQuery,
5212        cx: &mut ModelContext<Self>,
5213    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5214        if self.is_local() {
5215            self.search_local(query, cx)
5216        } else if let Some(project_id) = self.remote_id() {
5217            let (tx, rx) = smol::channel::unbounded();
5218            let request = self.client.request(query.to_proto(project_id));
5219            cx.spawn(|this, mut cx| async move {
5220                let response = request.await?;
5221                let mut result = HashMap::default();
5222                for location in response.locations {
5223                    let target_buffer = this
5224                        .update(&mut cx, |this, cx| {
5225                            this.wait_for_remote_buffer(location.buffer_id, cx)
5226                        })
5227                        .await?;
5228                    let start = location
5229                        .start
5230                        .and_then(deserialize_anchor)
5231                        .ok_or_else(|| anyhow!("missing target start"))?;
5232                    let end = location
5233                        .end
5234                        .and_then(deserialize_anchor)
5235                        .ok_or_else(|| anyhow!("missing target end"))?;
5236                    result
5237                        .entry(target_buffer)
5238                        .or_insert(Vec::new())
5239                        .push(start..end)
5240                }
5241                for (buffer, ranges) in result {
5242                    let _ = tx.send((buffer, ranges)).await;
5243                }
5244                Result::<(), anyhow::Error>::Ok(())
5245            })
5246            .detach_and_log_err(cx);
5247            rx
5248        } else {
5249            unimplemented!();
5250        }
5251    }
5252
5253    pub fn search_local(
5254        &self,
5255        query: SearchQuery,
5256        cx: &mut ModelContext<Self>,
5257    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5258        // Local search is split into several phases.
5259        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5260        // and the second phase that finds positions of all the matches found in the candidate files.
5261        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5262        //
5263        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5264        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5265        //
5266        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5267        //    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
5268        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5269        // 2. At this point, we have a list of all potentially matching buffers/files.
5270        //    We sort that list by buffer path - this list is retained for later use.
5271        //    We ensure that all buffers are now opened and available in project.
5272        // 3. We run a scan over all the candidate buffers on multiple background threads.
5273        //    We cannot assume that there will even be a match - while at least one match
5274        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5275        //    There is also an auxilliary background thread responsible for result gathering.
5276        //    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),
5277        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5278        //    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
5279        //    entry - which might already be available thanks to out-of-order processing.
5280        //
5281        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5282        // 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.
5283        // 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
5284        // in face of constantly updating list of sorted matches.
5285        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5286        let snapshots = self
5287            .visible_worktrees(cx)
5288            .filter_map(|tree| {
5289                let tree = tree.read(cx).as_local()?;
5290                Some(tree.snapshot())
5291            })
5292            .collect::<Vec<_>>();
5293
5294        let background = cx.background().clone();
5295        let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5296        if path_count == 0 {
5297            let (_, rx) = smol::channel::bounded(1024);
5298            return rx;
5299        }
5300        let workers = background.num_cpus().min(path_count);
5301        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5302        let mut unnamed_files = vec![];
5303        let opened_buffers = self
5304            .opened_buffers
5305            .iter()
5306            .filter_map(|(_, b)| {
5307                let buffer = b.upgrade(cx)?;
5308                let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
5309                if let Some(path) = snapshot.file().map(|file| file.path()) {
5310                    Some((path.clone(), (buffer, snapshot)))
5311                } else {
5312                    unnamed_files.push(buffer);
5313                    None
5314                }
5315            })
5316            .collect();
5317        cx.background()
5318            .spawn(Self::background_search(
5319                unnamed_files,
5320                opened_buffers,
5321                cx.background().clone(),
5322                self.fs.clone(),
5323                workers,
5324                query.clone(),
5325                path_count,
5326                snapshots,
5327                matching_paths_tx,
5328            ))
5329            .detach();
5330
5331        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5332        let background = cx.background().clone();
5333        let (result_tx, result_rx) = smol::channel::bounded(1024);
5334        cx.background()
5335            .spawn(async move {
5336                let Ok(buffers) = buffers.await else {
5337                    return;
5338                };
5339
5340                let buffers_len = buffers.len();
5341                if buffers_len == 0 {
5342                    return;
5343                }
5344                let query = &query;
5345                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5346                background
5347                    .scoped(|scope| {
5348                        #[derive(Clone)]
5349                        struct FinishedStatus {
5350                            entry: Option<(ModelHandle<Buffer>, Vec<Range<Anchor>>)>,
5351                            buffer_index: SearchMatchCandidateIndex,
5352                        }
5353
5354                        for _ in 0..workers {
5355                            let finished_tx = finished_tx.clone();
5356                            let mut buffers_rx = buffers_rx.clone();
5357                            scope.spawn(async move {
5358                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5359                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5360                                    {
5361                                        if query.file_matches(
5362                                            snapshot.file().map(|file| file.path().as_ref()),
5363                                        ) {
5364                                            query
5365                                                .search(&snapshot, None)
5366                                                .await
5367                                                .iter()
5368                                                .map(|range| {
5369                                                    snapshot.anchor_before(range.start)
5370                                                        ..snapshot.anchor_after(range.end)
5371                                                })
5372                                                .collect()
5373                                        } else {
5374                                            Vec::new()
5375                                        }
5376                                    } else {
5377                                        Vec::new()
5378                                    };
5379
5380                                    let status = if !buffer_matches.is_empty() {
5381                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5382                                            Some((buffer.clone(), buffer_matches))
5383                                        } else {
5384                                            None
5385                                        };
5386                                        FinishedStatus {
5387                                            entry,
5388                                            buffer_index,
5389                                        }
5390                                    } else {
5391                                        FinishedStatus {
5392                                            entry: None,
5393                                            buffer_index,
5394                                        }
5395                                    };
5396                                    if finished_tx.send(status).await.is_err() {
5397                                        break;
5398                                    }
5399                                }
5400                            });
5401                        }
5402                        // Report sorted matches
5403                        scope.spawn(async move {
5404                            let mut current_index = 0;
5405                            let mut scratch = vec![None; buffers_len];
5406                            while let Some(status) = finished_rx.next().await {
5407                                debug_assert!(
5408                                    scratch[status.buffer_index].is_none(),
5409                                    "Got match status of position {} twice",
5410                                    status.buffer_index
5411                                );
5412                                let index = status.buffer_index;
5413                                scratch[index] = Some(status);
5414                                while current_index < buffers_len {
5415                                    let Some(current_entry) = scratch[current_index].take() else {
5416                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5417                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5418                                        // this time.
5419                                        break;
5420                                    };
5421                                    if let Some(entry) = current_entry.entry {
5422                                        result_tx.send(entry).await.log_err();
5423                                    }
5424                                    current_index += 1;
5425                                }
5426                                if current_index == buffers_len {
5427                                    break;
5428                                }
5429                            }
5430                        });
5431                    })
5432                    .await;
5433            })
5434            .detach();
5435        result_rx
5436    }
5437    /// Pick paths that might potentially contain a match of a given search query.
5438    async fn background_search(
5439        unnamed_buffers: Vec<ModelHandle<Buffer>>,
5440        opened_buffers: HashMap<Arc<Path>, (ModelHandle<Buffer>, BufferSnapshot)>,
5441        background: Arc<Background>,
5442        fs: Arc<dyn Fs>,
5443        workers: usize,
5444        query: SearchQuery,
5445        path_count: usize,
5446        snapshots: Vec<LocalSnapshot>,
5447        matching_paths_tx: Sender<SearchMatchCandidate>,
5448    ) {
5449        let fs = &fs;
5450        let query = &query;
5451        let matching_paths_tx = &matching_paths_tx;
5452        let snapshots = &snapshots;
5453        let paths_per_worker = (path_count + workers - 1) / workers;
5454        for buffer in unnamed_buffers {
5455            matching_paths_tx
5456                .send(SearchMatchCandidate::OpenBuffer {
5457                    buffer: buffer.clone(),
5458                    path: None,
5459                })
5460                .await
5461                .log_err();
5462        }
5463        for (path, (buffer, _)) in opened_buffers.iter() {
5464            matching_paths_tx
5465                .send(SearchMatchCandidate::OpenBuffer {
5466                    buffer: buffer.clone(),
5467                    path: Some(path.clone()),
5468                })
5469                .await
5470                .log_err();
5471        }
5472        background
5473            .scoped(|scope| {
5474                for worker_ix in 0..workers {
5475                    let worker_start_ix = worker_ix * paths_per_worker;
5476                    let worker_end_ix = worker_start_ix + paths_per_worker;
5477                    let unnamed_buffers = opened_buffers.clone();
5478                    scope.spawn(async move {
5479                        let mut snapshot_start_ix = 0;
5480                        let mut abs_path = PathBuf::new();
5481                        for snapshot in snapshots {
5482                            let snapshot_end_ix = snapshot_start_ix + snapshot.visible_file_count();
5483                            if worker_end_ix <= snapshot_start_ix {
5484                                break;
5485                            } else if worker_start_ix > snapshot_end_ix {
5486                                snapshot_start_ix = snapshot_end_ix;
5487                                continue;
5488                            } else {
5489                                let start_in_snapshot =
5490                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5491                                let end_in_snapshot =
5492                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5493
5494                                for entry in snapshot
5495                                    .files(false, start_in_snapshot)
5496                                    .take(end_in_snapshot - start_in_snapshot)
5497                                {
5498                                    if matching_paths_tx.is_closed() {
5499                                        break;
5500                                    }
5501                                    if unnamed_buffers.contains_key(&entry.path) {
5502                                        continue;
5503                                    }
5504                                    let matches = if query.file_matches(Some(&entry.path)) {
5505                                        abs_path.clear();
5506                                        abs_path.push(&snapshot.abs_path());
5507                                        abs_path.push(&entry.path);
5508                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5509                                        {
5510                                            query.detect(file).unwrap_or(false)
5511                                        } else {
5512                                            false
5513                                        }
5514                                    } else {
5515                                        false
5516                                    };
5517
5518                                    if matches {
5519                                        let project_path = SearchMatchCandidate::Path {
5520                                            worktree_id: snapshot.id(),
5521                                            path: entry.path.clone(),
5522                                        };
5523                                        if matching_paths_tx.send(project_path).await.is_err() {
5524                                            break;
5525                                        }
5526                                    }
5527                                }
5528
5529                                snapshot_start_ix = snapshot_end_ix;
5530                            }
5531                        }
5532                    });
5533                }
5534            })
5535            .await;
5536    }
5537
5538    fn request_lsp<R: LspCommand>(
5539        &self,
5540        buffer_handle: ModelHandle<Buffer>,
5541        server: LanguageServerToQuery,
5542        request: R,
5543        cx: &mut ModelContext<Self>,
5544    ) -> Task<Result<R::Response>>
5545    where
5546        <R::LspRequest as lsp::request::Request>::Result: Send,
5547    {
5548        let buffer = buffer_handle.read(cx);
5549        if self.is_local() {
5550            let language_server = match server {
5551                LanguageServerToQuery::Primary => {
5552                    match self.primary_language_server_for_buffer(buffer, cx) {
5553                        Some((_, server)) => Some(Arc::clone(server)),
5554                        None => return Task::ready(Ok(Default::default())),
5555                    }
5556                }
5557                LanguageServerToQuery::Other(id) => self
5558                    .language_server_for_buffer(buffer, id, cx)
5559                    .map(|(_, server)| Arc::clone(server)),
5560            };
5561            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5562            if let (Some(file), Some(language_server)) = (file, language_server) {
5563                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5564                return cx.spawn(|this, cx| async move {
5565                    if !request.check_capabilities(language_server.capabilities()) {
5566                        return Ok(Default::default());
5567                    }
5568
5569                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5570                    let response = match result {
5571                        Ok(response) => response,
5572
5573                        Err(err) => {
5574                            log::warn!(
5575                                "Generic lsp request to {} failed: {}",
5576                                language_server.name(),
5577                                err
5578                            );
5579                            return Err(err);
5580                        }
5581                    };
5582
5583                    request
5584                        .response_from_lsp(
5585                            response,
5586                            this,
5587                            buffer_handle,
5588                            language_server.server_id(),
5589                            cx,
5590                        )
5591                        .await
5592                });
5593            }
5594        } else if let Some(project_id) = self.remote_id() {
5595            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
5596        }
5597
5598        Task::ready(Ok(Default::default()))
5599    }
5600
5601    fn send_lsp_proto_request<R: LspCommand>(
5602        &self,
5603        buffer: ModelHandle<Buffer>,
5604        project_id: u64,
5605        request: R,
5606        cx: &mut ModelContext<'_, Project>,
5607    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
5608        let rpc = self.client.clone();
5609        let message = request.to_proto(project_id, buffer.read(cx));
5610        cx.spawn_weak(|this, cx| async move {
5611            // Ensure the project is still alive by the time the task
5612            // is scheduled.
5613            this.upgrade(&cx)
5614                .ok_or_else(|| anyhow!("project dropped"))?;
5615            let response = rpc.request(message).await?;
5616            let this = this
5617                .upgrade(&cx)
5618                .ok_or_else(|| anyhow!("project dropped"))?;
5619            if this.read_with(&cx, |this, _| this.is_read_only()) {
5620                Err(anyhow!("disconnected before completing request"))
5621            } else {
5622                request
5623                    .response_from_proto(response, this, buffer, cx)
5624                    .await
5625            }
5626        })
5627    }
5628
5629    fn sort_candidates_and_open_buffers(
5630        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
5631        cx: &mut ModelContext<Self>,
5632    ) -> (
5633        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
5634        Receiver<(
5635            Option<(ModelHandle<Buffer>, BufferSnapshot)>,
5636            SearchMatchCandidateIndex,
5637        )>,
5638    ) {
5639        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5640        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
5641        cx.spawn(|this, cx| async move {
5642            let mut buffers = vec![];
5643            while let Some(entry) = matching_paths_rx.next().await {
5644                buffers.push(entry);
5645            }
5646            buffers.sort_by_key(|candidate| candidate.path());
5647            let matching_paths = buffers.clone();
5648            let _ = sorted_buffers_tx.send(buffers);
5649            for (index, candidate) in matching_paths.into_iter().enumerate() {
5650                if buffers_tx.is_closed() {
5651                    break;
5652                }
5653                let this = this.clone();
5654                let buffers_tx = buffers_tx.clone();
5655                cx.spawn(|mut cx| async move {
5656                    let buffer = match candidate {
5657                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
5658                        SearchMatchCandidate::Path { worktree_id, path } => this
5659                            .update(&mut cx, |this, cx| {
5660                                this.open_buffer((worktree_id, path), cx)
5661                            })
5662                            .await
5663                            .log_err(),
5664                    };
5665                    if let Some(buffer) = buffer {
5666                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5667                        buffers_tx
5668                            .send((Some((buffer, snapshot)), index))
5669                            .await
5670                            .log_err();
5671                    } else {
5672                        buffers_tx.send((None, index)).await.log_err();
5673                    }
5674
5675                    Ok::<_, anyhow::Error>(())
5676                })
5677                .detach();
5678            }
5679        })
5680        .detach();
5681        (sorted_buffers_rx, buffers_rx)
5682    }
5683
5684    pub fn find_or_create_local_worktree(
5685        &mut self,
5686        abs_path: impl AsRef<Path>,
5687        visible: bool,
5688        cx: &mut ModelContext<Self>,
5689    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5690        let abs_path = abs_path.as_ref();
5691        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5692            Task::ready(Ok((tree, relative_path)))
5693        } else {
5694            let worktree = self.create_local_worktree(abs_path, visible, cx);
5695            cx.foreground()
5696                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5697        }
5698    }
5699
5700    pub fn find_local_worktree(
5701        &self,
5702        abs_path: &Path,
5703        cx: &AppContext,
5704    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5705        for tree in &self.worktrees {
5706            if let Some(tree) = tree.upgrade(cx) {
5707                if let Some(relative_path) = tree
5708                    .read(cx)
5709                    .as_local()
5710                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5711                {
5712                    return Some((tree.clone(), relative_path.into()));
5713                }
5714            }
5715        }
5716        None
5717    }
5718
5719    pub fn is_shared(&self) -> bool {
5720        match &self.client_state {
5721            Some(ProjectClientState::Local { .. }) => true,
5722            _ => false,
5723        }
5724    }
5725
5726    fn create_local_worktree(
5727        &mut self,
5728        abs_path: impl AsRef<Path>,
5729        visible: bool,
5730        cx: &mut ModelContext<Self>,
5731    ) -> Task<Result<ModelHandle<Worktree>>> {
5732        let fs = self.fs.clone();
5733        let client = self.client.clone();
5734        let next_entry_id = self.next_entry_id.clone();
5735        let path: Arc<Path> = abs_path.as_ref().into();
5736        let task = self
5737            .loading_local_worktrees
5738            .entry(path.clone())
5739            .or_insert_with(|| {
5740                cx.spawn(|project, mut cx| {
5741                    async move {
5742                        let worktree = Worktree::local(
5743                            client.clone(),
5744                            path.clone(),
5745                            visible,
5746                            fs,
5747                            next_entry_id,
5748                            &mut cx,
5749                        )
5750                        .await;
5751
5752                        project.update(&mut cx, |project, _| {
5753                            project.loading_local_worktrees.remove(&path);
5754                        });
5755
5756                        let worktree = worktree?;
5757                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5758                        Ok(worktree)
5759                    }
5760                    .map_err(Arc::new)
5761                })
5762                .shared()
5763            })
5764            .clone();
5765        cx.foreground().spawn(async move {
5766            match task.await {
5767                Ok(worktree) => Ok(worktree),
5768                Err(err) => Err(anyhow!("{}", err)),
5769            }
5770        })
5771    }
5772
5773    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5774        self.worktrees.retain(|worktree| {
5775            if let Some(worktree) = worktree.upgrade(cx) {
5776                let id = worktree.read(cx).id();
5777                if id == id_to_remove {
5778                    cx.emit(Event::WorktreeRemoved(id));
5779                    false
5780                } else {
5781                    true
5782                }
5783            } else {
5784                false
5785            }
5786        });
5787        self.metadata_changed(cx);
5788    }
5789
5790    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5791        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5792        if worktree.read(cx).is_local() {
5793            cx.subscribe(worktree, |this, worktree, event, cx| match event {
5794                worktree::Event::UpdatedEntries(changes) => {
5795                    this.update_local_worktree_buffers(&worktree, changes, cx);
5796                    this.update_local_worktree_language_servers(&worktree, changes, cx);
5797                    this.update_local_worktree_settings(&worktree, changes, cx);
5798                    cx.emit(Event::WorktreeUpdatedEntries(
5799                        worktree.read(cx).id(),
5800                        changes.clone(),
5801                    ));
5802                }
5803                worktree::Event::UpdatedGitRepositories(updated_repos) => {
5804                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5805                }
5806            })
5807            .detach();
5808        }
5809
5810        let push_strong_handle = {
5811            let worktree = worktree.read(cx);
5812            self.is_shared() || worktree.is_visible() || worktree.is_remote()
5813        };
5814        if push_strong_handle {
5815            self.worktrees
5816                .push(WorktreeHandle::Strong(worktree.clone()));
5817        } else {
5818            self.worktrees
5819                .push(WorktreeHandle::Weak(worktree.downgrade()));
5820        }
5821
5822        let handle_id = worktree.id();
5823        cx.observe_release(worktree, move |this, worktree, cx| {
5824            let _ = this.remove_worktree(worktree.id(), cx);
5825            cx.update_global::<SettingsStore, _, _>(|store, cx| {
5826                store.clear_local_settings(handle_id, cx).log_err()
5827            });
5828        })
5829        .detach();
5830
5831        cx.emit(Event::WorktreeAdded);
5832        self.metadata_changed(cx);
5833    }
5834
5835    fn update_local_worktree_buffers(
5836        &mut self,
5837        worktree_handle: &ModelHandle<Worktree>,
5838        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5839        cx: &mut ModelContext<Self>,
5840    ) {
5841        let snapshot = worktree_handle.read(cx).snapshot();
5842
5843        let mut renamed_buffers = Vec::new();
5844        for (path, entry_id, _) in changes {
5845            let worktree_id = worktree_handle.read(cx).id();
5846            let project_path = ProjectPath {
5847                worktree_id,
5848                path: path.clone(),
5849            };
5850
5851            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5852                Some(&buffer_id) => buffer_id,
5853                None => match self.local_buffer_ids_by_path.get(&project_path) {
5854                    Some(&buffer_id) => buffer_id,
5855                    None => continue,
5856                },
5857            };
5858
5859            let open_buffer = self.opened_buffers.get(&buffer_id);
5860            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5861                buffer
5862            } else {
5863                self.opened_buffers.remove(&buffer_id);
5864                self.local_buffer_ids_by_path.remove(&project_path);
5865                self.local_buffer_ids_by_entry_id.remove(entry_id);
5866                continue;
5867            };
5868
5869            buffer.update(cx, |buffer, cx| {
5870                if let Some(old_file) = File::from_dyn(buffer.file()) {
5871                    if old_file.worktree != *worktree_handle {
5872                        return;
5873                    }
5874
5875                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5876                        File {
5877                            is_local: true,
5878                            entry_id: entry.id,
5879                            mtime: entry.mtime,
5880                            path: entry.path.clone(),
5881                            worktree: worktree_handle.clone(),
5882                            is_deleted: false,
5883                        }
5884                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5885                        File {
5886                            is_local: true,
5887                            entry_id: entry.id,
5888                            mtime: entry.mtime,
5889                            path: entry.path.clone(),
5890                            worktree: worktree_handle.clone(),
5891                            is_deleted: false,
5892                        }
5893                    } else {
5894                        File {
5895                            is_local: true,
5896                            entry_id: old_file.entry_id,
5897                            path: old_file.path().clone(),
5898                            mtime: old_file.mtime(),
5899                            worktree: worktree_handle.clone(),
5900                            is_deleted: true,
5901                        }
5902                    };
5903
5904                    let old_path = old_file.abs_path(cx);
5905                    if new_file.abs_path(cx) != old_path {
5906                        renamed_buffers.push((cx.handle(), old_file.clone()));
5907                        self.local_buffer_ids_by_path.remove(&project_path);
5908                        self.local_buffer_ids_by_path.insert(
5909                            ProjectPath {
5910                                worktree_id,
5911                                path: path.clone(),
5912                            },
5913                            buffer_id,
5914                        );
5915                    }
5916
5917                    if new_file.entry_id != *entry_id {
5918                        self.local_buffer_ids_by_entry_id.remove(entry_id);
5919                        self.local_buffer_ids_by_entry_id
5920                            .insert(new_file.entry_id, buffer_id);
5921                    }
5922
5923                    if new_file != *old_file {
5924                        if let Some(project_id) = self.remote_id() {
5925                            self.client
5926                                .send(proto::UpdateBufferFile {
5927                                    project_id,
5928                                    buffer_id: buffer_id as u64,
5929                                    file: Some(new_file.to_proto()),
5930                                })
5931                                .log_err();
5932                        }
5933
5934                        buffer.file_updated(Arc::new(new_file), cx).detach();
5935                    }
5936                }
5937            });
5938        }
5939
5940        for (buffer, old_file) in renamed_buffers {
5941            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5942            self.detect_language_for_buffer(&buffer, cx);
5943            self.register_buffer_with_language_servers(&buffer, cx);
5944        }
5945    }
5946
5947    fn update_local_worktree_language_servers(
5948        &mut self,
5949        worktree_handle: &ModelHandle<Worktree>,
5950        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5951        cx: &mut ModelContext<Self>,
5952    ) {
5953        if changes.is_empty() {
5954            return;
5955        }
5956
5957        let worktree_id = worktree_handle.read(cx).id();
5958        let mut language_server_ids = self
5959            .language_server_ids
5960            .iter()
5961            .filter_map(|((server_worktree_id, _), server_id)| {
5962                (*server_worktree_id == worktree_id).then_some(*server_id)
5963            })
5964            .collect::<Vec<_>>();
5965        language_server_ids.sort();
5966        language_server_ids.dedup();
5967
5968        let abs_path = worktree_handle.read(cx).abs_path();
5969        for server_id in &language_server_ids {
5970            if let Some(LanguageServerState::Running {
5971                server,
5972                watched_paths,
5973                ..
5974            }) = self.language_servers.get(server_id)
5975            {
5976                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5977                    let params = lsp::DidChangeWatchedFilesParams {
5978                        changes: changes
5979                            .iter()
5980                            .filter_map(|(path, _, change)| {
5981                                if !watched_paths.is_match(&path) {
5982                                    return None;
5983                                }
5984                                let typ = match change {
5985                                    PathChange::Loaded => return None,
5986                                    PathChange::Added => lsp::FileChangeType::CREATED,
5987                                    PathChange::Removed => lsp::FileChangeType::DELETED,
5988                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
5989                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5990                                };
5991                                Some(lsp::FileEvent {
5992                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5993                                    typ,
5994                                })
5995                            })
5996                            .collect(),
5997                    };
5998
5999                    if !params.changes.is_empty() {
6000                        server
6001                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6002                            .log_err();
6003                    }
6004                }
6005            }
6006        }
6007    }
6008
6009    fn update_local_worktree_buffers_git_repos(
6010        &mut self,
6011        worktree_handle: ModelHandle<Worktree>,
6012        changed_repos: &UpdatedGitRepositoriesSet,
6013        cx: &mut ModelContext<Self>,
6014    ) {
6015        debug_assert!(worktree_handle.read(cx).is_local());
6016
6017        // Identify the loading buffers whose containing repository that has changed.
6018        let future_buffers = self
6019            .loading_buffers_by_path
6020            .iter()
6021            .filter_map(|(project_path, receiver)| {
6022                if project_path.worktree_id != worktree_handle.read(cx).id() {
6023                    return None;
6024                }
6025                let path = &project_path.path;
6026                changed_repos
6027                    .iter()
6028                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6029                let receiver = receiver.clone();
6030                let path = path.clone();
6031                Some(async move {
6032                    wait_for_loading_buffer(receiver)
6033                        .await
6034                        .ok()
6035                        .map(|buffer| (buffer, path))
6036                })
6037            })
6038            .collect::<FuturesUnordered<_>>();
6039
6040        // Identify the current buffers whose containing repository has changed.
6041        let current_buffers = self
6042            .opened_buffers
6043            .values()
6044            .filter_map(|buffer| {
6045                let buffer = buffer.upgrade(cx)?;
6046                let file = File::from_dyn(buffer.read(cx).file())?;
6047                if file.worktree != worktree_handle {
6048                    return None;
6049                }
6050                let path = file.path();
6051                changed_repos
6052                    .iter()
6053                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6054                Some((buffer, path.clone()))
6055            })
6056            .collect::<Vec<_>>();
6057
6058        if future_buffers.len() + current_buffers.len() == 0 {
6059            return;
6060        }
6061
6062        let remote_id = self.remote_id();
6063        let client = self.client.clone();
6064        cx.spawn_weak(move |_, mut cx| async move {
6065            // Wait for all of the buffers to load.
6066            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6067
6068            // Reload the diff base for every buffer whose containing git repository has changed.
6069            let snapshot =
6070                worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
6071            let diff_bases_by_buffer = cx
6072                .background()
6073                .spawn(async move {
6074                    future_buffers
6075                        .into_iter()
6076                        .filter_map(|e| e)
6077                        .chain(current_buffers)
6078                        .filter_map(|(buffer, path)| {
6079                            let (work_directory, repo) =
6080                                snapshot.repository_and_work_directory_for_path(&path)?;
6081                            let repo = snapshot.get_local_repo(&repo)?;
6082                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6083                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6084                            Some((buffer, base_text))
6085                        })
6086                        .collect::<Vec<_>>()
6087                })
6088                .await;
6089
6090            // Assign the new diff bases on all of the buffers.
6091            for (buffer, diff_base) in diff_bases_by_buffer {
6092                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6093                    buffer.set_diff_base(diff_base.clone(), cx);
6094                    buffer.remote_id()
6095                });
6096                if let Some(project_id) = remote_id {
6097                    client
6098                        .send(proto::UpdateDiffBase {
6099                            project_id,
6100                            buffer_id,
6101                            diff_base,
6102                        })
6103                        .log_err();
6104                }
6105            }
6106        })
6107        .detach();
6108    }
6109
6110    fn update_local_worktree_settings(
6111        &mut self,
6112        worktree: &ModelHandle<Worktree>,
6113        changes: &UpdatedEntriesSet,
6114        cx: &mut ModelContext<Self>,
6115    ) {
6116        let project_id = self.remote_id();
6117        let worktree_id = worktree.id();
6118        let worktree = worktree.read(cx).as_local().unwrap();
6119        let remote_worktree_id = worktree.id();
6120
6121        let mut settings_contents = Vec::new();
6122        for (path, _, change) in changes.iter() {
6123            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6124                let settings_dir = Arc::from(
6125                    path.ancestors()
6126                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6127                        .unwrap(),
6128                );
6129                let fs = self.fs.clone();
6130                let removed = *change == PathChange::Removed;
6131                let abs_path = worktree.absolutize(path);
6132                settings_contents.push(async move {
6133                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6134                });
6135            }
6136        }
6137
6138        if settings_contents.is_empty() {
6139            return;
6140        }
6141
6142        let client = self.client.clone();
6143        cx.spawn_weak(move |_, mut cx| async move {
6144            let settings_contents: Vec<(Arc<Path>, _)> =
6145                futures::future::join_all(settings_contents).await;
6146            cx.update(|cx| {
6147                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6148                    for (directory, file_content) in settings_contents {
6149                        let file_content = file_content.and_then(|content| content.log_err());
6150                        store
6151                            .set_local_settings(
6152                                worktree_id,
6153                                directory.clone(),
6154                                file_content.as_ref().map(String::as_str),
6155                                cx,
6156                            )
6157                            .log_err();
6158                        if let Some(remote_id) = project_id {
6159                            client
6160                                .send(proto::UpdateWorktreeSettings {
6161                                    project_id: remote_id,
6162                                    worktree_id: remote_worktree_id.to_proto(),
6163                                    path: directory.to_string_lossy().into_owned(),
6164                                    content: file_content,
6165                                })
6166                                .log_err();
6167                        }
6168                    }
6169                });
6170            });
6171        })
6172        .detach();
6173    }
6174
6175    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6176        let new_active_entry = entry.and_then(|project_path| {
6177            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6178            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6179            Some(entry.id)
6180        });
6181        if new_active_entry != self.active_entry {
6182            self.active_entry = new_active_entry;
6183            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6184        }
6185    }
6186
6187    pub fn language_servers_running_disk_based_diagnostics(
6188        &self,
6189    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6190        self.language_server_statuses
6191            .iter()
6192            .filter_map(|(id, status)| {
6193                if status.has_pending_diagnostic_updates {
6194                    Some(*id)
6195                } else {
6196                    None
6197                }
6198            })
6199    }
6200
6201    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
6202        let mut summary = DiagnosticSummary::default();
6203        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
6204            summary.error_count += path_summary.error_count;
6205            summary.warning_count += path_summary.warning_count;
6206        }
6207        summary
6208    }
6209
6210    pub fn diagnostic_summaries<'a>(
6211        &'a self,
6212        cx: &'a AppContext,
6213    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6214        self.visible_worktrees(cx).flat_map(move |worktree| {
6215            let worktree = worktree.read(cx);
6216            let worktree_id = worktree.id();
6217            worktree
6218                .diagnostic_summaries()
6219                .map(move |(path, server_id, summary)| {
6220                    (ProjectPath { worktree_id, path }, server_id, summary)
6221                })
6222        })
6223    }
6224
6225    pub fn disk_based_diagnostics_started(
6226        &mut self,
6227        language_server_id: LanguageServerId,
6228        cx: &mut ModelContext<Self>,
6229    ) {
6230        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6231    }
6232
6233    pub fn disk_based_diagnostics_finished(
6234        &mut self,
6235        language_server_id: LanguageServerId,
6236        cx: &mut ModelContext<Self>,
6237    ) {
6238        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6239    }
6240
6241    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6242        self.active_entry
6243    }
6244
6245    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6246        self.worktree_for_id(path.worktree_id, cx)?
6247            .read(cx)
6248            .entry_for_path(&path.path)
6249            .cloned()
6250    }
6251
6252    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6253        let worktree = self.worktree_for_entry(entry_id, cx)?;
6254        let worktree = worktree.read(cx);
6255        let worktree_id = worktree.id();
6256        let path = worktree.entry_for_id(entry_id)?.path.clone();
6257        Some(ProjectPath { worktree_id, path })
6258    }
6259
6260    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6261        let workspace_root = self
6262            .worktree_for_id(project_path.worktree_id, cx)?
6263            .read(cx)
6264            .abs_path();
6265        let project_path = project_path.path.as_ref();
6266
6267        Some(if project_path == Path::new("") {
6268            workspace_root.to_path_buf()
6269        } else {
6270            workspace_root.join(project_path)
6271        })
6272    }
6273
6274    // RPC message handlers
6275
6276    async fn handle_unshare_project(
6277        this: ModelHandle<Self>,
6278        _: TypedEnvelope<proto::UnshareProject>,
6279        _: Arc<Client>,
6280        mut cx: AsyncAppContext,
6281    ) -> Result<()> {
6282        this.update(&mut cx, |this, cx| {
6283            if this.is_local() {
6284                this.unshare(cx)?;
6285            } else {
6286                this.disconnected_from_host(cx);
6287            }
6288            Ok(())
6289        })
6290    }
6291
6292    async fn handle_add_collaborator(
6293        this: ModelHandle<Self>,
6294        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6295        _: Arc<Client>,
6296        mut cx: AsyncAppContext,
6297    ) -> Result<()> {
6298        let collaborator = envelope
6299            .payload
6300            .collaborator
6301            .take()
6302            .ok_or_else(|| anyhow!("empty collaborator"))?;
6303
6304        let collaborator = Collaborator::from_proto(collaborator)?;
6305        this.update(&mut cx, |this, cx| {
6306            this.shared_buffers.remove(&collaborator.peer_id);
6307            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6308            this.collaborators
6309                .insert(collaborator.peer_id, collaborator);
6310            cx.notify();
6311        });
6312
6313        Ok(())
6314    }
6315
6316    async fn handle_update_project_collaborator(
6317        this: ModelHandle<Self>,
6318        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6319        _: Arc<Client>,
6320        mut cx: AsyncAppContext,
6321    ) -> Result<()> {
6322        let old_peer_id = envelope
6323            .payload
6324            .old_peer_id
6325            .ok_or_else(|| anyhow!("missing old peer id"))?;
6326        let new_peer_id = envelope
6327            .payload
6328            .new_peer_id
6329            .ok_or_else(|| anyhow!("missing new peer id"))?;
6330        this.update(&mut cx, |this, cx| {
6331            let collaborator = this
6332                .collaborators
6333                .remove(&old_peer_id)
6334                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6335            let is_host = collaborator.replica_id == 0;
6336            this.collaborators.insert(new_peer_id, collaborator);
6337
6338            let buffers = this.shared_buffers.remove(&old_peer_id);
6339            log::info!(
6340                "peer {} became {}. moving buffers {:?}",
6341                old_peer_id,
6342                new_peer_id,
6343                &buffers
6344            );
6345            if let Some(buffers) = buffers {
6346                this.shared_buffers.insert(new_peer_id, buffers);
6347            }
6348
6349            if is_host {
6350                this.opened_buffers
6351                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6352                this.buffer_ordered_messages_tx
6353                    .unbounded_send(BufferOrderedMessage::Resync)
6354                    .unwrap();
6355            }
6356
6357            cx.emit(Event::CollaboratorUpdated {
6358                old_peer_id,
6359                new_peer_id,
6360            });
6361            cx.notify();
6362            Ok(())
6363        })
6364    }
6365
6366    async fn handle_remove_collaborator(
6367        this: ModelHandle<Self>,
6368        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6369        _: Arc<Client>,
6370        mut cx: AsyncAppContext,
6371    ) -> Result<()> {
6372        this.update(&mut cx, |this, cx| {
6373            let peer_id = envelope
6374                .payload
6375                .peer_id
6376                .ok_or_else(|| anyhow!("invalid peer id"))?;
6377            let replica_id = this
6378                .collaborators
6379                .remove(&peer_id)
6380                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6381                .replica_id;
6382            for buffer in this.opened_buffers.values() {
6383                if let Some(buffer) = buffer.upgrade(cx) {
6384                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6385                }
6386            }
6387            this.shared_buffers.remove(&peer_id);
6388
6389            cx.emit(Event::CollaboratorLeft(peer_id));
6390            cx.notify();
6391            Ok(())
6392        })
6393    }
6394
6395    async fn handle_update_project(
6396        this: ModelHandle<Self>,
6397        envelope: TypedEnvelope<proto::UpdateProject>,
6398        _: Arc<Client>,
6399        mut cx: AsyncAppContext,
6400    ) -> Result<()> {
6401        this.update(&mut cx, |this, cx| {
6402            // Don't handle messages that were sent before the response to us joining the project
6403            if envelope.message_id > this.join_project_response_message_id {
6404                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6405            }
6406            Ok(())
6407        })
6408    }
6409
6410    async fn handle_update_worktree(
6411        this: ModelHandle<Self>,
6412        envelope: TypedEnvelope<proto::UpdateWorktree>,
6413        _: Arc<Client>,
6414        mut cx: AsyncAppContext,
6415    ) -> Result<()> {
6416        this.update(&mut cx, |this, cx| {
6417            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6418            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6419                worktree.update(cx, |worktree, _| {
6420                    let worktree = worktree.as_remote_mut().unwrap();
6421                    worktree.update_from_remote(envelope.payload);
6422                });
6423            }
6424            Ok(())
6425        })
6426    }
6427
6428    async fn handle_update_worktree_settings(
6429        this: ModelHandle<Self>,
6430        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6431        _: Arc<Client>,
6432        mut cx: AsyncAppContext,
6433    ) -> Result<()> {
6434        this.update(&mut cx, |this, cx| {
6435            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6436            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6437                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6438                    store
6439                        .set_local_settings(
6440                            worktree.id(),
6441                            PathBuf::from(&envelope.payload.path).into(),
6442                            envelope.payload.content.as_ref().map(String::as_str),
6443                            cx,
6444                        )
6445                        .log_err();
6446                });
6447            }
6448            Ok(())
6449        })
6450    }
6451
6452    async fn handle_create_project_entry(
6453        this: ModelHandle<Self>,
6454        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6455        _: Arc<Client>,
6456        mut cx: AsyncAppContext,
6457    ) -> Result<proto::ProjectEntryResponse> {
6458        let worktree = this.update(&mut cx, |this, cx| {
6459            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6460            this.worktree_for_id(worktree_id, cx)
6461                .ok_or_else(|| anyhow!("worktree not found"))
6462        })?;
6463        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6464        let entry = worktree
6465            .update(&mut cx, |worktree, cx| {
6466                let worktree = worktree.as_local_mut().unwrap();
6467                let path = PathBuf::from(envelope.payload.path);
6468                worktree.create_entry(path, envelope.payload.is_directory, cx)
6469            })
6470            .await?;
6471        Ok(proto::ProjectEntryResponse {
6472            entry: Some((&entry).into()),
6473            worktree_scan_id: worktree_scan_id as u64,
6474        })
6475    }
6476
6477    async fn handle_rename_project_entry(
6478        this: ModelHandle<Self>,
6479        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6480        _: Arc<Client>,
6481        mut cx: AsyncAppContext,
6482    ) -> Result<proto::ProjectEntryResponse> {
6483        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6484        let worktree = this.read_with(&cx, |this, cx| {
6485            this.worktree_for_entry(entry_id, cx)
6486                .ok_or_else(|| anyhow!("worktree not found"))
6487        })?;
6488        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6489        let entry = worktree
6490            .update(&mut cx, |worktree, cx| {
6491                let new_path = PathBuf::from(envelope.payload.new_path);
6492                worktree
6493                    .as_local_mut()
6494                    .unwrap()
6495                    .rename_entry(entry_id, new_path, cx)
6496                    .ok_or_else(|| anyhow!("invalid entry"))
6497            })?
6498            .await?;
6499        Ok(proto::ProjectEntryResponse {
6500            entry: Some((&entry).into()),
6501            worktree_scan_id: worktree_scan_id as u64,
6502        })
6503    }
6504
6505    async fn handle_copy_project_entry(
6506        this: ModelHandle<Self>,
6507        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6508        _: Arc<Client>,
6509        mut cx: AsyncAppContext,
6510    ) -> Result<proto::ProjectEntryResponse> {
6511        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6512        let worktree = this.read_with(&cx, |this, cx| {
6513            this.worktree_for_entry(entry_id, cx)
6514                .ok_or_else(|| anyhow!("worktree not found"))
6515        })?;
6516        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6517        let entry = worktree
6518            .update(&mut cx, |worktree, cx| {
6519                let new_path = PathBuf::from(envelope.payload.new_path);
6520                worktree
6521                    .as_local_mut()
6522                    .unwrap()
6523                    .copy_entry(entry_id, new_path, cx)
6524                    .ok_or_else(|| anyhow!("invalid entry"))
6525            })?
6526            .await?;
6527        Ok(proto::ProjectEntryResponse {
6528            entry: Some((&entry).into()),
6529            worktree_scan_id: worktree_scan_id as u64,
6530        })
6531    }
6532
6533    async fn handle_delete_project_entry(
6534        this: ModelHandle<Self>,
6535        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6536        _: Arc<Client>,
6537        mut cx: AsyncAppContext,
6538    ) -> Result<proto::ProjectEntryResponse> {
6539        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6540
6541        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6542
6543        let worktree = this.read_with(&cx, |this, cx| {
6544            this.worktree_for_entry(entry_id, cx)
6545                .ok_or_else(|| anyhow!("worktree not found"))
6546        })?;
6547        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6548        worktree
6549            .update(&mut cx, |worktree, cx| {
6550                worktree
6551                    .as_local_mut()
6552                    .unwrap()
6553                    .delete_entry(entry_id, cx)
6554                    .ok_or_else(|| anyhow!("invalid entry"))
6555            })?
6556            .await?;
6557        Ok(proto::ProjectEntryResponse {
6558            entry: None,
6559            worktree_scan_id: worktree_scan_id as u64,
6560        })
6561    }
6562
6563    async fn handle_expand_project_entry(
6564        this: ModelHandle<Self>,
6565        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6566        _: Arc<Client>,
6567        mut cx: AsyncAppContext,
6568    ) -> Result<proto::ExpandProjectEntryResponse> {
6569        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6570        let worktree = this
6571            .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6572            .ok_or_else(|| anyhow!("invalid request"))?;
6573        worktree
6574            .update(&mut cx, |worktree, cx| {
6575                worktree
6576                    .as_local_mut()
6577                    .unwrap()
6578                    .expand_entry(entry_id, cx)
6579                    .ok_or_else(|| anyhow!("invalid entry"))
6580            })?
6581            .await?;
6582        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6583        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6584    }
6585
6586    async fn handle_update_diagnostic_summary(
6587        this: ModelHandle<Self>,
6588        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6589        _: Arc<Client>,
6590        mut cx: AsyncAppContext,
6591    ) -> Result<()> {
6592        this.update(&mut cx, |this, cx| {
6593            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6594            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6595                if let Some(summary) = envelope.payload.summary {
6596                    let project_path = ProjectPath {
6597                        worktree_id,
6598                        path: Path::new(&summary.path).into(),
6599                    };
6600                    worktree.update(cx, |worktree, _| {
6601                        worktree
6602                            .as_remote_mut()
6603                            .unwrap()
6604                            .update_diagnostic_summary(project_path.path.clone(), &summary);
6605                    });
6606                    cx.emit(Event::DiagnosticsUpdated {
6607                        language_server_id: LanguageServerId(summary.language_server_id as usize),
6608                        path: project_path,
6609                    });
6610                }
6611            }
6612            Ok(())
6613        })
6614    }
6615
6616    async fn handle_start_language_server(
6617        this: ModelHandle<Self>,
6618        envelope: TypedEnvelope<proto::StartLanguageServer>,
6619        _: Arc<Client>,
6620        mut cx: AsyncAppContext,
6621    ) -> Result<()> {
6622        let server = envelope
6623            .payload
6624            .server
6625            .ok_or_else(|| anyhow!("invalid server"))?;
6626        this.update(&mut cx, |this, cx| {
6627            this.language_server_statuses.insert(
6628                LanguageServerId(server.id as usize),
6629                LanguageServerStatus {
6630                    name: server.name,
6631                    pending_work: Default::default(),
6632                    has_pending_diagnostic_updates: false,
6633                    progress_tokens: Default::default(),
6634                },
6635            );
6636            cx.notify();
6637        });
6638        Ok(())
6639    }
6640
6641    async fn handle_update_language_server(
6642        this: ModelHandle<Self>,
6643        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6644        _: Arc<Client>,
6645        mut cx: AsyncAppContext,
6646    ) -> Result<()> {
6647        this.update(&mut cx, |this, cx| {
6648            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6649
6650            match envelope
6651                .payload
6652                .variant
6653                .ok_or_else(|| anyhow!("invalid variant"))?
6654            {
6655                proto::update_language_server::Variant::WorkStart(payload) => {
6656                    this.on_lsp_work_start(
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::WorkProgress(payload) => {
6669                    this.on_lsp_work_progress(
6670                        language_server_id,
6671                        payload.token,
6672                        LanguageServerProgress {
6673                            message: payload.message,
6674                            percentage: payload.percentage.map(|p| p as usize),
6675                            last_update_at: Instant::now(),
6676                        },
6677                        cx,
6678                    );
6679                }
6680
6681                proto::update_language_server::Variant::WorkEnd(payload) => {
6682                    this.on_lsp_work_end(language_server_id, payload.token, cx);
6683                }
6684
6685                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6686                    this.disk_based_diagnostics_started(language_server_id, cx);
6687                }
6688
6689                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6690                    this.disk_based_diagnostics_finished(language_server_id, cx)
6691                }
6692            }
6693
6694            Ok(())
6695        })
6696    }
6697
6698    async fn handle_update_buffer(
6699        this: ModelHandle<Self>,
6700        envelope: TypedEnvelope<proto::UpdateBuffer>,
6701        _: Arc<Client>,
6702        mut cx: AsyncAppContext,
6703    ) -> Result<proto::Ack> {
6704        this.update(&mut cx, |this, cx| {
6705            let payload = envelope.payload.clone();
6706            let buffer_id = payload.buffer_id;
6707            let ops = payload
6708                .operations
6709                .into_iter()
6710                .map(language::proto::deserialize_operation)
6711                .collect::<Result<Vec<_>, _>>()?;
6712            let is_remote = this.is_remote();
6713            match this.opened_buffers.entry(buffer_id) {
6714                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6715                    OpenBuffer::Strong(buffer) => {
6716                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6717                    }
6718                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6719                    OpenBuffer::Weak(_) => {}
6720                },
6721                hash_map::Entry::Vacant(e) => {
6722                    assert!(
6723                        is_remote,
6724                        "received buffer update from {:?}",
6725                        envelope.original_sender_id
6726                    );
6727                    e.insert(OpenBuffer::Operations(ops));
6728                }
6729            }
6730            Ok(proto::Ack {})
6731        })
6732    }
6733
6734    async fn handle_create_buffer_for_peer(
6735        this: ModelHandle<Self>,
6736        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6737        _: Arc<Client>,
6738        mut cx: AsyncAppContext,
6739    ) -> Result<()> {
6740        this.update(&mut cx, |this, cx| {
6741            match envelope
6742                .payload
6743                .variant
6744                .ok_or_else(|| anyhow!("missing variant"))?
6745            {
6746                proto::create_buffer_for_peer::Variant::State(mut state) => {
6747                    let mut buffer_file = None;
6748                    if let Some(file) = state.file.take() {
6749                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
6750                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6751                            anyhow!("no worktree found for id {}", file.worktree_id)
6752                        })?;
6753                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6754                            as Arc<dyn language::File>);
6755                    }
6756
6757                    let buffer_id = state.id;
6758                    let buffer = cx.add_model(|_| {
6759                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6760                    });
6761                    this.incomplete_remote_buffers
6762                        .insert(buffer_id, Some(buffer));
6763                }
6764                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6765                    let buffer = this
6766                        .incomplete_remote_buffers
6767                        .get(&chunk.buffer_id)
6768                        .cloned()
6769                        .flatten()
6770                        .ok_or_else(|| {
6771                            anyhow!(
6772                                "received chunk for buffer {} without initial state",
6773                                chunk.buffer_id
6774                            )
6775                        })?;
6776                    let operations = chunk
6777                        .operations
6778                        .into_iter()
6779                        .map(language::proto::deserialize_operation)
6780                        .collect::<Result<Vec<_>>>()?;
6781                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6782
6783                    if chunk.is_last {
6784                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6785                        this.register_buffer(&buffer, cx)?;
6786                    }
6787                }
6788            }
6789
6790            Ok(())
6791        })
6792    }
6793
6794    async fn handle_update_diff_base(
6795        this: ModelHandle<Self>,
6796        envelope: TypedEnvelope<proto::UpdateDiffBase>,
6797        _: Arc<Client>,
6798        mut cx: AsyncAppContext,
6799    ) -> Result<()> {
6800        this.update(&mut cx, |this, cx| {
6801            let buffer_id = envelope.payload.buffer_id;
6802            let diff_base = envelope.payload.diff_base;
6803            if let Some(buffer) = this
6804                .opened_buffers
6805                .get_mut(&buffer_id)
6806                .and_then(|b| b.upgrade(cx))
6807                .or_else(|| {
6808                    this.incomplete_remote_buffers
6809                        .get(&buffer_id)
6810                        .cloned()
6811                        .flatten()
6812                })
6813            {
6814                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6815            }
6816            Ok(())
6817        })
6818    }
6819
6820    async fn handle_update_buffer_file(
6821        this: ModelHandle<Self>,
6822        envelope: TypedEnvelope<proto::UpdateBufferFile>,
6823        _: Arc<Client>,
6824        mut cx: AsyncAppContext,
6825    ) -> Result<()> {
6826        let buffer_id = envelope.payload.buffer_id;
6827
6828        this.update(&mut cx, |this, cx| {
6829            let payload = envelope.payload.clone();
6830            if let Some(buffer) = this
6831                .opened_buffers
6832                .get(&buffer_id)
6833                .and_then(|b| b.upgrade(cx))
6834                .or_else(|| {
6835                    this.incomplete_remote_buffers
6836                        .get(&buffer_id)
6837                        .cloned()
6838                        .flatten()
6839                })
6840            {
6841                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6842                let worktree = this
6843                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6844                    .ok_or_else(|| anyhow!("no such worktree"))?;
6845                let file = File::from_proto(file, worktree, cx)?;
6846                buffer.update(cx, |buffer, cx| {
6847                    buffer.file_updated(Arc::new(file), cx).detach();
6848                });
6849                this.detect_language_for_buffer(&buffer, cx);
6850            }
6851            Ok(())
6852        })
6853    }
6854
6855    async fn handle_save_buffer(
6856        this: ModelHandle<Self>,
6857        envelope: TypedEnvelope<proto::SaveBuffer>,
6858        _: Arc<Client>,
6859        mut cx: AsyncAppContext,
6860    ) -> Result<proto::BufferSaved> {
6861        let buffer_id = envelope.payload.buffer_id;
6862        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6863            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6864            let buffer = this
6865                .opened_buffers
6866                .get(&buffer_id)
6867                .and_then(|buffer| buffer.upgrade(cx))
6868                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6869            anyhow::Ok((project_id, buffer))
6870        })?;
6871        buffer
6872            .update(&mut cx, |buffer, _| {
6873                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6874            })
6875            .await?;
6876        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6877
6878        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6879            .await?;
6880        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6881            project_id,
6882            buffer_id,
6883            version: serialize_version(buffer.saved_version()),
6884            mtime: Some(buffer.saved_mtime().into()),
6885            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6886        }))
6887    }
6888
6889    async fn handle_reload_buffers(
6890        this: ModelHandle<Self>,
6891        envelope: TypedEnvelope<proto::ReloadBuffers>,
6892        _: Arc<Client>,
6893        mut cx: AsyncAppContext,
6894    ) -> Result<proto::ReloadBuffersResponse> {
6895        let sender_id = envelope.original_sender_id()?;
6896        let reload = this.update(&mut cx, |this, cx| {
6897            let mut buffers = HashSet::default();
6898            for buffer_id in &envelope.payload.buffer_ids {
6899                buffers.insert(
6900                    this.opened_buffers
6901                        .get(buffer_id)
6902                        .and_then(|buffer| buffer.upgrade(cx))
6903                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6904                );
6905            }
6906            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6907        })?;
6908
6909        let project_transaction = reload.await?;
6910        let project_transaction = this.update(&mut cx, |this, cx| {
6911            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6912        });
6913        Ok(proto::ReloadBuffersResponse {
6914            transaction: Some(project_transaction),
6915        })
6916    }
6917
6918    async fn handle_synchronize_buffers(
6919        this: ModelHandle<Self>,
6920        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6921        _: Arc<Client>,
6922        mut cx: AsyncAppContext,
6923    ) -> Result<proto::SynchronizeBuffersResponse> {
6924        let project_id = envelope.payload.project_id;
6925        let mut response = proto::SynchronizeBuffersResponse {
6926            buffers: Default::default(),
6927        };
6928
6929        this.update(&mut cx, |this, cx| {
6930            let Some(guest_id) = envelope.original_sender_id else {
6931                error!("missing original_sender_id on SynchronizeBuffers request");
6932                return;
6933            };
6934
6935            this.shared_buffers.entry(guest_id).or_default().clear();
6936            for buffer in envelope.payload.buffers {
6937                let buffer_id = buffer.id;
6938                let remote_version = language::proto::deserialize_version(&buffer.version);
6939                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6940                    this.shared_buffers
6941                        .entry(guest_id)
6942                        .or_default()
6943                        .insert(buffer_id);
6944
6945                    let buffer = buffer.read(cx);
6946                    response.buffers.push(proto::BufferVersion {
6947                        id: buffer_id,
6948                        version: language::proto::serialize_version(&buffer.version),
6949                    });
6950
6951                    let operations = buffer.serialize_ops(Some(remote_version), cx);
6952                    let client = this.client.clone();
6953                    if let Some(file) = buffer.file() {
6954                        client
6955                            .send(proto::UpdateBufferFile {
6956                                project_id,
6957                                buffer_id: buffer_id as u64,
6958                                file: Some(file.to_proto()),
6959                            })
6960                            .log_err();
6961                    }
6962
6963                    client
6964                        .send(proto::UpdateDiffBase {
6965                            project_id,
6966                            buffer_id: buffer_id as u64,
6967                            diff_base: buffer.diff_base().map(Into::into),
6968                        })
6969                        .log_err();
6970
6971                    client
6972                        .send(proto::BufferReloaded {
6973                            project_id,
6974                            buffer_id,
6975                            version: language::proto::serialize_version(buffer.saved_version()),
6976                            mtime: Some(buffer.saved_mtime().into()),
6977                            fingerprint: language::proto::serialize_fingerprint(
6978                                buffer.saved_version_fingerprint(),
6979                            ),
6980                            line_ending: language::proto::serialize_line_ending(
6981                                buffer.line_ending(),
6982                            ) as i32,
6983                        })
6984                        .log_err();
6985
6986                    cx.background()
6987                        .spawn(
6988                            async move {
6989                                let operations = operations.await;
6990                                for chunk in split_operations(operations) {
6991                                    client
6992                                        .request(proto::UpdateBuffer {
6993                                            project_id,
6994                                            buffer_id,
6995                                            operations: chunk,
6996                                        })
6997                                        .await?;
6998                                }
6999                                anyhow::Ok(())
7000                            }
7001                            .log_err(),
7002                        )
7003                        .detach();
7004                }
7005            }
7006        });
7007
7008        Ok(response)
7009    }
7010
7011    async fn handle_format_buffers(
7012        this: ModelHandle<Self>,
7013        envelope: TypedEnvelope<proto::FormatBuffers>,
7014        _: Arc<Client>,
7015        mut cx: AsyncAppContext,
7016    ) -> Result<proto::FormatBuffersResponse> {
7017        let sender_id = envelope.original_sender_id()?;
7018        let format = this.update(&mut cx, |this, cx| {
7019            let mut buffers = HashSet::default();
7020            for buffer_id in &envelope.payload.buffer_ids {
7021                buffers.insert(
7022                    this.opened_buffers
7023                        .get(buffer_id)
7024                        .and_then(|buffer| buffer.upgrade(cx))
7025                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7026                );
7027            }
7028            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7029            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7030        })?;
7031
7032        let project_transaction = format.await?;
7033        let project_transaction = this.update(&mut cx, |this, cx| {
7034            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7035        });
7036        Ok(proto::FormatBuffersResponse {
7037            transaction: Some(project_transaction),
7038        })
7039    }
7040
7041    async fn handle_apply_additional_edits_for_completion(
7042        this: ModelHandle<Self>,
7043        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7044        _: Arc<Client>,
7045        mut cx: AsyncAppContext,
7046    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7047        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7048            let buffer = this
7049                .opened_buffers
7050                .get(&envelope.payload.buffer_id)
7051                .and_then(|buffer| buffer.upgrade(cx))
7052                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7053            let language = buffer.read(cx).language();
7054            let completion = language::proto::deserialize_completion(
7055                envelope
7056                    .payload
7057                    .completion
7058                    .ok_or_else(|| anyhow!("invalid completion"))?,
7059                language.cloned(),
7060            );
7061            Ok::<_, anyhow::Error>((buffer, completion))
7062        })?;
7063
7064        let completion = completion.await?;
7065
7066        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7067            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7068        });
7069
7070        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7071            transaction: apply_additional_edits
7072                .await?
7073                .as_ref()
7074                .map(language::proto::serialize_transaction),
7075        })
7076    }
7077
7078    async fn handle_apply_code_action(
7079        this: ModelHandle<Self>,
7080        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7081        _: Arc<Client>,
7082        mut cx: AsyncAppContext,
7083    ) -> Result<proto::ApplyCodeActionResponse> {
7084        let sender_id = envelope.original_sender_id()?;
7085        let action = language::proto::deserialize_code_action(
7086            envelope
7087                .payload
7088                .action
7089                .ok_or_else(|| anyhow!("invalid action"))?,
7090        )?;
7091        let apply_code_action = this.update(&mut cx, |this, cx| {
7092            let buffer = this
7093                .opened_buffers
7094                .get(&envelope.payload.buffer_id)
7095                .and_then(|buffer| buffer.upgrade(cx))
7096                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7097            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7098        })?;
7099
7100        let project_transaction = apply_code_action.await?;
7101        let project_transaction = this.update(&mut cx, |this, cx| {
7102            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7103        });
7104        Ok(proto::ApplyCodeActionResponse {
7105            transaction: Some(project_transaction),
7106        })
7107    }
7108
7109    async fn handle_on_type_formatting(
7110        this: ModelHandle<Self>,
7111        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7112        _: Arc<Client>,
7113        mut cx: AsyncAppContext,
7114    ) -> Result<proto::OnTypeFormattingResponse> {
7115        let on_type_formatting = this.update(&mut cx, |this, cx| {
7116            let buffer = this
7117                .opened_buffers
7118                .get(&envelope.payload.buffer_id)
7119                .and_then(|buffer| buffer.upgrade(cx))
7120                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7121            let position = envelope
7122                .payload
7123                .position
7124                .and_then(deserialize_anchor)
7125                .ok_or_else(|| anyhow!("invalid position"))?;
7126            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7127                buffer,
7128                position,
7129                envelope.payload.trigger.clone(),
7130                cx,
7131            ))
7132        })?;
7133
7134        let transaction = on_type_formatting
7135            .await?
7136            .as_ref()
7137            .map(language::proto::serialize_transaction);
7138        Ok(proto::OnTypeFormattingResponse { transaction })
7139    }
7140
7141    async fn handle_inlay_hints(
7142        this: ModelHandle<Self>,
7143        envelope: TypedEnvelope<proto::InlayHints>,
7144        _: Arc<Client>,
7145        mut cx: AsyncAppContext,
7146    ) -> Result<proto::InlayHintsResponse> {
7147        let sender_id = envelope.original_sender_id()?;
7148        let buffer = this.update(&mut cx, |this, cx| {
7149            this.opened_buffers
7150                .get(&envelope.payload.buffer_id)
7151                .and_then(|buffer| buffer.upgrade(cx))
7152                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7153        })?;
7154        let buffer_version = deserialize_version(&envelope.payload.version);
7155
7156        buffer
7157            .update(&mut cx, |buffer, _| {
7158                buffer.wait_for_version(buffer_version.clone())
7159            })
7160            .await
7161            .with_context(|| {
7162                format!(
7163                    "waiting for version {:?} for buffer {}",
7164                    buffer_version,
7165                    buffer.id()
7166                )
7167            })?;
7168
7169        let start = envelope
7170            .payload
7171            .start
7172            .and_then(deserialize_anchor)
7173            .context("missing range start")?;
7174        let end = envelope
7175            .payload
7176            .end
7177            .and_then(deserialize_anchor)
7178            .context("missing range end")?;
7179        let buffer_hints = this
7180            .update(&mut cx, |project, cx| {
7181                project.inlay_hints(buffer, start..end, cx)
7182            })
7183            .await
7184            .context("inlay hints fetch")?;
7185
7186        Ok(this.update(&mut cx, |project, cx| {
7187            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7188        }))
7189    }
7190
7191    async fn handle_resolve_inlay_hint(
7192        this: ModelHandle<Self>,
7193        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7194        _: Arc<Client>,
7195        mut cx: AsyncAppContext,
7196    ) -> Result<proto::ResolveInlayHintResponse> {
7197        let proto_hint = envelope
7198            .payload
7199            .hint
7200            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7201        let hint = InlayHints::proto_to_project_hint(proto_hint)
7202            .context("resolved proto inlay hint conversion")?;
7203        let buffer = this.update(&mut cx, |this, cx| {
7204            this.opened_buffers
7205                .get(&envelope.payload.buffer_id)
7206                .and_then(|buffer| buffer.upgrade(cx))
7207                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7208        })?;
7209        let response_hint = this
7210            .update(&mut cx, |project, cx| {
7211                project.resolve_inlay_hint(
7212                    hint,
7213                    buffer,
7214                    LanguageServerId(envelope.payload.language_server_id as usize),
7215                    cx,
7216                )
7217            })
7218            .await
7219            .context("inlay hints fetch")?;
7220        Ok(proto::ResolveInlayHintResponse {
7221            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7222        })
7223    }
7224
7225    async fn handle_refresh_inlay_hints(
7226        this: ModelHandle<Self>,
7227        _: TypedEnvelope<proto::RefreshInlayHints>,
7228        _: Arc<Client>,
7229        mut cx: AsyncAppContext,
7230    ) -> Result<proto::Ack> {
7231        this.update(&mut cx, |_, cx| {
7232            cx.emit(Event::RefreshInlayHints);
7233        });
7234        Ok(proto::Ack {})
7235    }
7236
7237    async fn handle_lsp_command<T: LspCommand>(
7238        this: ModelHandle<Self>,
7239        envelope: TypedEnvelope<T::ProtoRequest>,
7240        _: Arc<Client>,
7241        mut cx: AsyncAppContext,
7242    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7243    where
7244        <T::LspRequest as lsp::request::Request>::Result: Send,
7245    {
7246        let sender_id = envelope.original_sender_id()?;
7247        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7248        let buffer_handle = this.read_with(&cx, |this, _| {
7249            this.opened_buffers
7250                .get(&buffer_id)
7251                .and_then(|buffer| buffer.upgrade(&cx))
7252                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7253        })?;
7254        let request = T::from_proto(
7255            envelope.payload,
7256            this.clone(),
7257            buffer_handle.clone(),
7258            cx.clone(),
7259        )
7260        .await?;
7261        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
7262        let response = this
7263            .update(&mut cx, |this, cx| {
7264                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7265            })
7266            .await?;
7267        this.update(&mut cx, |this, cx| {
7268            Ok(T::response_to_proto(
7269                response,
7270                this,
7271                sender_id,
7272                &buffer_version,
7273                cx,
7274            ))
7275        })
7276    }
7277
7278    async fn handle_get_project_symbols(
7279        this: ModelHandle<Self>,
7280        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7281        _: Arc<Client>,
7282        mut cx: AsyncAppContext,
7283    ) -> Result<proto::GetProjectSymbolsResponse> {
7284        let symbols = this
7285            .update(&mut cx, |this, cx| {
7286                this.symbols(&envelope.payload.query, cx)
7287            })
7288            .await?;
7289
7290        Ok(proto::GetProjectSymbolsResponse {
7291            symbols: symbols.iter().map(serialize_symbol).collect(),
7292        })
7293    }
7294
7295    async fn handle_search_project(
7296        this: ModelHandle<Self>,
7297        envelope: TypedEnvelope<proto::SearchProject>,
7298        _: Arc<Client>,
7299        mut cx: AsyncAppContext,
7300    ) -> Result<proto::SearchProjectResponse> {
7301        let peer_id = envelope.original_sender_id()?;
7302        let query = SearchQuery::from_proto(envelope.payload)?;
7303        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx));
7304
7305        cx.spawn(|mut cx| async move {
7306            let mut locations = Vec::new();
7307            while let Some((buffer, ranges)) = result.next().await {
7308                for range in ranges {
7309                    let start = serialize_anchor(&range.start);
7310                    let end = serialize_anchor(&range.end);
7311                    let buffer_id = this.update(&mut cx, |this, cx| {
7312                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7313                    });
7314                    locations.push(proto::Location {
7315                        buffer_id,
7316                        start: Some(start),
7317                        end: Some(end),
7318                    });
7319                }
7320            }
7321            Ok(proto::SearchProjectResponse { locations })
7322        })
7323        .await
7324    }
7325
7326    async fn handle_open_buffer_for_symbol(
7327        this: ModelHandle<Self>,
7328        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7329        _: Arc<Client>,
7330        mut cx: AsyncAppContext,
7331    ) -> Result<proto::OpenBufferForSymbolResponse> {
7332        let peer_id = envelope.original_sender_id()?;
7333        let symbol = envelope
7334            .payload
7335            .symbol
7336            .ok_or_else(|| anyhow!("invalid symbol"))?;
7337        let symbol = this
7338            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
7339            .await?;
7340        let symbol = this.read_with(&cx, |this, _| {
7341            let signature = this.symbol_signature(&symbol.path);
7342            if signature == symbol.signature {
7343                Ok(symbol)
7344            } else {
7345                Err(anyhow!("invalid symbol signature"))
7346            }
7347        })?;
7348        let buffer = this
7349            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
7350            .await?;
7351
7352        Ok(proto::OpenBufferForSymbolResponse {
7353            buffer_id: this.update(&mut cx, |this, cx| {
7354                this.create_buffer_for_peer(&buffer, peer_id, cx)
7355            }),
7356        })
7357    }
7358
7359    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7360        let mut hasher = Sha256::new();
7361        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7362        hasher.update(project_path.path.to_string_lossy().as_bytes());
7363        hasher.update(self.nonce.to_be_bytes());
7364        hasher.finalize().as_slice().try_into().unwrap()
7365    }
7366
7367    async fn handle_open_buffer_by_id(
7368        this: ModelHandle<Self>,
7369        envelope: TypedEnvelope<proto::OpenBufferById>,
7370        _: Arc<Client>,
7371        mut cx: AsyncAppContext,
7372    ) -> Result<proto::OpenBufferResponse> {
7373        let peer_id = envelope.original_sender_id()?;
7374        let buffer = this
7375            .update(&mut cx, |this, cx| {
7376                this.open_buffer_by_id(envelope.payload.id, cx)
7377            })
7378            .await?;
7379        this.update(&mut cx, |this, cx| {
7380            Ok(proto::OpenBufferResponse {
7381                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7382            })
7383        })
7384    }
7385
7386    async fn handle_open_buffer_by_path(
7387        this: ModelHandle<Self>,
7388        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7389        _: Arc<Client>,
7390        mut cx: AsyncAppContext,
7391    ) -> Result<proto::OpenBufferResponse> {
7392        let peer_id = envelope.original_sender_id()?;
7393        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7394        let open_buffer = this.update(&mut cx, |this, cx| {
7395            this.open_buffer(
7396                ProjectPath {
7397                    worktree_id,
7398                    path: PathBuf::from(envelope.payload.path).into(),
7399                },
7400                cx,
7401            )
7402        });
7403
7404        let buffer = open_buffer.await?;
7405        this.update(&mut cx, |this, cx| {
7406            Ok(proto::OpenBufferResponse {
7407                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7408            })
7409        })
7410    }
7411
7412    fn serialize_project_transaction_for_peer(
7413        &mut self,
7414        project_transaction: ProjectTransaction,
7415        peer_id: proto::PeerId,
7416        cx: &mut AppContext,
7417    ) -> proto::ProjectTransaction {
7418        let mut serialized_transaction = proto::ProjectTransaction {
7419            buffer_ids: Default::default(),
7420            transactions: Default::default(),
7421        };
7422        for (buffer, transaction) in project_transaction.0 {
7423            serialized_transaction
7424                .buffer_ids
7425                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7426            serialized_transaction
7427                .transactions
7428                .push(language::proto::serialize_transaction(&transaction));
7429        }
7430        serialized_transaction
7431    }
7432
7433    fn deserialize_project_transaction(
7434        &mut self,
7435        message: proto::ProjectTransaction,
7436        push_to_history: bool,
7437        cx: &mut ModelContext<Self>,
7438    ) -> Task<Result<ProjectTransaction>> {
7439        cx.spawn(|this, mut cx| async move {
7440            let mut project_transaction = ProjectTransaction::default();
7441            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7442            {
7443                let buffer = this
7444                    .update(&mut cx, |this, cx| {
7445                        this.wait_for_remote_buffer(buffer_id, cx)
7446                    })
7447                    .await?;
7448                let transaction = language::proto::deserialize_transaction(transaction)?;
7449                project_transaction.0.insert(buffer, transaction);
7450            }
7451
7452            for (buffer, transaction) in &project_transaction.0 {
7453                buffer
7454                    .update(&mut cx, |buffer, _| {
7455                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7456                    })
7457                    .await?;
7458
7459                if push_to_history {
7460                    buffer.update(&mut cx, |buffer, _| {
7461                        buffer.push_transaction(transaction.clone(), Instant::now());
7462                    });
7463                }
7464            }
7465
7466            Ok(project_transaction)
7467        })
7468    }
7469
7470    fn create_buffer_for_peer(
7471        &mut self,
7472        buffer: &ModelHandle<Buffer>,
7473        peer_id: proto::PeerId,
7474        cx: &mut AppContext,
7475    ) -> u64 {
7476        let buffer_id = buffer.read(cx).remote_id();
7477        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7478            updates_tx
7479                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7480                .ok();
7481        }
7482        buffer_id
7483    }
7484
7485    fn wait_for_remote_buffer(
7486        &mut self,
7487        id: u64,
7488        cx: &mut ModelContext<Self>,
7489    ) -> Task<Result<ModelHandle<Buffer>>> {
7490        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7491
7492        cx.spawn_weak(|this, mut cx| async move {
7493            let buffer = loop {
7494                let Some(this) = this.upgrade(&cx) else {
7495                    return Err(anyhow!("project dropped"));
7496                };
7497
7498                let buffer = this.read_with(&cx, |this, cx| {
7499                    this.opened_buffers
7500                        .get(&id)
7501                        .and_then(|buffer| buffer.upgrade(cx))
7502                });
7503
7504                if let Some(buffer) = buffer {
7505                    break buffer;
7506                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7507                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7508                }
7509
7510                this.update(&mut cx, |this, _| {
7511                    this.incomplete_remote_buffers.entry(id).or_default();
7512                });
7513                drop(this);
7514
7515                opened_buffer_rx
7516                    .next()
7517                    .await
7518                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7519            };
7520
7521            Ok(buffer)
7522        })
7523    }
7524
7525    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7526        let project_id = match self.client_state.as_ref() {
7527            Some(ProjectClientState::Remote {
7528                sharing_has_stopped,
7529                remote_id,
7530                ..
7531            }) => {
7532                if *sharing_has_stopped {
7533                    return Task::ready(Err(anyhow!(
7534                        "can't synchronize remote buffers on a readonly project"
7535                    )));
7536                } else {
7537                    *remote_id
7538                }
7539            }
7540            Some(ProjectClientState::Local { .. }) | None => {
7541                return Task::ready(Err(anyhow!(
7542                    "can't synchronize remote buffers on a local project"
7543                )))
7544            }
7545        };
7546
7547        let client = self.client.clone();
7548        cx.spawn(|this, cx| async move {
7549            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7550                let buffers = this
7551                    .opened_buffers
7552                    .iter()
7553                    .filter_map(|(id, buffer)| {
7554                        let buffer = buffer.upgrade(cx)?;
7555                        Some(proto::BufferVersion {
7556                            id: *id,
7557                            version: language::proto::serialize_version(&buffer.read(cx).version),
7558                        })
7559                    })
7560                    .collect();
7561                let incomplete_buffer_ids = this
7562                    .incomplete_remote_buffers
7563                    .keys()
7564                    .copied()
7565                    .collect::<Vec<_>>();
7566
7567                (buffers, incomplete_buffer_ids)
7568            });
7569            let response = client
7570                .request(proto::SynchronizeBuffers {
7571                    project_id,
7572                    buffers,
7573                })
7574                .await?;
7575
7576            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7577                let client = client.clone();
7578                let buffer_id = buffer.id;
7579                let remote_version = language::proto::deserialize_version(&buffer.version);
7580                this.read_with(&cx, |this, cx| {
7581                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7582                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7583                        cx.background().spawn(async move {
7584                            let operations = operations.await;
7585                            for chunk in split_operations(operations) {
7586                                client
7587                                    .request(proto::UpdateBuffer {
7588                                        project_id,
7589                                        buffer_id,
7590                                        operations: chunk,
7591                                    })
7592                                    .await?;
7593                            }
7594                            anyhow::Ok(())
7595                        })
7596                    } else {
7597                        Task::ready(Ok(()))
7598                    }
7599                })
7600            });
7601
7602            // Any incomplete buffers have open requests waiting. Request that the host sends
7603            // creates these buffers for us again to unblock any waiting futures.
7604            for id in incomplete_buffer_ids {
7605                cx.background()
7606                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
7607                    .detach();
7608            }
7609
7610            futures::future::join_all(send_updates_for_buffers)
7611                .await
7612                .into_iter()
7613                .collect()
7614        })
7615    }
7616
7617    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7618        self.worktrees(cx)
7619            .map(|worktree| {
7620                let worktree = worktree.read(cx);
7621                proto::WorktreeMetadata {
7622                    id: worktree.id().to_proto(),
7623                    root_name: worktree.root_name().into(),
7624                    visible: worktree.is_visible(),
7625                    abs_path: worktree.abs_path().to_string_lossy().into(),
7626                }
7627            })
7628            .collect()
7629    }
7630
7631    fn set_worktrees_from_proto(
7632        &mut self,
7633        worktrees: Vec<proto::WorktreeMetadata>,
7634        cx: &mut ModelContext<Project>,
7635    ) -> Result<()> {
7636        let replica_id = self.replica_id();
7637        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
7638
7639        let mut old_worktrees_by_id = self
7640            .worktrees
7641            .drain(..)
7642            .filter_map(|worktree| {
7643                let worktree = worktree.upgrade(cx)?;
7644                Some((worktree.read(cx).id(), worktree))
7645            })
7646            .collect::<HashMap<_, _>>();
7647
7648        for worktree in worktrees {
7649            if let Some(old_worktree) =
7650                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
7651            {
7652                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
7653            } else {
7654                let worktree =
7655                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
7656                let _ = self.add_worktree(&worktree, cx);
7657            }
7658        }
7659
7660        self.metadata_changed(cx);
7661        for id in old_worktrees_by_id.keys() {
7662            cx.emit(Event::WorktreeRemoved(*id));
7663        }
7664
7665        Ok(())
7666    }
7667
7668    fn set_collaborators_from_proto(
7669        &mut self,
7670        messages: Vec<proto::Collaborator>,
7671        cx: &mut ModelContext<Self>,
7672    ) -> Result<()> {
7673        let mut collaborators = HashMap::default();
7674        for message in messages {
7675            let collaborator = Collaborator::from_proto(message)?;
7676            collaborators.insert(collaborator.peer_id, collaborator);
7677        }
7678        for old_peer_id in self.collaborators.keys() {
7679            if !collaborators.contains_key(old_peer_id) {
7680                cx.emit(Event::CollaboratorLeft(*old_peer_id));
7681            }
7682        }
7683        self.collaborators = collaborators;
7684        Ok(())
7685    }
7686
7687    fn deserialize_symbol(
7688        &self,
7689        serialized_symbol: proto::Symbol,
7690    ) -> impl Future<Output = Result<Symbol>> {
7691        let languages = self.languages.clone();
7692        async move {
7693            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7694            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7695            let start = serialized_symbol
7696                .start
7697                .ok_or_else(|| anyhow!("invalid start"))?;
7698            let end = serialized_symbol
7699                .end
7700                .ok_or_else(|| anyhow!("invalid end"))?;
7701            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7702            let path = ProjectPath {
7703                worktree_id,
7704                path: PathBuf::from(serialized_symbol.path).into(),
7705            };
7706            let language = languages
7707                .language_for_file(&path.path, None)
7708                .await
7709                .log_err();
7710            Ok(Symbol {
7711                language_server_name: LanguageServerName(
7712                    serialized_symbol.language_server_name.into(),
7713                ),
7714                source_worktree_id,
7715                path,
7716                label: {
7717                    match language {
7718                        Some(language) => {
7719                            language
7720                                .label_for_symbol(&serialized_symbol.name, kind)
7721                                .await
7722                        }
7723                        None => None,
7724                    }
7725                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7726                },
7727
7728                name: serialized_symbol.name,
7729                range: Unclipped(PointUtf16::new(start.row, start.column))
7730                    ..Unclipped(PointUtf16::new(end.row, end.column)),
7731                kind,
7732                signature: serialized_symbol
7733                    .signature
7734                    .try_into()
7735                    .map_err(|_| anyhow!("invalid signature"))?,
7736            })
7737        }
7738    }
7739
7740    async fn handle_buffer_saved(
7741        this: ModelHandle<Self>,
7742        envelope: TypedEnvelope<proto::BufferSaved>,
7743        _: Arc<Client>,
7744        mut cx: AsyncAppContext,
7745    ) -> Result<()> {
7746        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7747        let version = deserialize_version(&envelope.payload.version);
7748        let mtime = envelope
7749            .payload
7750            .mtime
7751            .ok_or_else(|| anyhow!("missing mtime"))?
7752            .into();
7753
7754        this.update(&mut cx, |this, cx| {
7755            let buffer = this
7756                .opened_buffers
7757                .get(&envelope.payload.buffer_id)
7758                .and_then(|buffer| buffer.upgrade(cx))
7759                .or_else(|| {
7760                    this.incomplete_remote_buffers
7761                        .get(&envelope.payload.buffer_id)
7762                        .and_then(|b| b.clone())
7763                });
7764            if let Some(buffer) = buffer {
7765                buffer.update(cx, |buffer, cx| {
7766                    buffer.did_save(version, fingerprint, mtime, cx);
7767                });
7768            }
7769            Ok(())
7770        })
7771    }
7772
7773    async fn handle_buffer_reloaded(
7774        this: ModelHandle<Self>,
7775        envelope: TypedEnvelope<proto::BufferReloaded>,
7776        _: Arc<Client>,
7777        mut cx: AsyncAppContext,
7778    ) -> Result<()> {
7779        let payload = envelope.payload;
7780        let version = deserialize_version(&payload.version);
7781        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7782        let line_ending = deserialize_line_ending(
7783            proto::LineEnding::from_i32(payload.line_ending)
7784                .ok_or_else(|| anyhow!("missing line ending"))?,
7785        );
7786        let mtime = payload
7787            .mtime
7788            .ok_or_else(|| anyhow!("missing mtime"))?
7789            .into();
7790        this.update(&mut cx, |this, cx| {
7791            let buffer = this
7792                .opened_buffers
7793                .get(&payload.buffer_id)
7794                .and_then(|buffer| buffer.upgrade(cx))
7795                .or_else(|| {
7796                    this.incomplete_remote_buffers
7797                        .get(&payload.buffer_id)
7798                        .cloned()
7799                        .flatten()
7800                });
7801            if let Some(buffer) = buffer {
7802                buffer.update(cx, |buffer, cx| {
7803                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7804                });
7805            }
7806            Ok(())
7807        })
7808    }
7809
7810    #[allow(clippy::type_complexity)]
7811    fn edits_from_lsp(
7812        &mut self,
7813        buffer: &ModelHandle<Buffer>,
7814        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7815        server_id: LanguageServerId,
7816        version: Option<i32>,
7817        cx: &mut ModelContext<Self>,
7818    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7819        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7820        cx.background().spawn(async move {
7821            let snapshot = snapshot?;
7822            let mut lsp_edits = lsp_edits
7823                .into_iter()
7824                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7825                .collect::<Vec<_>>();
7826            lsp_edits.sort_by_key(|(range, _)| range.start);
7827
7828            let mut lsp_edits = lsp_edits.into_iter().peekable();
7829            let mut edits = Vec::new();
7830            while let Some((range, mut new_text)) = lsp_edits.next() {
7831                // Clip invalid ranges provided by the language server.
7832                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7833                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
7834
7835                // Combine any LSP edits that are adjacent.
7836                //
7837                // Also, combine LSP edits that are separated from each other by only
7838                // a newline. This is important because for some code actions,
7839                // Rust-analyzer rewrites the entire buffer via a series of edits that
7840                // are separated by unchanged newline characters.
7841                //
7842                // In order for the diffing logic below to work properly, any edits that
7843                // cancel each other out must be combined into one.
7844                while let Some((next_range, next_text)) = lsp_edits.peek() {
7845                    if next_range.start.0 > range.end {
7846                        if next_range.start.0.row > range.end.row + 1
7847                            || next_range.start.0.column > 0
7848                            || snapshot.clip_point_utf16(
7849                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7850                                Bias::Left,
7851                            ) > range.end
7852                        {
7853                            break;
7854                        }
7855                        new_text.push('\n');
7856                    }
7857                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7858                    new_text.push_str(next_text);
7859                    lsp_edits.next();
7860                }
7861
7862                // For multiline edits, perform a diff of the old and new text so that
7863                // we can identify the changes more precisely, preserving the locations
7864                // of any anchors positioned in the unchanged regions.
7865                if range.end.row > range.start.row {
7866                    let mut offset = range.start.to_offset(&snapshot);
7867                    let old_text = snapshot.text_for_range(range).collect::<String>();
7868
7869                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7870                    let mut moved_since_edit = true;
7871                    for change in diff.iter_all_changes() {
7872                        let tag = change.tag();
7873                        let value = change.value();
7874                        match tag {
7875                            ChangeTag::Equal => {
7876                                offset += value.len();
7877                                moved_since_edit = true;
7878                            }
7879                            ChangeTag::Delete => {
7880                                let start = snapshot.anchor_after(offset);
7881                                let end = snapshot.anchor_before(offset + value.len());
7882                                if moved_since_edit {
7883                                    edits.push((start..end, String::new()));
7884                                } else {
7885                                    edits.last_mut().unwrap().0.end = end;
7886                                }
7887                                offset += value.len();
7888                                moved_since_edit = false;
7889                            }
7890                            ChangeTag::Insert => {
7891                                if moved_since_edit {
7892                                    let anchor = snapshot.anchor_after(offset);
7893                                    edits.push((anchor..anchor, value.to_string()));
7894                                } else {
7895                                    edits.last_mut().unwrap().1.push_str(value);
7896                                }
7897                                moved_since_edit = false;
7898                            }
7899                        }
7900                    }
7901                } else if range.end == range.start {
7902                    let anchor = snapshot.anchor_after(range.start);
7903                    edits.push((anchor..anchor, new_text));
7904                } else {
7905                    let edit_start = snapshot.anchor_after(range.start);
7906                    let edit_end = snapshot.anchor_before(range.end);
7907                    edits.push((edit_start..edit_end, new_text));
7908                }
7909            }
7910
7911            Ok(edits)
7912        })
7913    }
7914
7915    fn buffer_snapshot_for_lsp_version(
7916        &mut self,
7917        buffer: &ModelHandle<Buffer>,
7918        server_id: LanguageServerId,
7919        version: Option<i32>,
7920        cx: &AppContext,
7921    ) -> Result<TextBufferSnapshot> {
7922        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7923
7924        if let Some(version) = version {
7925            let buffer_id = buffer.read(cx).remote_id();
7926            let snapshots = self
7927                .buffer_snapshots
7928                .get_mut(&buffer_id)
7929                .and_then(|m| m.get_mut(&server_id))
7930                .ok_or_else(|| {
7931                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7932                })?;
7933
7934            let found_snapshot = snapshots
7935                .binary_search_by_key(&version, |e| e.version)
7936                .map(|ix| snapshots[ix].snapshot.clone())
7937                .map_err(|_| {
7938                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7939                })?;
7940
7941            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7942            Ok(found_snapshot)
7943        } else {
7944            Ok((buffer.read(cx)).text_snapshot())
7945        }
7946    }
7947
7948    pub fn language_servers(
7949        &self,
7950    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7951        self.language_server_ids
7952            .iter()
7953            .map(|((worktree_id, server_name), server_id)| {
7954                (*server_id, server_name.clone(), *worktree_id)
7955            })
7956    }
7957
7958    pub fn supplementary_language_servers(
7959        &self,
7960    ) -> impl '_
7961           + Iterator<
7962        Item = (
7963            &LanguageServerId,
7964            &(LanguageServerName, Arc<LanguageServer>),
7965        ),
7966    > {
7967        self.supplementary_language_servers.iter()
7968    }
7969
7970    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7971        if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
7972            Some(server.clone())
7973        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
7974            Some(Arc::clone(server))
7975        } else {
7976            None
7977        }
7978    }
7979
7980    pub fn language_servers_for_buffer(
7981        &self,
7982        buffer: &Buffer,
7983        cx: &AppContext,
7984    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7985        self.language_server_ids_for_buffer(buffer, cx)
7986            .into_iter()
7987            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
7988                LanguageServerState::Running {
7989                    adapter, server, ..
7990                } => Some((adapter, server)),
7991                _ => None,
7992            })
7993    }
7994
7995    fn primary_language_server_for_buffer(
7996        &self,
7997        buffer: &Buffer,
7998        cx: &AppContext,
7999    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8000        self.language_servers_for_buffer(buffer, cx).next()
8001    }
8002
8003    pub fn language_server_for_buffer(
8004        &self,
8005        buffer: &Buffer,
8006        server_id: LanguageServerId,
8007        cx: &AppContext,
8008    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8009        self.language_servers_for_buffer(buffer, cx)
8010            .find(|(_, s)| s.server_id() == server_id)
8011    }
8012
8013    fn language_server_ids_for_buffer(
8014        &self,
8015        buffer: &Buffer,
8016        cx: &AppContext,
8017    ) -> Vec<LanguageServerId> {
8018        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8019            let worktree_id = file.worktree_id(cx);
8020            language
8021                .lsp_adapters()
8022                .iter()
8023                .flat_map(|adapter| {
8024                    let key = (worktree_id, adapter.name.clone());
8025                    self.language_server_ids.get(&key).copied()
8026                })
8027                .collect()
8028        } else {
8029            Vec::new()
8030        }
8031    }
8032}
8033
8034fn subscribe_for_copilot_events(
8035    copilot: &ModelHandle<Copilot>,
8036    cx: &mut ModelContext<'_, Project>,
8037) -> gpui::Subscription {
8038    cx.subscribe(
8039        copilot,
8040        |project, copilot, copilot_event, cx| match copilot_event {
8041            copilot::Event::CopilotLanguageServerStarted => {
8042                if let Some((name, copilot_server)) = copilot.read(cx).language_server() {
8043                    let new_server_id = copilot_server.server_id();
8044                    if let hash_map::Entry::Vacant(v) =
8045                        project.supplementary_language_servers.entry(new_server_id)
8046                    {
8047                        let weak_project = cx.weak_handle();
8048                        let copilot_log_subscription = copilot_server
8049                            .on_notification::<copilot::request::LogMessage, _>(
8050                                move |params, mut cx| {
8051                                    if let Some(project) = weak_project.upgrade(&mut cx) {
8052                                        project.update(&mut cx, |_, cx| {
8053                                            cx.emit(Event::LanguageServerLog(
8054                                                new_server_id,
8055                                                params.message,
8056                                            ));
8057                                        })
8058                                    }
8059                                },
8060                            );
8061                        project.copilot_log_subscription = Some(copilot_log_subscription);
8062                        v.insert((name.clone(), Arc::clone(copilot_server)));
8063                        cx.emit(Event::LanguageServerAdded(new_server_id));
8064                    }
8065                }
8066            }
8067        },
8068    )
8069}
8070
8071fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8072    let mut literal_end = 0;
8073    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8074        if part.contains(&['*', '?', '{', '}']) {
8075            break;
8076        } else {
8077            if i > 0 {
8078                // Acount for separator prior to this part
8079                literal_end += path::MAIN_SEPARATOR.len_utf8();
8080            }
8081            literal_end += part.len();
8082        }
8083    }
8084    &glob[..literal_end]
8085}
8086
8087impl WorktreeHandle {
8088    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
8089        match self {
8090            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8091            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
8092        }
8093    }
8094
8095    pub fn handle_id(&self) -> usize {
8096        match self {
8097            WorktreeHandle::Strong(handle) => handle.id(),
8098            WorktreeHandle::Weak(handle) => handle.id(),
8099        }
8100    }
8101}
8102
8103impl OpenBuffer {
8104    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
8105        match self {
8106            OpenBuffer::Strong(handle) => Some(handle.clone()),
8107            OpenBuffer::Weak(handle) => handle.upgrade(cx),
8108            OpenBuffer::Operations(_) => None,
8109        }
8110    }
8111}
8112
8113pub struct PathMatchCandidateSet {
8114    pub snapshot: Snapshot,
8115    pub include_ignored: bool,
8116    pub include_root_name: bool,
8117}
8118
8119impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8120    type Candidates = PathMatchCandidateSetIter<'a>;
8121
8122    fn id(&self) -> usize {
8123        self.snapshot.id().to_usize()
8124    }
8125
8126    fn len(&self) -> usize {
8127        if self.include_ignored {
8128            self.snapshot.file_count()
8129        } else {
8130            self.snapshot.visible_file_count()
8131        }
8132    }
8133
8134    fn prefix(&self) -> Arc<str> {
8135        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8136            self.snapshot.root_name().into()
8137        } else if self.include_root_name {
8138            format!("{}/", self.snapshot.root_name()).into()
8139        } else {
8140            "".into()
8141        }
8142    }
8143
8144    fn candidates(&'a self, start: usize) -> Self::Candidates {
8145        PathMatchCandidateSetIter {
8146            traversal: self.snapshot.files(self.include_ignored, start),
8147        }
8148    }
8149}
8150
8151pub struct PathMatchCandidateSetIter<'a> {
8152    traversal: Traversal<'a>,
8153}
8154
8155impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8156    type Item = fuzzy::PathMatchCandidate<'a>;
8157
8158    fn next(&mut self) -> Option<Self::Item> {
8159        self.traversal.next().map(|entry| {
8160            if let EntryKind::File(char_bag) = entry.kind {
8161                fuzzy::PathMatchCandidate {
8162                    path: &entry.path,
8163                    char_bag,
8164                }
8165            } else {
8166                unreachable!()
8167            }
8168        })
8169    }
8170}
8171
8172impl Entity for Project {
8173    type Event = Event;
8174
8175    fn release(&mut self, cx: &mut gpui::AppContext) {
8176        match &self.client_state {
8177            Some(ProjectClientState::Local { .. }) => {
8178                let _ = self.unshare_internal(cx);
8179            }
8180            Some(ProjectClientState::Remote { remote_id, .. }) => {
8181                let _ = self.client.send(proto::LeaveProject {
8182                    project_id: *remote_id,
8183                });
8184                self.disconnected_from_host_internal(cx);
8185            }
8186            _ => {}
8187        }
8188    }
8189
8190    fn app_will_quit(
8191        &mut self,
8192        _: &mut AppContext,
8193    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
8194        let shutdown_futures = self
8195            .language_servers
8196            .drain()
8197            .map(|(_, server_state)| async {
8198                use LanguageServerState::*;
8199                match server_state {
8200                    Running { server, .. } => server.shutdown()?.await,
8201                    Starting(task) => task.await?.shutdown()?.await,
8202                }
8203            })
8204            .collect::<Vec<_>>();
8205
8206        Some(
8207            async move {
8208                futures::future::join_all(shutdown_futures).await;
8209            }
8210            .boxed(),
8211        )
8212    }
8213}
8214
8215impl Collaborator {
8216    fn from_proto(message: proto::Collaborator) -> Result<Self> {
8217        Ok(Self {
8218            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
8219            replica_id: message.replica_id as ReplicaId,
8220            user_id: message.user_id as UserId,
8221        })
8222    }
8223}
8224
8225impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8226    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8227        Self {
8228            worktree_id,
8229            path: path.as_ref().into(),
8230        }
8231    }
8232}
8233
8234impl ProjectLspAdapterDelegate {
8235    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8236        Arc::new(Self {
8237            project: cx.handle(),
8238            http_client: project.client.http_client(),
8239        })
8240    }
8241}
8242
8243impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8244    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8245        self.project
8246            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8247    }
8248
8249    fn http_client(&self) -> Arc<dyn HttpClient> {
8250        self.http_client.clone()
8251    }
8252}
8253
8254fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8255    proto::Symbol {
8256        language_server_name: symbol.language_server_name.0.to_string(),
8257        source_worktree_id: symbol.source_worktree_id.to_proto(),
8258        worktree_id: symbol.path.worktree_id.to_proto(),
8259        path: symbol.path.path.to_string_lossy().to_string(),
8260        name: symbol.name.clone(),
8261        kind: unsafe { mem::transmute(symbol.kind) },
8262        start: Some(proto::PointUtf16 {
8263            row: symbol.range.start.0.row,
8264            column: symbol.range.start.0.column,
8265        }),
8266        end: Some(proto::PointUtf16 {
8267            row: symbol.range.end.0.row,
8268            column: symbol.range.end.0.column,
8269        }),
8270        signature: symbol.signature.to_vec(),
8271    }
8272}
8273
8274fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8275    let mut path_components = path.components();
8276    let mut base_components = base.components();
8277    let mut components: Vec<Component> = Vec::new();
8278    loop {
8279        match (path_components.next(), base_components.next()) {
8280            (None, None) => break,
8281            (Some(a), None) => {
8282                components.push(a);
8283                components.extend(path_components.by_ref());
8284                break;
8285            }
8286            (None, _) => components.push(Component::ParentDir),
8287            (Some(a), Some(b)) if components.is_empty() && a == b => (),
8288            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8289            (Some(a), Some(_)) => {
8290                components.push(Component::ParentDir);
8291                for _ in base_components {
8292                    components.push(Component::ParentDir);
8293                }
8294                components.push(a);
8295                components.extend(path_components.by_ref());
8296                break;
8297            }
8298        }
8299    }
8300    components.iter().map(|c| c.as_os_str()).collect()
8301}
8302
8303impl Item for Buffer {
8304    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8305        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8306    }
8307
8308    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8309        File::from_dyn(self.file()).map(|file| ProjectPath {
8310            worktree_id: file.worktree_id(cx),
8311            path: file.path().clone(),
8312        })
8313    }
8314}
8315
8316async fn wait_for_loading_buffer(
8317    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
8318) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
8319    loop {
8320        if let Some(result) = receiver.borrow().as_ref() {
8321            match result {
8322                Ok(buffer) => return Ok(buffer.to_owned()),
8323                Err(e) => return Err(e.to_owned()),
8324            }
8325        }
8326        receiver.next().await;
8327    }
8328}