project.rs

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