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 = cx
3134            .update(|cx| language_server.initialize(initialization_options, cx))?
3135            .await?;
3136
3137        language_server
3138            .notify::<lsp::notification::DidChangeConfiguration>(
3139                lsp::DidChangeConfigurationParams {
3140                    settings: workspace_config,
3141                },
3142            )
3143            .ok();
3144
3145        Ok(language_server)
3146    }
3147
3148    fn insert_newly_running_language_server(
3149        &mut self,
3150        language: Arc<Language>,
3151        adapter: Arc<CachedLspAdapter>,
3152        language_server: Arc<LanguageServer>,
3153        server_id: LanguageServerId,
3154        key: (WorktreeId, LanguageServerName),
3155        cx: &mut ModelContext<Self>,
3156    ) -> Result<()> {
3157        // If the language server for this key doesn't match the server id, don't store the
3158        // server. Which will cause it to be dropped, killing the process
3159        if self
3160            .language_server_ids
3161            .get(&key)
3162            .map(|id| id != &server_id)
3163            .unwrap_or(false)
3164        {
3165            return Ok(());
3166        }
3167
3168        // Update language_servers collection with Running variant of LanguageServerState
3169        // indicating that the server is up and running and ready
3170        self.language_servers.insert(
3171            server_id,
3172            LanguageServerState::Running {
3173                adapter: adapter.clone(),
3174                language: language.clone(),
3175                watched_paths: Default::default(),
3176                server: language_server.clone(),
3177                simulate_disk_based_diagnostics_completion: None,
3178            },
3179        );
3180
3181        self.language_server_statuses.insert(
3182            server_id,
3183            LanguageServerStatus {
3184                name: language_server.name().to_string(),
3185                pending_work: Default::default(),
3186                has_pending_diagnostic_updates: false,
3187                progress_tokens: Default::default(),
3188            },
3189        );
3190
3191        cx.emit(Event::LanguageServerAdded(server_id));
3192
3193        if let Some(project_id) = self.remote_id() {
3194            self.client.send(proto::StartLanguageServer {
3195                project_id,
3196                server: Some(proto::LanguageServer {
3197                    id: server_id.0 as u64,
3198                    name: language_server.name().to_string(),
3199                }),
3200            })?;
3201        }
3202
3203        // Tell the language server about every open buffer in the worktree that matches the language.
3204        for buffer in self.opened_buffers.values() {
3205            if let Some(buffer_handle) = buffer.upgrade() {
3206                let buffer = buffer_handle.read(cx);
3207                let file = match File::from_dyn(buffer.file()) {
3208                    Some(file) => file,
3209                    None => continue,
3210                };
3211                let language = match buffer.language() {
3212                    Some(language) => language,
3213                    None => continue,
3214                };
3215
3216                if file.worktree.read(cx).id() != key.0
3217                    || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3218                {
3219                    continue;
3220                }
3221
3222                let file = match file.as_local() {
3223                    Some(file) => file,
3224                    None => continue,
3225                };
3226
3227                let versions = self
3228                    .buffer_snapshots
3229                    .entry(buffer.remote_id())
3230                    .or_default()
3231                    .entry(server_id)
3232                    .or_insert_with(|| {
3233                        vec![LspBufferSnapshot {
3234                            version: 0,
3235                            snapshot: buffer.text_snapshot(),
3236                        }]
3237                    });
3238
3239                let snapshot = versions.last().unwrap();
3240                let version = snapshot.version;
3241                let initial_snapshot = &snapshot.snapshot;
3242                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3243                language_server.notify::<lsp::notification::DidOpenTextDocument>(
3244                    lsp::DidOpenTextDocumentParams {
3245                        text_document: lsp::TextDocumentItem::new(
3246                            uri,
3247                            adapter
3248                                .language_ids
3249                                .get(language.name().as_ref())
3250                                .cloned()
3251                                .unwrap_or_default(),
3252                            version,
3253                            initial_snapshot.text(),
3254                        ),
3255                    },
3256                )?;
3257
3258                buffer_handle.update(cx, |buffer, cx| {
3259                    buffer.set_completion_triggers(
3260                        language_server
3261                            .capabilities()
3262                            .completion_provider
3263                            .as_ref()
3264                            .and_then(|provider| provider.trigger_characters.clone())
3265                            .unwrap_or_default(),
3266                        cx,
3267                    )
3268                });
3269            }
3270        }
3271
3272        cx.notify();
3273        Ok(())
3274    }
3275
3276    // Returns a list of all of the worktrees which no longer have a language server and the root path
3277    // for the stopped server
3278    fn stop_language_server(
3279        &mut self,
3280        worktree_id: WorktreeId,
3281        adapter_name: LanguageServerName,
3282        cx: &mut ModelContext<Self>,
3283    ) -> Task<Vec<WorktreeId>> {
3284        let key = (worktree_id, adapter_name);
3285        if let Some(server_id) = self.language_server_ids.remove(&key) {
3286            log::info!("stopping language server {}", key.1 .0);
3287
3288            // Remove other entries for this language server as well
3289            let mut orphaned_worktrees = vec![worktree_id];
3290            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3291            for other_key in other_keys {
3292                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3293                    self.language_server_ids.remove(&other_key);
3294                    orphaned_worktrees.push(other_key.0);
3295                }
3296            }
3297
3298            for buffer in self.opened_buffers.values() {
3299                if let Some(buffer) = buffer.upgrade() {
3300                    buffer.update(cx, |buffer, cx| {
3301                        buffer.update_diagnostics(server_id, Default::default(), cx);
3302                    });
3303                }
3304            }
3305            for worktree in &self.worktrees {
3306                if let Some(worktree) = worktree.upgrade() {
3307                    worktree.update(cx, |worktree, cx| {
3308                        if let Some(worktree) = worktree.as_local_mut() {
3309                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3310                        }
3311                    });
3312                }
3313            }
3314
3315            self.language_server_statuses.remove(&server_id);
3316            cx.notify();
3317
3318            let server_state = self.language_servers.remove(&server_id);
3319            cx.emit(Event::LanguageServerRemoved(server_id));
3320            cx.spawn(move |this, mut cx| async move {
3321                let server = match server_state {
3322                    Some(LanguageServerState::Starting(task)) => task.await,
3323                    Some(LanguageServerState::Running { server, .. }) => Some(server),
3324                    None => None,
3325                };
3326
3327                if let Some(server) = server {
3328                    if let Some(shutdown) = server.shutdown() {
3329                        shutdown.await;
3330                    }
3331                }
3332
3333                if let Some(this) = this.upgrade() {
3334                    this.update(&mut cx, |this, cx| {
3335                        this.language_server_statuses.remove(&server_id);
3336                        cx.notify();
3337                    })
3338                    .ok();
3339                }
3340
3341                orphaned_worktrees
3342            })
3343        } else {
3344            Task::ready(Vec::new())
3345        }
3346    }
3347
3348    pub fn restart_language_servers_for_buffers(
3349        &mut self,
3350        buffers: impl IntoIterator<Item = Model<Buffer>>,
3351        cx: &mut ModelContext<Self>,
3352    ) -> Option<()> {
3353        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3354            .into_iter()
3355            .filter_map(|buffer| {
3356                let buffer = buffer.read(cx);
3357                let file = File::from_dyn(buffer.file())?;
3358                let full_path = file.full_path(cx);
3359                let language = self
3360                    .languages
3361                    .language_for_file(&full_path, Some(buffer.as_rope()))
3362                    .now_or_never()?
3363                    .ok()?;
3364                Some((file.worktree.clone(), language))
3365            })
3366            .collect();
3367        for (worktree, language) in language_server_lookup_info {
3368            self.restart_language_servers(worktree, language, cx);
3369        }
3370
3371        None
3372    }
3373
3374    fn restart_language_servers(
3375        &mut self,
3376        worktree: Model<Worktree>,
3377        language: Arc<Language>,
3378        cx: &mut ModelContext<Self>,
3379    ) {
3380        let worktree_id = worktree.read(cx).id();
3381
3382        let stop_tasks = language
3383            .lsp_adapters()
3384            .iter()
3385            .map(|adapter| {
3386                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
3387                (stop_task, adapter.name.clone())
3388            })
3389            .collect::<Vec<_>>();
3390        if stop_tasks.is_empty() {
3391            return;
3392        }
3393
3394        cx.spawn(move |this, mut cx| async move {
3395            // For each stopped language server, record all of the worktrees with which
3396            // it was associated.
3397            let mut affected_worktrees = Vec::new();
3398            for (stop_task, language_server_name) in stop_tasks {
3399                for affected_worktree_id in stop_task.await {
3400                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
3401                }
3402            }
3403
3404            this.update(&mut cx, |this, cx| {
3405                // Restart the language server for the given worktree.
3406                this.start_language_servers(&worktree, language.clone(), cx);
3407
3408                // Lookup new server ids and set them for each of the orphaned worktrees
3409                for (affected_worktree_id, language_server_name) in affected_worktrees {
3410                    if let Some(new_server_id) = this
3411                        .language_server_ids
3412                        .get(&(worktree_id, language_server_name.clone()))
3413                        .cloned()
3414                    {
3415                        this.language_server_ids
3416                            .insert((affected_worktree_id, language_server_name), new_server_id);
3417                    }
3418                }
3419            })
3420            .ok();
3421        })
3422        .detach();
3423    }
3424
3425    fn check_errored_server(
3426        language: Arc<Language>,
3427        adapter: Arc<CachedLspAdapter>,
3428        server_id: LanguageServerId,
3429        installation_test_binary: Option<LanguageServerBinary>,
3430        cx: &mut ModelContext<Self>,
3431    ) {
3432        if !adapter.can_be_reinstalled() {
3433            log::info!(
3434                "Validation check requested for {:?} but it cannot be reinstalled",
3435                adapter.name.0
3436            );
3437            return;
3438        }
3439
3440        cx.spawn(move |this, mut cx| async move {
3441            log::info!("About to spawn test binary");
3442
3443            // A lack of test binary counts as a failure
3444            let process = installation_test_binary.and_then(|binary| {
3445                smol::process::Command::new(&binary.path)
3446                    .current_dir(&binary.path)
3447                    .args(binary.arguments)
3448                    .stdin(Stdio::piped())
3449                    .stdout(Stdio::piped())
3450                    .stderr(Stdio::inherit())
3451                    .kill_on_drop(true)
3452                    .spawn()
3453                    .ok()
3454            });
3455
3456            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3457            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3458
3459            let mut errored = false;
3460            if let Some(mut process) = process {
3461                futures::select! {
3462                    status = process.status().fuse() => match status {
3463                        Ok(status) => errored = !status.success(),
3464                        Err(_) => errored = true,
3465                    },
3466
3467                    _ = timeout => {
3468                        log::info!("test binary time-ed out, this counts as a success");
3469                        _ = process.kill();
3470                    }
3471                }
3472            } else {
3473                log::warn!("test binary failed to launch");
3474                errored = true;
3475            }
3476
3477            if errored {
3478                log::warn!("test binary check failed");
3479                let task = this
3480                    .update(&mut cx, move |this, cx| {
3481                        this.reinstall_language_server(language, adapter, server_id, cx)
3482                    })
3483                    .ok()
3484                    .flatten();
3485
3486                if let Some(task) = task {
3487                    task.await;
3488                }
3489            }
3490        })
3491        .detach();
3492    }
3493
3494    fn on_lsp_progress(
3495        &mut self,
3496        progress: lsp::ProgressParams,
3497        language_server_id: LanguageServerId,
3498        disk_based_diagnostics_progress_token: Option<String>,
3499        cx: &mut ModelContext<Self>,
3500    ) {
3501        let token = match progress.token {
3502            lsp::NumberOrString::String(token) => token,
3503            lsp::NumberOrString::Number(token) => {
3504                log::info!("skipping numeric progress token {}", token);
3505                return;
3506            }
3507        };
3508        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3509        let language_server_status =
3510            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3511                status
3512            } else {
3513                return;
3514            };
3515
3516        if !language_server_status.progress_tokens.contains(&token) {
3517            return;
3518        }
3519
3520        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3521            .as_ref()
3522            .map_or(false, |disk_based_token| {
3523                token.starts_with(disk_based_token)
3524            });
3525
3526        match progress {
3527            lsp::WorkDoneProgress::Begin(report) => {
3528                if is_disk_based_diagnostics_progress {
3529                    language_server_status.has_pending_diagnostic_updates = true;
3530                    self.disk_based_diagnostics_started(language_server_id, cx);
3531                    self.buffer_ordered_messages_tx
3532                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3533                            language_server_id,
3534                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3535                        })
3536                        .ok();
3537                } else {
3538                    self.on_lsp_work_start(
3539                        language_server_id,
3540                        token.clone(),
3541                        LanguageServerProgress {
3542                            message: report.message.clone(),
3543                            percentage: report.percentage.map(|p| p as usize),
3544                            last_update_at: Instant::now(),
3545                        },
3546                        cx,
3547                    );
3548                    self.buffer_ordered_messages_tx
3549                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3550                            language_server_id,
3551                            message: proto::update_language_server::Variant::WorkStart(
3552                                proto::LspWorkStart {
3553                                    token,
3554                                    message: report.message,
3555                                    percentage: report.percentage.map(|p| p as u32),
3556                                },
3557                            ),
3558                        })
3559                        .ok();
3560                }
3561            }
3562            lsp::WorkDoneProgress::Report(report) => {
3563                if !is_disk_based_diagnostics_progress {
3564                    self.on_lsp_work_progress(
3565                        language_server_id,
3566                        token.clone(),
3567                        LanguageServerProgress {
3568                            message: report.message.clone(),
3569                            percentage: report.percentage.map(|p| p as usize),
3570                            last_update_at: Instant::now(),
3571                        },
3572                        cx,
3573                    );
3574                    self.buffer_ordered_messages_tx
3575                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3576                            language_server_id,
3577                            message: proto::update_language_server::Variant::WorkProgress(
3578                                proto::LspWorkProgress {
3579                                    token,
3580                                    message: report.message,
3581                                    percentage: report.percentage.map(|p| p as u32),
3582                                },
3583                            ),
3584                        })
3585                        .ok();
3586                }
3587            }
3588            lsp::WorkDoneProgress::End(_) => {
3589                language_server_status.progress_tokens.remove(&token);
3590
3591                if is_disk_based_diagnostics_progress {
3592                    language_server_status.has_pending_diagnostic_updates = false;
3593                    self.disk_based_diagnostics_finished(language_server_id, cx);
3594                    self.buffer_ordered_messages_tx
3595                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3596                            language_server_id,
3597                            message:
3598                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3599                                    Default::default(),
3600                                ),
3601                        })
3602                        .ok();
3603                } else {
3604                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3605                    self.buffer_ordered_messages_tx
3606                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3607                            language_server_id,
3608                            message: proto::update_language_server::Variant::WorkEnd(
3609                                proto::LspWorkEnd { token },
3610                            ),
3611                        })
3612                        .ok();
3613                }
3614            }
3615        }
3616    }
3617
3618    fn on_lsp_work_start(
3619        &mut self,
3620        language_server_id: LanguageServerId,
3621        token: String,
3622        progress: LanguageServerProgress,
3623        cx: &mut ModelContext<Self>,
3624    ) {
3625        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3626            status.pending_work.insert(token, progress);
3627            cx.notify();
3628        }
3629    }
3630
3631    fn on_lsp_work_progress(
3632        &mut self,
3633        language_server_id: LanguageServerId,
3634        token: String,
3635        progress: LanguageServerProgress,
3636        cx: &mut ModelContext<Self>,
3637    ) {
3638        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3639            let entry = status
3640                .pending_work
3641                .entry(token)
3642                .or_insert(LanguageServerProgress {
3643                    message: Default::default(),
3644                    percentage: Default::default(),
3645                    last_update_at: progress.last_update_at,
3646                });
3647            if progress.message.is_some() {
3648                entry.message = progress.message;
3649            }
3650            if progress.percentage.is_some() {
3651                entry.percentage = progress.percentage;
3652            }
3653            entry.last_update_at = progress.last_update_at;
3654            cx.notify();
3655        }
3656    }
3657
3658    fn on_lsp_work_end(
3659        &mut self,
3660        language_server_id: LanguageServerId,
3661        token: String,
3662        cx: &mut ModelContext<Self>,
3663    ) {
3664        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3665            cx.emit(Event::RefreshInlayHints);
3666            status.pending_work.remove(&token);
3667            cx.notify();
3668        }
3669    }
3670
3671    fn on_lsp_did_change_watched_files(
3672        &mut self,
3673        language_server_id: LanguageServerId,
3674        params: DidChangeWatchedFilesRegistrationOptions,
3675        cx: &mut ModelContext<Self>,
3676    ) {
3677        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3678            self.language_servers.get_mut(&language_server_id)
3679        {
3680            let mut builders = HashMap::default();
3681            for watcher in params.watchers {
3682                for worktree in &self.worktrees {
3683                    if let Some(worktree) = worktree.upgrade() {
3684                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3685                            if let Some(abs_path) = tree.abs_path().to_str() {
3686                                let relative_glob_pattern = match &watcher.glob_pattern {
3687                                    lsp::GlobPattern::String(s) => s
3688                                        .strip_prefix(abs_path)
3689                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3690                                    lsp::GlobPattern::Relative(rp) => {
3691                                        let base_uri = match &rp.base_uri {
3692                                            lsp::OneOf::Left(workspace_folder) => {
3693                                                &workspace_folder.uri
3694                                            }
3695                                            lsp::OneOf::Right(base_uri) => base_uri,
3696                                        };
3697                                        base_uri.to_file_path().ok().and_then(|file_path| {
3698                                            (file_path.to_str() == Some(abs_path))
3699                                                .then_some(rp.pattern.as_str())
3700                                        })
3701                                    }
3702                                };
3703                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3704                                    let literal_prefix = glob_literal_prefix(relative_glob_pattern);
3705                                    tree.as_local_mut()
3706                                        .unwrap()
3707                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3708                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3709                                        builders
3710                                            .entry(tree.id())
3711                                            .or_insert_with(|| GlobSetBuilder::new())
3712                                            .add(glob);
3713                                    }
3714                                    return true;
3715                                }
3716                            }
3717                            false
3718                        });
3719                        if glob_is_inside_worktree {
3720                            break;
3721                        }
3722                    }
3723                }
3724            }
3725
3726            watched_paths.clear();
3727            for (worktree_id, builder) in builders {
3728                if let Ok(globset) = builder.build() {
3729                    watched_paths.insert(worktree_id, globset);
3730                }
3731            }
3732
3733            cx.notify();
3734        }
3735    }
3736
3737    async fn on_lsp_workspace_edit(
3738        this: WeakModel<Self>,
3739        params: lsp::ApplyWorkspaceEditParams,
3740        server_id: LanguageServerId,
3741        adapter: Arc<CachedLspAdapter>,
3742        mut cx: AsyncAppContext,
3743    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3744        let this = this
3745            .upgrade()
3746            .ok_or_else(|| anyhow!("project project closed"))?;
3747        let language_server = this
3748            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3749            .ok_or_else(|| anyhow!("language server not found"))?;
3750        let transaction = Self::deserialize_workspace_edit(
3751            this.clone(),
3752            params.edit,
3753            true,
3754            adapter.clone(),
3755            language_server.clone(),
3756            &mut cx,
3757        )
3758        .await
3759        .log_err();
3760        this.update(&mut cx, |this, _| {
3761            if let Some(transaction) = transaction {
3762                this.last_workspace_edits_by_language_server
3763                    .insert(server_id, transaction);
3764            }
3765        })?;
3766        Ok(lsp::ApplyWorkspaceEditResponse {
3767            applied: true,
3768            failed_change: None,
3769            failure_reason: None,
3770        })
3771    }
3772
3773    pub fn language_server_statuses(
3774        &self,
3775    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3776        self.language_server_statuses.values()
3777    }
3778
3779    pub fn update_diagnostics(
3780        &mut self,
3781        language_server_id: LanguageServerId,
3782        mut params: lsp::PublishDiagnosticsParams,
3783        disk_based_sources: &[String],
3784        cx: &mut ModelContext<Self>,
3785    ) -> Result<()> {
3786        let abs_path = params
3787            .uri
3788            .to_file_path()
3789            .map_err(|_| anyhow!("URI is not a file"))?;
3790        let mut diagnostics = Vec::default();
3791        let mut primary_diagnostic_group_ids = HashMap::default();
3792        let mut sources_by_group_id = HashMap::default();
3793        let mut supporting_diagnostics = HashMap::default();
3794
3795        // Ensure that primary diagnostics are always the most severe
3796        params.diagnostics.sort_by_key(|item| item.severity);
3797
3798        for diagnostic in &params.diagnostics {
3799            let source = diagnostic.source.as_ref();
3800            let code = diagnostic.code.as_ref().map(|code| match code {
3801                lsp::NumberOrString::Number(code) => code.to_string(),
3802                lsp::NumberOrString::String(code) => code.clone(),
3803            });
3804            let range = range_from_lsp(diagnostic.range);
3805            let is_supporting = diagnostic
3806                .related_information
3807                .as_ref()
3808                .map_or(false, |infos| {
3809                    infos.iter().any(|info| {
3810                        primary_diagnostic_group_ids.contains_key(&(
3811                            source,
3812                            code.clone(),
3813                            range_from_lsp(info.location.range),
3814                        ))
3815                    })
3816                });
3817
3818            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3819                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3820            });
3821
3822            if is_supporting {
3823                supporting_diagnostics.insert(
3824                    (source, code.clone(), range),
3825                    (diagnostic.severity, is_unnecessary),
3826                );
3827            } else {
3828                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3829                let is_disk_based =
3830                    source.map_or(false, |source| disk_based_sources.contains(source));
3831
3832                sources_by_group_id.insert(group_id, source);
3833                primary_diagnostic_group_ids
3834                    .insert((source, code.clone(), range.clone()), group_id);
3835
3836                diagnostics.push(DiagnosticEntry {
3837                    range,
3838                    diagnostic: Diagnostic {
3839                        source: diagnostic.source.clone(),
3840                        code: code.clone(),
3841                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3842                        message: diagnostic.message.trim().to_string(),
3843                        group_id,
3844                        is_primary: true,
3845                        is_disk_based,
3846                        is_unnecessary,
3847                    },
3848                });
3849                if let Some(infos) = &diagnostic.related_information {
3850                    for info in infos {
3851                        if info.location.uri == params.uri && !info.message.is_empty() {
3852                            let range = range_from_lsp(info.location.range);
3853                            diagnostics.push(DiagnosticEntry {
3854                                range,
3855                                diagnostic: Diagnostic {
3856                                    source: diagnostic.source.clone(),
3857                                    code: code.clone(),
3858                                    severity: DiagnosticSeverity::INFORMATION,
3859                                    message: info.message.trim().to_string(),
3860                                    group_id,
3861                                    is_primary: false,
3862                                    is_disk_based,
3863                                    is_unnecessary: false,
3864                                },
3865                            });
3866                        }
3867                    }
3868                }
3869            }
3870        }
3871
3872        for entry in &mut diagnostics {
3873            let diagnostic = &mut entry.diagnostic;
3874            if !diagnostic.is_primary {
3875                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3876                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3877                    source,
3878                    diagnostic.code.clone(),
3879                    entry.range.clone(),
3880                )) {
3881                    if let Some(severity) = severity {
3882                        diagnostic.severity = severity;
3883                    }
3884                    diagnostic.is_unnecessary = is_unnecessary;
3885                }
3886            }
3887        }
3888
3889        self.update_diagnostic_entries(
3890            language_server_id,
3891            abs_path,
3892            params.version,
3893            diagnostics,
3894            cx,
3895        )?;
3896        Ok(())
3897    }
3898
3899    pub fn update_diagnostic_entries(
3900        &mut self,
3901        server_id: LanguageServerId,
3902        abs_path: PathBuf,
3903        version: Option<i32>,
3904        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3905        cx: &mut ModelContext<Project>,
3906    ) -> Result<(), anyhow::Error> {
3907        let (worktree, relative_path) = self
3908            .find_local_worktree(&abs_path, cx)
3909            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3910
3911        let project_path = ProjectPath {
3912            worktree_id: worktree.read(cx).id(),
3913            path: relative_path.into(),
3914        };
3915
3916        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3917            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3918        }
3919
3920        let updated = worktree.update(cx, |worktree, cx| {
3921            worktree
3922                .as_local_mut()
3923                .ok_or_else(|| anyhow!("not a local worktree"))?
3924                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3925        })?;
3926        if updated {
3927            cx.emit(Event::DiagnosticsUpdated {
3928                language_server_id: server_id,
3929                path: project_path,
3930            });
3931        }
3932        Ok(())
3933    }
3934
3935    fn update_buffer_diagnostics(
3936        &mut self,
3937        buffer: &Model<Buffer>,
3938        server_id: LanguageServerId,
3939        version: Option<i32>,
3940        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3941        cx: &mut ModelContext<Self>,
3942    ) -> Result<()> {
3943        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3944            Ordering::Equal
3945                .then_with(|| b.is_primary.cmp(&a.is_primary))
3946                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3947                .then_with(|| a.severity.cmp(&b.severity))
3948                .then_with(|| a.message.cmp(&b.message))
3949        }
3950
3951        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3952
3953        diagnostics.sort_unstable_by(|a, b| {
3954            Ordering::Equal
3955                .then_with(|| a.range.start.cmp(&b.range.start))
3956                .then_with(|| b.range.end.cmp(&a.range.end))
3957                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3958        });
3959
3960        let mut sanitized_diagnostics = Vec::new();
3961        let edits_since_save = Patch::new(
3962            snapshot
3963                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3964                .collect(),
3965        );
3966        for entry in diagnostics {
3967            let start;
3968            let end;
3969            if entry.diagnostic.is_disk_based {
3970                // Some diagnostics are based on files on disk instead of buffers'
3971                // current contents. Adjust these diagnostics' ranges to reflect
3972                // any unsaved edits.
3973                start = edits_since_save.old_to_new(entry.range.start);
3974                end = edits_since_save.old_to_new(entry.range.end);
3975            } else {
3976                start = entry.range.start;
3977                end = entry.range.end;
3978            }
3979
3980            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3981                ..snapshot.clip_point_utf16(end, Bias::Right);
3982
3983            // Expand empty ranges by one codepoint
3984            if range.start == range.end {
3985                // This will be go to the next boundary when being clipped
3986                range.end.column += 1;
3987                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3988                if range.start == range.end && range.end.column > 0 {
3989                    range.start.column -= 1;
3990                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3991                }
3992            }
3993
3994            sanitized_diagnostics.push(DiagnosticEntry {
3995                range,
3996                diagnostic: entry.diagnostic,
3997            });
3998        }
3999        drop(edits_since_save);
4000
4001        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4002        buffer.update(cx, |buffer, cx| {
4003            buffer.update_diagnostics(server_id, set, cx)
4004        });
4005        Ok(())
4006    }
4007
4008    pub fn reload_buffers(
4009        &self,
4010        buffers: HashSet<Model<Buffer>>,
4011        push_to_history: bool,
4012        cx: &mut ModelContext<Self>,
4013    ) -> Task<Result<ProjectTransaction>> {
4014        let mut local_buffers = Vec::new();
4015        let mut remote_buffers = None;
4016        for buffer_handle in buffers {
4017            let buffer = buffer_handle.read(cx);
4018            if buffer.is_dirty() {
4019                if let Some(file) = File::from_dyn(buffer.file()) {
4020                    if file.is_local() {
4021                        local_buffers.push(buffer_handle);
4022                    } else {
4023                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4024                    }
4025                }
4026            }
4027        }
4028
4029        let remote_buffers = self.remote_id().zip(remote_buffers);
4030        let client = self.client.clone();
4031
4032        cx.spawn(move |this, mut cx| async move {
4033            let mut project_transaction = ProjectTransaction::default();
4034
4035            if let Some((project_id, remote_buffers)) = remote_buffers {
4036                let response = client
4037                    .request(proto::ReloadBuffers {
4038                        project_id,
4039                        buffer_ids: remote_buffers
4040                            .iter()
4041                            .filter_map(|buffer| {
4042                                buffer
4043                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
4044                                    .ok()
4045                            })
4046                            .collect(),
4047                    })
4048                    .await?
4049                    .transaction
4050                    .ok_or_else(|| anyhow!("missing transaction"))?;
4051                project_transaction = this
4052                    .update(&mut cx, |this, cx| {
4053                        this.deserialize_project_transaction(response, push_to_history, cx)
4054                    })?
4055                    .await?;
4056            }
4057
4058            for buffer in local_buffers {
4059                let transaction = buffer
4060                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4061                    .await?;
4062                buffer.update(&mut cx, |buffer, cx| {
4063                    if let Some(transaction) = transaction {
4064                        if !push_to_history {
4065                            buffer.forget_transaction(transaction.id);
4066                        }
4067                        project_transaction.0.insert(cx.handle(), transaction);
4068                    }
4069                })?;
4070            }
4071
4072            Ok(project_transaction)
4073        })
4074    }
4075
4076    pub fn format(
4077        &mut self,
4078        buffers: HashSet<Model<Buffer>>,
4079        push_to_history: bool,
4080        trigger: FormatTrigger,
4081        cx: &mut ModelContext<Project>,
4082    ) -> Task<anyhow::Result<ProjectTransaction>> {
4083        if self.is_local() {
4084            let mut buffers_with_paths_and_servers = buffers
4085                .into_iter()
4086                .filter_map(|buffer_handle| {
4087                    let buffer = buffer_handle.read(cx);
4088                    let file = File::from_dyn(buffer.file())?;
4089                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4090                    let server = self
4091                        .primary_language_server_for_buffer(buffer, cx)
4092                        .map(|s| s.1.clone());
4093                    Some((buffer_handle, buffer_abs_path, server))
4094                })
4095                .collect::<Vec<_>>();
4096
4097            cx.spawn(move |project, mut cx| async move {
4098                // Do not allow multiple concurrent formatting requests for the
4099                // same buffer.
4100                project.update(&mut cx, |this, cx| {
4101                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
4102                        this.buffers_being_formatted
4103                            .insert(buffer.read(cx).remote_id())
4104                    });
4105                })?;
4106
4107                let _cleanup = defer({
4108                    let this = project.clone();
4109                    let mut cx = cx.clone();
4110                    let buffers = &buffers_with_paths_and_servers;
4111                    move || {
4112                        this.update(&mut cx, |this, cx| {
4113                            for (buffer, _, _) in buffers {
4114                                this.buffers_being_formatted
4115                                    .remove(&buffer.read(cx).remote_id());
4116                            }
4117                        })
4118                        .ok();
4119                    }
4120                });
4121
4122                let mut project_transaction = ProjectTransaction::default();
4123                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
4124                    let settings = buffer.update(&mut cx, |buffer, cx| {
4125                        language_settings(buffer.language(), buffer.file(), cx).clone()
4126                    })?;
4127
4128                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4129                    let ensure_final_newline = settings.ensure_final_newline_on_save;
4130                    let tab_size = settings.tab_size;
4131
4132                    // First, format buffer's whitespace according to the settings.
4133                    let trailing_whitespace_diff = if remove_trailing_whitespace {
4134                        Some(
4135                            buffer
4136                                .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4137                                .await,
4138                        )
4139                    } else {
4140                        None
4141                    };
4142                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4143                        buffer.finalize_last_transaction();
4144                        buffer.start_transaction();
4145                        if let Some(diff) = trailing_whitespace_diff {
4146                            buffer.apply_diff(diff, cx);
4147                        }
4148                        if ensure_final_newline {
4149                            buffer.ensure_final_newline(cx);
4150                        }
4151                        buffer.end_transaction(cx)
4152                    })?;
4153
4154                    // Apply language-specific formatting using either a language server
4155                    // or external command.
4156                    let mut format_operation = None;
4157                    match (&settings.formatter, &settings.format_on_save) {
4158                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4159
4160                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4161                        | (_, FormatOnSave::LanguageServer) => {
4162                            if let Some((language_server, buffer_abs_path)) =
4163                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4164                            {
4165                                format_operation = Some(FormatOperation::Lsp(
4166                                    Self::format_via_lsp(
4167                                        &project,
4168                                        buffer,
4169                                        buffer_abs_path,
4170                                        language_server,
4171                                        tab_size,
4172                                        &mut cx,
4173                                    )
4174                                    .await
4175                                    .context("failed to format via language server")?,
4176                                ));
4177                            }
4178                        }
4179
4180                        (
4181                            Formatter::External { command, arguments },
4182                            FormatOnSave::On | FormatOnSave::Off,
4183                        )
4184                        | (_, FormatOnSave::External { command, arguments }) => {
4185                            if let Some(buffer_abs_path) = buffer_abs_path {
4186                                format_operation = Self::format_via_external_command(
4187                                    buffer,
4188                                    buffer_abs_path,
4189                                    command,
4190                                    arguments,
4191                                    &mut cx,
4192                                )
4193                                .await
4194                                .context(format!(
4195                                    "failed to format via external command {:?}",
4196                                    command
4197                                ))?
4198                                .map(FormatOperation::External);
4199                            }
4200                        }
4201                        (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4202                            if let Some(new_operation) =
4203                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4204                                    .await
4205                            {
4206                                format_operation = Some(new_operation);
4207                            } else if let Some((language_server, buffer_abs_path)) =
4208                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4209                            {
4210                                format_operation = Some(FormatOperation::Lsp(
4211                                    Self::format_via_lsp(
4212                                        &project,
4213                                        buffer,
4214                                        buffer_abs_path,
4215                                        language_server,
4216                                        tab_size,
4217                                        &mut cx,
4218                                    )
4219                                    .await
4220                                    .context("failed to format via language server")?,
4221                                ));
4222                            }
4223                        }
4224                        (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4225                            if let Some(new_operation) =
4226                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4227                                    .await
4228                            {
4229                                format_operation = Some(new_operation);
4230                            }
4231                        }
4232                    };
4233
4234                    buffer.update(&mut cx, |b, cx| {
4235                        // If the buffer had its whitespace formatted and was edited while the language-specific
4236                        // formatting was being computed, avoid applying the language-specific formatting, because
4237                        // it can't be grouped with the whitespace formatting in the undo history.
4238                        if let Some(transaction_id) = whitespace_transaction_id {
4239                            if b.peek_undo_stack()
4240                                .map_or(true, |e| e.transaction_id() != transaction_id)
4241                            {
4242                                format_operation.take();
4243                            }
4244                        }
4245
4246                        // Apply any language-specific formatting, and group the two formatting operations
4247                        // in the buffer's undo history.
4248                        if let Some(operation) = format_operation {
4249                            match operation {
4250                                FormatOperation::Lsp(edits) => {
4251                                    b.edit(edits, None, cx);
4252                                }
4253                                FormatOperation::External(diff) => {
4254                                    b.apply_diff(diff, cx);
4255                                }
4256                                FormatOperation::Prettier(diff) => {
4257                                    b.apply_diff(diff, cx);
4258                                }
4259                            }
4260
4261                            if let Some(transaction_id) = whitespace_transaction_id {
4262                                b.group_until_transaction(transaction_id);
4263                            }
4264                        }
4265
4266                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4267                            if !push_to_history {
4268                                b.forget_transaction(transaction.id);
4269                            }
4270                            project_transaction.0.insert(buffer.clone(), transaction);
4271                        }
4272                    })?;
4273                }
4274
4275                Ok(project_transaction)
4276            })
4277        } else {
4278            let remote_id = self.remote_id();
4279            let client = self.client.clone();
4280            cx.spawn(move |this, mut cx| async move {
4281                let mut project_transaction = ProjectTransaction::default();
4282                if let Some(project_id) = remote_id {
4283                    let response = client
4284                        .request(proto::FormatBuffers {
4285                            project_id,
4286                            trigger: trigger as i32,
4287                            buffer_ids: buffers
4288                                .iter()
4289                                .map(|buffer| {
4290                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
4291                                })
4292                                .collect::<Result<_>>()?,
4293                        })
4294                        .await?
4295                        .transaction
4296                        .ok_or_else(|| anyhow!("missing transaction"))?;
4297                    project_transaction = this
4298                        .update(&mut cx, |this, cx| {
4299                            this.deserialize_project_transaction(response, push_to_history, cx)
4300                        })?
4301                        .await?;
4302                }
4303                Ok(project_transaction)
4304            })
4305        }
4306    }
4307
4308    async fn format_via_lsp(
4309        this: &WeakModel<Self>,
4310        buffer: &Model<Buffer>,
4311        abs_path: &Path,
4312        language_server: &Arc<LanguageServer>,
4313        tab_size: NonZeroU32,
4314        cx: &mut AsyncAppContext,
4315    ) -> Result<Vec<(Range<Anchor>, String)>> {
4316        let uri = lsp::Url::from_file_path(abs_path)
4317            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4318        let text_document = lsp::TextDocumentIdentifier::new(uri);
4319        let capabilities = &language_server.capabilities();
4320
4321        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4322        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4323
4324        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4325            language_server
4326                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4327                    text_document,
4328                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4329                    work_done_progress_params: Default::default(),
4330                })
4331                .await?
4332        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4333            let buffer_start = lsp::Position::new(0, 0);
4334            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4335
4336            language_server
4337                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4338                    text_document,
4339                    range: lsp::Range::new(buffer_start, buffer_end),
4340                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4341                    work_done_progress_params: Default::default(),
4342                })
4343                .await?
4344        } else {
4345            None
4346        };
4347
4348        if let Some(lsp_edits) = lsp_edits {
4349            this.update(cx, |this, cx| {
4350                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4351            })?
4352            .await
4353        } else {
4354            Ok(Vec::new())
4355        }
4356    }
4357
4358    async fn format_via_external_command(
4359        buffer: &Model<Buffer>,
4360        buffer_abs_path: &Path,
4361        command: &str,
4362        arguments: &[String],
4363        cx: &mut AsyncAppContext,
4364    ) -> Result<Option<Diff>> {
4365        let working_dir_path = buffer.update(cx, |buffer, cx| {
4366            let file = File::from_dyn(buffer.file())?;
4367            let worktree = file.worktree.read(cx).as_local()?;
4368            let mut worktree_path = worktree.abs_path().to_path_buf();
4369            if worktree.root_entry()?.is_file() {
4370                worktree_path.pop();
4371            }
4372            Some(worktree_path)
4373        })?;
4374
4375        if let Some(working_dir_path) = working_dir_path {
4376            let mut child =
4377                smol::process::Command::new(command)
4378                    .args(arguments.iter().map(|arg| {
4379                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4380                    }))
4381                    .current_dir(&working_dir_path)
4382                    .stdin(smol::process::Stdio::piped())
4383                    .stdout(smol::process::Stdio::piped())
4384                    .stderr(smol::process::Stdio::piped())
4385                    .spawn()?;
4386            let stdin = child
4387                .stdin
4388                .as_mut()
4389                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4390            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4391            for chunk in text.chunks() {
4392                stdin.write_all(chunk.as_bytes()).await?;
4393            }
4394            stdin.flush().await?;
4395
4396            let output = child.output().await?;
4397            if !output.status.success() {
4398                return Err(anyhow!(
4399                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4400                    output.status.code(),
4401                    String::from_utf8_lossy(&output.stdout),
4402                    String::from_utf8_lossy(&output.stderr),
4403                ));
4404            }
4405
4406            let stdout = String::from_utf8(output.stdout)?;
4407            Ok(Some(
4408                buffer
4409                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4410                    .await,
4411            ))
4412        } else {
4413            Ok(None)
4414        }
4415    }
4416
4417    pub fn definition<T: ToPointUtf16>(
4418        &self,
4419        buffer: &Model<Buffer>,
4420        position: T,
4421        cx: &mut ModelContext<Self>,
4422    ) -> Task<Result<Vec<LocationLink>>> {
4423        let position = position.to_point_utf16(buffer.read(cx));
4424        self.request_lsp(
4425            buffer.clone(),
4426            LanguageServerToQuery::Primary,
4427            GetDefinition { position },
4428            cx,
4429        )
4430    }
4431
4432    pub fn type_definition<T: ToPointUtf16>(
4433        &self,
4434        buffer: &Model<Buffer>,
4435        position: T,
4436        cx: &mut ModelContext<Self>,
4437    ) -> Task<Result<Vec<LocationLink>>> {
4438        let position = position.to_point_utf16(buffer.read(cx));
4439        self.request_lsp(
4440            buffer.clone(),
4441            LanguageServerToQuery::Primary,
4442            GetTypeDefinition { position },
4443            cx,
4444        )
4445    }
4446
4447    pub fn references<T: ToPointUtf16>(
4448        &self,
4449        buffer: &Model<Buffer>,
4450        position: T,
4451        cx: &mut ModelContext<Self>,
4452    ) -> Task<Result<Vec<Location>>> {
4453        let position = position.to_point_utf16(buffer.read(cx));
4454        self.request_lsp(
4455            buffer.clone(),
4456            LanguageServerToQuery::Primary,
4457            GetReferences { position },
4458            cx,
4459        )
4460    }
4461
4462    pub fn document_highlights<T: ToPointUtf16>(
4463        &self,
4464        buffer: &Model<Buffer>,
4465        position: T,
4466        cx: &mut ModelContext<Self>,
4467    ) -> Task<Result<Vec<DocumentHighlight>>> {
4468        let position = position.to_point_utf16(buffer.read(cx));
4469        self.request_lsp(
4470            buffer.clone(),
4471            LanguageServerToQuery::Primary,
4472            GetDocumentHighlights { position },
4473            cx,
4474        )
4475    }
4476
4477    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4478        if self.is_local() {
4479            let mut requests = Vec::new();
4480            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4481                let worktree_id = *worktree_id;
4482                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4483                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4484                    Some(worktree) => worktree,
4485                    None => continue,
4486                };
4487                let worktree_abs_path = worktree.abs_path().clone();
4488
4489                let (adapter, language, server) = match self.language_servers.get(server_id) {
4490                    Some(LanguageServerState::Running {
4491                        adapter,
4492                        language,
4493                        server,
4494                        ..
4495                    }) => (adapter.clone(), language.clone(), server),
4496
4497                    _ => continue,
4498                };
4499
4500                requests.push(
4501                    server
4502                        .request::<lsp::request::WorkspaceSymbolRequest>(
4503                            lsp::WorkspaceSymbolParams {
4504                                query: query.to_string(),
4505                                ..Default::default()
4506                            },
4507                        )
4508                        .log_err()
4509                        .map(move |response| {
4510                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4511                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4512                                    flat_responses.into_iter().map(|lsp_symbol| {
4513                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4514                                    }).collect::<Vec<_>>()
4515                                }
4516                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4517                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4518                                        let location = match lsp_symbol.location {
4519                                            OneOf::Left(location) => location,
4520                                            OneOf::Right(_) => {
4521                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4522                                                return None
4523                                            }
4524                                        };
4525                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4526                                    }).collect::<Vec<_>>()
4527                                }
4528                            }).unwrap_or_default();
4529
4530                            (
4531                                adapter,
4532                                language,
4533                                worktree_id,
4534                                worktree_abs_path,
4535                                lsp_symbols,
4536                            )
4537                        }),
4538                );
4539            }
4540
4541            cx.spawn(move |this, mut cx| async move {
4542                let responses = futures::future::join_all(requests).await;
4543                let this = match this.upgrade() {
4544                    Some(this) => this,
4545                    None => return Ok(Vec::new()),
4546                };
4547
4548                let symbols = this.update(&mut cx, |this, cx| {
4549                    let mut symbols = Vec::new();
4550                    for (
4551                        adapter,
4552                        adapter_language,
4553                        source_worktree_id,
4554                        worktree_abs_path,
4555                        lsp_symbols,
4556                    ) in responses
4557                    {
4558                        symbols.extend(lsp_symbols.into_iter().filter_map(
4559                            |(symbol_name, symbol_kind, symbol_location)| {
4560                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4561                                let mut worktree_id = source_worktree_id;
4562                                let path;
4563                                if let Some((worktree, rel_path)) =
4564                                    this.find_local_worktree(&abs_path, cx)
4565                                {
4566                                    worktree_id = worktree.read(cx).id();
4567                                    path = rel_path;
4568                                } else {
4569                                    path = relativize_path(&worktree_abs_path, &abs_path);
4570                                }
4571
4572                                let project_path = ProjectPath {
4573                                    worktree_id,
4574                                    path: path.into(),
4575                                };
4576                                let signature = this.symbol_signature(&project_path);
4577                                let adapter_language = adapter_language.clone();
4578                                let language = this
4579                                    .languages
4580                                    .language_for_file(&project_path.path, None)
4581                                    .unwrap_or_else(move |_| adapter_language);
4582                                let language_server_name = adapter.name.clone();
4583                                Some(async move {
4584                                    let language = language.await;
4585                                    let label =
4586                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4587
4588                                    Symbol {
4589                                        language_server_name,
4590                                        source_worktree_id,
4591                                        path: project_path,
4592                                        label: label.unwrap_or_else(|| {
4593                                            CodeLabel::plain(symbol_name.clone(), None)
4594                                        }),
4595                                        kind: symbol_kind,
4596                                        name: symbol_name,
4597                                        range: range_from_lsp(symbol_location.range),
4598                                        signature,
4599                                    }
4600                                })
4601                            },
4602                        ));
4603                    }
4604
4605                    symbols
4606                })?;
4607
4608                Ok(futures::future::join_all(symbols).await)
4609            })
4610        } else if let Some(project_id) = self.remote_id() {
4611            let request = self.client.request(proto::GetProjectSymbols {
4612                project_id,
4613                query: query.to_string(),
4614            });
4615            cx.spawn(move |this, mut cx| async move {
4616                let response = request.await?;
4617                let mut symbols = Vec::new();
4618                if let Some(this) = this.upgrade() {
4619                    let new_symbols = this.update(&mut cx, |this, _| {
4620                        response
4621                            .symbols
4622                            .into_iter()
4623                            .map(|symbol| this.deserialize_symbol(symbol))
4624                            .collect::<Vec<_>>()
4625                    })?;
4626                    symbols = futures::future::join_all(new_symbols)
4627                        .await
4628                        .into_iter()
4629                        .filter_map(|symbol| symbol.log_err())
4630                        .collect::<Vec<_>>();
4631                }
4632                Ok(symbols)
4633            })
4634        } else {
4635            Task::ready(Ok(Default::default()))
4636        }
4637    }
4638
4639    pub fn open_buffer_for_symbol(
4640        &mut self,
4641        symbol: &Symbol,
4642        cx: &mut ModelContext<Self>,
4643    ) -> Task<Result<Model<Buffer>>> {
4644        if self.is_local() {
4645            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4646                symbol.source_worktree_id,
4647                symbol.language_server_name.clone(),
4648            )) {
4649                *id
4650            } else {
4651                return Task::ready(Err(anyhow!(
4652                    "language server for worktree and language not found"
4653                )));
4654            };
4655
4656            let worktree_abs_path = if let Some(worktree_abs_path) = self
4657                .worktree_for_id(symbol.path.worktree_id, cx)
4658                .and_then(|worktree| worktree.read(cx).as_local())
4659                .map(|local_worktree| local_worktree.abs_path())
4660            {
4661                worktree_abs_path
4662            } else {
4663                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4664            };
4665
4666            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4667            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4668                uri
4669            } else {
4670                return Task::ready(Err(anyhow!("invalid symbol path")));
4671            };
4672
4673            self.open_local_buffer_via_lsp(
4674                symbol_uri,
4675                language_server_id,
4676                symbol.language_server_name.clone(),
4677                cx,
4678            )
4679        } else if let Some(project_id) = self.remote_id() {
4680            let request = self.client.request(proto::OpenBufferForSymbol {
4681                project_id,
4682                symbol: Some(serialize_symbol(symbol)),
4683            });
4684            cx.spawn(move |this, mut cx| async move {
4685                let response = request.await?;
4686                let buffer_id = BufferId::new(response.buffer_id)?;
4687                this.update(&mut cx, |this, cx| {
4688                    this.wait_for_remote_buffer(buffer_id, cx)
4689                })?
4690                .await
4691            })
4692        } else {
4693            Task::ready(Err(anyhow!("project does not have a remote id")))
4694        }
4695    }
4696
4697    pub fn hover<T: ToPointUtf16>(
4698        &self,
4699        buffer: &Model<Buffer>,
4700        position: T,
4701        cx: &mut ModelContext<Self>,
4702    ) -> Task<Result<Option<Hover>>> {
4703        let position = position.to_point_utf16(buffer.read(cx));
4704        self.request_lsp(
4705            buffer.clone(),
4706            LanguageServerToQuery::Primary,
4707            GetHover { position },
4708            cx,
4709        )
4710    }
4711
4712    pub fn completions<T: ToOffset + ToPointUtf16>(
4713        &self,
4714        buffer: &Model<Buffer>,
4715        position: T,
4716        cx: &mut ModelContext<Self>,
4717    ) -> Task<Result<Vec<Completion>>> {
4718        let position = position.to_point_utf16(buffer.read(cx));
4719        if self.is_local() {
4720            let snapshot = buffer.read(cx).snapshot();
4721            let offset = position.to_offset(&snapshot);
4722            let scope = snapshot.language_scope_at(offset);
4723
4724            let server_ids: Vec<_> = self
4725                .language_servers_for_buffer(buffer.read(cx), cx)
4726                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4727                .filter(|(adapter, _)| {
4728                    scope
4729                        .as_ref()
4730                        .map(|scope| scope.language_allowed(&adapter.name))
4731                        .unwrap_or(true)
4732                })
4733                .map(|(_, server)| server.server_id())
4734                .collect();
4735
4736            let buffer = buffer.clone();
4737            cx.spawn(move |this, mut cx| async move {
4738                let mut tasks = Vec::with_capacity(server_ids.len());
4739                this.update(&mut cx, |this, cx| {
4740                    for server_id in server_ids {
4741                        tasks.push(this.request_lsp(
4742                            buffer.clone(),
4743                            LanguageServerToQuery::Other(server_id),
4744                            GetCompletions { position },
4745                            cx,
4746                        ));
4747                    }
4748                })?;
4749
4750                let mut completions = Vec::new();
4751                for task in tasks {
4752                    if let Ok(new_completions) = task.await {
4753                        completions.extend_from_slice(&new_completions);
4754                    }
4755                }
4756
4757                Ok(completions)
4758            })
4759        } else if let Some(project_id) = self.remote_id() {
4760            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4761        } else {
4762            Task::ready(Ok(Default::default()))
4763        }
4764    }
4765
4766    pub fn resolve_completions(
4767        &self,
4768        completion_indices: Vec<usize>,
4769        completions: Arc<RwLock<Box<[Completion]>>>,
4770        cx: &mut ModelContext<Self>,
4771    ) -> Task<Result<bool>> {
4772        let client = self.client();
4773        let language_registry = self.languages().clone();
4774
4775        let is_remote = self.is_remote();
4776        let project_id = self.remote_id();
4777
4778        cx.spawn(move |this, mut cx| async move {
4779            let mut did_resolve = false;
4780            if is_remote {
4781                let project_id =
4782                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
4783
4784                for completion_index in completion_indices {
4785                    let completions_guard = completions.read();
4786                    let completion = &completions_guard[completion_index];
4787                    if completion.documentation.is_some() {
4788                        continue;
4789                    }
4790
4791                    did_resolve = true;
4792                    let server_id = completion.server_id;
4793                    let completion = completion.lsp_completion.clone();
4794                    drop(completions_guard);
4795
4796                    Self::resolve_completion_documentation_remote(
4797                        project_id,
4798                        server_id,
4799                        completions.clone(),
4800                        completion_index,
4801                        completion,
4802                        client.clone(),
4803                        language_registry.clone(),
4804                    )
4805                    .await;
4806                }
4807            } else {
4808                for completion_index in completion_indices {
4809                    let completions_guard = completions.read();
4810                    let completion = &completions_guard[completion_index];
4811                    if completion.documentation.is_some() {
4812                        continue;
4813                    }
4814
4815                    let server_id = completion.server_id;
4816                    let completion = completion.lsp_completion.clone();
4817                    drop(completions_guard);
4818
4819                    let server = this
4820                        .read_with(&mut cx, |project, _| {
4821                            project.language_server_for_id(server_id)
4822                        })
4823                        .ok()
4824                        .flatten();
4825                    let Some(server) = server else {
4826                        continue;
4827                    };
4828
4829                    did_resolve = true;
4830                    Self::resolve_completion_documentation_local(
4831                        server,
4832                        completions.clone(),
4833                        completion_index,
4834                        completion,
4835                        language_registry.clone(),
4836                    )
4837                    .await;
4838                }
4839            }
4840
4841            Ok(did_resolve)
4842        })
4843    }
4844
4845    async fn resolve_completion_documentation_local(
4846        server: Arc<lsp::LanguageServer>,
4847        completions: Arc<RwLock<Box<[Completion]>>>,
4848        completion_index: usize,
4849        completion: lsp::CompletionItem,
4850        language_registry: Arc<LanguageRegistry>,
4851    ) {
4852        let can_resolve = server
4853            .capabilities()
4854            .completion_provider
4855            .as_ref()
4856            .and_then(|options| options.resolve_provider)
4857            .unwrap_or(false);
4858        if !can_resolve {
4859            return;
4860        }
4861
4862        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
4863        let Some(completion_item) = request.await.log_err() else {
4864            return;
4865        };
4866
4867        if let Some(lsp_documentation) = completion_item.documentation {
4868            let documentation = language::prepare_completion_documentation(
4869                &lsp_documentation,
4870                &language_registry,
4871                None, // TODO: Try to reasonably work out which language the completion is for
4872            )
4873            .await;
4874
4875            let mut completions = completions.write();
4876            let completion = &mut completions[completion_index];
4877            completion.documentation = Some(documentation);
4878        } else {
4879            let mut completions = completions.write();
4880            let completion = &mut completions[completion_index];
4881            completion.documentation = Some(Documentation::Undocumented);
4882        }
4883    }
4884
4885    async fn resolve_completion_documentation_remote(
4886        project_id: u64,
4887        server_id: LanguageServerId,
4888        completions: Arc<RwLock<Box<[Completion]>>>,
4889        completion_index: usize,
4890        completion: lsp::CompletionItem,
4891        client: Arc<Client>,
4892        language_registry: Arc<LanguageRegistry>,
4893    ) {
4894        let request = proto::ResolveCompletionDocumentation {
4895            project_id,
4896            language_server_id: server_id.0 as u64,
4897            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
4898        };
4899
4900        let Some(response) = client
4901            .request(request)
4902            .await
4903            .context("completion documentation resolve proto request")
4904            .log_err()
4905        else {
4906            return;
4907        };
4908
4909        if response.text.is_empty() {
4910            let mut completions = completions.write();
4911            let completion = &mut completions[completion_index];
4912            completion.documentation = Some(Documentation::Undocumented);
4913        }
4914
4915        let documentation = if response.is_markdown {
4916            Documentation::MultiLineMarkdown(
4917                markdown::parse_markdown(&response.text, &language_registry, None).await,
4918            )
4919        } else if response.text.lines().count() <= 1 {
4920            Documentation::SingleLine(response.text)
4921        } else {
4922            Documentation::MultiLinePlainText(response.text)
4923        };
4924
4925        let mut completions = completions.write();
4926        let completion = &mut completions[completion_index];
4927        completion.documentation = Some(documentation);
4928    }
4929
4930    pub fn apply_additional_edits_for_completion(
4931        &self,
4932        buffer_handle: Model<Buffer>,
4933        completion: Completion,
4934        push_to_history: bool,
4935        cx: &mut ModelContext<Self>,
4936    ) -> Task<Result<Option<Transaction>>> {
4937        let buffer = buffer_handle.read(cx);
4938        let buffer_id = buffer.remote_id();
4939
4940        if self.is_local() {
4941            let server_id = completion.server_id;
4942            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4943                Some((_, server)) => server.clone(),
4944                _ => return Task::ready(Ok(Default::default())),
4945            };
4946
4947            cx.spawn(move |this, mut cx| async move {
4948                let can_resolve = lang_server
4949                    .capabilities()
4950                    .completion_provider
4951                    .as_ref()
4952                    .and_then(|options| options.resolve_provider)
4953                    .unwrap_or(false);
4954                let additional_text_edits = if can_resolve {
4955                    lang_server
4956                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4957                        .await?
4958                        .additional_text_edits
4959                } else {
4960                    completion.lsp_completion.additional_text_edits
4961                };
4962                if let Some(edits) = additional_text_edits {
4963                    let edits = this
4964                        .update(&mut cx, |this, cx| {
4965                            this.edits_from_lsp(
4966                                &buffer_handle,
4967                                edits,
4968                                lang_server.server_id(),
4969                                None,
4970                                cx,
4971                            )
4972                        })?
4973                        .await?;
4974
4975                    buffer_handle.update(&mut cx, |buffer, cx| {
4976                        buffer.finalize_last_transaction();
4977                        buffer.start_transaction();
4978
4979                        for (range, text) in edits {
4980                            let primary = &completion.old_range;
4981                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4982                                && primary.end.cmp(&range.start, buffer).is_ge();
4983                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4984                                && range.end.cmp(&primary.end, buffer).is_ge();
4985
4986                            //Skip additional edits which overlap with the primary completion edit
4987                            //https://github.com/zed-industries/zed/pull/1871
4988                            if !start_within && !end_within {
4989                                buffer.edit([(range, text)], None, cx);
4990                            }
4991                        }
4992
4993                        let transaction = if buffer.end_transaction(cx).is_some() {
4994                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4995                            if !push_to_history {
4996                                buffer.forget_transaction(transaction.id);
4997                            }
4998                            Some(transaction)
4999                        } else {
5000                            None
5001                        };
5002                        Ok(transaction)
5003                    })?
5004                } else {
5005                    Ok(None)
5006                }
5007            })
5008        } else if let Some(project_id) = self.remote_id() {
5009            let client = self.client.clone();
5010            cx.spawn(move |_, mut cx| async move {
5011                let response = client
5012                    .request(proto::ApplyCompletionAdditionalEdits {
5013                        project_id,
5014                        buffer_id: buffer_id.into(),
5015                        completion: Some(language::proto::serialize_completion(&completion)),
5016                    })
5017                    .await?;
5018
5019                if let Some(transaction) = response.transaction {
5020                    let transaction = language::proto::deserialize_transaction(transaction)?;
5021                    buffer_handle
5022                        .update(&mut cx, |buffer, _| {
5023                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5024                        })?
5025                        .await?;
5026                    if push_to_history {
5027                        buffer_handle.update(&mut cx, |buffer, _| {
5028                            buffer.push_transaction(transaction.clone(), Instant::now());
5029                        })?;
5030                    }
5031                    Ok(Some(transaction))
5032                } else {
5033                    Ok(None)
5034                }
5035            })
5036        } else {
5037            Task::ready(Err(anyhow!("project does not have a remote id")))
5038        }
5039    }
5040
5041    pub fn code_actions<T: Clone + ToOffset>(
5042        &self,
5043        buffer_handle: &Model<Buffer>,
5044        range: Range<T>,
5045        cx: &mut ModelContext<Self>,
5046    ) -> Task<Result<Vec<CodeAction>>> {
5047        let buffer = buffer_handle.read(cx);
5048        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5049        self.request_lsp(
5050            buffer_handle.clone(),
5051            LanguageServerToQuery::Primary,
5052            GetCodeActions { range },
5053            cx,
5054        )
5055    }
5056
5057    pub fn apply_code_action(
5058        &self,
5059        buffer_handle: Model<Buffer>,
5060        mut action: CodeAction,
5061        push_to_history: bool,
5062        cx: &mut ModelContext<Self>,
5063    ) -> Task<Result<ProjectTransaction>> {
5064        if self.is_local() {
5065            let buffer = buffer_handle.read(cx);
5066            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5067                self.language_server_for_buffer(buffer, action.server_id, cx)
5068            {
5069                (adapter.clone(), server.clone())
5070            } else {
5071                return Task::ready(Ok(Default::default()));
5072            };
5073            let range = action.range.to_point_utf16(buffer);
5074
5075            cx.spawn(move |this, mut cx| async move {
5076                if let Some(lsp_range) = action
5077                    .lsp_action
5078                    .data
5079                    .as_mut()
5080                    .and_then(|d| d.get_mut("codeActionParams"))
5081                    .and_then(|d| d.get_mut("range"))
5082                {
5083                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
5084                    action.lsp_action = lang_server
5085                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
5086                        .await?;
5087                } else {
5088                    let actions = this
5089                        .update(&mut cx, |this, cx| {
5090                            this.code_actions(&buffer_handle, action.range, cx)
5091                        })?
5092                        .await?;
5093                    action.lsp_action = actions
5094                        .into_iter()
5095                        .find(|a| a.lsp_action.title == action.lsp_action.title)
5096                        .ok_or_else(|| anyhow!("code action is outdated"))?
5097                        .lsp_action;
5098                }
5099
5100                if let Some(edit) = action.lsp_action.edit {
5101                    if edit.changes.is_some() || edit.document_changes.is_some() {
5102                        return Self::deserialize_workspace_edit(
5103                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5104                            edit,
5105                            push_to_history,
5106                            lsp_adapter.clone(),
5107                            lang_server.clone(),
5108                            &mut cx,
5109                        )
5110                        .await;
5111                    }
5112                }
5113
5114                if let Some(command) = action.lsp_action.command {
5115                    this.update(&mut cx, |this, _| {
5116                        this.last_workspace_edits_by_language_server
5117                            .remove(&lang_server.server_id());
5118                    })?;
5119
5120                    let result = lang_server
5121                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5122                            command: command.command,
5123                            arguments: command.arguments.unwrap_or_default(),
5124                            ..Default::default()
5125                        })
5126                        .await;
5127
5128                    if let Err(err) = result {
5129                        // TODO: LSP ERROR
5130                        return Err(err);
5131                    }
5132
5133                    return Ok(this.update(&mut cx, |this, _| {
5134                        this.last_workspace_edits_by_language_server
5135                            .remove(&lang_server.server_id())
5136                            .unwrap_or_default()
5137                    })?);
5138                }
5139
5140                Ok(ProjectTransaction::default())
5141            })
5142        } else if let Some(project_id) = self.remote_id() {
5143            let client = self.client.clone();
5144            let request = proto::ApplyCodeAction {
5145                project_id,
5146                buffer_id: buffer_handle.read(cx).remote_id().into(),
5147                action: Some(language::proto::serialize_code_action(&action)),
5148            };
5149            cx.spawn(move |this, mut cx| async move {
5150                let response = client
5151                    .request(request)
5152                    .await?
5153                    .transaction
5154                    .ok_or_else(|| anyhow!("missing transaction"))?;
5155                this.update(&mut cx, |this, cx| {
5156                    this.deserialize_project_transaction(response, push_to_history, cx)
5157                })?
5158                .await
5159            })
5160        } else {
5161            Task::ready(Err(anyhow!("project does not have a remote id")))
5162        }
5163    }
5164
5165    fn apply_on_type_formatting(
5166        &self,
5167        buffer: Model<Buffer>,
5168        position: Anchor,
5169        trigger: String,
5170        cx: &mut ModelContext<Self>,
5171    ) -> Task<Result<Option<Transaction>>> {
5172        if self.is_local() {
5173            cx.spawn(move |this, mut cx| async move {
5174                // Do not allow multiple concurrent formatting requests for the
5175                // same buffer.
5176                this.update(&mut cx, |this, cx| {
5177                    this.buffers_being_formatted
5178                        .insert(buffer.read(cx).remote_id())
5179                })?;
5180
5181                let _cleanup = defer({
5182                    let this = this.clone();
5183                    let mut cx = cx.clone();
5184                    let closure_buffer = buffer.clone();
5185                    move || {
5186                        this.update(&mut cx, |this, cx| {
5187                            this.buffers_being_formatted
5188                                .remove(&closure_buffer.read(cx).remote_id());
5189                        })
5190                        .ok();
5191                    }
5192                });
5193
5194                buffer
5195                    .update(&mut cx, |buffer, _| {
5196                        buffer.wait_for_edits(Some(position.timestamp))
5197                    })?
5198                    .await?;
5199                this.update(&mut cx, |this, cx| {
5200                    let position = position.to_point_utf16(buffer.read(cx));
5201                    this.on_type_format(buffer, position, trigger, false, cx)
5202                })?
5203                .await
5204            })
5205        } else if let Some(project_id) = self.remote_id() {
5206            let client = self.client.clone();
5207            let request = proto::OnTypeFormatting {
5208                project_id,
5209                buffer_id: buffer.read(cx).remote_id().into(),
5210                position: Some(serialize_anchor(&position)),
5211                trigger,
5212                version: serialize_version(&buffer.read(cx).version()),
5213            };
5214            cx.spawn(move |_, _| async move {
5215                client
5216                    .request(request)
5217                    .await?
5218                    .transaction
5219                    .map(language::proto::deserialize_transaction)
5220                    .transpose()
5221            })
5222        } else {
5223            Task::ready(Err(anyhow!("project does not have a remote id")))
5224        }
5225    }
5226
5227    async fn deserialize_edits(
5228        this: Model<Self>,
5229        buffer_to_edit: Model<Buffer>,
5230        edits: Vec<lsp::TextEdit>,
5231        push_to_history: bool,
5232        _: Arc<CachedLspAdapter>,
5233        language_server: Arc<LanguageServer>,
5234        cx: &mut AsyncAppContext,
5235    ) -> Result<Option<Transaction>> {
5236        let edits = this
5237            .update(cx, |this, cx| {
5238                this.edits_from_lsp(
5239                    &buffer_to_edit,
5240                    edits,
5241                    language_server.server_id(),
5242                    None,
5243                    cx,
5244                )
5245            })?
5246            .await?;
5247
5248        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5249            buffer.finalize_last_transaction();
5250            buffer.start_transaction();
5251            for (range, text) in edits {
5252                buffer.edit([(range, text)], None, cx);
5253            }
5254
5255            if buffer.end_transaction(cx).is_some() {
5256                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5257                if !push_to_history {
5258                    buffer.forget_transaction(transaction.id);
5259                }
5260                Some(transaction)
5261            } else {
5262                None
5263            }
5264        })?;
5265
5266        Ok(transaction)
5267    }
5268
5269    async fn deserialize_workspace_edit(
5270        this: Model<Self>,
5271        edit: lsp::WorkspaceEdit,
5272        push_to_history: bool,
5273        lsp_adapter: Arc<CachedLspAdapter>,
5274        language_server: Arc<LanguageServer>,
5275        cx: &mut AsyncAppContext,
5276    ) -> Result<ProjectTransaction> {
5277        let fs = this.update(cx, |this, _| this.fs.clone())?;
5278        let mut operations = Vec::new();
5279        if let Some(document_changes) = edit.document_changes {
5280            match document_changes {
5281                lsp::DocumentChanges::Edits(edits) => {
5282                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5283                }
5284                lsp::DocumentChanges::Operations(ops) => operations = ops,
5285            }
5286        } else if let Some(changes) = edit.changes {
5287            operations.extend(changes.into_iter().map(|(uri, edits)| {
5288                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5289                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5290                        uri,
5291                        version: None,
5292                    },
5293                    edits: edits.into_iter().map(OneOf::Left).collect(),
5294                })
5295            }));
5296        }
5297
5298        let mut project_transaction = ProjectTransaction::default();
5299        for operation in operations {
5300            match operation {
5301                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5302                    let abs_path = op
5303                        .uri
5304                        .to_file_path()
5305                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5306
5307                    if let Some(parent_path) = abs_path.parent() {
5308                        fs.create_dir(parent_path).await?;
5309                    }
5310                    if abs_path.ends_with("/") {
5311                        fs.create_dir(&abs_path).await?;
5312                    } else {
5313                        fs.create_file(
5314                            &abs_path,
5315                            op.options
5316                                .map(|options| fs::CreateOptions {
5317                                    overwrite: options.overwrite.unwrap_or(false),
5318                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5319                                })
5320                                .unwrap_or_default(),
5321                        )
5322                        .await?;
5323                    }
5324                }
5325
5326                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5327                    let source_abs_path = op
5328                        .old_uri
5329                        .to_file_path()
5330                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5331                    let target_abs_path = op
5332                        .new_uri
5333                        .to_file_path()
5334                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5335                    fs.rename(
5336                        &source_abs_path,
5337                        &target_abs_path,
5338                        op.options
5339                            .map(|options| fs::RenameOptions {
5340                                overwrite: options.overwrite.unwrap_or(false),
5341                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5342                            })
5343                            .unwrap_or_default(),
5344                    )
5345                    .await?;
5346                }
5347
5348                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5349                    let abs_path = op
5350                        .uri
5351                        .to_file_path()
5352                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5353                    let options = op
5354                        .options
5355                        .map(|options| fs::RemoveOptions {
5356                            recursive: options.recursive.unwrap_or(false),
5357                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5358                        })
5359                        .unwrap_or_default();
5360                    if abs_path.ends_with("/") {
5361                        fs.remove_dir(&abs_path, options).await?;
5362                    } else {
5363                        fs.remove_file(&abs_path, options).await?;
5364                    }
5365                }
5366
5367                lsp::DocumentChangeOperation::Edit(op) => {
5368                    let buffer_to_edit = this
5369                        .update(cx, |this, cx| {
5370                            this.open_local_buffer_via_lsp(
5371                                op.text_document.uri,
5372                                language_server.server_id(),
5373                                lsp_adapter.name.clone(),
5374                                cx,
5375                            )
5376                        })?
5377                        .await?;
5378
5379                    let edits = this
5380                        .update(cx, |this, cx| {
5381                            let edits = op.edits.into_iter().map(|edit| match edit {
5382                                OneOf::Left(edit) => edit,
5383                                OneOf::Right(edit) => edit.text_edit,
5384                            });
5385                            this.edits_from_lsp(
5386                                &buffer_to_edit,
5387                                edits,
5388                                language_server.server_id(),
5389                                op.text_document.version,
5390                                cx,
5391                            )
5392                        })?
5393                        .await?;
5394
5395                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5396                        buffer.finalize_last_transaction();
5397                        buffer.start_transaction();
5398                        for (range, text) in edits {
5399                            buffer.edit([(range, text)], None, cx);
5400                        }
5401                        let transaction = if buffer.end_transaction(cx).is_some() {
5402                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5403                            if !push_to_history {
5404                                buffer.forget_transaction(transaction.id);
5405                            }
5406                            Some(transaction)
5407                        } else {
5408                            None
5409                        };
5410
5411                        transaction
5412                    })?;
5413                    if let Some(transaction) = transaction {
5414                        project_transaction.0.insert(buffer_to_edit, transaction);
5415                    }
5416                }
5417            }
5418        }
5419
5420        Ok(project_transaction)
5421    }
5422
5423    pub fn prepare_rename<T: ToPointUtf16>(
5424        &self,
5425        buffer: Model<Buffer>,
5426        position: T,
5427        cx: &mut ModelContext<Self>,
5428    ) -> Task<Result<Option<Range<Anchor>>>> {
5429        let position = position.to_point_utf16(buffer.read(cx));
5430        self.request_lsp(
5431            buffer,
5432            LanguageServerToQuery::Primary,
5433            PrepareRename { position },
5434            cx,
5435        )
5436    }
5437
5438    pub fn perform_rename<T: ToPointUtf16>(
5439        &self,
5440        buffer: Model<Buffer>,
5441        position: T,
5442        new_name: String,
5443        push_to_history: bool,
5444        cx: &mut ModelContext<Self>,
5445    ) -> Task<Result<ProjectTransaction>> {
5446        let position = position.to_point_utf16(buffer.read(cx));
5447        self.request_lsp(
5448            buffer,
5449            LanguageServerToQuery::Primary,
5450            PerformRename {
5451                position,
5452                new_name,
5453                push_to_history,
5454            },
5455            cx,
5456        )
5457    }
5458
5459    pub fn on_type_format<T: ToPointUtf16>(
5460        &self,
5461        buffer: Model<Buffer>,
5462        position: T,
5463        trigger: String,
5464        push_to_history: bool,
5465        cx: &mut ModelContext<Self>,
5466    ) -> Task<Result<Option<Transaction>>> {
5467        let (position, tab_size) = buffer.update(cx, |buffer, cx| {
5468            let position = position.to_point_utf16(buffer);
5469            (
5470                position,
5471                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5472                    .tab_size,
5473            )
5474        });
5475        self.request_lsp(
5476            buffer.clone(),
5477            LanguageServerToQuery::Primary,
5478            OnTypeFormatting {
5479                position,
5480                trigger,
5481                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5482                push_to_history,
5483            },
5484            cx,
5485        )
5486    }
5487
5488    pub fn inlay_hints<T: ToOffset>(
5489        &self,
5490        buffer_handle: Model<Buffer>,
5491        range: Range<T>,
5492        cx: &mut ModelContext<Self>,
5493    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5494        let buffer = buffer_handle.read(cx);
5495        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5496        let range_start = range.start;
5497        let range_end = range.end;
5498        let buffer_id = buffer.remote_id().into();
5499        let buffer_version = buffer.version().clone();
5500        let lsp_request = InlayHints { range };
5501
5502        if self.is_local() {
5503            let lsp_request_task = self.request_lsp(
5504                buffer_handle.clone(),
5505                LanguageServerToQuery::Primary,
5506                lsp_request,
5507                cx,
5508            );
5509            cx.spawn(move |_, mut cx| async move {
5510                buffer_handle
5511                    .update(&mut cx, |buffer, _| {
5512                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5513                    })?
5514                    .await
5515                    .context("waiting for inlay hint request range edits")?;
5516                lsp_request_task.await.context("inlay hints LSP request")
5517            })
5518        } else if let Some(project_id) = self.remote_id() {
5519            let client = self.client.clone();
5520            let request = proto::InlayHints {
5521                project_id,
5522                buffer_id,
5523                start: Some(serialize_anchor(&range_start)),
5524                end: Some(serialize_anchor(&range_end)),
5525                version: serialize_version(&buffer_version),
5526            };
5527            cx.spawn(move |project, cx| async move {
5528                let response = client
5529                    .request(request)
5530                    .await
5531                    .context("inlay hints proto request")?;
5532                let hints_request_result = LspCommand::response_from_proto(
5533                    lsp_request,
5534                    response,
5535                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5536                    buffer_handle.clone(),
5537                    cx,
5538                )
5539                .await;
5540
5541                hints_request_result.context("inlay hints proto response conversion")
5542            })
5543        } else {
5544            Task::ready(Err(anyhow!("project does not have a remote id")))
5545        }
5546    }
5547
5548    pub fn resolve_inlay_hint(
5549        &self,
5550        hint: InlayHint,
5551        buffer_handle: Model<Buffer>,
5552        server_id: LanguageServerId,
5553        cx: &mut ModelContext<Self>,
5554    ) -> Task<anyhow::Result<InlayHint>> {
5555        if self.is_local() {
5556            let buffer = buffer_handle.read(cx);
5557            let (_, lang_server) = if let Some((adapter, server)) =
5558                self.language_server_for_buffer(buffer, server_id, cx)
5559            {
5560                (adapter.clone(), server.clone())
5561            } else {
5562                return Task::ready(Ok(hint));
5563            };
5564            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5565                return Task::ready(Ok(hint));
5566            }
5567
5568            let buffer_snapshot = buffer.snapshot();
5569            cx.spawn(move |_, mut cx| async move {
5570                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5571                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5572                );
5573                let resolved_hint = resolve_task
5574                    .await
5575                    .context("inlay hint resolve LSP request")?;
5576                let resolved_hint = InlayHints::lsp_to_project_hint(
5577                    resolved_hint,
5578                    &buffer_handle,
5579                    server_id,
5580                    ResolveState::Resolved,
5581                    false,
5582                    &mut cx,
5583                )
5584                .await?;
5585                Ok(resolved_hint)
5586            })
5587        } else if let Some(project_id) = self.remote_id() {
5588            let client = self.client.clone();
5589            let request = proto::ResolveInlayHint {
5590                project_id,
5591                buffer_id: buffer_handle.read(cx).remote_id().into(),
5592                language_server_id: server_id.0 as u64,
5593                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5594            };
5595            cx.spawn(move |_, _| async move {
5596                let response = client
5597                    .request(request)
5598                    .await
5599                    .context("inlay hints proto request")?;
5600                match response.hint {
5601                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5602                        .context("inlay hints proto resolve response conversion"),
5603                    None => Ok(hint),
5604                }
5605            })
5606        } else {
5607            Task::ready(Err(anyhow!("project does not have a remote id")))
5608        }
5609    }
5610
5611    #[allow(clippy::type_complexity)]
5612    pub fn search(
5613        &self,
5614        query: SearchQuery,
5615        cx: &mut ModelContext<Self>,
5616    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5617        if self.is_local() {
5618            self.search_local(query, cx)
5619        } else if let Some(project_id) = self.remote_id() {
5620            let (tx, rx) = smol::channel::unbounded();
5621            let request = self.client.request(query.to_proto(project_id));
5622            cx.spawn(move |this, mut cx| async move {
5623                let response = request.await?;
5624                let mut result = HashMap::default();
5625                for location in response.locations {
5626                    let buffer_id = BufferId::new(location.buffer_id)?;
5627                    let target_buffer = this
5628                        .update(&mut cx, |this, cx| {
5629                            this.wait_for_remote_buffer(buffer_id, cx)
5630                        })?
5631                        .await?;
5632                    let start = location
5633                        .start
5634                        .and_then(deserialize_anchor)
5635                        .ok_or_else(|| anyhow!("missing target start"))?;
5636                    let end = location
5637                        .end
5638                        .and_then(deserialize_anchor)
5639                        .ok_or_else(|| anyhow!("missing target end"))?;
5640                    result
5641                        .entry(target_buffer)
5642                        .or_insert(Vec::new())
5643                        .push(start..end)
5644                }
5645                for (buffer, ranges) in result {
5646                    let _ = tx.send((buffer, ranges)).await;
5647                }
5648                Result::<(), anyhow::Error>::Ok(())
5649            })
5650            .detach_and_log_err(cx);
5651            rx
5652        } else {
5653            unimplemented!();
5654        }
5655    }
5656
5657    pub fn search_local(
5658        &self,
5659        query: SearchQuery,
5660        cx: &mut ModelContext<Self>,
5661    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5662        // Local search is split into several phases.
5663        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5664        // and the second phase that finds positions of all the matches found in the candidate files.
5665        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5666        //
5667        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5668        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5669        //
5670        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5671        //    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
5672        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5673        // 2. At this point, we have a list of all potentially matching buffers/files.
5674        //    We sort that list by buffer path - this list is retained for later use.
5675        //    We ensure that all buffers are now opened and available in project.
5676        // 3. We run a scan over all the candidate buffers on multiple background threads.
5677        //    We cannot assume that there will even be a match - while at least one match
5678        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5679        //    There is also an auxiliary background thread responsible for result gathering.
5680        //    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),
5681        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5682        //    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
5683        //    entry - which might already be available thanks to out-of-order processing.
5684        //
5685        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5686        // 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.
5687        // 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
5688        // in face of constantly updating list of sorted matches.
5689        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5690        let snapshots = self
5691            .visible_worktrees(cx)
5692            .filter_map(|tree| {
5693                let tree = tree.read(cx).as_local()?;
5694                Some(tree.snapshot())
5695            })
5696            .collect::<Vec<_>>();
5697
5698        let background = cx.background_executor().clone();
5699        let path_count: usize = snapshots
5700            .iter()
5701            .map(|s| {
5702                if query.include_ignored() {
5703                    s.file_count()
5704                } else {
5705                    s.visible_file_count()
5706                }
5707            })
5708            .sum();
5709        if path_count == 0 {
5710            let (_, rx) = smol::channel::bounded(1024);
5711            return rx;
5712        }
5713        let workers = background.num_cpus().min(path_count);
5714        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5715        let mut unnamed_files = vec![];
5716        let opened_buffers = self
5717            .opened_buffers
5718            .iter()
5719            .filter_map(|(_, b)| {
5720                let buffer = b.upgrade()?;
5721                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
5722                    let is_ignored = buffer
5723                        .project_path(cx)
5724                        .and_then(|path| self.entry_for_path(&path, cx))
5725                        .map_or(false, |entry| entry.is_ignored);
5726                    (is_ignored, buffer.snapshot())
5727                });
5728                if is_ignored && !query.include_ignored() {
5729                    return None;
5730                } else if let Some(path) = snapshot.file().map(|file| file.path()) {
5731                    Some((path.clone(), (buffer, snapshot)))
5732                } else {
5733                    unnamed_files.push(buffer);
5734                    None
5735                }
5736            })
5737            .collect();
5738        cx.background_executor()
5739            .spawn(Self::background_search(
5740                unnamed_files,
5741                opened_buffers,
5742                cx.background_executor().clone(),
5743                self.fs.clone(),
5744                workers,
5745                query.clone(),
5746                path_count,
5747                snapshots,
5748                matching_paths_tx,
5749            ))
5750            .detach();
5751
5752        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5753        let background = cx.background_executor().clone();
5754        let (result_tx, result_rx) = smol::channel::bounded(1024);
5755        cx.background_executor()
5756            .spawn(async move {
5757                let Ok(buffers) = buffers.await else {
5758                    return;
5759                };
5760
5761                let buffers_len = buffers.len();
5762                if buffers_len == 0 {
5763                    return;
5764                }
5765                let query = &query;
5766                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5767                background
5768                    .scoped(|scope| {
5769                        #[derive(Clone)]
5770                        struct FinishedStatus {
5771                            entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
5772                            buffer_index: SearchMatchCandidateIndex,
5773                        }
5774
5775                        for _ in 0..workers {
5776                            let finished_tx = finished_tx.clone();
5777                            let mut buffers_rx = buffers_rx.clone();
5778                            scope.spawn(async move {
5779                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5780                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5781                                    {
5782                                        if query.file_matches(
5783                                            snapshot.file().map(|file| file.path().as_ref()),
5784                                        ) {
5785                                            query
5786                                                .search(snapshot, None)
5787                                                .await
5788                                                .iter()
5789                                                .map(|range| {
5790                                                    snapshot.anchor_before(range.start)
5791                                                        ..snapshot.anchor_after(range.end)
5792                                                })
5793                                                .collect()
5794                                        } else {
5795                                            Vec::new()
5796                                        }
5797                                    } else {
5798                                        Vec::new()
5799                                    };
5800
5801                                    let status = if !buffer_matches.is_empty() {
5802                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5803                                            Some((buffer.clone(), buffer_matches))
5804                                        } else {
5805                                            None
5806                                        };
5807                                        FinishedStatus {
5808                                            entry,
5809                                            buffer_index,
5810                                        }
5811                                    } else {
5812                                        FinishedStatus {
5813                                            entry: None,
5814                                            buffer_index,
5815                                        }
5816                                    };
5817                                    if finished_tx.send(status).await.is_err() {
5818                                        break;
5819                                    }
5820                                }
5821                            });
5822                        }
5823                        // Report sorted matches
5824                        scope.spawn(async move {
5825                            let mut current_index = 0;
5826                            let mut scratch = vec![None; buffers_len];
5827                            while let Some(status) = finished_rx.next().await {
5828                                debug_assert!(
5829                                    scratch[status.buffer_index].is_none(),
5830                                    "Got match status of position {} twice",
5831                                    status.buffer_index
5832                                );
5833                                let index = status.buffer_index;
5834                                scratch[index] = Some(status);
5835                                while current_index < buffers_len {
5836                                    let Some(current_entry) = scratch[current_index].take() else {
5837                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5838                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5839                                        // this time.
5840                                        break;
5841                                    };
5842                                    if let Some(entry) = current_entry.entry {
5843                                        result_tx.send(entry).await.log_err();
5844                                    }
5845                                    current_index += 1;
5846                                }
5847                                if current_index == buffers_len {
5848                                    break;
5849                                }
5850                            }
5851                        });
5852                    })
5853                    .await;
5854            })
5855            .detach();
5856        result_rx
5857    }
5858
5859    /// Pick paths that might potentially contain a match of a given search query.
5860    async fn background_search(
5861        unnamed_buffers: Vec<Model<Buffer>>,
5862        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
5863        executor: BackgroundExecutor,
5864        fs: Arc<dyn Fs>,
5865        workers: usize,
5866        query: SearchQuery,
5867        path_count: usize,
5868        snapshots: Vec<LocalSnapshot>,
5869        matching_paths_tx: Sender<SearchMatchCandidate>,
5870    ) {
5871        let fs = &fs;
5872        let query = &query;
5873        let matching_paths_tx = &matching_paths_tx;
5874        let snapshots = &snapshots;
5875        let paths_per_worker = (path_count + workers - 1) / workers;
5876        for buffer in unnamed_buffers {
5877            matching_paths_tx
5878                .send(SearchMatchCandidate::OpenBuffer {
5879                    buffer: buffer.clone(),
5880                    path: None,
5881                })
5882                .await
5883                .log_err();
5884        }
5885        for (path, (buffer, _)) in opened_buffers.iter() {
5886            matching_paths_tx
5887                .send(SearchMatchCandidate::OpenBuffer {
5888                    buffer: buffer.clone(),
5889                    path: Some(path.clone()),
5890                })
5891                .await
5892                .log_err();
5893        }
5894        executor
5895            .scoped(|scope| {
5896                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
5897
5898                for worker_ix in 0..workers {
5899                    let worker_start_ix = worker_ix * paths_per_worker;
5900                    let worker_end_ix = worker_start_ix + paths_per_worker;
5901                    let unnamed_buffers = opened_buffers.clone();
5902                    let limiter = Arc::clone(&max_concurrent_workers);
5903                    scope.spawn(async move {
5904                        let _guard = limiter.acquire().await;
5905                        let mut snapshot_start_ix = 0;
5906                        let mut abs_path = PathBuf::new();
5907                        for snapshot in snapshots {
5908                            let snapshot_end_ix = snapshot_start_ix
5909                                + if query.include_ignored() {
5910                                    snapshot.file_count()
5911                                } else {
5912                                    snapshot.visible_file_count()
5913                                };
5914                            if worker_end_ix <= snapshot_start_ix {
5915                                break;
5916                            } else if worker_start_ix > snapshot_end_ix {
5917                                snapshot_start_ix = snapshot_end_ix;
5918                                continue;
5919                            } else {
5920                                let start_in_snapshot =
5921                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5922                                let end_in_snapshot =
5923                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5924
5925                                for entry in snapshot
5926                                    .files(query.include_ignored(), start_in_snapshot)
5927                                    .take(end_in_snapshot - start_in_snapshot)
5928                                {
5929                                    if matching_paths_tx.is_closed() {
5930                                        break;
5931                                    }
5932                                    if unnamed_buffers.contains_key(&entry.path) {
5933                                        continue;
5934                                    }
5935                                    let matches = if query.file_matches(Some(&entry.path)) {
5936                                        abs_path.clear();
5937                                        abs_path.push(&snapshot.abs_path());
5938                                        abs_path.push(&entry.path);
5939                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5940                                        {
5941                                            query.detect(file).unwrap_or(false)
5942                                        } else {
5943                                            false
5944                                        }
5945                                    } else {
5946                                        false
5947                                    };
5948
5949                                    if matches {
5950                                        let project_path = SearchMatchCandidate::Path {
5951                                            worktree_id: snapshot.id(),
5952                                            path: entry.path.clone(),
5953                                            is_ignored: entry.is_ignored,
5954                                        };
5955                                        if matching_paths_tx.send(project_path).await.is_err() {
5956                                            break;
5957                                        }
5958                                    }
5959                                }
5960
5961                                snapshot_start_ix = snapshot_end_ix;
5962                            }
5963                        }
5964                    });
5965                }
5966
5967                if query.include_ignored() {
5968                    for snapshot in snapshots {
5969                        for ignored_entry in snapshot
5970                            .entries(query.include_ignored())
5971                            .filter(|e| e.is_ignored)
5972                        {
5973                            let limiter = Arc::clone(&max_concurrent_workers);
5974                            scope.spawn(async move {
5975                                let _guard = limiter.acquire().await;
5976                                let mut ignored_paths_to_process =
5977                                    VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
5978                                while let Some(ignored_abs_path) =
5979                                    ignored_paths_to_process.pop_front()
5980                                {
5981                                    if let Some(fs_metadata) = fs
5982                                        .metadata(&ignored_abs_path)
5983                                        .await
5984                                        .with_context(|| {
5985                                            format!("fetching fs metadata for {ignored_abs_path:?}")
5986                                        })
5987                                        .log_err()
5988                                        .flatten()
5989                                    {
5990                                        if fs_metadata.is_dir {
5991                                            if let Some(mut subfiles) = fs
5992                                                .read_dir(&ignored_abs_path)
5993                                                .await
5994                                                .with_context(|| {
5995                                                    format!(
5996                                                        "listing ignored path {ignored_abs_path:?}"
5997                                                    )
5998                                                })
5999                                                .log_err()
6000                                            {
6001                                                while let Some(subfile) = subfiles.next().await {
6002                                                    if let Some(subfile) = subfile.log_err() {
6003                                                        ignored_paths_to_process.push_back(subfile);
6004                                                    }
6005                                                }
6006                                            }
6007                                        } else if !fs_metadata.is_symlink {
6008                                            if !query.file_matches(Some(&ignored_abs_path))
6009                                                || snapshot.is_path_excluded(
6010                                                    ignored_entry.path.to_path_buf(),
6011                                                )
6012                                            {
6013                                                continue;
6014                                            }
6015                                            let matches = if let Some(file) = fs
6016                                                .open_sync(&ignored_abs_path)
6017                                                .await
6018                                                .with_context(|| {
6019                                                    format!(
6020                                                        "Opening ignored path {ignored_abs_path:?}"
6021                                                    )
6022                                                })
6023                                                .log_err()
6024                                            {
6025                                                query.detect(file).unwrap_or(false)
6026                                            } else {
6027                                                false
6028                                            };
6029                                            if matches {
6030                                                let project_path = SearchMatchCandidate::Path {
6031                                                    worktree_id: snapshot.id(),
6032                                                    path: Arc::from(
6033                                                        ignored_abs_path
6034                                                            .strip_prefix(snapshot.abs_path())
6035                                                            .expect(
6036                                                                "scanning worktree-related files",
6037                                                            ),
6038                                                    ),
6039                                                    is_ignored: true,
6040                                                };
6041                                                if matching_paths_tx
6042                                                    .send(project_path)
6043                                                    .await
6044                                                    .is_err()
6045                                                {
6046                                                    return;
6047                                                }
6048                                            }
6049                                        }
6050                                    }
6051                                }
6052                            });
6053                        }
6054                    }
6055                }
6056            })
6057            .await;
6058    }
6059
6060    pub fn request_lsp<R: LspCommand>(
6061        &self,
6062        buffer_handle: Model<Buffer>,
6063        server: LanguageServerToQuery,
6064        request: R,
6065        cx: &mut ModelContext<Self>,
6066    ) -> Task<Result<R::Response>>
6067    where
6068        <R::LspRequest as lsp::request::Request>::Result: Send,
6069        <R::LspRequest as lsp::request::Request>::Params: Send,
6070    {
6071        let buffer = buffer_handle.read(cx);
6072        if self.is_local() {
6073            let language_server = match server {
6074                LanguageServerToQuery::Primary => {
6075                    match self.primary_language_server_for_buffer(buffer, cx) {
6076                        Some((_, server)) => Some(Arc::clone(server)),
6077                        None => return Task::ready(Ok(Default::default())),
6078                    }
6079                }
6080                LanguageServerToQuery::Other(id) => self
6081                    .language_server_for_buffer(buffer, id, cx)
6082                    .map(|(_, server)| Arc::clone(server)),
6083            };
6084            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6085            if let (Some(file), Some(language_server)) = (file, language_server) {
6086                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6087                return cx.spawn(move |this, cx| async move {
6088                    if !request.check_capabilities(language_server.capabilities()) {
6089                        return Ok(Default::default());
6090                    }
6091
6092                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
6093                    let response = match result {
6094                        Ok(response) => response,
6095
6096                        Err(err) => {
6097                            log::warn!(
6098                                "Generic lsp request to {} failed: {}",
6099                                language_server.name(),
6100                                err
6101                            );
6102                            return Err(err);
6103                        }
6104                    };
6105
6106                    request
6107                        .response_from_lsp(
6108                            response,
6109                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6110                            buffer_handle,
6111                            language_server.server_id(),
6112                            cx,
6113                        )
6114                        .await
6115                });
6116            }
6117        } else if let Some(project_id) = self.remote_id() {
6118            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6119        }
6120
6121        Task::ready(Ok(Default::default()))
6122    }
6123
6124    fn send_lsp_proto_request<R: LspCommand>(
6125        &self,
6126        buffer: Model<Buffer>,
6127        project_id: u64,
6128        request: R,
6129        cx: &mut ModelContext<'_, Project>,
6130    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6131        let rpc = self.client.clone();
6132        let message = request.to_proto(project_id, buffer.read(cx));
6133        cx.spawn(move |this, mut cx| async move {
6134            // Ensure the project is still alive by the time the task
6135            // is scheduled.
6136            this.upgrade().context("project dropped")?;
6137            let response = rpc.request(message).await?;
6138            let this = this.upgrade().context("project dropped")?;
6139            if this.update(&mut cx, |this, _| this.is_disconnected())? {
6140                Err(anyhow!("disconnected before completing request"))
6141            } else {
6142                request
6143                    .response_from_proto(response, this, buffer, cx)
6144                    .await
6145            }
6146        })
6147    }
6148
6149    fn sort_candidates_and_open_buffers(
6150        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6151        cx: &mut ModelContext<Self>,
6152    ) -> (
6153        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6154        Receiver<(
6155            Option<(Model<Buffer>, BufferSnapshot)>,
6156            SearchMatchCandidateIndex,
6157        )>,
6158    ) {
6159        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6160        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6161        cx.spawn(move |this, cx| async move {
6162            let mut buffers = Vec::new();
6163            let mut ignored_buffers = Vec::new();
6164            while let Some(entry) = matching_paths_rx.next().await {
6165                if matches!(
6166                    entry,
6167                    SearchMatchCandidate::Path {
6168                        is_ignored: true,
6169                        ..
6170                    }
6171                ) {
6172                    ignored_buffers.push(entry);
6173                } else {
6174                    buffers.push(entry);
6175                }
6176            }
6177            buffers.sort_by_key(|candidate| candidate.path());
6178            ignored_buffers.sort_by_key(|candidate| candidate.path());
6179            buffers.extend(ignored_buffers);
6180            let matching_paths = buffers.clone();
6181            let _ = sorted_buffers_tx.send(buffers);
6182            for (index, candidate) in matching_paths.into_iter().enumerate() {
6183                if buffers_tx.is_closed() {
6184                    break;
6185                }
6186                let this = this.clone();
6187                let buffers_tx = buffers_tx.clone();
6188                cx.spawn(move |mut cx| async move {
6189                    let buffer = match candidate {
6190                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6191                        SearchMatchCandidate::Path {
6192                            worktree_id, path, ..
6193                        } => this
6194                            .update(&mut cx, |this, cx| {
6195                                this.open_buffer((worktree_id, path), cx)
6196                            })?
6197                            .await
6198                            .log_err(),
6199                    };
6200                    if let Some(buffer) = buffer {
6201                        let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6202                        buffers_tx
6203                            .send((Some((buffer, snapshot)), index))
6204                            .await
6205                            .log_err();
6206                    } else {
6207                        buffers_tx.send((None, index)).await.log_err();
6208                    }
6209
6210                    Ok::<_, anyhow::Error>(())
6211                })
6212                .detach();
6213            }
6214        })
6215        .detach();
6216        (sorted_buffers_rx, buffers_rx)
6217    }
6218
6219    pub fn find_or_create_local_worktree(
6220        &mut self,
6221        abs_path: impl AsRef<Path>,
6222        visible: bool,
6223        cx: &mut ModelContext<Self>,
6224    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6225        let abs_path = abs_path.as_ref();
6226        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6227            Task::ready(Ok((tree, relative_path)))
6228        } else {
6229            let worktree = self.create_local_worktree(abs_path, visible, cx);
6230            cx.background_executor()
6231                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6232        }
6233    }
6234
6235    pub fn find_local_worktree(
6236        &self,
6237        abs_path: &Path,
6238        cx: &AppContext,
6239    ) -> Option<(Model<Worktree>, PathBuf)> {
6240        for tree in &self.worktrees {
6241            if let Some(tree) = tree.upgrade() {
6242                if let Some(relative_path) = tree
6243                    .read(cx)
6244                    .as_local()
6245                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6246                {
6247                    return Some((tree.clone(), relative_path.into()));
6248                }
6249            }
6250        }
6251        None
6252    }
6253
6254    pub fn is_shared(&self) -> bool {
6255        match &self.client_state {
6256            ProjectClientState::Shared { .. } => true,
6257            ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6258        }
6259    }
6260
6261    fn create_local_worktree(
6262        &mut self,
6263        abs_path: impl AsRef<Path>,
6264        visible: bool,
6265        cx: &mut ModelContext<Self>,
6266    ) -> Task<Result<Model<Worktree>>> {
6267        let fs = self.fs.clone();
6268        let client = self.client.clone();
6269        let next_entry_id = self.next_entry_id.clone();
6270        let path: Arc<Path> = abs_path.as_ref().into();
6271        let task = self
6272            .loading_local_worktrees
6273            .entry(path.clone())
6274            .or_insert_with(|| {
6275                cx.spawn(move |project, mut cx| {
6276                    async move {
6277                        let worktree = Worktree::local(
6278                            client.clone(),
6279                            path.clone(),
6280                            visible,
6281                            fs,
6282                            next_entry_id,
6283                            &mut cx,
6284                        )
6285                        .await;
6286
6287                        project.update(&mut cx, |project, _| {
6288                            project.loading_local_worktrees.remove(&path);
6289                        })?;
6290
6291                        let worktree = worktree?;
6292                        project
6293                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6294                        Ok(worktree)
6295                    }
6296                    .map_err(Arc::new)
6297                })
6298                .shared()
6299            })
6300            .clone();
6301        cx.background_executor().spawn(async move {
6302            match task.await {
6303                Ok(worktree) => Ok(worktree),
6304                Err(err) => Err(anyhow!("{}", err)),
6305            }
6306        })
6307    }
6308
6309    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6310        let mut servers_to_remove = HashMap::default();
6311        let mut servers_to_preserve = HashSet::default();
6312        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6313            if worktree_id == &id_to_remove {
6314                servers_to_remove.insert(server_id, server_name.clone());
6315            } else {
6316                servers_to_preserve.insert(server_id);
6317            }
6318        }
6319        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6320        for (server_id_to_remove, server_name) in servers_to_remove {
6321            self.language_server_ids
6322                .remove(&(id_to_remove, server_name));
6323            self.language_server_statuses.remove(&server_id_to_remove);
6324            self.last_workspace_edits_by_language_server
6325                .remove(&server_id_to_remove);
6326            self.language_servers.remove(&server_id_to_remove);
6327            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6328        }
6329
6330        let mut prettier_instances_to_clean = FuturesUnordered::new();
6331        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6332            for path in prettier_paths.iter().flatten() {
6333                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6334                    prettier_instances_to_clean.push(async move {
6335                        prettier_instance
6336                            .server()
6337                            .await
6338                            .map(|server| server.server_id())
6339                    });
6340                }
6341            }
6342        }
6343        cx.spawn(|project, mut cx| async move {
6344            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6345                if let Some(prettier_server_id) = prettier_server_id {
6346                    project
6347                        .update(&mut cx, |project, cx| {
6348                            project
6349                                .supplementary_language_servers
6350                                .remove(&prettier_server_id);
6351                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6352                        })
6353                        .ok();
6354                }
6355            }
6356        })
6357        .detach();
6358
6359        self.worktrees.retain(|worktree| {
6360            if let Some(worktree) = worktree.upgrade() {
6361                let id = worktree.read(cx).id();
6362                if id == id_to_remove {
6363                    cx.emit(Event::WorktreeRemoved(id));
6364                    false
6365                } else {
6366                    true
6367                }
6368            } else {
6369                false
6370            }
6371        });
6372        self.metadata_changed(cx);
6373    }
6374
6375    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6376        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6377        if worktree.read(cx).is_local() {
6378            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6379                worktree::Event::UpdatedEntries(changes) => {
6380                    this.update_local_worktree_buffers(&worktree, changes, cx);
6381                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6382                    this.update_local_worktree_settings(&worktree, changes, cx);
6383                    this.update_prettier_settings(&worktree, changes, cx);
6384                    cx.emit(Event::WorktreeUpdatedEntries(
6385                        worktree.read(cx).id(),
6386                        changes.clone(),
6387                    ));
6388                }
6389                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6390                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6391                }
6392            })
6393            .detach();
6394        }
6395
6396        let push_strong_handle = {
6397            let worktree = worktree.read(cx);
6398            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6399        };
6400        if push_strong_handle {
6401            self.worktrees
6402                .push(WorktreeHandle::Strong(worktree.clone()));
6403        } else {
6404            self.worktrees
6405                .push(WorktreeHandle::Weak(worktree.downgrade()));
6406        }
6407
6408        let handle_id = worktree.entity_id();
6409        cx.observe_release(worktree, move |this, worktree, cx| {
6410            let _ = this.remove_worktree(worktree.id(), cx);
6411            cx.update_global::<SettingsStore, _>(|store, cx| {
6412                store
6413                    .clear_local_settings(handle_id.as_u64() as usize, cx)
6414                    .log_err()
6415            });
6416        })
6417        .detach();
6418
6419        cx.emit(Event::WorktreeAdded);
6420        self.metadata_changed(cx);
6421    }
6422
6423    fn update_local_worktree_buffers(
6424        &mut self,
6425        worktree_handle: &Model<Worktree>,
6426        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6427        cx: &mut ModelContext<Self>,
6428    ) {
6429        let snapshot = worktree_handle.read(cx).snapshot();
6430
6431        let mut renamed_buffers = Vec::new();
6432        for (path, entry_id, _) in changes {
6433            let worktree_id = worktree_handle.read(cx).id();
6434            let project_path = ProjectPath {
6435                worktree_id,
6436                path: path.clone(),
6437            };
6438
6439            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6440                Some(&buffer_id) => buffer_id,
6441                None => match self.local_buffer_ids_by_path.get(&project_path) {
6442                    Some(&buffer_id) => buffer_id,
6443                    None => {
6444                        continue;
6445                    }
6446                },
6447            };
6448
6449            let open_buffer = self.opened_buffers.get(&buffer_id);
6450            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6451                buffer
6452            } else {
6453                self.opened_buffers.remove(&buffer_id);
6454                self.local_buffer_ids_by_path.remove(&project_path);
6455                self.local_buffer_ids_by_entry_id.remove(entry_id);
6456                continue;
6457            };
6458
6459            buffer.update(cx, |buffer, cx| {
6460                if let Some(old_file) = File::from_dyn(buffer.file()) {
6461                    if old_file.worktree != *worktree_handle {
6462                        return;
6463                    }
6464
6465                    let new_file = if let Some(entry) = old_file
6466                        .entry_id
6467                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6468                    {
6469                        File {
6470                            is_local: true,
6471                            entry_id: Some(entry.id),
6472                            mtime: entry.mtime,
6473                            path: entry.path.clone(),
6474                            worktree: worktree_handle.clone(),
6475                            is_deleted: false,
6476                            is_private: entry.is_private,
6477                        }
6478                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6479                        File {
6480                            is_local: true,
6481                            entry_id: Some(entry.id),
6482                            mtime: entry.mtime,
6483                            path: entry.path.clone(),
6484                            worktree: worktree_handle.clone(),
6485                            is_deleted: false,
6486                            is_private: entry.is_private,
6487                        }
6488                    } else {
6489                        File {
6490                            is_local: true,
6491                            entry_id: old_file.entry_id,
6492                            path: old_file.path().clone(),
6493                            mtime: old_file.mtime(),
6494                            worktree: worktree_handle.clone(),
6495                            is_deleted: true,
6496                            is_private: old_file.is_private,
6497                        }
6498                    };
6499
6500                    let old_path = old_file.abs_path(cx);
6501                    if new_file.abs_path(cx) != old_path {
6502                        renamed_buffers.push((cx.handle(), old_file.clone()));
6503                        self.local_buffer_ids_by_path.remove(&project_path);
6504                        self.local_buffer_ids_by_path.insert(
6505                            ProjectPath {
6506                                worktree_id,
6507                                path: path.clone(),
6508                            },
6509                            buffer_id,
6510                        );
6511                    }
6512
6513                    if new_file.entry_id != Some(*entry_id) {
6514                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6515                        if let Some(entry_id) = new_file.entry_id {
6516                            self.local_buffer_ids_by_entry_id
6517                                .insert(entry_id, buffer_id);
6518                        }
6519                    }
6520
6521                    if new_file != *old_file {
6522                        if let Some(project_id) = self.remote_id() {
6523                            self.client
6524                                .send(proto::UpdateBufferFile {
6525                                    project_id,
6526                                    buffer_id: buffer_id.into(),
6527                                    file: Some(new_file.to_proto()),
6528                                })
6529                                .log_err();
6530                        }
6531
6532                        buffer.file_updated(Arc::new(new_file), cx);
6533                    }
6534                }
6535            });
6536        }
6537
6538        for (buffer, old_file) in renamed_buffers {
6539            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6540            self.detect_language_for_buffer(&buffer, cx);
6541            self.register_buffer_with_language_servers(&buffer, cx);
6542        }
6543    }
6544
6545    fn update_local_worktree_language_servers(
6546        &mut self,
6547        worktree_handle: &Model<Worktree>,
6548        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6549        cx: &mut ModelContext<Self>,
6550    ) {
6551        if changes.is_empty() {
6552            return;
6553        }
6554
6555        let worktree_id = worktree_handle.read(cx).id();
6556        let mut language_server_ids = self
6557            .language_server_ids
6558            .iter()
6559            .filter_map(|((server_worktree_id, _), server_id)| {
6560                (*server_worktree_id == worktree_id).then_some(*server_id)
6561            })
6562            .collect::<Vec<_>>();
6563        language_server_ids.sort();
6564        language_server_ids.dedup();
6565
6566        let abs_path = worktree_handle.read(cx).abs_path();
6567        for server_id in &language_server_ids {
6568            if let Some(LanguageServerState::Running {
6569                server,
6570                watched_paths,
6571                ..
6572            }) = self.language_servers.get(server_id)
6573            {
6574                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6575                    let params = lsp::DidChangeWatchedFilesParams {
6576                        changes: changes
6577                            .iter()
6578                            .filter_map(|(path, _, change)| {
6579                                if !watched_paths.is_match(&path) {
6580                                    return None;
6581                                }
6582                                let typ = match change {
6583                                    PathChange::Loaded => return None,
6584                                    PathChange::Added => lsp::FileChangeType::CREATED,
6585                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6586                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6587                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6588                                };
6589                                Some(lsp::FileEvent {
6590                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6591                                    typ,
6592                                })
6593                            })
6594                            .collect(),
6595                    };
6596
6597                    if !params.changes.is_empty() {
6598                        server
6599                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6600                            .log_err();
6601                    }
6602                }
6603            }
6604        }
6605    }
6606
6607    fn update_local_worktree_buffers_git_repos(
6608        &mut self,
6609        worktree_handle: Model<Worktree>,
6610        changed_repos: &UpdatedGitRepositoriesSet,
6611        cx: &mut ModelContext<Self>,
6612    ) {
6613        debug_assert!(worktree_handle.read(cx).is_local());
6614
6615        // Identify the loading buffers whose containing repository that has changed.
6616        let future_buffers = self
6617            .loading_buffers_by_path
6618            .iter()
6619            .filter_map(|(project_path, receiver)| {
6620                if project_path.worktree_id != worktree_handle.read(cx).id() {
6621                    return None;
6622                }
6623                let path = &project_path.path;
6624                changed_repos
6625                    .iter()
6626                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6627                let receiver = receiver.clone();
6628                let path = path.clone();
6629                Some(async move {
6630                    wait_for_loading_buffer(receiver)
6631                        .await
6632                        .ok()
6633                        .map(|buffer| (buffer, path))
6634                })
6635            })
6636            .collect::<FuturesUnordered<_>>();
6637
6638        // Identify the current buffers whose containing repository has changed.
6639        let current_buffers = self
6640            .opened_buffers
6641            .values()
6642            .filter_map(|buffer| {
6643                let buffer = buffer.upgrade()?;
6644                let file = File::from_dyn(buffer.read(cx).file())?;
6645                if file.worktree != worktree_handle {
6646                    return None;
6647                }
6648                let path = file.path();
6649                changed_repos
6650                    .iter()
6651                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6652                Some((buffer, path.clone()))
6653            })
6654            .collect::<Vec<_>>();
6655
6656        if future_buffers.len() + current_buffers.len() == 0 {
6657            return;
6658        }
6659
6660        let remote_id = self.remote_id();
6661        let client = self.client.clone();
6662        cx.spawn(move |_, mut cx| async move {
6663            // Wait for all of the buffers to load.
6664            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6665
6666            // Reload the diff base for every buffer whose containing git repository has changed.
6667            let snapshot =
6668                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6669            let diff_bases_by_buffer = cx
6670                .background_executor()
6671                .spawn(async move {
6672                    future_buffers
6673                        .into_iter()
6674                        .filter_map(|e| e)
6675                        .chain(current_buffers)
6676                        .filter_map(|(buffer, path)| {
6677                            let (work_directory, repo) =
6678                                snapshot.repository_and_work_directory_for_path(&path)?;
6679                            let repo = snapshot.get_local_repo(&repo)?;
6680                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6681                            let base_text = repo.repo_ptr.lock().load_index_text(relative_path);
6682                            Some((buffer, base_text))
6683                        })
6684                        .collect::<Vec<_>>()
6685                })
6686                .await;
6687
6688            // Assign the new diff bases on all of the buffers.
6689            for (buffer, diff_base) in diff_bases_by_buffer {
6690                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6691                    buffer.set_diff_base(diff_base.clone(), cx);
6692                    buffer.remote_id().into()
6693                })?;
6694                if let Some(project_id) = remote_id {
6695                    client
6696                        .send(proto::UpdateDiffBase {
6697                            project_id,
6698                            buffer_id,
6699                            diff_base,
6700                        })
6701                        .log_err();
6702                }
6703            }
6704
6705            anyhow::Ok(())
6706        })
6707        .detach();
6708    }
6709
6710    fn update_local_worktree_settings(
6711        &mut self,
6712        worktree: &Model<Worktree>,
6713        changes: &UpdatedEntriesSet,
6714        cx: &mut ModelContext<Self>,
6715    ) {
6716        let project_id = self.remote_id();
6717        let worktree_id = worktree.entity_id();
6718        let worktree = worktree.read(cx).as_local().unwrap();
6719        let remote_worktree_id = worktree.id();
6720
6721        let mut settings_contents = Vec::new();
6722        for (path, _, change) in changes.iter() {
6723            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6724                let settings_dir = Arc::from(
6725                    path.ancestors()
6726                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6727                        .unwrap(),
6728                );
6729                let fs = self.fs.clone();
6730                let removed = *change == PathChange::Removed;
6731                let abs_path = worktree.absolutize(path);
6732                settings_contents.push(async move {
6733                    (
6734                        settings_dir,
6735                        if removed {
6736                            None
6737                        } else {
6738                            Some(async move { fs.load(&abs_path?).await }.await)
6739                        },
6740                    )
6741                });
6742            }
6743        }
6744
6745        if settings_contents.is_empty() {
6746            return;
6747        }
6748
6749        let client = self.client.clone();
6750        cx.spawn(move |_, cx| async move {
6751            let settings_contents: Vec<(Arc<Path>, _)> =
6752                futures::future::join_all(settings_contents).await;
6753            cx.update(|cx| {
6754                cx.update_global::<SettingsStore, _>(|store, cx| {
6755                    for (directory, file_content) in settings_contents {
6756                        let file_content = file_content.and_then(|content| content.log_err());
6757                        store
6758                            .set_local_settings(
6759                                worktree_id.as_u64() as usize,
6760                                directory.clone(),
6761                                file_content.as_ref().map(String::as_str),
6762                                cx,
6763                            )
6764                            .log_err();
6765                        if let Some(remote_id) = project_id {
6766                            client
6767                                .send(proto::UpdateWorktreeSettings {
6768                                    project_id: remote_id,
6769                                    worktree_id: remote_worktree_id.to_proto(),
6770                                    path: directory.to_string_lossy().into_owned(),
6771                                    content: file_content,
6772                                })
6773                                .log_err();
6774                        }
6775                    }
6776                });
6777            })
6778            .ok();
6779        })
6780        .detach();
6781    }
6782
6783    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6784        let new_active_entry = entry.and_then(|project_path| {
6785            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6786            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6787            Some(entry.id)
6788        });
6789        if new_active_entry != self.active_entry {
6790            self.active_entry = new_active_entry;
6791            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6792        }
6793    }
6794
6795    pub fn language_servers_running_disk_based_diagnostics(
6796        &self,
6797    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6798        self.language_server_statuses
6799            .iter()
6800            .filter_map(|(id, status)| {
6801                if status.has_pending_diagnostic_updates {
6802                    Some(*id)
6803                } else {
6804                    None
6805                }
6806            })
6807    }
6808
6809    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
6810        let mut summary = DiagnosticSummary::default();
6811        for (_, _, path_summary) in
6812            self.diagnostic_summaries(include_ignored, cx)
6813                .filter(|(path, _, _)| {
6814                    let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
6815                    include_ignored || worktree == Some(false)
6816                })
6817        {
6818            summary.error_count += path_summary.error_count;
6819            summary.warning_count += path_summary.warning_count;
6820        }
6821        summary
6822    }
6823
6824    pub fn diagnostic_summaries<'a>(
6825        &'a self,
6826        include_ignored: bool,
6827        cx: &'a AppContext,
6828    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6829        self.visible_worktrees(cx)
6830            .flat_map(move |worktree| {
6831                let worktree = worktree.read(cx);
6832                let worktree_id = worktree.id();
6833                worktree
6834                    .diagnostic_summaries()
6835                    .map(move |(path, server_id, summary)| {
6836                        (ProjectPath { worktree_id, path }, server_id, summary)
6837                    })
6838            })
6839            .filter(move |(path, _, _)| {
6840                let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
6841                include_ignored || worktree == Some(false)
6842            })
6843    }
6844
6845    pub fn disk_based_diagnostics_started(
6846        &mut self,
6847        language_server_id: LanguageServerId,
6848        cx: &mut ModelContext<Self>,
6849    ) {
6850        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6851    }
6852
6853    pub fn disk_based_diagnostics_finished(
6854        &mut self,
6855        language_server_id: LanguageServerId,
6856        cx: &mut ModelContext<Self>,
6857    ) {
6858        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6859    }
6860
6861    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6862        self.active_entry
6863    }
6864
6865    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6866        self.worktree_for_id(path.worktree_id, cx)?
6867            .read(cx)
6868            .entry_for_path(&path.path)
6869            .cloned()
6870    }
6871
6872    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6873        let worktree = self.worktree_for_entry(entry_id, cx)?;
6874        let worktree = worktree.read(cx);
6875        let worktree_id = worktree.id();
6876        let path = worktree.entry_for_id(entry_id)?.path.clone();
6877        Some(ProjectPath { worktree_id, path })
6878    }
6879
6880    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6881        let workspace_root = self
6882            .worktree_for_id(project_path.worktree_id, cx)?
6883            .read(cx)
6884            .abs_path();
6885        let project_path = project_path.path.as_ref();
6886
6887        Some(if project_path == Path::new("") {
6888            workspace_root.to_path_buf()
6889        } else {
6890            workspace_root.join(project_path)
6891        })
6892    }
6893
6894    // RPC message handlers
6895
6896    async fn handle_unshare_project(
6897        this: Model<Self>,
6898        _: TypedEnvelope<proto::UnshareProject>,
6899        _: Arc<Client>,
6900        mut cx: AsyncAppContext,
6901    ) -> Result<()> {
6902        this.update(&mut cx, |this, cx| {
6903            if this.is_local() {
6904                this.unshare(cx)?;
6905            } else {
6906                this.disconnected_from_host(cx);
6907            }
6908            Ok(())
6909        })?
6910    }
6911
6912    async fn handle_add_collaborator(
6913        this: Model<Self>,
6914        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6915        _: Arc<Client>,
6916        mut cx: AsyncAppContext,
6917    ) -> Result<()> {
6918        let collaborator = envelope
6919            .payload
6920            .collaborator
6921            .take()
6922            .ok_or_else(|| anyhow!("empty collaborator"))?;
6923
6924        let collaborator = Collaborator::from_proto(collaborator)?;
6925        this.update(&mut cx, |this, cx| {
6926            this.shared_buffers.remove(&collaborator.peer_id);
6927            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6928            this.collaborators
6929                .insert(collaborator.peer_id, collaborator);
6930            cx.notify();
6931        })?;
6932
6933        Ok(())
6934    }
6935
6936    async fn handle_update_project_collaborator(
6937        this: Model<Self>,
6938        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6939        _: Arc<Client>,
6940        mut cx: AsyncAppContext,
6941    ) -> Result<()> {
6942        let old_peer_id = envelope
6943            .payload
6944            .old_peer_id
6945            .ok_or_else(|| anyhow!("missing old peer id"))?;
6946        let new_peer_id = envelope
6947            .payload
6948            .new_peer_id
6949            .ok_or_else(|| anyhow!("missing new peer id"))?;
6950        this.update(&mut cx, |this, cx| {
6951            let collaborator = this
6952                .collaborators
6953                .remove(&old_peer_id)
6954                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6955            let is_host = collaborator.replica_id == 0;
6956            this.collaborators.insert(new_peer_id, collaborator);
6957
6958            let buffers = this.shared_buffers.remove(&old_peer_id);
6959            log::info!(
6960                "peer {} became {}. moving buffers {:?}",
6961                old_peer_id,
6962                new_peer_id,
6963                &buffers
6964            );
6965            if let Some(buffers) = buffers {
6966                this.shared_buffers.insert(new_peer_id, buffers);
6967            }
6968
6969            if is_host {
6970                this.opened_buffers
6971                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6972                this.buffer_ordered_messages_tx
6973                    .unbounded_send(BufferOrderedMessage::Resync)
6974                    .unwrap();
6975            }
6976
6977            cx.emit(Event::CollaboratorUpdated {
6978                old_peer_id,
6979                new_peer_id,
6980            });
6981            cx.notify();
6982            Ok(())
6983        })?
6984    }
6985
6986    async fn handle_remove_collaborator(
6987        this: Model<Self>,
6988        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6989        _: Arc<Client>,
6990        mut cx: AsyncAppContext,
6991    ) -> Result<()> {
6992        this.update(&mut cx, |this, cx| {
6993            let peer_id = envelope
6994                .payload
6995                .peer_id
6996                .ok_or_else(|| anyhow!("invalid peer id"))?;
6997            let replica_id = this
6998                .collaborators
6999                .remove(&peer_id)
7000                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7001                .replica_id;
7002            for buffer in this.opened_buffers.values() {
7003                if let Some(buffer) = buffer.upgrade() {
7004                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7005                }
7006            }
7007            this.shared_buffers.remove(&peer_id);
7008
7009            cx.emit(Event::CollaboratorLeft(peer_id));
7010            cx.notify();
7011            Ok(())
7012        })?
7013    }
7014
7015    async fn handle_update_project(
7016        this: Model<Self>,
7017        envelope: TypedEnvelope<proto::UpdateProject>,
7018        _: Arc<Client>,
7019        mut cx: AsyncAppContext,
7020    ) -> Result<()> {
7021        this.update(&mut cx, |this, cx| {
7022            // Don't handle messages that were sent before the response to us joining the project
7023            if envelope.message_id > this.join_project_response_message_id {
7024                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7025            }
7026            Ok(())
7027        })?
7028    }
7029
7030    async fn handle_update_worktree(
7031        this: Model<Self>,
7032        envelope: TypedEnvelope<proto::UpdateWorktree>,
7033        _: Arc<Client>,
7034        mut cx: AsyncAppContext,
7035    ) -> Result<()> {
7036        this.update(&mut cx, |this, cx| {
7037            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7038            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7039                worktree.update(cx, |worktree, _| {
7040                    let worktree = worktree.as_remote_mut().unwrap();
7041                    worktree.update_from_remote(envelope.payload);
7042                });
7043            }
7044            Ok(())
7045        })?
7046    }
7047
7048    async fn handle_update_worktree_settings(
7049        this: Model<Self>,
7050        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7051        _: Arc<Client>,
7052        mut cx: AsyncAppContext,
7053    ) -> Result<()> {
7054        this.update(&mut cx, |this, cx| {
7055            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7056            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7057                cx.update_global::<SettingsStore, _>(|store, cx| {
7058                    store
7059                        .set_local_settings(
7060                            worktree.entity_id().as_u64() as usize,
7061                            PathBuf::from(&envelope.payload.path).into(),
7062                            envelope.payload.content.as_ref().map(String::as_str),
7063                            cx,
7064                        )
7065                        .log_err();
7066                });
7067            }
7068            Ok(())
7069        })?
7070    }
7071
7072    async fn handle_create_project_entry(
7073        this: Model<Self>,
7074        envelope: TypedEnvelope<proto::CreateProjectEntry>,
7075        _: Arc<Client>,
7076        mut cx: AsyncAppContext,
7077    ) -> Result<proto::ProjectEntryResponse> {
7078        let worktree = this.update(&mut cx, |this, cx| {
7079            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7080            this.worktree_for_id(worktree_id, cx)
7081                .ok_or_else(|| anyhow!("worktree not found"))
7082        })??;
7083        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7084        let entry = worktree
7085            .update(&mut cx, |worktree, cx| {
7086                let worktree = worktree.as_local_mut().unwrap();
7087                let path = PathBuf::from(envelope.payload.path);
7088                worktree.create_entry(path, envelope.payload.is_directory, cx)
7089            })?
7090            .await?;
7091        Ok(proto::ProjectEntryResponse {
7092            entry: entry.as_ref().map(|e| e.into()),
7093            worktree_scan_id: worktree_scan_id as u64,
7094        })
7095    }
7096
7097    async fn handle_rename_project_entry(
7098        this: Model<Self>,
7099        envelope: TypedEnvelope<proto::RenameProjectEntry>,
7100        _: Arc<Client>,
7101        mut cx: AsyncAppContext,
7102    ) -> Result<proto::ProjectEntryResponse> {
7103        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7104        let worktree = this.update(&mut cx, |this, cx| {
7105            this.worktree_for_entry(entry_id, cx)
7106                .ok_or_else(|| anyhow!("worktree not found"))
7107        })??;
7108        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7109        let entry = worktree
7110            .update(&mut cx, |worktree, cx| {
7111                let new_path = PathBuf::from(envelope.payload.new_path);
7112                worktree
7113                    .as_local_mut()
7114                    .unwrap()
7115                    .rename_entry(entry_id, new_path, cx)
7116            })?
7117            .await?;
7118        Ok(proto::ProjectEntryResponse {
7119            entry: entry.as_ref().map(|e| e.into()),
7120            worktree_scan_id: worktree_scan_id as u64,
7121        })
7122    }
7123
7124    async fn handle_copy_project_entry(
7125        this: Model<Self>,
7126        envelope: TypedEnvelope<proto::CopyProjectEntry>,
7127        _: Arc<Client>,
7128        mut cx: AsyncAppContext,
7129    ) -> Result<proto::ProjectEntryResponse> {
7130        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7131        let worktree = this.update(&mut cx, |this, cx| {
7132            this.worktree_for_entry(entry_id, cx)
7133                .ok_or_else(|| anyhow!("worktree not found"))
7134        })??;
7135        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7136        let entry = worktree
7137            .update(&mut cx, |worktree, cx| {
7138                let new_path = PathBuf::from(envelope.payload.new_path);
7139                worktree
7140                    .as_local_mut()
7141                    .unwrap()
7142                    .copy_entry(entry_id, new_path, cx)
7143            })?
7144            .await?;
7145        Ok(proto::ProjectEntryResponse {
7146            entry: entry.as_ref().map(|e| e.into()),
7147            worktree_scan_id: worktree_scan_id as u64,
7148        })
7149    }
7150
7151    async fn handle_delete_project_entry(
7152        this: Model<Self>,
7153        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7154        _: Arc<Client>,
7155        mut cx: AsyncAppContext,
7156    ) -> Result<proto::ProjectEntryResponse> {
7157        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7158
7159        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7160
7161        let worktree = this.update(&mut cx, |this, cx| {
7162            this.worktree_for_entry(entry_id, cx)
7163                .ok_or_else(|| anyhow!("worktree not found"))
7164        })??;
7165        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7166        worktree
7167            .update(&mut cx, |worktree, cx| {
7168                worktree
7169                    .as_local_mut()
7170                    .unwrap()
7171                    .delete_entry(entry_id, cx)
7172                    .ok_or_else(|| anyhow!("invalid entry"))
7173            })??
7174            .await?;
7175        Ok(proto::ProjectEntryResponse {
7176            entry: None,
7177            worktree_scan_id: worktree_scan_id as u64,
7178        })
7179    }
7180
7181    async fn handle_expand_project_entry(
7182        this: Model<Self>,
7183        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7184        _: Arc<Client>,
7185        mut cx: AsyncAppContext,
7186    ) -> Result<proto::ExpandProjectEntryResponse> {
7187        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7188        let worktree = this
7189            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7190            .ok_or_else(|| anyhow!("invalid request"))?;
7191        worktree
7192            .update(&mut cx, |worktree, cx| {
7193                worktree
7194                    .as_local_mut()
7195                    .unwrap()
7196                    .expand_entry(entry_id, cx)
7197                    .ok_or_else(|| anyhow!("invalid entry"))
7198            })??
7199            .await?;
7200        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7201        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7202    }
7203
7204    async fn handle_update_diagnostic_summary(
7205        this: Model<Self>,
7206        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7207        _: Arc<Client>,
7208        mut cx: AsyncAppContext,
7209    ) -> Result<()> {
7210        this.update(&mut cx, |this, cx| {
7211            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7212            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7213                if let Some(summary) = envelope.payload.summary {
7214                    let project_path = ProjectPath {
7215                        worktree_id,
7216                        path: Path::new(&summary.path).into(),
7217                    };
7218                    worktree.update(cx, |worktree, _| {
7219                        worktree
7220                            .as_remote_mut()
7221                            .unwrap()
7222                            .update_diagnostic_summary(project_path.path.clone(), &summary);
7223                    });
7224                    cx.emit(Event::DiagnosticsUpdated {
7225                        language_server_id: LanguageServerId(summary.language_server_id as usize),
7226                        path: project_path,
7227                    });
7228                }
7229            }
7230            Ok(())
7231        })?
7232    }
7233
7234    async fn handle_start_language_server(
7235        this: Model<Self>,
7236        envelope: TypedEnvelope<proto::StartLanguageServer>,
7237        _: Arc<Client>,
7238        mut cx: AsyncAppContext,
7239    ) -> Result<()> {
7240        let server = envelope
7241            .payload
7242            .server
7243            .ok_or_else(|| anyhow!("invalid server"))?;
7244        this.update(&mut cx, |this, cx| {
7245            this.language_server_statuses.insert(
7246                LanguageServerId(server.id as usize),
7247                LanguageServerStatus {
7248                    name: server.name,
7249                    pending_work: Default::default(),
7250                    has_pending_diagnostic_updates: false,
7251                    progress_tokens: Default::default(),
7252                },
7253            );
7254            cx.notify();
7255        })?;
7256        Ok(())
7257    }
7258
7259    async fn handle_update_language_server(
7260        this: Model<Self>,
7261        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7262        _: Arc<Client>,
7263        mut cx: AsyncAppContext,
7264    ) -> Result<()> {
7265        this.update(&mut cx, |this, cx| {
7266            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7267
7268            match envelope
7269                .payload
7270                .variant
7271                .ok_or_else(|| anyhow!("invalid variant"))?
7272            {
7273                proto::update_language_server::Variant::WorkStart(payload) => {
7274                    this.on_lsp_work_start(
7275                        language_server_id,
7276                        payload.token,
7277                        LanguageServerProgress {
7278                            message: payload.message,
7279                            percentage: payload.percentage.map(|p| p as usize),
7280                            last_update_at: Instant::now(),
7281                        },
7282                        cx,
7283                    );
7284                }
7285
7286                proto::update_language_server::Variant::WorkProgress(payload) => {
7287                    this.on_lsp_work_progress(
7288                        language_server_id,
7289                        payload.token,
7290                        LanguageServerProgress {
7291                            message: payload.message,
7292                            percentage: payload.percentage.map(|p| p as usize),
7293                            last_update_at: Instant::now(),
7294                        },
7295                        cx,
7296                    );
7297                }
7298
7299                proto::update_language_server::Variant::WorkEnd(payload) => {
7300                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7301                }
7302
7303                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7304                    this.disk_based_diagnostics_started(language_server_id, cx);
7305                }
7306
7307                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7308                    this.disk_based_diagnostics_finished(language_server_id, cx)
7309                }
7310            }
7311
7312            Ok(())
7313        })?
7314    }
7315
7316    async fn handle_update_buffer(
7317        this: Model<Self>,
7318        envelope: TypedEnvelope<proto::UpdateBuffer>,
7319        _: Arc<Client>,
7320        mut cx: AsyncAppContext,
7321    ) -> Result<proto::Ack> {
7322        this.update(&mut cx, |this, cx| {
7323            let payload = envelope.payload.clone();
7324            let buffer_id = BufferId::new(payload.buffer_id)?;
7325            let ops = payload
7326                .operations
7327                .into_iter()
7328                .map(language::proto::deserialize_operation)
7329                .collect::<Result<Vec<_>, _>>()?;
7330            let is_remote = this.is_remote();
7331            match this.opened_buffers.entry(buffer_id) {
7332                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7333                    OpenBuffer::Strong(buffer) => {
7334                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7335                    }
7336                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7337                    OpenBuffer::Weak(_) => {}
7338                },
7339                hash_map::Entry::Vacant(e) => {
7340                    assert!(
7341                        is_remote,
7342                        "received buffer update from {:?}",
7343                        envelope.original_sender_id
7344                    );
7345                    e.insert(OpenBuffer::Operations(ops));
7346                }
7347            }
7348            Ok(proto::Ack {})
7349        })?
7350    }
7351
7352    async fn handle_create_buffer_for_peer(
7353        this: Model<Self>,
7354        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7355        _: Arc<Client>,
7356        mut cx: AsyncAppContext,
7357    ) -> Result<()> {
7358        this.update(&mut cx, |this, cx| {
7359            match envelope
7360                .payload
7361                .variant
7362                .ok_or_else(|| anyhow!("missing variant"))?
7363            {
7364                proto::create_buffer_for_peer::Variant::State(mut state) => {
7365                    let mut buffer_file = None;
7366                    if let Some(file) = state.file.take() {
7367                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7368                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7369                            anyhow!("no worktree found for id {}", file.worktree_id)
7370                        })?;
7371                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7372                            as Arc<dyn language::File>);
7373                    }
7374
7375                    let buffer_id = BufferId::new(state.id)?;
7376                    let buffer = cx.new_model(|_| {
7377                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7378                            .unwrap()
7379                    });
7380                    this.incomplete_remote_buffers
7381                        .insert(buffer_id, Some(buffer));
7382                }
7383                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7384                    let buffer_id = BufferId::new(chunk.buffer_id)?;
7385                    let buffer = this
7386                        .incomplete_remote_buffers
7387                        .get(&buffer_id)
7388                        .cloned()
7389                        .flatten()
7390                        .ok_or_else(|| {
7391                            anyhow!(
7392                                "received chunk for buffer {} without initial state",
7393                                chunk.buffer_id
7394                            )
7395                        })?;
7396                    let operations = chunk
7397                        .operations
7398                        .into_iter()
7399                        .map(language::proto::deserialize_operation)
7400                        .collect::<Result<Vec<_>>>()?;
7401                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7402
7403                    if chunk.is_last {
7404                        this.incomplete_remote_buffers.remove(&buffer_id);
7405                        this.register_buffer(&buffer, cx)?;
7406                    }
7407                }
7408            }
7409
7410            Ok(())
7411        })?
7412    }
7413
7414    async fn handle_update_diff_base(
7415        this: Model<Self>,
7416        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7417        _: Arc<Client>,
7418        mut cx: AsyncAppContext,
7419    ) -> Result<()> {
7420        this.update(&mut cx, |this, cx| {
7421            let buffer_id = envelope.payload.buffer_id;
7422            let buffer_id = BufferId::new(buffer_id)?;
7423            let diff_base = envelope.payload.diff_base;
7424            if let Some(buffer) = this
7425                .opened_buffers
7426                .get_mut(&buffer_id)
7427                .and_then(|b| b.upgrade())
7428                .or_else(|| {
7429                    this.incomplete_remote_buffers
7430                        .get(&buffer_id)
7431                        .cloned()
7432                        .flatten()
7433                })
7434            {
7435                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7436            }
7437            Ok(())
7438        })?
7439    }
7440
7441    async fn handle_update_buffer_file(
7442        this: Model<Self>,
7443        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7444        _: Arc<Client>,
7445        mut cx: AsyncAppContext,
7446    ) -> Result<()> {
7447        let buffer_id = envelope.payload.buffer_id;
7448        let buffer_id = BufferId::new(buffer_id)?;
7449
7450        this.update(&mut cx, |this, cx| {
7451            let payload = envelope.payload.clone();
7452            if let Some(buffer) = this
7453                .opened_buffers
7454                .get(&buffer_id)
7455                .and_then(|b| b.upgrade())
7456                .or_else(|| {
7457                    this.incomplete_remote_buffers
7458                        .get(&buffer_id)
7459                        .cloned()
7460                        .flatten()
7461                })
7462            {
7463                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7464                let worktree = this
7465                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7466                    .ok_or_else(|| anyhow!("no such worktree"))?;
7467                let file = File::from_proto(file, worktree, cx)?;
7468                buffer.update(cx, |buffer, cx| {
7469                    buffer.file_updated(Arc::new(file), cx);
7470                });
7471                this.detect_language_for_buffer(&buffer, cx);
7472            }
7473            Ok(())
7474        })?
7475    }
7476
7477    async fn handle_save_buffer(
7478        this: Model<Self>,
7479        envelope: TypedEnvelope<proto::SaveBuffer>,
7480        _: Arc<Client>,
7481        mut cx: AsyncAppContext,
7482    ) -> Result<proto::BufferSaved> {
7483        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7484        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7485            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7486            let buffer = this
7487                .opened_buffers
7488                .get(&buffer_id)
7489                .and_then(|buffer| buffer.upgrade())
7490                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7491            anyhow::Ok((project_id, buffer))
7492        })??;
7493        buffer
7494            .update(&mut cx, |buffer, _| {
7495                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7496            })?
7497            .await?;
7498        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7499
7500        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7501            .await?;
7502        Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7503            project_id,
7504            buffer_id: buffer_id.into(),
7505            version: serialize_version(buffer.saved_version()),
7506            mtime: Some(buffer.saved_mtime().into()),
7507            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7508        })?)
7509    }
7510
7511    async fn handle_reload_buffers(
7512        this: Model<Self>,
7513        envelope: TypedEnvelope<proto::ReloadBuffers>,
7514        _: Arc<Client>,
7515        mut cx: AsyncAppContext,
7516    ) -> Result<proto::ReloadBuffersResponse> {
7517        let sender_id = envelope.original_sender_id()?;
7518        let reload = this.update(&mut cx, |this, cx| {
7519            let mut buffers = HashSet::default();
7520            for buffer_id in &envelope.payload.buffer_ids {
7521                let buffer_id = BufferId::new(*buffer_id)?;
7522                buffers.insert(
7523                    this.opened_buffers
7524                        .get(&buffer_id)
7525                        .and_then(|buffer| buffer.upgrade())
7526                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7527                );
7528            }
7529            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7530        })??;
7531
7532        let project_transaction = reload.await?;
7533        let project_transaction = this.update(&mut cx, |this, cx| {
7534            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7535        })?;
7536        Ok(proto::ReloadBuffersResponse {
7537            transaction: Some(project_transaction),
7538        })
7539    }
7540
7541    async fn handle_synchronize_buffers(
7542        this: Model<Self>,
7543        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7544        _: Arc<Client>,
7545        mut cx: AsyncAppContext,
7546    ) -> Result<proto::SynchronizeBuffersResponse> {
7547        let project_id = envelope.payload.project_id;
7548        let mut response = proto::SynchronizeBuffersResponse {
7549            buffers: Default::default(),
7550        };
7551
7552        this.update(&mut cx, |this, cx| {
7553            let Some(guest_id) = envelope.original_sender_id else {
7554                error!("missing original_sender_id on SynchronizeBuffers request");
7555                bail!("missing original_sender_id on SynchronizeBuffers request");
7556            };
7557
7558            this.shared_buffers.entry(guest_id).or_default().clear();
7559            for buffer in envelope.payload.buffers {
7560                let buffer_id = BufferId::new(buffer.id)?;
7561                let remote_version = language::proto::deserialize_version(&buffer.version);
7562                if let Some(buffer) = this.buffer_for_id(buffer_id) {
7563                    this.shared_buffers
7564                        .entry(guest_id)
7565                        .or_default()
7566                        .insert(buffer_id);
7567
7568                    let buffer = buffer.read(cx);
7569                    response.buffers.push(proto::BufferVersion {
7570                        id: buffer_id.into(),
7571                        version: language::proto::serialize_version(&buffer.version),
7572                    });
7573
7574                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7575                    let client = this.client.clone();
7576                    if let Some(file) = buffer.file() {
7577                        client
7578                            .send(proto::UpdateBufferFile {
7579                                project_id,
7580                                buffer_id: buffer_id.into(),
7581                                file: Some(file.to_proto()),
7582                            })
7583                            .log_err();
7584                    }
7585
7586                    client
7587                        .send(proto::UpdateDiffBase {
7588                            project_id,
7589                            buffer_id: buffer_id.into(),
7590                            diff_base: buffer.diff_base().map(Into::into),
7591                        })
7592                        .log_err();
7593
7594                    client
7595                        .send(proto::BufferReloaded {
7596                            project_id,
7597                            buffer_id: buffer_id.into(),
7598                            version: language::proto::serialize_version(buffer.saved_version()),
7599                            mtime: Some(buffer.saved_mtime().into()),
7600                            fingerprint: language::proto::serialize_fingerprint(
7601                                buffer.saved_version_fingerprint(),
7602                            ),
7603                            line_ending: language::proto::serialize_line_ending(
7604                                buffer.line_ending(),
7605                            ) as i32,
7606                        })
7607                        .log_err();
7608
7609                    cx.background_executor()
7610                        .spawn(
7611                            async move {
7612                                let operations = operations.await;
7613                                for chunk in split_operations(operations) {
7614                                    client
7615                                        .request(proto::UpdateBuffer {
7616                                            project_id,
7617                                            buffer_id: buffer_id.into(),
7618                                            operations: chunk,
7619                                        })
7620                                        .await?;
7621                                }
7622                                anyhow::Ok(())
7623                            }
7624                            .log_err(),
7625                        )
7626                        .detach();
7627                }
7628            }
7629            Ok(())
7630        })??;
7631
7632        Ok(response)
7633    }
7634
7635    async fn handle_format_buffers(
7636        this: Model<Self>,
7637        envelope: TypedEnvelope<proto::FormatBuffers>,
7638        _: Arc<Client>,
7639        mut cx: AsyncAppContext,
7640    ) -> Result<proto::FormatBuffersResponse> {
7641        let sender_id = envelope.original_sender_id()?;
7642        let format = this.update(&mut cx, |this, cx| {
7643            let mut buffers = HashSet::default();
7644            for buffer_id in &envelope.payload.buffer_ids {
7645                let buffer_id = BufferId::new(*buffer_id)?;
7646                buffers.insert(
7647                    this.opened_buffers
7648                        .get(&buffer_id)
7649                        .and_then(|buffer| buffer.upgrade())
7650                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7651                );
7652            }
7653            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7654            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7655        })??;
7656
7657        let project_transaction = format.await?;
7658        let project_transaction = this.update(&mut cx, |this, cx| {
7659            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7660        })?;
7661        Ok(proto::FormatBuffersResponse {
7662            transaction: Some(project_transaction),
7663        })
7664    }
7665
7666    async fn handle_apply_additional_edits_for_completion(
7667        this: Model<Self>,
7668        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7669        _: Arc<Client>,
7670        mut cx: AsyncAppContext,
7671    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7672        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7673            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7674            let buffer = this
7675                .opened_buffers
7676                .get(&buffer_id)
7677                .and_then(|buffer| buffer.upgrade())
7678                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7679            let language = buffer.read(cx).language();
7680            let completion = language::proto::deserialize_completion(
7681                envelope
7682                    .payload
7683                    .completion
7684                    .ok_or_else(|| anyhow!("invalid completion"))?,
7685                language.cloned(),
7686            );
7687            Ok::<_, anyhow::Error>((buffer, completion))
7688        })??;
7689
7690        let completion = completion.await?;
7691
7692        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7693            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7694        })?;
7695
7696        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7697            transaction: apply_additional_edits
7698                .await?
7699                .as_ref()
7700                .map(language::proto::serialize_transaction),
7701        })
7702    }
7703
7704    async fn handle_resolve_completion_documentation(
7705        this: Model<Self>,
7706        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7707        _: Arc<Client>,
7708        mut cx: AsyncAppContext,
7709    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7710        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7711
7712        let completion = this
7713            .read_with(&mut cx, |this, _| {
7714                let id = LanguageServerId(envelope.payload.language_server_id as usize);
7715                let Some(server) = this.language_server_for_id(id) else {
7716                    return Err(anyhow!("No language server {id}"));
7717                };
7718
7719                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
7720            })??
7721            .await?;
7722
7723        let mut is_markdown = false;
7724        let text = match completion.documentation {
7725            Some(lsp::Documentation::String(text)) => text,
7726
7727            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7728                is_markdown = kind == lsp::MarkupKind::Markdown;
7729                value
7730            }
7731
7732            _ => String::new(),
7733        };
7734
7735        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
7736    }
7737
7738    async fn handle_apply_code_action(
7739        this: Model<Self>,
7740        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7741        _: Arc<Client>,
7742        mut cx: AsyncAppContext,
7743    ) -> Result<proto::ApplyCodeActionResponse> {
7744        let sender_id = envelope.original_sender_id()?;
7745        let action = language::proto::deserialize_code_action(
7746            envelope
7747                .payload
7748                .action
7749                .ok_or_else(|| anyhow!("invalid action"))?,
7750        )?;
7751        let apply_code_action = this.update(&mut cx, |this, cx| {
7752            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7753            let buffer = this
7754                .opened_buffers
7755                .get(&buffer_id)
7756                .and_then(|buffer| buffer.upgrade())
7757                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7758            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7759        })??;
7760
7761        let project_transaction = apply_code_action.await?;
7762        let project_transaction = this.update(&mut cx, |this, cx| {
7763            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7764        })?;
7765        Ok(proto::ApplyCodeActionResponse {
7766            transaction: Some(project_transaction),
7767        })
7768    }
7769
7770    async fn handle_on_type_formatting(
7771        this: Model<Self>,
7772        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7773        _: Arc<Client>,
7774        mut cx: AsyncAppContext,
7775    ) -> Result<proto::OnTypeFormattingResponse> {
7776        let on_type_formatting = this.update(&mut cx, |this, cx| {
7777            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7778            let buffer = this
7779                .opened_buffers
7780                .get(&buffer_id)
7781                .and_then(|buffer| buffer.upgrade())
7782                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7783            let position = envelope
7784                .payload
7785                .position
7786                .and_then(deserialize_anchor)
7787                .ok_or_else(|| anyhow!("invalid position"))?;
7788            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7789                buffer,
7790                position,
7791                envelope.payload.trigger.clone(),
7792                cx,
7793            ))
7794        })??;
7795
7796        let transaction = on_type_formatting
7797            .await?
7798            .as_ref()
7799            .map(language::proto::serialize_transaction);
7800        Ok(proto::OnTypeFormattingResponse { transaction })
7801    }
7802
7803    async fn handle_inlay_hints(
7804        this: Model<Self>,
7805        envelope: TypedEnvelope<proto::InlayHints>,
7806        _: Arc<Client>,
7807        mut cx: AsyncAppContext,
7808    ) -> Result<proto::InlayHintsResponse> {
7809        let sender_id = envelope.original_sender_id()?;
7810        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7811        let buffer = this.update(&mut cx, |this, _| {
7812            this.opened_buffers
7813                .get(&buffer_id)
7814                .and_then(|buffer| buffer.upgrade())
7815                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7816        })??;
7817        let buffer_version = deserialize_version(&envelope.payload.version);
7818
7819        buffer
7820            .update(&mut cx, |buffer, _| {
7821                buffer.wait_for_version(buffer_version.clone())
7822            })?
7823            .await
7824            .with_context(|| {
7825                format!(
7826                    "waiting for version {:?} for buffer {}",
7827                    buffer_version,
7828                    buffer.entity_id()
7829                )
7830            })?;
7831
7832        let start = envelope
7833            .payload
7834            .start
7835            .and_then(deserialize_anchor)
7836            .context("missing range start")?;
7837        let end = envelope
7838            .payload
7839            .end
7840            .and_then(deserialize_anchor)
7841            .context("missing range end")?;
7842        let buffer_hints = this
7843            .update(&mut cx, |project, cx| {
7844                project.inlay_hints(buffer, start..end, cx)
7845            })?
7846            .await
7847            .context("inlay hints fetch")?;
7848
7849        Ok(this.update(&mut cx, |project, cx| {
7850            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7851        })?)
7852    }
7853
7854    async fn handle_resolve_inlay_hint(
7855        this: Model<Self>,
7856        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7857        _: Arc<Client>,
7858        mut cx: AsyncAppContext,
7859    ) -> Result<proto::ResolveInlayHintResponse> {
7860        let proto_hint = envelope
7861            .payload
7862            .hint
7863            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7864        let hint = InlayHints::proto_to_project_hint(proto_hint)
7865            .context("resolved proto inlay hint conversion")?;
7866        let buffer = this.update(&mut cx, |this, _cx| {
7867            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7868            this.opened_buffers
7869                .get(&buffer_id)
7870                .and_then(|buffer| buffer.upgrade())
7871                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7872        })??;
7873        let response_hint = this
7874            .update(&mut cx, |project, cx| {
7875                project.resolve_inlay_hint(
7876                    hint,
7877                    buffer,
7878                    LanguageServerId(envelope.payload.language_server_id as usize),
7879                    cx,
7880                )
7881            })?
7882            .await
7883            .context("inlay hints fetch")?;
7884        Ok(proto::ResolveInlayHintResponse {
7885            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7886        })
7887    }
7888
7889    async fn handle_refresh_inlay_hints(
7890        this: Model<Self>,
7891        _: TypedEnvelope<proto::RefreshInlayHints>,
7892        _: Arc<Client>,
7893        mut cx: AsyncAppContext,
7894    ) -> Result<proto::Ack> {
7895        this.update(&mut cx, |_, cx| {
7896            cx.emit(Event::RefreshInlayHints);
7897        })?;
7898        Ok(proto::Ack {})
7899    }
7900
7901    async fn handle_lsp_command<T: LspCommand>(
7902        this: Model<Self>,
7903        envelope: TypedEnvelope<T::ProtoRequest>,
7904        _: Arc<Client>,
7905        mut cx: AsyncAppContext,
7906    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7907    where
7908        <T::LspRequest as lsp::request::Request>::Params: Send,
7909        <T::LspRequest as lsp::request::Request>::Result: Send,
7910    {
7911        let sender_id = envelope.original_sender_id()?;
7912        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
7913        let buffer_handle = this.update(&mut cx, |this, _cx| {
7914            this.opened_buffers
7915                .get(&buffer_id)
7916                .and_then(|buffer| buffer.upgrade())
7917                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7918        })??;
7919        let request = T::from_proto(
7920            envelope.payload,
7921            this.clone(),
7922            buffer_handle.clone(),
7923            cx.clone(),
7924        )
7925        .await?;
7926        let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
7927        let response = this
7928            .update(&mut cx, |this, cx| {
7929                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7930            })?
7931            .await?;
7932        this.update(&mut cx, |this, cx| {
7933            Ok(T::response_to_proto(
7934                response,
7935                this,
7936                sender_id,
7937                &buffer_version,
7938                cx,
7939            ))
7940        })?
7941    }
7942
7943    async fn handle_get_project_symbols(
7944        this: Model<Self>,
7945        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7946        _: Arc<Client>,
7947        mut cx: AsyncAppContext,
7948    ) -> Result<proto::GetProjectSymbolsResponse> {
7949        let symbols = this
7950            .update(&mut cx, |this, cx| {
7951                this.symbols(&envelope.payload.query, cx)
7952            })?
7953            .await?;
7954
7955        Ok(proto::GetProjectSymbolsResponse {
7956            symbols: symbols.iter().map(serialize_symbol).collect(),
7957        })
7958    }
7959
7960    async fn handle_search_project(
7961        this: Model<Self>,
7962        envelope: TypedEnvelope<proto::SearchProject>,
7963        _: Arc<Client>,
7964        mut cx: AsyncAppContext,
7965    ) -> Result<proto::SearchProjectResponse> {
7966        let peer_id = envelope.original_sender_id()?;
7967        let query = SearchQuery::from_proto(envelope.payload)?;
7968        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
7969
7970        cx.spawn(move |mut cx| async move {
7971            let mut locations = Vec::new();
7972            while let Some((buffer, ranges)) = result.next().await {
7973                for range in ranges {
7974                    let start = serialize_anchor(&range.start);
7975                    let end = serialize_anchor(&range.end);
7976                    let buffer_id = this.update(&mut cx, |this, cx| {
7977                        this.create_buffer_for_peer(&buffer, peer_id, cx).into()
7978                    })?;
7979                    locations.push(proto::Location {
7980                        buffer_id,
7981                        start: Some(start),
7982                        end: Some(end),
7983                    });
7984                }
7985            }
7986            Ok(proto::SearchProjectResponse { locations })
7987        })
7988        .await
7989    }
7990
7991    async fn handle_open_buffer_for_symbol(
7992        this: Model<Self>,
7993        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7994        _: Arc<Client>,
7995        mut cx: AsyncAppContext,
7996    ) -> Result<proto::OpenBufferForSymbolResponse> {
7997        let peer_id = envelope.original_sender_id()?;
7998        let symbol = envelope
7999            .payload
8000            .symbol
8001            .ok_or_else(|| anyhow!("invalid symbol"))?;
8002        let symbol = this
8003            .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8004            .await?;
8005        let symbol = this.update(&mut cx, |this, _| {
8006            let signature = this.symbol_signature(&symbol.path);
8007            if signature == symbol.signature {
8008                Ok(symbol)
8009            } else {
8010                Err(anyhow!("invalid symbol signature"))
8011            }
8012        })??;
8013        let buffer = this
8014            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8015            .await?;
8016
8017        this.update(&mut cx, |this, cx| {
8018            let is_private = buffer
8019                .read(cx)
8020                .file()
8021                .map(|f| f.is_private())
8022                .unwrap_or_default();
8023            if is_private {
8024                Err(anyhow!(ErrorCode::UnsharedItem))
8025            } else {
8026                Ok(proto::OpenBufferForSymbolResponse {
8027                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8028                })
8029            }
8030        })?
8031    }
8032
8033    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8034        let mut hasher = Sha256::new();
8035        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8036        hasher.update(project_path.path.to_string_lossy().as_bytes());
8037        hasher.update(self.nonce.to_be_bytes());
8038        hasher.finalize().as_slice().try_into().unwrap()
8039    }
8040
8041    async fn handle_open_buffer_by_id(
8042        this: Model<Self>,
8043        envelope: TypedEnvelope<proto::OpenBufferById>,
8044        _: Arc<Client>,
8045        mut cx: AsyncAppContext,
8046    ) -> Result<proto::OpenBufferResponse> {
8047        let peer_id = envelope.original_sender_id()?;
8048        let buffer_id = BufferId::new(envelope.payload.id)?;
8049        let buffer = this
8050            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
8051            .await?;
8052        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8053    }
8054
8055    async fn handle_open_buffer_by_path(
8056        this: Model<Self>,
8057        envelope: TypedEnvelope<proto::OpenBufferByPath>,
8058        _: Arc<Client>,
8059        mut cx: AsyncAppContext,
8060    ) -> Result<proto::OpenBufferResponse> {
8061        let peer_id = envelope.original_sender_id()?;
8062        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8063        let open_buffer = this.update(&mut cx, |this, cx| {
8064            this.open_buffer(
8065                ProjectPath {
8066                    worktree_id,
8067                    path: PathBuf::from(envelope.payload.path).into(),
8068                },
8069                cx,
8070            )
8071        })?;
8072
8073        let buffer = open_buffer.await?;
8074        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8075    }
8076
8077    fn respond_to_open_buffer_request(
8078        this: Model<Self>,
8079        buffer: Model<Buffer>,
8080        peer_id: proto::PeerId,
8081        cx: &mut AsyncAppContext,
8082    ) -> Result<proto::OpenBufferResponse> {
8083        this.update(cx, |this, cx| {
8084            let is_private = buffer
8085                .read(cx)
8086                .file()
8087                .map(|f| f.is_private())
8088                .unwrap_or_default();
8089            if is_private {
8090                Err(anyhow!(ErrorCode::UnsharedItem))
8091            } else {
8092                Ok(proto::OpenBufferResponse {
8093                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8094                })
8095            }
8096        })?
8097    }
8098
8099    fn serialize_project_transaction_for_peer(
8100        &mut self,
8101        project_transaction: ProjectTransaction,
8102        peer_id: proto::PeerId,
8103        cx: &mut AppContext,
8104    ) -> proto::ProjectTransaction {
8105        let mut serialized_transaction = proto::ProjectTransaction {
8106            buffer_ids: Default::default(),
8107            transactions: Default::default(),
8108        };
8109        for (buffer, transaction) in project_transaction.0 {
8110            serialized_transaction
8111                .buffer_ids
8112                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
8113            serialized_transaction
8114                .transactions
8115                .push(language::proto::serialize_transaction(&transaction));
8116        }
8117        serialized_transaction
8118    }
8119
8120    fn deserialize_project_transaction(
8121        &mut self,
8122        message: proto::ProjectTransaction,
8123        push_to_history: bool,
8124        cx: &mut ModelContext<Self>,
8125    ) -> Task<Result<ProjectTransaction>> {
8126        cx.spawn(move |this, mut cx| async move {
8127            let mut project_transaction = ProjectTransaction::default();
8128            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8129            {
8130                let buffer_id = BufferId::new(buffer_id)?;
8131                let buffer = this
8132                    .update(&mut cx, |this, cx| {
8133                        this.wait_for_remote_buffer(buffer_id, cx)
8134                    })?
8135                    .await?;
8136                let transaction = language::proto::deserialize_transaction(transaction)?;
8137                project_transaction.0.insert(buffer, transaction);
8138            }
8139
8140            for (buffer, transaction) in &project_transaction.0 {
8141                buffer
8142                    .update(&mut cx, |buffer, _| {
8143                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8144                    })?
8145                    .await?;
8146
8147                if push_to_history {
8148                    buffer.update(&mut cx, |buffer, _| {
8149                        buffer.push_transaction(transaction.clone(), Instant::now());
8150                    })?;
8151                }
8152            }
8153
8154            Ok(project_transaction)
8155        })
8156    }
8157
8158    fn create_buffer_for_peer(
8159        &mut self,
8160        buffer: &Model<Buffer>,
8161        peer_id: proto::PeerId,
8162        cx: &mut AppContext,
8163    ) -> BufferId {
8164        let buffer_id = buffer.read(cx).remote_id();
8165        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8166            updates_tx
8167                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8168                .ok();
8169        }
8170        buffer_id
8171    }
8172
8173    fn wait_for_remote_buffer(
8174        &mut self,
8175        id: BufferId,
8176        cx: &mut ModelContext<Self>,
8177    ) -> Task<Result<Model<Buffer>>> {
8178        let mut opened_buffer_rx = self.opened_buffer.1.clone();
8179
8180        cx.spawn(move |this, mut cx| async move {
8181            let buffer = loop {
8182                let Some(this) = this.upgrade() else {
8183                    return Err(anyhow!("project dropped"));
8184                };
8185
8186                let buffer = this.update(&mut cx, |this, _cx| {
8187                    this.opened_buffers
8188                        .get(&id)
8189                        .and_then(|buffer| buffer.upgrade())
8190                })?;
8191
8192                if let Some(buffer) = buffer {
8193                    break buffer;
8194                } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8195                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
8196                }
8197
8198                this.update(&mut cx, |this, _| {
8199                    this.incomplete_remote_buffers.entry(id).or_default();
8200                })?;
8201                drop(this);
8202
8203                opened_buffer_rx
8204                    .next()
8205                    .await
8206                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8207            };
8208
8209            Ok(buffer)
8210        })
8211    }
8212
8213    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8214        let project_id = match self.client_state {
8215            ProjectClientState::Remote {
8216                sharing_has_stopped,
8217                remote_id,
8218                ..
8219            } => {
8220                if sharing_has_stopped {
8221                    return Task::ready(Err(anyhow!(
8222                        "can't synchronize remote buffers on a readonly project"
8223                    )));
8224                } else {
8225                    remote_id
8226                }
8227            }
8228            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8229                return Task::ready(Err(anyhow!(
8230                    "can't synchronize remote buffers on a local project"
8231                )))
8232            }
8233        };
8234
8235        let client = self.client.clone();
8236        cx.spawn(move |this, mut cx| async move {
8237            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8238                let buffers = this
8239                    .opened_buffers
8240                    .iter()
8241                    .filter_map(|(id, buffer)| {
8242                        let buffer = buffer.upgrade()?;
8243                        Some(proto::BufferVersion {
8244                            id: (*id).into(),
8245                            version: language::proto::serialize_version(&buffer.read(cx).version),
8246                        })
8247                    })
8248                    .collect();
8249                let incomplete_buffer_ids = this
8250                    .incomplete_remote_buffers
8251                    .keys()
8252                    .copied()
8253                    .collect::<Vec<_>>();
8254
8255                (buffers, incomplete_buffer_ids)
8256            })?;
8257            let response = client
8258                .request(proto::SynchronizeBuffers {
8259                    project_id,
8260                    buffers,
8261                })
8262                .await?;
8263
8264            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8265                response
8266                    .buffers
8267                    .into_iter()
8268                    .map(|buffer| {
8269                        let client = client.clone();
8270                        let buffer_id = match BufferId::new(buffer.id) {
8271                            Ok(id) => id,
8272                            Err(e) => {
8273                                return Task::ready(Err(e));
8274                            }
8275                        };
8276                        let remote_version = language::proto::deserialize_version(&buffer.version);
8277                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
8278                            let operations =
8279                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
8280                            cx.background_executor().spawn(async move {
8281                                let operations = operations.await;
8282                                for chunk in split_operations(operations) {
8283                                    client
8284                                        .request(proto::UpdateBuffer {
8285                                            project_id,
8286                                            buffer_id: buffer_id.into(),
8287                                            operations: chunk,
8288                                        })
8289                                        .await?;
8290                                }
8291                                anyhow::Ok(())
8292                            })
8293                        } else {
8294                            Task::ready(Ok(()))
8295                        }
8296                    })
8297                    .collect::<Vec<_>>()
8298            })?;
8299
8300            // Any incomplete buffers have open requests waiting. Request that the host sends
8301            // creates these buffers for us again to unblock any waiting futures.
8302            for id in incomplete_buffer_ids {
8303                cx.background_executor()
8304                    .spawn(client.request(proto::OpenBufferById {
8305                        project_id,
8306                        id: id.into(),
8307                    }))
8308                    .detach();
8309            }
8310
8311            futures::future::join_all(send_updates_for_buffers)
8312                .await
8313                .into_iter()
8314                .collect()
8315        })
8316    }
8317
8318    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8319        self.worktrees()
8320            .map(|worktree| {
8321                let worktree = worktree.read(cx);
8322                proto::WorktreeMetadata {
8323                    id: worktree.id().to_proto(),
8324                    root_name: worktree.root_name().into(),
8325                    visible: worktree.is_visible(),
8326                    abs_path: worktree.abs_path().to_string_lossy().into(),
8327                }
8328            })
8329            .collect()
8330    }
8331
8332    fn set_worktrees_from_proto(
8333        &mut self,
8334        worktrees: Vec<proto::WorktreeMetadata>,
8335        cx: &mut ModelContext<Project>,
8336    ) -> Result<()> {
8337        let replica_id = self.replica_id();
8338        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8339
8340        let mut old_worktrees_by_id = self
8341            .worktrees
8342            .drain(..)
8343            .filter_map(|worktree| {
8344                let worktree = worktree.upgrade()?;
8345                Some((worktree.read(cx).id(), worktree))
8346            })
8347            .collect::<HashMap<_, _>>();
8348
8349        for worktree in worktrees {
8350            if let Some(old_worktree) =
8351                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8352            {
8353                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8354            } else {
8355                let worktree =
8356                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8357                let _ = self.add_worktree(&worktree, cx);
8358            }
8359        }
8360
8361        self.metadata_changed(cx);
8362        for id in old_worktrees_by_id.keys() {
8363            cx.emit(Event::WorktreeRemoved(*id));
8364        }
8365
8366        Ok(())
8367    }
8368
8369    fn set_collaborators_from_proto(
8370        &mut self,
8371        messages: Vec<proto::Collaborator>,
8372        cx: &mut ModelContext<Self>,
8373    ) -> Result<()> {
8374        let mut collaborators = HashMap::default();
8375        for message in messages {
8376            let collaborator = Collaborator::from_proto(message)?;
8377            collaborators.insert(collaborator.peer_id, collaborator);
8378        }
8379        for old_peer_id in self.collaborators.keys() {
8380            if !collaborators.contains_key(old_peer_id) {
8381                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8382            }
8383        }
8384        self.collaborators = collaborators;
8385        Ok(())
8386    }
8387
8388    fn deserialize_symbol(
8389        &self,
8390        serialized_symbol: proto::Symbol,
8391    ) -> impl Future<Output = Result<Symbol>> {
8392        let languages = self.languages.clone();
8393        async move {
8394            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8395            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8396            let start = serialized_symbol
8397                .start
8398                .ok_or_else(|| anyhow!("invalid start"))?;
8399            let end = serialized_symbol
8400                .end
8401                .ok_or_else(|| anyhow!("invalid end"))?;
8402            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8403            let path = ProjectPath {
8404                worktree_id,
8405                path: PathBuf::from(serialized_symbol.path).into(),
8406            };
8407            let language = languages
8408                .language_for_file(&path.path, None)
8409                .await
8410                .log_err();
8411            Ok(Symbol {
8412                language_server_name: LanguageServerName(
8413                    serialized_symbol.language_server_name.into(),
8414                ),
8415                source_worktree_id,
8416                path,
8417                label: {
8418                    match language {
8419                        Some(language) => {
8420                            language
8421                                .label_for_symbol(&serialized_symbol.name, kind)
8422                                .await
8423                        }
8424                        None => None,
8425                    }
8426                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8427                },
8428
8429                name: serialized_symbol.name,
8430                range: Unclipped(PointUtf16::new(start.row, start.column))
8431                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8432                kind,
8433                signature: serialized_symbol
8434                    .signature
8435                    .try_into()
8436                    .map_err(|_| anyhow!("invalid signature"))?,
8437            })
8438        }
8439    }
8440
8441    async fn handle_buffer_saved(
8442        this: Model<Self>,
8443        envelope: TypedEnvelope<proto::BufferSaved>,
8444        _: Arc<Client>,
8445        mut cx: AsyncAppContext,
8446    ) -> Result<()> {
8447        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8448        let version = deserialize_version(&envelope.payload.version);
8449        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8450        let mtime = envelope
8451            .payload
8452            .mtime
8453            .ok_or_else(|| anyhow!("missing mtime"))?
8454            .into();
8455
8456        this.update(&mut cx, |this, cx| {
8457            let buffer = this
8458                .opened_buffers
8459                .get(&buffer_id)
8460                .and_then(|buffer| buffer.upgrade())
8461                .or_else(|| {
8462                    this.incomplete_remote_buffers
8463                        .get(&buffer_id)
8464                        .and_then(|b| b.clone())
8465                });
8466            if let Some(buffer) = buffer {
8467                buffer.update(cx, |buffer, cx| {
8468                    buffer.did_save(version, fingerprint, mtime, cx);
8469                });
8470            }
8471            Ok(())
8472        })?
8473    }
8474
8475    async fn handle_buffer_reloaded(
8476        this: Model<Self>,
8477        envelope: TypedEnvelope<proto::BufferReloaded>,
8478        _: Arc<Client>,
8479        mut cx: AsyncAppContext,
8480    ) -> Result<()> {
8481        let payload = envelope.payload;
8482        let version = deserialize_version(&payload.version);
8483        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8484        let line_ending = deserialize_line_ending(
8485            proto::LineEnding::from_i32(payload.line_ending)
8486                .ok_or_else(|| anyhow!("missing line ending"))?,
8487        );
8488        let mtime = payload
8489            .mtime
8490            .ok_or_else(|| anyhow!("missing mtime"))?
8491            .into();
8492        let buffer_id = BufferId::new(payload.buffer_id)?;
8493        this.update(&mut cx, |this, cx| {
8494            let buffer = this
8495                .opened_buffers
8496                .get(&buffer_id)
8497                .and_then(|buffer| buffer.upgrade())
8498                .or_else(|| {
8499                    this.incomplete_remote_buffers
8500                        .get(&buffer_id)
8501                        .cloned()
8502                        .flatten()
8503                });
8504            if let Some(buffer) = buffer {
8505                buffer.update(cx, |buffer, cx| {
8506                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8507                });
8508            }
8509            Ok(())
8510        })?
8511    }
8512
8513    #[allow(clippy::type_complexity)]
8514    fn edits_from_lsp(
8515        &mut self,
8516        buffer: &Model<Buffer>,
8517        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8518        server_id: LanguageServerId,
8519        version: Option<i32>,
8520        cx: &mut ModelContext<Self>,
8521    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8522        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8523        cx.background_executor().spawn(async move {
8524            let snapshot = snapshot?;
8525            let mut lsp_edits = lsp_edits
8526                .into_iter()
8527                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8528                .collect::<Vec<_>>();
8529            lsp_edits.sort_by_key(|(range, _)| range.start);
8530
8531            let mut lsp_edits = lsp_edits.into_iter().peekable();
8532            let mut edits = Vec::new();
8533            while let Some((range, mut new_text)) = lsp_edits.next() {
8534                // Clip invalid ranges provided by the language server.
8535                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8536                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8537
8538                // Combine any LSP edits that are adjacent.
8539                //
8540                // Also, combine LSP edits that are separated from each other by only
8541                // a newline. This is important because for some code actions,
8542                // Rust-analyzer rewrites the entire buffer via a series of edits that
8543                // are separated by unchanged newline characters.
8544                //
8545                // In order for the diffing logic below to work properly, any edits that
8546                // cancel each other out must be combined into one.
8547                while let Some((next_range, next_text)) = lsp_edits.peek() {
8548                    if next_range.start.0 > range.end {
8549                        if next_range.start.0.row > range.end.row + 1
8550                            || next_range.start.0.column > 0
8551                            || snapshot.clip_point_utf16(
8552                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8553                                Bias::Left,
8554                            ) > range.end
8555                        {
8556                            break;
8557                        }
8558                        new_text.push('\n');
8559                    }
8560                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8561                    new_text.push_str(next_text);
8562                    lsp_edits.next();
8563                }
8564
8565                // For multiline edits, perform a diff of the old and new text so that
8566                // we can identify the changes more precisely, preserving the locations
8567                // of any anchors positioned in the unchanged regions.
8568                if range.end.row > range.start.row {
8569                    let mut offset = range.start.to_offset(&snapshot);
8570                    let old_text = snapshot.text_for_range(range).collect::<String>();
8571
8572                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8573                    let mut moved_since_edit = true;
8574                    for change in diff.iter_all_changes() {
8575                        let tag = change.tag();
8576                        let value = change.value();
8577                        match tag {
8578                            ChangeTag::Equal => {
8579                                offset += value.len();
8580                                moved_since_edit = true;
8581                            }
8582                            ChangeTag::Delete => {
8583                                let start = snapshot.anchor_after(offset);
8584                                let end = snapshot.anchor_before(offset + value.len());
8585                                if moved_since_edit {
8586                                    edits.push((start..end, String::new()));
8587                                } else {
8588                                    edits.last_mut().unwrap().0.end = end;
8589                                }
8590                                offset += value.len();
8591                                moved_since_edit = false;
8592                            }
8593                            ChangeTag::Insert => {
8594                                if moved_since_edit {
8595                                    let anchor = snapshot.anchor_after(offset);
8596                                    edits.push((anchor..anchor, value.to_string()));
8597                                } else {
8598                                    edits.last_mut().unwrap().1.push_str(value);
8599                                }
8600                                moved_since_edit = false;
8601                            }
8602                        }
8603                    }
8604                } else if range.end == range.start {
8605                    let anchor = snapshot.anchor_after(range.start);
8606                    edits.push((anchor..anchor, new_text));
8607                } else {
8608                    let edit_start = snapshot.anchor_after(range.start);
8609                    let edit_end = snapshot.anchor_before(range.end);
8610                    edits.push((edit_start..edit_end, new_text));
8611                }
8612            }
8613
8614            Ok(edits)
8615        })
8616    }
8617
8618    fn buffer_snapshot_for_lsp_version(
8619        &mut self,
8620        buffer: &Model<Buffer>,
8621        server_id: LanguageServerId,
8622        version: Option<i32>,
8623        cx: &AppContext,
8624    ) -> Result<TextBufferSnapshot> {
8625        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8626
8627        if let Some(version) = version {
8628            let buffer_id = buffer.read(cx).remote_id();
8629            let snapshots = self
8630                .buffer_snapshots
8631                .get_mut(&buffer_id)
8632                .and_then(|m| m.get_mut(&server_id))
8633                .ok_or_else(|| {
8634                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8635                })?;
8636
8637            let found_snapshot = snapshots
8638                .binary_search_by_key(&version, |e| e.version)
8639                .map(|ix| snapshots[ix].snapshot.clone())
8640                .map_err(|_| {
8641                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8642                })?;
8643
8644            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8645            Ok(found_snapshot)
8646        } else {
8647            Ok((buffer.read(cx)).text_snapshot())
8648        }
8649    }
8650
8651    pub fn language_servers(
8652        &self,
8653    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8654        self.language_server_ids
8655            .iter()
8656            .map(|((worktree_id, server_name), server_id)| {
8657                (*server_id, server_name.clone(), *worktree_id)
8658            })
8659    }
8660
8661    pub fn supplementary_language_servers(
8662        &self,
8663    ) -> impl '_
8664           + Iterator<
8665        Item = (
8666            &LanguageServerId,
8667            &(LanguageServerName, Arc<LanguageServer>),
8668        ),
8669    > {
8670        self.supplementary_language_servers.iter()
8671    }
8672
8673    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8674        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8675            Some(server.clone())
8676        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8677            Some(Arc::clone(server))
8678        } else {
8679            None
8680        }
8681    }
8682
8683    pub fn language_servers_for_buffer(
8684        &self,
8685        buffer: &Buffer,
8686        cx: &AppContext,
8687    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8688        self.language_server_ids_for_buffer(buffer, cx)
8689            .into_iter()
8690            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8691                LanguageServerState::Running {
8692                    adapter, server, ..
8693                } => Some((adapter, server)),
8694                _ => None,
8695            })
8696    }
8697
8698    fn primary_language_server_for_buffer(
8699        &self,
8700        buffer: &Buffer,
8701        cx: &AppContext,
8702    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8703        self.language_servers_for_buffer(buffer, cx).next()
8704    }
8705
8706    pub fn language_server_for_buffer(
8707        &self,
8708        buffer: &Buffer,
8709        server_id: LanguageServerId,
8710        cx: &AppContext,
8711    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8712        self.language_servers_for_buffer(buffer, cx)
8713            .find(|(_, s)| s.server_id() == server_id)
8714    }
8715
8716    fn language_server_ids_for_buffer(
8717        &self,
8718        buffer: &Buffer,
8719        cx: &AppContext,
8720    ) -> Vec<LanguageServerId> {
8721        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8722            let worktree_id = file.worktree_id(cx);
8723            language
8724                .lsp_adapters()
8725                .iter()
8726                .flat_map(|adapter| {
8727                    let key = (worktree_id, adapter.name.clone());
8728                    self.language_server_ids.get(&key).copied()
8729                })
8730                .collect()
8731        } else {
8732            Vec::new()
8733        }
8734    }
8735}
8736
8737fn subscribe_for_copilot_events(
8738    copilot: &Model<Copilot>,
8739    cx: &mut ModelContext<'_, Project>,
8740) -> gpui::Subscription {
8741    cx.subscribe(
8742        copilot,
8743        |project, copilot, copilot_event, cx| match copilot_event {
8744            copilot::Event::CopilotLanguageServerStarted => {
8745                match copilot.read(cx).language_server() {
8746                    Some((name, copilot_server)) => {
8747                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8748                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8749                            let new_server_id = copilot_server.server_id();
8750                            let weak_project = cx.weak_model();
8751                            let copilot_log_subscription = copilot_server
8752                                .on_notification::<copilot::request::LogMessage, _>(
8753                                    move |params, mut cx| {
8754                                        weak_project.update(&mut cx, |_, cx| {
8755                                            cx.emit(Event::LanguageServerLog(
8756                                                new_server_id,
8757                                                params.message,
8758                                            ));
8759                                        }).ok();
8760                                    },
8761                                );
8762                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8763                            project.copilot_log_subscription = Some(copilot_log_subscription);
8764                            cx.emit(Event::LanguageServerAdded(new_server_id));
8765                        }
8766                    }
8767                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8768                }
8769            }
8770        },
8771    )
8772}
8773
8774fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8775    let mut literal_end = 0;
8776    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8777        if part.contains(&['*', '?', '{', '}']) {
8778            break;
8779        } else {
8780            if i > 0 {
8781                // Account for separator prior to this part
8782                literal_end += path::MAIN_SEPARATOR.len_utf8();
8783            }
8784            literal_end += part.len();
8785        }
8786    }
8787    &glob[..literal_end]
8788}
8789
8790impl WorktreeHandle {
8791    pub fn upgrade(&self) -> Option<Model<Worktree>> {
8792        match self {
8793            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8794            WorktreeHandle::Weak(handle) => handle.upgrade(),
8795        }
8796    }
8797
8798    pub fn handle_id(&self) -> usize {
8799        match self {
8800            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
8801            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
8802        }
8803    }
8804}
8805
8806impl OpenBuffer {
8807    pub fn upgrade(&self) -> Option<Model<Buffer>> {
8808        match self {
8809            OpenBuffer::Strong(handle) => Some(handle.clone()),
8810            OpenBuffer::Weak(handle) => handle.upgrade(),
8811            OpenBuffer::Operations(_) => None,
8812        }
8813    }
8814}
8815
8816pub struct PathMatchCandidateSet {
8817    pub snapshot: Snapshot,
8818    pub include_ignored: bool,
8819    pub include_root_name: bool,
8820}
8821
8822impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8823    type Candidates = PathMatchCandidateSetIter<'a>;
8824
8825    fn id(&self) -> usize {
8826        self.snapshot.id().to_usize()
8827    }
8828
8829    fn len(&self) -> usize {
8830        if self.include_ignored {
8831            self.snapshot.file_count()
8832        } else {
8833            self.snapshot.visible_file_count()
8834        }
8835    }
8836
8837    fn prefix(&self) -> Arc<str> {
8838        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8839            self.snapshot.root_name().into()
8840        } else if self.include_root_name {
8841            format!("{}/", self.snapshot.root_name()).into()
8842        } else {
8843            "".into()
8844        }
8845    }
8846
8847    fn candidates(&'a self, start: usize) -> Self::Candidates {
8848        PathMatchCandidateSetIter {
8849            traversal: self.snapshot.files(self.include_ignored, start),
8850        }
8851    }
8852}
8853
8854pub struct PathMatchCandidateSetIter<'a> {
8855    traversal: Traversal<'a>,
8856}
8857
8858impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8859    type Item = fuzzy::PathMatchCandidate<'a>;
8860
8861    fn next(&mut self) -> Option<Self::Item> {
8862        self.traversal.next().map(|entry| {
8863            if let EntryKind::File(char_bag) = entry.kind {
8864                fuzzy::PathMatchCandidate {
8865                    path: &entry.path,
8866                    char_bag,
8867                }
8868            } else {
8869                unreachable!()
8870            }
8871        })
8872    }
8873}
8874
8875impl EventEmitter<Event> for Project {}
8876
8877impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8878    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8879        Self {
8880            worktree_id,
8881            path: path.as_ref().into(),
8882        }
8883    }
8884}
8885
8886impl ProjectLspAdapterDelegate {
8887    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8888        Arc::new(Self {
8889            project: cx.handle(),
8890            http_client: project.client.http_client(),
8891        })
8892    }
8893}
8894
8895impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8896    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8897        self.project
8898            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8899    }
8900
8901    fn http_client(&self) -> Arc<dyn HttpClient> {
8902        self.http_client.clone()
8903    }
8904}
8905
8906fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8907    proto::Symbol {
8908        language_server_name: symbol.language_server_name.0.to_string(),
8909        source_worktree_id: symbol.source_worktree_id.to_proto(),
8910        worktree_id: symbol.path.worktree_id.to_proto(),
8911        path: symbol.path.path.to_string_lossy().to_string(),
8912        name: symbol.name.clone(),
8913        kind: unsafe { mem::transmute(symbol.kind) },
8914        start: Some(proto::PointUtf16 {
8915            row: symbol.range.start.0.row,
8916            column: symbol.range.start.0.column,
8917        }),
8918        end: Some(proto::PointUtf16 {
8919            row: symbol.range.end.0.row,
8920            column: symbol.range.end.0.column,
8921        }),
8922        signature: symbol.signature.to_vec(),
8923    }
8924}
8925
8926fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8927    let mut path_components = path.components();
8928    let mut base_components = base.components();
8929    let mut components: Vec<Component> = Vec::new();
8930    loop {
8931        match (path_components.next(), base_components.next()) {
8932            (None, None) => break,
8933            (Some(a), None) => {
8934                components.push(a);
8935                components.extend(path_components.by_ref());
8936                break;
8937            }
8938            (None, _) => components.push(Component::ParentDir),
8939            (Some(a), Some(b)) if components.is_empty() && a == b => (),
8940            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8941            (Some(a), Some(_)) => {
8942                components.push(Component::ParentDir);
8943                for _ in base_components {
8944                    components.push(Component::ParentDir);
8945                }
8946                components.push(a);
8947                components.extend(path_components.by_ref());
8948                break;
8949            }
8950        }
8951    }
8952    components.iter().map(|c| c.as_os_str()).collect()
8953}
8954
8955fn resolve_path(base: &Path, path: &Path) -> PathBuf {
8956    let mut result = base.to_path_buf();
8957    for component in path.components() {
8958        match component {
8959            Component::ParentDir => {
8960                result.pop();
8961            }
8962            Component::CurDir => (),
8963            _ => result.push(component),
8964        }
8965    }
8966    result
8967}
8968
8969impl Item for Buffer {
8970    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8971        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8972    }
8973
8974    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8975        File::from_dyn(self.file()).map(|file| ProjectPath {
8976            worktree_id: file.worktree_id(cx),
8977            path: file.path().clone(),
8978        })
8979    }
8980}
8981
8982async fn wait_for_loading_buffer(
8983    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
8984) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
8985    loop {
8986        if let Some(result) = receiver.borrow().as_ref() {
8987            match result {
8988                Ok(buffer) => return Ok(buffer.to_owned()),
8989                Err(e) => return Err(e.to_owned()),
8990            }
8991        }
8992        receiver.next().await;
8993    }
8994}
8995
8996fn include_text(server: &lsp::LanguageServer) -> bool {
8997    server
8998        .capabilities()
8999        .text_document_sync
9000        .as_ref()
9001        .and_then(|sync| match sync {
9002            lsp::TextDocumentSyncCapability::Kind(_) => None,
9003            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9004        })
9005        .and_then(|save_options| match save_options {
9006            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9007            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9008        })
9009        .unwrap_or(false)
9010}