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