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    #[inline(never)]
4418    fn definition_impl(
4419        &self,
4420        buffer: &Model<Buffer>,
4421        position: PointUtf16,
4422        cx: &mut ModelContext<Self>,
4423    ) -> Task<Result<Vec<LocationLink>>> {
4424        self.request_lsp(
4425            buffer.clone(),
4426            LanguageServerToQuery::Primary,
4427            GetDefinition { position },
4428            cx,
4429        )
4430    }
4431    pub fn definition<T: ToPointUtf16>(
4432        &self,
4433        buffer: &Model<Buffer>,
4434        position: T,
4435        cx: &mut ModelContext<Self>,
4436    ) -> Task<Result<Vec<LocationLink>>> {
4437        let position = position.to_point_utf16(buffer.read(cx));
4438        self.definition_impl(buffer, position, cx)
4439    }
4440
4441    fn type_definition_impl(
4442        &self,
4443        buffer: &Model<Buffer>,
4444        position: PointUtf16,
4445        cx: &mut ModelContext<Self>,
4446    ) -> Task<Result<Vec<LocationLink>>> {
4447        self.request_lsp(
4448            buffer.clone(),
4449            LanguageServerToQuery::Primary,
4450            GetTypeDefinition { position },
4451            cx,
4452        )
4453    }
4454    pub fn type_definition<T: ToPointUtf16>(
4455        &self,
4456        buffer: &Model<Buffer>,
4457        position: T,
4458        cx: &mut ModelContext<Self>,
4459    ) -> Task<Result<Vec<LocationLink>>> {
4460        let position = position.to_point_utf16(buffer.read(cx));
4461
4462        self.type_definition_impl(buffer, position, cx)
4463    }
4464
4465    fn references_impl(
4466        &self,
4467        buffer: &Model<Buffer>,
4468        position: PointUtf16,
4469        cx: &mut ModelContext<Self>,
4470    ) -> Task<Result<Vec<Location>>> {
4471        self.request_lsp(
4472            buffer.clone(),
4473            LanguageServerToQuery::Primary,
4474            GetReferences { position },
4475            cx,
4476        )
4477    }
4478    pub fn references<T: ToPointUtf16>(
4479        &self,
4480        buffer: &Model<Buffer>,
4481        position: T,
4482        cx: &mut ModelContext<Self>,
4483    ) -> Task<Result<Vec<Location>>> {
4484        let position = position.to_point_utf16(buffer.read(cx));
4485        self.references_impl(buffer, position, cx)
4486    }
4487
4488    fn document_highlights_impl(
4489        &self,
4490        buffer: &Model<Buffer>,
4491        position: PointUtf16,
4492        cx: &mut ModelContext<Self>,
4493    ) -> Task<Result<Vec<DocumentHighlight>>> {
4494        self.request_lsp(
4495            buffer.clone(),
4496            LanguageServerToQuery::Primary,
4497            GetDocumentHighlights { position },
4498            cx,
4499        )
4500    }
4501
4502    pub fn document_highlights<T: ToPointUtf16>(
4503        &self,
4504        buffer: &Model<Buffer>,
4505        position: T,
4506        cx: &mut ModelContext<Self>,
4507    ) -> Task<Result<Vec<DocumentHighlight>>> {
4508        let position = position.to_point_utf16(buffer.read(cx));
4509        self.document_highlights_impl(buffer, position, cx)
4510    }
4511
4512    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4513        if self.is_local() {
4514            let mut requests = Vec::new();
4515            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4516                let worktree_id = *worktree_id;
4517                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4518                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4519                    Some(worktree) => worktree,
4520                    None => continue,
4521                };
4522                let worktree_abs_path = worktree.abs_path().clone();
4523
4524                let (adapter, language, server) = match self.language_servers.get(server_id) {
4525                    Some(LanguageServerState::Running {
4526                        adapter,
4527                        language,
4528                        server,
4529                        ..
4530                    }) => (adapter.clone(), language.clone(), server),
4531
4532                    _ => continue,
4533                };
4534
4535                requests.push(
4536                    server
4537                        .request::<lsp::request::WorkspaceSymbolRequest>(
4538                            lsp::WorkspaceSymbolParams {
4539                                query: query.to_string(),
4540                                ..Default::default()
4541                            },
4542                        )
4543                        .log_err()
4544                        .map(move |response| {
4545                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4546                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4547                                    flat_responses.into_iter().map(|lsp_symbol| {
4548                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4549                                    }).collect::<Vec<_>>()
4550                                }
4551                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4552                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4553                                        let location = match lsp_symbol.location {
4554                                            OneOf::Left(location) => location,
4555                                            OneOf::Right(_) => {
4556                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4557                                                return None
4558                                            }
4559                                        };
4560                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4561                                    }).collect::<Vec<_>>()
4562                                }
4563                            }).unwrap_or_default();
4564
4565                            (
4566                                adapter,
4567                                language,
4568                                worktree_id,
4569                                worktree_abs_path,
4570                                lsp_symbols,
4571                            )
4572                        }),
4573                );
4574            }
4575
4576            cx.spawn(move |this, mut cx| async move {
4577                let responses = futures::future::join_all(requests).await;
4578                let this = match this.upgrade() {
4579                    Some(this) => this,
4580                    None => return Ok(Vec::new()),
4581                };
4582
4583                let symbols = this.update(&mut cx, |this, cx| {
4584                    let mut symbols = Vec::new();
4585                    for (
4586                        adapter,
4587                        adapter_language,
4588                        source_worktree_id,
4589                        worktree_abs_path,
4590                        lsp_symbols,
4591                    ) in responses
4592                    {
4593                        symbols.extend(lsp_symbols.into_iter().filter_map(
4594                            |(symbol_name, symbol_kind, symbol_location)| {
4595                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4596                                let mut worktree_id = source_worktree_id;
4597                                let path;
4598                                if let Some((worktree, rel_path)) =
4599                                    this.find_local_worktree(&abs_path, cx)
4600                                {
4601                                    worktree_id = worktree.read(cx).id();
4602                                    path = rel_path;
4603                                } else {
4604                                    path = relativize_path(&worktree_abs_path, &abs_path);
4605                                }
4606
4607                                let project_path = ProjectPath {
4608                                    worktree_id,
4609                                    path: path.into(),
4610                                };
4611                                let signature = this.symbol_signature(&project_path);
4612                                let adapter_language = adapter_language.clone();
4613                                let language = this
4614                                    .languages
4615                                    .language_for_file(&project_path.path, None)
4616                                    .unwrap_or_else(move |_| adapter_language);
4617                                let language_server_name = adapter.name.clone();
4618                                Some(async move {
4619                                    let language = language.await;
4620                                    let label =
4621                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4622
4623                                    Symbol {
4624                                        language_server_name,
4625                                        source_worktree_id,
4626                                        path: project_path,
4627                                        label: label.unwrap_or_else(|| {
4628                                            CodeLabel::plain(symbol_name.clone(), None)
4629                                        }),
4630                                        kind: symbol_kind,
4631                                        name: symbol_name,
4632                                        range: range_from_lsp(symbol_location.range),
4633                                        signature,
4634                                    }
4635                                })
4636                            },
4637                        ));
4638                    }
4639
4640                    symbols
4641                })?;
4642
4643                Ok(futures::future::join_all(symbols).await)
4644            })
4645        } else if let Some(project_id) = self.remote_id() {
4646            let request = self.client.request(proto::GetProjectSymbols {
4647                project_id,
4648                query: query.to_string(),
4649            });
4650            cx.spawn(move |this, mut cx| async move {
4651                let response = request.await?;
4652                let mut symbols = Vec::new();
4653                if let Some(this) = this.upgrade() {
4654                    let new_symbols = this.update(&mut cx, |this, _| {
4655                        response
4656                            .symbols
4657                            .into_iter()
4658                            .map(|symbol| this.deserialize_symbol(symbol))
4659                            .collect::<Vec<_>>()
4660                    })?;
4661                    symbols = futures::future::join_all(new_symbols)
4662                        .await
4663                        .into_iter()
4664                        .filter_map(|symbol| symbol.log_err())
4665                        .collect::<Vec<_>>();
4666                }
4667                Ok(symbols)
4668            })
4669        } else {
4670            Task::ready(Ok(Default::default()))
4671        }
4672    }
4673
4674    pub fn open_buffer_for_symbol(
4675        &mut self,
4676        symbol: &Symbol,
4677        cx: &mut ModelContext<Self>,
4678    ) -> Task<Result<Model<Buffer>>> {
4679        if self.is_local() {
4680            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4681                symbol.source_worktree_id,
4682                symbol.language_server_name.clone(),
4683            )) {
4684                *id
4685            } else {
4686                return Task::ready(Err(anyhow!(
4687                    "language server for worktree and language not found"
4688                )));
4689            };
4690
4691            let worktree_abs_path = if let Some(worktree_abs_path) = self
4692                .worktree_for_id(symbol.path.worktree_id, cx)
4693                .and_then(|worktree| worktree.read(cx).as_local())
4694                .map(|local_worktree| local_worktree.abs_path())
4695            {
4696                worktree_abs_path
4697            } else {
4698                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4699            };
4700
4701            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4702            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4703                uri
4704            } else {
4705                return Task::ready(Err(anyhow!("invalid symbol path")));
4706            };
4707
4708            self.open_local_buffer_via_lsp(
4709                symbol_uri,
4710                language_server_id,
4711                symbol.language_server_name.clone(),
4712                cx,
4713            )
4714        } else if let Some(project_id) = self.remote_id() {
4715            let request = self.client.request(proto::OpenBufferForSymbol {
4716                project_id,
4717                symbol: Some(serialize_symbol(symbol)),
4718            });
4719            cx.spawn(move |this, mut cx| async move {
4720                let response = request.await?;
4721                let buffer_id = BufferId::new(response.buffer_id)?;
4722                this.update(&mut cx, |this, cx| {
4723                    this.wait_for_remote_buffer(buffer_id, cx)
4724                })?
4725                .await
4726            })
4727        } else {
4728            Task::ready(Err(anyhow!("project does not have a remote id")))
4729        }
4730    }
4731
4732    fn hover_impl(
4733        &self,
4734        buffer: &Model<Buffer>,
4735        position: PointUtf16,
4736        cx: &mut ModelContext<Self>,
4737    ) -> Task<Result<Option<Hover>>> {
4738        self.request_lsp(
4739            buffer.clone(),
4740            LanguageServerToQuery::Primary,
4741            GetHover { position },
4742            cx,
4743        )
4744    }
4745    pub fn hover<T: ToPointUtf16>(
4746        &self,
4747        buffer: &Model<Buffer>,
4748        position: T,
4749        cx: &mut ModelContext<Self>,
4750    ) -> Task<Result<Option<Hover>>> {
4751        let position = position.to_point_utf16(buffer.read(cx));
4752        self.hover_impl(buffer, position, cx)
4753    }
4754
4755    #[inline(never)]
4756    fn completions_impl(
4757        &self,
4758        buffer: &Model<Buffer>,
4759        position: PointUtf16,
4760        cx: &mut ModelContext<Self>,
4761    ) -> Task<Result<Vec<Completion>>> {
4762        if self.is_local() {
4763            let snapshot = buffer.read(cx).snapshot();
4764            let offset = position.to_offset(&snapshot);
4765            let scope = snapshot.language_scope_at(offset);
4766
4767            let server_ids: Vec<_> = self
4768                .language_servers_for_buffer(buffer.read(cx), cx)
4769                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4770                .filter(|(adapter, _)| {
4771                    scope
4772                        .as_ref()
4773                        .map(|scope| scope.language_allowed(&adapter.name))
4774                        .unwrap_or(true)
4775                })
4776                .map(|(_, server)| server.server_id())
4777                .collect();
4778
4779            let buffer = buffer.clone();
4780            cx.spawn(move |this, mut cx| async move {
4781                let mut tasks = Vec::with_capacity(server_ids.len());
4782                this.update(&mut cx, |this, cx| {
4783                    for server_id in server_ids {
4784                        tasks.push(this.request_lsp(
4785                            buffer.clone(),
4786                            LanguageServerToQuery::Other(server_id),
4787                            GetCompletions { position },
4788                            cx,
4789                        ));
4790                    }
4791                })?;
4792
4793                let mut completions = Vec::new();
4794                for task in tasks {
4795                    if let Ok(new_completions) = task.await {
4796                        completions.extend_from_slice(&new_completions);
4797                    }
4798                }
4799
4800                Ok(completions)
4801            })
4802        } else if let Some(project_id) = self.remote_id() {
4803            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4804        } else {
4805            Task::ready(Ok(Default::default()))
4806        }
4807    }
4808    pub fn completions<T: ToOffset + ToPointUtf16>(
4809        &self,
4810        buffer: &Model<Buffer>,
4811        position: T,
4812        cx: &mut ModelContext<Self>,
4813    ) -> Task<Result<Vec<Completion>>> {
4814        let position = position.to_point_utf16(buffer.read(cx));
4815        self.completions_impl(buffer, position, cx)
4816    }
4817
4818    pub fn resolve_completions(
4819        &self,
4820        completion_indices: Vec<usize>,
4821        completions: Arc<RwLock<Box<[Completion]>>>,
4822        cx: &mut ModelContext<Self>,
4823    ) -> Task<Result<bool>> {
4824        let client = self.client();
4825        let language_registry = self.languages().clone();
4826
4827        let is_remote = self.is_remote();
4828        let project_id = self.remote_id();
4829
4830        cx.spawn(move |this, mut cx| async move {
4831            let mut did_resolve = false;
4832            if is_remote {
4833                let project_id =
4834                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
4835
4836                for completion_index in completion_indices {
4837                    let completions_guard = completions.read();
4838                    let completion = &completions_guard[completion_index];
4839                    if completion.documentation.is_some() {
4840                        continue;
4841                    }
4842
4843                    did_resolve = true;
4844                    let server_id = completion.server_id;
4845                    let completion = completion.lsp_completion.clone();
4846                    drop(completions_guard);
4847
4848                    Self::resolve_completion_documentation_remote(
4849                        project_id,
4850                        server_id,
4851                        completions.clone(),
4852                        completion_index,
4853                        completion,
4854                        client.clone(),
4855                        language_registry.clone(),
4856                    )
4857                    .await;
4858                }
4859            } else {
4860                for completion_index in completion_indices {
4861                    let completions_guard = completions.read();
4862                    let completion = &completions_guard[completion_index];
4863                    if completion.documentation.is_some() {
4864                        continue;
4865                    }
4866
4867                    let server_id = completion.server_id;
4868                    let completion = completion.lsp_completion.clone();
4869                    drop(completions_guard);
4870
4871                    let server = this
4872                        .read_with(&mut cx, |project, _| {
4873                            project.language_server_for_id(server_id)
4874                        })
4875                        .ok()
4876                        .flatten();
4877                    let Some(server) = server else {
4878                        continue;
4879                    };
4880
4881                    did_resolve = true;
4882                    Self::resolve_completion_documentation_local(
4883                        server,
4884                        completions.clone(),
4885                        completion_index,
4886                        completion,
4887                        language_registry.clone(),
4888                    )
4889                    .await;
4890                }
4891            }
4892
4893            Ok(did_resolve)
4894        })
4895    }
4896
4897    async fn resolve_completion_documentation_local(
4898        server: Arc<lsp::LanguageServer>,
4899        completions: Arc<RwLock<Box<[Completion]>>>,
4900        completion_index: usize,
4901        completion: lsp::CompletionItem,
4902        language_registry: Arc<LanguageRegistry>,
4903    ) {
4904        let can_resolve = server
4905            .capabilities()
4906            .completion_provider
4907            .as_ref()
4908            .and_then(|options| options.resolve_provider)
4909            .unwrap_or(false);
4910        if !can_resolve {
4911            return;
4912        }
4913
4914        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
4915        let Some(completion_item) = request.await.log_err() else {
4916            return;
4917        };
4918
4919        if let Some(lsp_documentation) = completion_item.documentation {
4920            let documentation = language::prepare_completion_documentation(
4921                &lsp_documentation,
4922                &language_registry,
4923                None, // TODO: Try to reasonably work out which language the completion is for
4924            )
4925            .await;
4926
4927            let mut completions = completions.write();
4928            let completion = &mut completions[completion_index];
4929            completion.documentation = Some(documentation);
4930        } else {
4931            let mut completions = completions.write();
4932            let completion = &mut completions[completion_index];
4933            completion.documentation = Some(Documentation::Undocumented);
4934        }
4935    }
4936
4937    async fn resolve_completion_documentation_remote(
4938        project_id: u64,
4939        server_id: LanguageServerId,
4940        completions: Arc<RwLock<Box<[Completion]>>>,
4941        completion_index: usize,
4942        completion: lsp::CompletionItem,
4943        client: Arc<Client>,
4944        language_registry: Arc<LanguageRegistry>,
4945    ) {
4946        let request = proto::ResolveCompletionDocumentation {
4947            project_id,
4948            language_server_id: server_id.0 as u64,
4949            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
4950        };
4951
4952        let Some(response) = client
4953            .request(request)
4954            .await
4955            .context("completion documentation resolve proto request")
4956            .log_err()
4957        else {
4958            return;
4959        };
4960
4961        if response.text.is_empty() {
4962            let mut completions = completions.write();
4963            let completion = &mut completions[completion_index];
4964            completion.documentation = Some(Documentation::Undocumented);
4965        }
4966
4967        let documentation = if response.is_markdown {
4968            Documentation::MultiLineMarkdown(
4969                markdown::parse_markdown(&response.text, &language_registry, None).await,
4970            )
4971        } else if response.text.lines().count() <= 1 {
4972            Documentation::SingleLine(response.text)
4973        } else {
4974            Documentation::MultiLinePlainText(response.text)
4975        };
4976
4977        let mut completions = completions.write();
4978        let completion = &mut completions[completion_index];
4979        completion.documentation = Some(documentation);
4980    }
4981
4982    pub fn apply_additional_edits_for_completion(
4983        &self,
4984        buffer_handle: Model<Buffer>,
4985        completion: Completion,
4986        push_to_history: bool,
4987        cx: &mut ModelContext<Self>,
4988    ) -> Task<Result<Option<Transaction>>> {
4989        let buffer = buffer_handle.read(cx);
4990        let buffer_id = buffer.remote_id();
4991
4992        if self.is_local() {
4993            let server_id = completion.server_id;
4994            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4995                Some((_, server)) => server.clone(),
4996                _ => return Task::ready(Ok(Default::default())),
4997            };
4998
4999            cx.spawn(move |this, mut cx| async move {
5000                let can_resolve = lang_server
5001                    .capabilities()
5002                    .completion_provider
5003                    .as_ref()
5004                    .and_then(|options| options.resolve_provider)
5005                    .unwrap_or(false);
5006                let additional_text_edits = if can_resolve {
5007                    lang_server
5008                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5009                        .await?
5010                        .additional_text_edits
5011                } else {
5012                    completion.lsp_completion.additional_text_edits
5013                };
5014                if let Some(edits) = additional_text_edits {
5015                    let edits = this
5016                        .update(&mut cx, |this, cx| {
5017                            this.edits_from_lsp(
5018                                &buffer_handle,
5019                                edits,
5020                                lang_server.server_id(),
5021                                None,
5022                                cx,
5023                            )
5024                        })?
5025                        .await?;
5026
5027                    buffer_handle.update(&mut cx, |buffer, cx| {
5028                        buffer.finalize_last_transaction();
5029                        buffer.start_transaction();
5030
5031                        for (range, text) in edits {
5032                            let primary = &completion.old_range;
5033                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
5034                                && primary.end.cmp(&range.start, buffer).is_ge();
5035                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
5036                                && range.end.cmp(&primary.end, buffer).is_ge();
5037
5038                            //Skip additional edits which overlap with the primary completion edit
5039                            //https://github.com/zed-industries/zed/pull/1871
5040                            if !start_within && !end_within {
5041                                buffer.edit([(range, text)], None, cx);
5042                            }
5043                        }
5044
5045                        let transaction = if buffer.end_transaction(cx).is_some() {
5046                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5047                            if !push_to_history {
5048                                buffer.forget_transaction(transaction.id);
5049                            }
5050                            Some(transaction)
5051                        } else {
5052                            None
5053                        };
5054                        Ok(transaction)
5055                    })?
5056                } else {
5057                    Ok(None)
5058                }
5059            })
5060        } else if let Some(project_id) = self.remote_id() {
5061            let client = self.client.clone();
5062            cx.spawn(move |_, mut cx| async move {
5063                let response = client
5064                    .request(proto::ApplyCompletionAdditionalEdits {
5065                        project_id,
5066                        buffer_id: buffer_id.into(),
5067                        completion: Some(language::proto::serialize_completion(&completion)),
5068                    })
5069                    .await?;
5070
5071                if let Some(transaction) = response.transaction {
5072                    let transaction = language::proto::deserialize_transaction(transaction)?;
5073                    buffer_handle
5074                        .update(&mut cx, |buffer, _| {
5075                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5076                        })?
5077                        .await?;
5078                    if push_to_history {
5079                        buffer_handle.update(&mut cx, |buffer, _| {
5080                            buffer.push_transaction(transaction.clone(), Instant::now());
5081                        })?;
5082                    }
5083                    Ok(Some(transaction))
5084                } else {
5085                    Ok(None)
5086                }
5087            })
5088        } else {
5089            Task::ready(Err(anyhow!("project does not have a remote id")))
5090        }
5091    }
5092
5093    fn code_actions_impl(
5094        &self,
5095        buffer_handle: &Model<Buffer>,
5096        range: Range<Anchor>,
5097        cx: &mut ModelContext<Self>,
5098    ) -> Task<Result<Vec<CodeAction>>> {
5099        self.request_lsp(
5100            buffer_handle.clone(),
5101            LanguageServerToQuery::Primary,
5102            GetCodeActions { range },
5103            cx,
5104        )
5105    }
5106
5107    pub fn code_actions<T: Clone + ToOffset>(
5108        &self,
5109        buffer_handle: &Model<Buffer>,
5110        range: Range<T>,
5111        cx: &mut ModelContext<Self>,
5112    ) -> Task<Result<Vec<CodeAction>>> {
5113        let buffer = buffer_handle.read(cx);
5114        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5115        self.code_actions_impl(buffer_handle, range, cx)
5116    }
5117
5118    pub fn apply_code_action(
5119        &self,
5120        buffer_handle: Model<Buffer>,
5121        mut action: CodeAction,
5122        push_to_history: bool,
5123        cx: &mut ModelContext<Self>,
5124    ) -> Task<Result<ProjectTransaction>> {
5125        if self.is_local() {
5126            let buffer = buffer_handle.read(cx);
5127            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5128                self.language_server_for_buffer(buffer, action.server_id, cx)
5129            {
5130                (adapter.clone(), server.clone())
5131            } else {
5132                return Task::ready(Ok(Default::default()));
5133            };
5134            let range = action.range.to_point_utf16(buffer);
5135
5136            cx.spawn(move |this, mut cx| async move {
5137                if let Some(lsp_range) = action
5138                    .lsp_action
5139                    .data
5140                    .as_mut()
5141                    .and_then(|d| d.get_mut("codeActionParams"))
5142                    .and_then(|d| d.get_mut("range"))
5143                {
5144                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
5145                    action.lsp_action = lang_server
5146                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
5147                        .await?;
5148                } else {
5149                    let actions = this
5150                        .update(&mut cx, |this, cx| {
5151                            this.code_actions(&buffer_handle, action.range, cx)
5152                        })?
5153                        .await?;
5154                    action.lsp_action = actions
5155                        .into_iter()
5156                        .find(|a| a.lsp_action.title == action.lsp_action.title)
5157                        .ok_or_else(|| anyhow!("code action is outdated"))?
5158                        .lsp_action;
5159                }
5160
5161                if let Some(edit) = action.lsp_action.edit {
5162                    if edit.changes.is_some() || edit.document_changes.is_some() {
5163                        return Self::deserialize_workspace_edit(
5164                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5165                            edit,
5166                            push_to_history,
5167                            lsp_adapter.clone(),
5168                            lang_server.clone(),
5169                            &mut cx,
5170                        )
5171                        .await;
5172                    }
5173                }
5174
5175                if let Some(command) = action.lsp_action.command {
5176                    this.update(&mut cx, |this, _| {
5177                        this.last_workspace_edits_by_language_server
5178                            .remove(&lang_server.server_id());
5179                    })?;
5180
5181                    let result = lang_server
5182                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5183                            command: command.command,
5184                            arguments: command.arguments.unwrap_or_default(),
5185                            ..Default::default()
5186                        })
5187                        .await;
5188
5189                    if let Err(err) = result {
5190                        // TODO: LSP ERROR
5191                        return Err(err);
5192                    }
5193
5194                    return Ok(this.update(&mut cx, |this, _| {
5195                        this.last_workspace_edits_by_language_server
5196                            .remove(&lang_server.server_id())
5197                            .unwrap_or_default()
5198                    })?);
5199                }
5200
5201                Ok(ProjectTransaction::default())
5202            })
5203        } else if let Some(project_id) = self.remote_id() {
5204            let client = self.client.clone();
5205            let request = proto::ApplyCodeAction {
5206                project_id,
5207                buffer_id: buffer_handle.read(cx).remote_id().into(),
5208                action: Some(language::proto::serialize_code_action(&action)),
5209            };
5210            cx.spawn(move |this, mut cx| async move {
5211                let response = client
5212                    .request(request)
5213                    .await?
5214                    .transaction
5215                    .ok_or_else(|| anyhow!("missing transaction"))?;
5216                this.update(&mut cx, |this, cx| {
5217                    this.deserialize_project_transaction(response, push_to_history, cx)
5218                })?
5219                .await
5220            })
5221        } else {
5222            Task::ready(Err(anyhow!("project does not have a remote id")))
5223        }
5224    }
5225
5226    fn apply_on_type_formatting(
5227        &self,
5228        buffer: Model<Buffer>,
5229        position: Anchor,
5230        trigger: String,
5231        cx: &mut ModelContext<Self>,
5232    ) -> Task<Result<Option<Transaction>>> {
5233        if self.is_local() {
5234            cx.spawn(move |this, mut cx| async move {
5235                // Do not allow multiple concurrent formatting requests for the
5236                // same buffer.
5237                this.update(&mut cx, |this, cx| {
5238                    this.buffers_being_formatted
5239                        .insert(buffer.read(cx).remote_id())
5240                })?;
5241
5242                let _cleanup = defer({
5243                    let this = this.clone();
5244                    let mut cx = cx.clone();
5245                    let closure_buffer = buffer.clone();
5246                    move || {
5247                        this.update(&mut cx, |this, cx| {
5248                            this.buffers_being_formatted
5249                                .remove(&closure_buffer.read(cx).remote_id());
5250                        })
5251                        .ok();
5252                    }
5253                });
5254
5255                buffer
5256                    .update(&mut cx, |buffer, _| {
5257                        buffer.wait_for_edits(Some(position.timestamp))
5258                    })?
5259                    .await?;
5260                this.update(&mut cx, |this, cx| {
5261                    let position = position.to_point_utf16(buffer.read(cx));
5262                    this.on_type_format(buffer, position, trigger, false, cx)
5263                })?
5264                .await
5265            })
5266        } else if let Some(project_id) = self.remote_id() {
5267            let client = self.client.clone();
5268            let request = proto::OnTypeFormatting {
5269                project_id,
5270                buffer_id: buffer.read(cx).remote_id().into(),
5271                position: Some(serialize_anchor(&position)),
5272                trigger,
5273                version: serialize_version(&buffer.read(cx).version()),
5274            };
5275            cx.spawn(move |_, _| async move {
5276                client
5277                    .request(request)
5278                    .await?
5279                    .transaction
5280                    .map(language::proto::deserialize_transaction)
5281                    .transpose()
5282            })
5283        } else {
5284            Task::ready(Err(anyhow!("project does not have a remote id")))
5285        }
5286    }
5287
5288    async fn deserialize_edits(
5289        this: Model<Self>,
5290        buffer_to_edit: Model<Buffer>,
5291        edits: Vec<lsp::TextEdit>,
5292        push_to_history: bool,
5293        _: Arc<CachedLspAdapter>,
5294        language_server: Arc<LanguageServer>,
5295        cx: &mut AsyncAppContext,
5296    ) -> Result<Option<Transaction>> {
5297        let edits = this
5298            .update(cx, |this, cx| {
5299                this.edits_from_lsp(
5300                    &buffer_to_edit,
5301                    edits,
5302                    language_server.server_id(),
5303                    None,
5304                    cx,
5305                )
5306            })?
5307            .await?;
5308
5309        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5310            buffer.finalize_last_transaction();
5311            buffer.start_transaction();
5312            for (range, text) in edits {
5313                buffer.edit([(range, text)], None, cx);
5314            }
5315
5316            if buffer.end_transaction(cx).is_some() {
5317                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5318                if !push_to_history {
5319                    buffer.forget_transaction(transaction.id);
5320                }
5321                Some(transaction)
5322            } else {
5323                None
5324            }
5325        })?;
5326
5327        Ok(transaction)
5328    }
5329
5330    async fn deserialize_workspace_edit(
5331        this: Model<Self>,
5332        edit: lsp::WorkspaceEdit,
5333        push_to_history: bool,
5334        lsp_adapter: Arc<CachedLspAdapter>,
5335        language_server: Arc<LanguageServer>,
5336        cx: &mut AsyncAppContext,
5337    ) -> Result<ProjectTransaction> {
5338        let fs = this.update(cx, |this, _| this.fs.clone())?;
5339        let mut operations = Vec::new();
5340        if let Some(document_changes) = edit.document_changes {
5341            match document_changes {
5342                lsp::DocumentChanges::Edits(edits) => {
5343                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5344                }
5345                lsp::DocumentChanges::Operations(ops) => operations = ops,
5346            }
5347        } else if let Some(changes) = edit.changes {
5348            operations.extend(changes.into_iter().map(|(uri, edits)| {
5349                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5350                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5351                        uri,
5352                        version: None,
5353                    },
5354                    edits: edits.into_iter().map(OneOf::Left).collect(),
5355                })
5356            }));
5357        }
5358
5359        let mut project_transaction = ProjectTransaction::default();
5360        for operation in operations {
5361            match operation {
5362                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5363                    let abs_path = op
5364                        .uri
5365                        .to_file_path()
5366                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5367
5368                    if let Some(parent_path) = abs_path.parent() {
5369                        fs.create_dir(parent_path).await?;
5370                    }
5371                    if abs_path.ends_with("/") {
5372                        fs.create_dir(&abs_path).await?;
5373                    } else {
5374                        fs.create_file(
5375                            &abs_path,
5376                            op.options
5377                                .map(|options| fs::CreateOptions {
5378                                    overwrite: options.overwrite.unwrap_or(false),
5379                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5380                                })
5381                                .unwrap_or_default(),
5382                        )
5383                        .await?;
5384                    }
5385                }
5386
5387                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5388                    let source_abs_path = op
5389                        .old_uri
5390                        .to_file_path()
5391                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5392                    let target_abs_path = op
5393                        .new_uri
5394                        .to_file_path()
5395                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5396                    fs.rename(
5397                        &source_abs_path,
5398                        &target_abs_path,
5399                        op.options
5400                            .map(|options| fs::RenameOptions {
5401                                overwrite: options.overwrite.unwrap_or(false),
5402                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5403                            })
5404                            .unwrap_or_default(),
5405                    )
5406                    .await?;
5407                }
5408
5409                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5410                    let abs_path = op
5411                        .uri
5412                        .to_file_path()
5413                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5414                    let options = op
5415                        .options
5416                        .map(|options| fs::RemoveOptions {
5417                            recursive: options.recursive.unwrap_or(false),
5418                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5419                        })
5420                        .unwrap_or_default();
5421                    if abs_path.ends_with("/") {
5422                        fs.remove_dir(&abs_path, options).await?;
5423                    } else {
5424                        fs.remove_file(&abs_path, options).await?;
5425                    }
5426                }
5427
5428                lsp::DocumentChangeOperation::Edit(op) => {
5429                    let buffer_to_edit = this
5430                        .update(cx, |this, cx| {
5431                            this.open_local_buffer_via_lsp(
5432                                op.text_document.uri,
5433                                language_server.server_id(),
5434                                lsp_adapter.name.clone(),
5435                                cx,
5436                            )
5437                        })?
5438                        .await?;
5439
5440                    let edits = this
5441                        .update(cx, |this, cx| {
5442                            let edits = op.edits.into_iter().map(|edit| match edit {
5443                                OneOf::Left(edit) => edit,
5444                                OneOf::Right(edit) => edit.text_edit,
5445                            });
5446                            this.edits_from_lsp(
5447                                &buffer_to_edit,
5448                                edits,
5449                                language_server.server_id(),
5450                                op.text_document.version,
5451                                cx,
5452                            )
5453                        })?
5454                        .await?;
5455
5456                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5457                        buffer.finalize_last_transaction();
5458                        buffer.start_transaction();
5459                        for (range, text) in edits {
5460                            buffer.edit([(range, text)], None, cx);
5461                        }
5462                        let transaction = if buffer.end_transaction(cx).is_some() {
5463                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5464                            if !push_to_history {
5465                                buffer.forget_transaction(transaction.id);
5466                            }
5467                            Some(transaction)
5468                        } else {
5469                            None
5470                        };
5471
5472                        transaction
5473                    })?;
5474                    if let Some(transaction) = transaction {
5475                        project_transaction.0.insert(buffer_to_edit, transaction);
5476                    }
5477                }
5478            }
5479        }
5480
5481        Ok(project_transaction)
5482    }
5483
5484    fn prepare_rename_impl(
5485        &self,
5486        buffer: Model<Buffer>,
5487        position: PointUtf16,
5488        cx: &mut ModelContext<Self>,
5489    ) -> Task<Result<Option<Range<Anchor>>>> {
5490        self.request_lsp(
5491            buffer,
5492            LanguageServerToQuery::Primary,
5493            PrepareRename { position },
5494            cx,
5495        )
5496    }
5497    pub fn prepare_rename<T: ToPointUtf16>(
5498        &self,
5499        buffer: Model<Buffer>,
5500        position: T,
5501        cx: &mut ModelContext<Self>,
5502    ) -> Task<Result<Option<Range<Anchor>>>> {
5503        let position = position.to_point_utf16(buffer.read(cx));
5504        self.prepare_rename_impl(buffer, position, cx)
5505    }
5506
5507    fn perform_rename_impl(
5508        &self,
5509        buffer: Model<Buffer>,
5510        position: PointUtf16,
5511        new_name: String,
5512        push_to_history: bool,
5513        cx: &mut ModelContext<Self>,
5514    ) -> Task<Result<ProjectTransaction>> {
5515        let position = position.to_point_utf16(buffer.read(cx));
5516        self.request_lsp(
5517            buffer,
5518            LanguageServerToQuery::Primary,
5519            PerformRename {
5520                position,
5521                new_name,
5522                push_to_history,
5523            },
5524            cx,
5525        )
5526    }
5527    pub fn perform_rename<T: ToPointUtf16>(
5528        &self,
5529        buffer: Model<Buffer>,
5530        position: T,
5531        new_name: String,
5532        push_to_history: bool,
5533        cx: &mut ModelContext<Self>,
5534    ) -> Task<Result<ProjectTransaction>> {
5535        let position = position.to_point_utf16(buffer.read(cx));
5536        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
5537    }
5538
5539    pub fn on_type_format_impl(
5540        &self,
5541        buffer: Model<Buffer>,
5542        position: PointUtf16,
5543        trigger: String,
5544        push_to_history: bool,
5545        cx: &mut ModelContext<Self>,
5546    ) -> Task<Result<Option<Transaction>>> {
5547        let tab_size = buffer.update(cx, |buffer, cx| {
5548            language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
5549        });
5550        self.request_lsp(
5551            buffer.clone(),
5552            LanguageServerToQuery::Primary,
5553            OnTypeFormatting {
5554                position,
5555                trigger,
5556                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5557                push_to_history,
5558            },
5559            cx,
5560        )
5561    }
5562
5563    pub fn on_type_format<T: ToPointUtf16>(
5564        &self,
5565        buffer: Model<Buffer>,
5566        position: T,
5567        trigger: String,
5568        push_to_history: bool,
5569        cx: &mut ModelContext<Self>,
5570    ) -> Task<Result<Option<Transaction>>> {
5571        let position = position.to_point_utf16(buffer.read(cx));
5572        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5573    }
5574
5575    pub fn inlay_hints<T: ToOffset>(
5576        &self,
5577        buffer_handle: Model<Buffer>,
5578        range: Range<T>,
5579        cx: &mut ModelContext<Self>,
5580    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5581        let buffer = buffer_handle.read(cx);
5582        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5583        self.inlay_hints_impl(buffer_handle, range, cx)
5584    }
5585    fn inlay_hints_impl(
5586        &self,
5587        buffer_handle: Model<Buffer>,
5588        range: Range<Anchor>,
5589        cx: &mut ModelContext<Self>,
5590    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5591        let buffer = buffer_handle.read(cx);
5592        let range_start = range.start;
5593        let range_end = range.end;
5594        let buffer_id = buffer.remote_id().into();
5595        let buffer_version = buffer.version().clone();
5596        let lsp_request = InlayHints { range };
5597
5598        if self.is_local() {
5599            let lsp_request_task = self.request_lsp(
5600                buffer_handle.clone(),
5601                LanguageServerToQuery::Primary,
5602                lsp_request,
5603                cx,
5604            );
5605            cx.spawn(move |_, mut cx| async move {
5606                buffer_handle
5607                    .update(&mut cx, |buffer, _| {
5608                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5609                    })?
5610                    .await
5611                    .context("waiting for inlay hint request range edits")?;
5612                lsp_request_task.await.context("inlay hints LSP request")
5613            })
5614        } else if let Some(project_id) = self.remote_id() {
5615            let client = self.client.clone();
5616            let request = proto::InlayHints {
5617                project_id,
5618                buffer_id,
5619                start: Some(serialize_anchor(&range_start)),
5620                end: Some(serialize_anchor(&range_end)),
5621                version: serialize_version(&buffer_version),
5622            };
5623            cx.spawn(move |project, cx| async move {
5624                let response = client
5625                    .request(request)
5626                    .await
5627                    .context("inlay hints proto request")?;
5628                let hints_request_result = LspCommand::response_from_proto(
5629                    lsp_request,
5630                    response,
5631                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5632                    buffer_handle.clone(),
5633                    cx,
5634                )
5635                .await;
5636
5637                hints_request_result.context("inlay hints proto response conversion")
5638            })
5639        } else {
5640            Task::ready(Err(anyhow!("project does not have a remote id")))
5641        }
5642    }
5643
5644    pub fn resolve_inlay_hint(
5645        &self,
5646        hint: InlayHint,
5647        buffer_handle: Model<Buffer>,
5648        server_id: LanguageServerId,
5649        cx: &mut ModelContext<Self>,
5650    ) -> Task<anyhow::Result<InlayHint>> {
5651        if self.is_local() {
5652            let buffer = buffer_handle.read(cx);
5653            let (_, lang_server) = if let Some((adapter, server)) =
5654                self.language_server_for_buffer(buffer, server_id, cx)
5655            {
5656                (adapter.clone(), server.clone())
5657            } else {
5658                return Task::ready(Ok(hint));
5659            };
5660            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5661                return Task::ready(Ok(hint));
5662            }
5663
5664            let buffer_snapshot = buffer.snapshot();
5665            cx.spawn(move |_, mut cx| async move {
5666                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5667                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5668                );
5669                let resolved_hint = resolve_task
5670                    .await
5671                    .context("inlay hint resolve LSP request")?;
5672                let resolved_hint = InlayHints::lsp_to_project_hint(
5673                    resolved_hint,
5674                    &buffer_handle,
5675                    server_id,
5676                    ResolveState::Resolved,
5677                    false,
5678                    &mut cx,
5679                )
5680                .await?;
5681                Ok(resolved_hint)
5682            })
5683        } else if let Some(project_id) = self.remote_id() {
5684            let client = self.client.clone();
5685            let request = proto::ResolveInlayHint {
5686                project_id,
5687                buffer_id: buffer_handle.read(cx).remote_id().into(),
5688                language_server_id: server_id.0 as u64,
5689                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5690            };
5691            cx.spawn(move |_, _| async move {
5692                let response = client
5693                    .request(request)
5694                    .await
5695                    .context("inlay hints proto request")?;
5696                match response.hint {
5697                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5698                        .context("inlay hints proto resolve response conversion"),
5699                    None => Ok(hint),
5700                }
5701            })
5702        } else {
5703            Task::ready(Err(anyhow!("project does not have a remote id")))
5704        }
5705    }
5706
5707    #[allow(clippy::type_complexity)]
5708    pub fn search(
5709        &self,
5710        query: SearchQuery,
5711        cx: &mut ModelContext<Self>,
5712    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5713        if self.is_local() {
5714            self.search_local(query, cx)
5715        } else if let Some(project_id) = self.remote_id() {
5716            let (tx, rx) = smol::channel::unbounded();
5717            let request = self.client.request(query.to_proto(project_id));
5718            cx.spawn(move |this, mut cx| async move {
5719                let response = request.await?;
5720                let mut result = HashMap::default();
5721                for location in response.locations {
5722                    let buffer_id = BufferId::new(location.buffer_id)?;
5723                    let target_buffer = this
5724                        .update(&mut cx, |this, cx| {
5725                            this.wait_for_remote_buffer(buffer_id, cx)
5726                        })?
5727                        .await?;
5728                    let start = location
5729                        .start
5730                        .and_then(deserialize_anchor)
5731                        .ok_or_else(|| anyhow!("missing target start"))?;
5732                    let end = location
5733                        .end
5734                        .and_then(deserialize_anchor)
5735                        .ok_or_else(|| anyhow!("missing target end"))?;
5736                    result
5737                        .entry(target_buffer)
5738                        .or_insert(Vec::new())
5739                        .push(start..end)
5740                }
5741                for (buffer, ranges) in result {
5742                    let _ = tx.send((buffer, ranges)).await;
5743                }
5744                Result::<(), anyhow::Error>::Ok(())
5745            })
5746            .detach_and_log_err(cx);
5747            rx
5748        } else {
5749            unimplemented!();
5750        }
5751    }
5752
5753    pub fn search_local(
5754        &self,
5755        query: SearchQuery,
5756        cx: &mut ModelContext<Self>,
5757    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5758        // Local search is split into several phases.
5759        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5760        // and the second phase that finds positions of all the matches found in the candidate files.
5761        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5762        //
5763        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5764        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5765        //
5766        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5767        //    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
5768        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5769        // 2. At this point, we have a list of all potentially matching buffers/files.
5770        //    We sort that list by buffer path - this list is retained for later use.
5771        //    We ensure that all buffers are now opened and available in project.
5772        // 3. We run a scan over all the candidate buffers on multiple background threads.
5773        //    We cannot assume that there will even be a match - while at least one match
5774        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5775        //    There is also an auxiliary background thread responsible for result gathering.
5776        //    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),
5777        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5778        //    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
5779        //    entry - which might already be available thanks to out-of-order processing.
5780        //
5781        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5782        // 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.
5783        // 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
5784        // in face of constantly updating list of sorted matches.
5785        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5786        let snapshots = self
5787            .visible_worktrees(cx)
5788            .filter_map(|tree| {
5789                let tree = tree.read(cx).as_local()?;
5790                Some(tree.snapshot())
5791            })
5792            .collect::<Vec<_>>();
5793
5794        let background = cx.background_executor().clone();
5795        let path_count: usize = snapshots
5796            .iter()
5797            .map(|s| {
5798                if query.include_ignored() {
5799                    s.file_count()
5800                } else {
5801                    s.visible_file_count()
5802                }
5803            })
5804            .sum();
5805        if path_count == 0 {
5806            let (_, rx) = smol::channel::bounded(1024);
5807            return rx;
5808        }
5809        let workers = background.num_cpus().min(path_count);
5810        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5811        let mut unnamed_files = vec![];
5812        let opened_buffers = self
5813            .opened_buffers
5814            .iter()
5815            .filter_map(|(_, b)| {
5816                let buffer = b.upgrade()?;
5817                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
5818                    let is_ignored = buffer
5819                        .project_path(cx)
5820                        .and_then(|path| self.entry_for_path(&path, cx))
5821                        .map_or(false, |entry| entry.is_ignored);
5822                    (is_ignored, buffer.snapshot())
5823                });
5824                if is_ignored && !query.include_ignored() {
5825                    return None;
5826                } else if let Some(path) = snapshot.file().map(|file| file.path()) {
5827                    Some((path.clone(), (buffer, snapshot)))
5828                } else {
5829                    unnamed_files.push(buffer);
5830                    None
5831                }
5832            })
5833            .collect();
5834        cx.background_executor()
5835            .spawn(Self::background_search(
5836                unnamed_files,
5837                opened_buffers,
5838                cx.background_executor().clone(),
5839                self.fs.clone(),
5840                workers,
5841                query.clone(),
5842                path_count,
5843                snapshots,
5844                matching_paths_tx,
5845            ))
5846            .detach();
5847
5848        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5849        let background = cx.background_executor().clone();
5850        let (result_tx, result_rx) = smol::channel::bounded(1024);
5851        cx.background_executor()
5852            .spawn(async move {
5853                let Ok(buffers) = buffers.await else {
5854                    return;
5855                };
5856
5857                let buffers_len = buffers.len();
5858                if buffers_len == 0 {
5859                    return;
5860                }
5861                let query = &query;
5862                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5863                background
5864                    .scoped(|scope| {
5865                        #[derive(Clone)]
5866                        struct FinishedStatus {
5867                            entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
5868                            buffer_index: SearchMatchCandidateIndex,
5869                        }
5870
5871                        for _ in 0..workers {
5872                            let finished_tx = finished_tx.clone();
5873                            let mut buffers_rx = buffers_rx.clone();
5874                            scope.spawn(async move {
5875                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5876                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5877                                    {
5878                                        if query.file_matches(
5879                                            snapshot.file().map(|file| file.path().as_ref()),
5880                                        ) {
5881                                            query
5882                                                .search(snapshot, None)
5883                                                .await
5884                                                .iter()
5885                                                .map(|range| {
5886                                                    snapshot.anchor_before(range.start)
5887                                                        ..snapshot.anchor_after(range.end)
5888                                                })
5889                                                .collect()
5890                                        } else {
5891                                            Vec::new()
5892                                        }
5893                                    } else {
5894                                        Vec::new()
5895                                    };
5896
5897                                    let status = if !buffer_matches.is_empty() {
5898                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5899                                            Some((buffer.clone(), buffer_matches))
5900                                        } else {
5901                                            None
5902                                        };
5903                                        FinishedStatus {
5904                                            entry,
5905                                            buffer_index,
5906                                        }
5907                                    } else {
5908                                        FinishedStatus {
5909                                            entry: None,
5910                                            buffer_index,
5911                                        }
5912                                    };
5913                                    if finished_tx.send(status).await.is_err() {
5914                                        break;
5915                                    }
5916                                }
5917                            });
5918                        }
5919                        // Report sorted matches
5920                        scope.spawn(async move {
5921                            let mut current_index = 0;
5922                            let mut scratch = vec![None; buffers_len];
5923                            while let Some(status) = finished_rx.next().await {
5924                                debug_assert!(
5925                                    scratch[status.buffer_index].is_none(),
5926                                    "Got match status of position {} twice",
5927                                    status.buffer_index
5928                                );
5929                                let index = status.buffer_index;
5930                                scratch[index] = Some(status);
5931                                while current_index < buffers_len {
5932                                    let Some(current_entry) = scratch[current_index].take() else {
5933                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5934                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5935                                        // this time.
5936                                        break;
5937                                    };
5938                                    if let Some(entry) = current_entry.entry {
5939                                        result_tx.send(entry).await.log_err();
5940                                    }
5941                                    current_index += 1;
5942                                }
5943                                if current_index == buffers_len {
5944                                    break;
5945                                }
5946                            }
5947                        });
5948                    })
5949                    .await;
5950            })
5951            .detach();
5952        result_rx
5953    }
5954
5955    /// Pick paths that might potentially contain a match of a given search query.
5956    async fn background_search(
5957        unnamed_buffers: Vec<Model<Buffer>>,
5958        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
5959        executor: BackgroundExecutor,
5960        fs: Arc<dyn Fs>,
5961        workers: usize,
5962        query: SearchQuery,
5963        path_count: usize,
5964        snapshots: Vec<LocalSnapshot>,
5965        matching_paths_tx: Sender<SearchMatchCandidate>,
5966    ) {
5967        let fs = &fs;
5968        let query = &query;
5969        let matching_paths_tx = &matching_paths_tx;
5970        let snapshots = &snapshots;
5971        let paths_per_worker = (path_count + workers - 1) / workers;
5972        for buffer in unnamed_buffers {
5973            matching_paths_tx
5974                .send(SearchMatchCandidate::OpenBuffer {
5975                    buffer: buffer.clone(),
5976                    path: None,
5977                })
5978                .await
5979                .log_err();
5980        }
5981        for (path, (buffer, _)) in opened_buffers.iter() {
5982            matching_paths_tx
5983                .send(SearchMatchCandidate::OpenBuffer {
5984                    buffer: buffer.clone(),
5985                    path: Some(path.clone()),
5986                })
5987                .await
5988                .log_err();
5989        }
5990        executor
5991            .scoped(|scope| {
5992                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
5993
5994                for worker_ix in 0..workers {
5995                    let worker_start_ix = worker_ix * paths_per_worker;
5996                    let worker_end_ix = worker_start_ix + paths_per_worker;
5997                    let unnamed_buffers = opened_buffers.clone();
5998                    let limiter = Arc::clone(&max_concurrent_workers);
5999                    scope.spawn(async move {
6000                        let _guard = limiter.acquire().await;
6001                        let mut snapshot_start_ix = 0;
6002                        let mut abs_path = PathBuf::new();
6003                        for snapshot in snapshots {
6004                            let snapshot_end_ix = snapshot_start_ix
6005                                + if query.include_ignored() {
6006                                    snapshot.file_count()
6007                                } else {
6008                                    snapshot.visible_file_count()
6009                                };
6010                            if worker_end_ix <= snapshot_start_ix {
6011                                break;
6012                            } else if worker_start_ix > snapshot_end_ix {
6013                                snapshot_start_ix = snapshot_end_ix;
6014                                continue;
6015                            } else {
6016                                let start_in_snapshot =
6017                                    worker_start_ix.saturating_sub(snapshot_start_ix);
6018                                let end_in_snapshot =
6019                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
6020
6021                                for entry in snapshot
6022                                    .files(query.include_ignored(), start_in_snapshot)
6023                                    .take(end_in_snapshot - start_in_snapshot)
6024                                {
6025                                    if matching_paths_tx.is_closed() {
6026                                        break;
6027                                    }
6028                                    if unnamed_buffers.contains_key(&entry.path) {
6029                                        continue;
6030                                    }
6031                                    let matches = if query.file_matches(Some(&entry.path)) {
6032                                        abs_path.clear();
6033                                        abs_path.push(&snapshot.abs_path());
6034                                        abs_path.push(&entry.path);
6035                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
6036                                        {
6037                                            query.detect(file).unwrap_or(false)
6038                                        } else {
6039                                            false
6040                                        }
6041                                    } else {
6042                                        false
6043                                    };
6044
6045                                    if matches {
6046                                        let project_path = SearchMatchCandidate::Path {
6047                                            worktree_id: snapshot.id(),
6048                                            path: entry.path.clone(),
6049                                            is_ignored: entry.is_ignored,
6050                                        };
6051                                        if matching_paths_tx.send(project_path).await.is_err() {
6052                                            break;
6053                                        }
6054                                    }
6055                                }
6056
6057                                snapshot_start_ix = snapshot_end_ix;
6058                            }
6059                        }
6060                    });
6061                }
6062
6063                if query.include_ignored() {
6064                    for snapshot in snapshots {
6065                        for ignored_entry in snapshot
6066                            .entries(query.include_ignored())
6067                            .filter(|e| e.is_ignored)
6068                        {
6069                            let limiter = Arc::clone(&max_concurrent_workers);
6070                            scope.spawn(async move {
6071                                let _guard = limiter.acquire().await;
6072                                let mut ignored_paths_to_process =
6073                                    VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
6074                                while let Some(ignored_abs_path) =
6075                                    ignored_paths_to_process.pop_front()
6076                                {
6077                                    if let Some(fs_metadata) = fs
6078                                        .metadata(&ignored_abs_path)
6079                                        .await
6080                                        .with_context(|| {
6081                                            format!("fetching fs metadata for {ignored_abs_path:?}")
6082                                        })
6083                                        .log_err()
6084                                        .flatten()
6085                                    {
6086                                        if fs_metadata.is_dir {
6087                                            if let Some(mut subfiles) = fs
6088                                                .read_dir(&ignored_abs_path)
6089                                                .await
6090                                                .with_context(|| {
6091                                                    format!(
6092                                                        "listing ignored path {ignored_abs_path:?}"
6093                                                    )
6094                                                })
6095                                                .log_err()
6096                                            {
6097                                                while let Some(subfile) = subfiles.next().await {
6098                                                    if let Some(subfile) = subfile.log_err() {
6099                                                        ignored_paths_to_process.push_back(subfile);
6100                                                    }
6101                                                }
6102                                            }
6103                                        } else if !fs_metadata.is_symlink {
6104                                            if !query.file_matches(Some(&ignored_abs_path))
6105                                                || snapshot.is_path_excluded(
6106                                                    ignored_entry.path.to_path_buf(),
6107                                                )
6108                                            {
6109                                                continue;
6110                                            }
6111                                            let matches = if let Some(file) = fs
6112                                                .open_sync(&ignored_abs_path)
6113                                                .await
6114                                                .with_context(|| {
6115                                                    format!(
6116                                                        "Opening ignored path {ignored_abs_path:?}"
6117                                                    )
6118                                                })
6119                                                .log_err()
6120                                            {
6121                                                query.detect(file).unwrap_or(false)
6122                                            } else {
6123                                                false
6124                                            };
6125                                            if matches {
6126                                                let project_path = SearchMatchCandidate::Path {
6127                                                    worktree_id: snapshot.id(),
6128                                                    path: Arc::from(
6129                                                        ignored_abs_path
6130                                                            .strip_prefix(snapshot.abs_path())
6131                                                            .expect(
6132                                                                "scanning worktree-related files",
6133                                                            ),
6134                                                    ),
6135                                                    is_ignored: true,
6136                                                };
6137                                                if matching_paths_tx
6138                                                    .send(project_path)
6139                                                    .await
6140                                                    .is_err()
6141                                                {
6142                                                    return;
6143                                                }
6144                                            }
6145                                        }
6146                                    }
6147                                }
6148                            });
6149                        }
6150                    }
6151                }
6152            })
6153            .await;
6154    }
6155
6156    pub fn request_lsp<R: LspCommand>(
6157        &self,
6158        buffer_handle: Model<Buffer>,
6159        server: LanguageServerToQuery,
6160        request: R,
6161        cx: &mut ModelContext<Self>,
6162    ) -> Task<Result<R::Response>>
6163    where
6164        <R::LspRequest as lsp::request::Request>::Result: Send,
6165        <R::LspRequest as lsp::request::Request>::Params: Send,
6166    {
6167        let buffer = buffer_handle.read(cx);
6168        if self.is_local() {
6169            let language_server = match server {
6170                LanguageServerToQuery::Primary => {
6171                    match self.primary_language_server_for_buffer(buffer, cx) {
6172                        Some((_, server)) => Some(Arc::clone(server)),
6173                        None => return Task::ready(Ok(Default::default())),
6174                    }
6175                }
6176                LanguageServerToQuery::Other(id) => self
6177                    .language_server_for_buffer(buffer, id, cx)
6178                    .map(|(_, server)| Arc::clone(server)),
6179            };
6180            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6181            if let (Some(file), Some(language_server)) = (file, language_server) {
6182                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6183                return cx.spawn(move |this, cx| async move {
6184                    if !request.check_capabilities(language_server.capabilities()) {
6185                        return Ok(Default::default());
6186                    }
6187
6188                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
6189                    let response = match result {
6190                        Ok(response) => response,
6191
6192                        Err(err) => {
6193                            log::warn!(
6194                                "Generic lsp request to {} failed: {}",
6195                                language_server.name(),
6196                                err
6197                            );
6198                            return Err(err);
6199                        }
6200                    };
6201
6202                    request
6203                        .response_from_lsp(
6204                            response,
6205                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6206                            buffer_handle,
6207                            language_server.server_id(),
6208                            cx,
6209                        )
6210                        .await
6211                });
6212            }
6213        } else if let Some(project_id) = self.remote_id() {
6214            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6215        }
6216
6217        Task::ready(Ok(Default::default()))
6218    }
6219
6220    fn send_lsp_proto_request<R: LspCommand>(
6221        &self,
6222        buffer: Model<Buffer>,
6223        project_id: u64,
6224        request: R,
6225        cx: &mut ModelContext<'_, Project>,
6226    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6227        let rpc = self.client.clone();
6228        let message = request.to_proto(project_id, buffer.read(cx));
6229        cx.spawn(move |this, mut cx| async move {
6230            // Ensure the project is still alive by the time the task
6231            // is scheduled.
6232            this.upgrade().context("project dropped")?;
6233            let response = rpc.request(message).await?;
6234            let this = this.upgrade().context("project dropped")?;
6235            if this.update(&mut cx, |this, _| this.is_disconnected())? {
6236                Err(anyhow!("disconnected before completing request"))
6237            } else {
6238                request
6239                    .response_from_proto(response, this, buffer, cx)
6240                    .await
6241            }
6242        })
6243    }
6244
6245    fn sort_candidates_and_open_buffers(
6246        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6247        cx: &mut ModelContext<Self>,
6248    ) -> (
6249        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6250        Receiver<(
6251            Option<(Model<Buffer>, BufferSnapshot)>,
6252            SearchMatchCandidateIndex,
6253        )>,
6254    ) {
6255        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6256        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6257        cx.spawn(move |this, cx| async move {
6258            let mut buffers = Vec::new();
6259            let mut ignored_buffers = Vec::new();
6260            while let Some(entry) = matching_paths_rx.next().await {
6261                if matches!(
6262                    entry,
6263                    SearchMatchCandidate::Path {
6264                        is_ignored: true,
6265                        ..
6266                    }
6267                ) {
6268                    ignored_buffers.push(entry);
6269                } else {
6270                    buffers.push(entry);
6271                }
6272            }
6273            buffers.sort_by_key(|candidate| candidate.path());
6274            ignored_buffers.sort_by_key(|candidate| candidate.path());
6275            buffers.extend(ignored_buffers);
6276            let matching_paths = buffers.clone();
6277            let _ = sorted_buffers_tx.send(buffers);
6278            for (index, candidate) in matching_paths.into_iter().enumerate() {
6279                if buffers_tx.is_closed() {
6280                    break;
6281                }
6282                let this = this.clone();
6283                let buffers_tx = buffers_tx.clone();
6284                cx.spawn(move |mut cx| async move {
6285                    let buffer = match candidate {
6286                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6287                        SearchMatchCandidate::Path {
6288                            worktree_id, path, ..
6289                        } => this
6290                            .update(&mut cx, |this, cx| {
6291                                this.open_buffer((worktree_id, path), cx)
6292                            })?
6293                            .await
6294                            .log_err(),
6295                    };
6296                    if let Some(buffer) = buffer {
6297                        let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6298                        buffers_tx
6299                            .send((Some((buffer, snapshot)), index))
6300                            .await
6301                            .log_err();
6302                    } else {
6303                        buffers_tx.send((None, index)).await.log_err();
6304                    }
6305
6306                    Ok::<_, anyhow::Error>(())
6307                })
6308                .detach();
6309            }
6310        })
6311        .detach();
6312        (sorted_buffers_rx, buffers_rx)
6313    }
6314
6315    pub fn find_or_create_local_worktree(
6316        &mut self,
6317        abs_path: impl AsRef<Path>,
6318        visible: bool,
6319        cx: &mut ModelContext<Self>,
6320    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6321        let abs_path = abs_path.as_ref();
6322        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6323            Task::ready(Ok((tree, relative_path)))
6324        } else {
6325            let worktree = self.create_local_worktree(abs_path, visible, cx);
6326            cx.background_executor()
6327                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6328        }
6329    }
6330
6331    pub fn find_local_worktree(
6332        &self,
6333        abs_path: &Path,
6334        cx: &AppContext,
6335    ) -> Option<(Model<Worktree>, PathBuf)> {
6336        for tree in &self.worktrees {
6337            if let Some(tree) = tree.upgrade() {
6338                if let Some(relative_path) = tree
6339                    .read(cx)
6340                    .as_local()
6341                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6342                {
6343                    return Some((tree.clone(), relative_path.into()));
6344                }
6345            }
6346        }
6347        None
6348    }
6349
6350    pub fn is_shared(&self) -> bool {
6351        match &self.client_state {
6352            ProjectClientState::Shared { .. } => true,
6353            ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6354        }
6355    }
6356
6357    fn create_local_worktree(
6358        &mut self,
6359        abs_path: impl AsRef<Path>,
6360        visible: bool,
6361        cx: &mut ModelContext<Self>,
6362    ) -> Task<Result<Model<Worktree>>> {
6363        let fs = self.fs.clone();
6364        let client = self.client.clone();
6365        let next_entry_id = self.next_entry_id.clone();
6366        let path: Arc<Path> = abs_path.as_ref().into();
6367        let task = self
6368            .loading_local_worktrees
6369            .entry(path.clone())
6370            .or_insert_with(|| {
6371                cx.spawn(move |project, mut cx| {
6372                    async move {
6373                        let worktree = Worktree::local(
6374                            client.clone(),
6375                            path.clone(),
6376                            visible,
6377                            fs,
6378                            next_entry_id,
6379                            &mut cx,
6380                        )
6381                        .await;
6382
6383                        project.update(&mut cx, |project, _| {
6384                            project.loading_local_worktrees.remove(&path);
6385                        })?;
6386
6387                        let worktree = worktree?;
6388                        project
6389                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6390                        Ok(worktree)
6391                    }
6392                    .map_err(Arc::new)
6393                })
6394                .shared()
6395            })
6396            .clone();
6397        cx.background_executor().spawn(async move {
6398            match task.await {
6399                Ok(worktree) => Ok(worktree),
6400                Err(err) => Err(anyhow!("{}", err)),
6401            }
6402        })
6403    }
6404
6405    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6406        let mut servers_to_remove = HashMap::default();
6407        let mut servers_to_preserve = HashSet::default();
6408        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6409            if worktree_id == &id_to_remove {
6410                servers_to_remove.insert(server_id, server_name.clone());
6411            } else {
6412                servers_to_preserve.insert(server_id);
6413            }
6414        }
6415        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6416        for (server_id_to_remove, server_name) in servers_to_remove {
6417            self.language_server_ids
6418                .remove(&(id_to_remove, server_name));
6419            self.language_server_statuses.remove(&server_id_to_remove);
6420            self.last_workspace_edits_by_language_server
6421                .remove(&server_id_to_remove);
6422            self.language_servers.remove(&server_id_to_remove);
6423            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6424        }
6425
6426        let mut prettier_instances_to_clean = FuturesUnordered::new();
6427        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6428            for path in prettier_paths.iter().flatten() {
6429                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6430                    prettier_instances_to_clean.push(async move {
6431                        prettier_instance
6432                            .server()
6433                            .await
6434                            .map(|server| server.server_id())
6435                    });
6436                }
6437            }
6438        }
6439        cx.spawn(|project, mut cx| async move {
6440            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6441                if let Some(prettier_server_id) = prettier_server_id {
6442                    project
6443                        .update(&mut cx, |project, cx| {
6444                            project
6445                                .supplementary_language_servers
6446                                .remove(&prettier_server_id);
6447                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6448                        })
6449                        .ok();
6450                }
6451            }
6452        })
6453        .detach();
6454
6455        self.worktrees.retain(|worktree| {
6456            if let Some(worktree) = worktree.upgrade() {
6457                let id = worktree.read(cx).id();
6458                if id == id_to_remove {
6459                    cx.emit(Event::WorktreeRemoved(id));
6460                    false
6461                } else {
6462                    true
6463                }
6464            } else {
6465                false
6466            }
6467        });
6468        self.metadata_changed(cx);
6469    }
6470
6471    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6472        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6473        if worktree.read(cx).is_local() {
6474            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6475                worktree::Event::UpdatedEntries(changes) => {
6476                    this.update_local_worktree_buffers(&worktree, changes, cx);
6477                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6478                    this.update_local_worktree_settings(&worktree, changes, cx);
6479                    this.update_prettier_settings(&worktree, changes, cx);
6480                    cx.emit(Event::WorktreeUpdatedEntries(
6481                        worktree.read(cx).id(),
6482                        changes.clone(),
6483                    ));
6484                }
6485                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6486                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6487                }
6488            })
6489            .detach();
6490        }
6491
6492        let push_strong_handle = {
6493            let worktree = worktree.read(cx);
6494            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6495        };
6496        if push_strong_handle {
6497            self.worktrees
6498                .push(WorktreeHandle::Strong(worktree.clone()));
6499        } else {
6500            self.worktrees
6501                .push(WorktreeHandle::Weak(worktree.downgrade()));
6502        }
6503
6504        let handle_id = worktree.entity_id();
6505        cx.observe_release(worktree, move |this, worktree, cx| {
6506            let _ = this.remove_worktree(worktree.id(), cx);
6507            cx.update_global::<SettingsStore, _>(|store, cx| {
6508                store
6509                    .clear_local_settings(handle_id.as_u64() as usize, cx)
6510                    .log_err()
6511            });
6512        })
6513        .detach();
6514
6515        cx.emit(Event::WorktreeAdded);
6516        self.metadata_changed(cx);
6517    }
6518
6519    fn update_local_worktree_buffers(
6520        &mut self,
6521        worktree_handle: &Model<Worktree>,
6522        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6523        cx: &mut ModelContext<Self>,
6524    ) {
6525        let snapshot = worktree_handle.read(cx).snapshot();
6526
6527        let mut renamed_buffers = Vec::new();
6528        for (path, entry_id, _) in changes {
6529            let worktree_id = worktree_handle.read(cx).id();
6530            let project_path = ProjectPath {
6531                worktree_id,
6532                path: path.clone(),
6533            };
6534
6535            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6536                Some(&buffer_id) => buffer_id,
6537                None => match self.local_buffer_ids_by_path.get(&project_path) {
6538                    Some(&buffer_id) => buffer_id,
6539                    None => {
6540                        continue;
6541                    }
6542                },
6543            };
6544
6545            let open_buffer = self.opened_buffers.get(&buffer_id);
6546            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6547                buffer
6548            } else {
6549                self.opened_buffers.remove(&buffer_id);
6550                self.local_buffer_ids_by_path.remove(&project_path);
6551                self.local_buffer_ids_by_entry_id.remove(entry_id);
6552                continue;
6553            };
6554
6555            buffer.update(cx, |buffer, cx| {
6556                if let Some(old_file) = File::from_dyn(buffer.file()) {
6557                    if old_file.worktree != *worktree_handle {
6558                        return;
6559                    }
6560
6561                    let new_file = if let Some(entry) = old_file
6562                        .entry_id
6563                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6564                    {
6565                        File {
6566                            is_local: true,
6567                            entry_id: Some(entry.id),
6568                            mtime: entry.mtime,
6569                            path: entry.path.clone(),
6570                            worktree: worktree_handle.clone(),
6571                            is_deleted: false,
6572                            is_private: entry.is_private,
6573                        }
6574                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6575                        File {
6576                            is_local: true,
6577                            entry_id: Some(entry.id),
6578                            mtime: entry.mtime,
6579                            path: entry.path.clone(),
6580                            worktree: worktree_handle.clone(),
6581                            is_deleted: false,
6582                            is_private: entry.is_private,
6583                        }
6584                    } else {
6585                        File {
6586                            is_local: true,
6587                            entry_id: old_file.entry_id,
6588                            path: old_file.path().clone(),
6589                            mtime: old_file.mtime(),
6590                            worktree: worktree_handle.clone(),
6591                            is_deleted: true,
6592                            is_private: old_file.is_private,
6593                        }
6594                    };
6595
6596                    let old_path = old_file.abs_path(cx);
6597                    if new_file.abs_path(cx) != old_path {
6598                        renamed_buffers.push((cx.handle(), old_file.clone()));
6599                        self.local_buffer_ids_by_path.remove(&project_path);
6600                        self.local_buffer_ids_by_path.insert(
6601                            ProjectPath {
6602                                worktree_id,
6603                                path: path.clone(),
6604                            },
6605                            buffer_id,
6606                        );
6607                    }
6608
6609                    if new_file.entry_id != Some(*entry_id) {
6610                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6611                        if let Some(entry_id) = new_file.entry_id {
6612                            self.local_buffer_ids_by_entry_id
6613                                .insert(entry_id, buffer_id);
6614                        }
6615                    }
6616
6617                    if new_file != *old_file {
6618                        if let Some(project_id) = self.remote_id() {
6619                            self.client
6620                                .send(proto::UpdateBufferFile {
6621                                    project_id,
6622                                    buffer_id: buffer_id.into(),
6623                                    file: Some(new_file.to_proto()),
6624                                })
6625                                .log_err();
6626                        }
6627
6628                        buffer.file_updated(Arc::new(new_file), cx);
6629                    }
6630                }
6631            });
6632        }
6633
6634        for (buffer, old_file) in renamed_buffers {
6635            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6636            self.detect_language_for_buffer(&buffer, cx);
6637            self.register_buffer_with_language_servers(&buffer, cx);
6638        }
6639    }
6640
6641    fn update_local_worktree_language_servers(
6642        &mut self,
6643        worktree_handle: &Model<Worktree>,
6644        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6645        cx: &mut ModelContext<Self>,
6646    ) {
6647        if changes.is_empty() {
6648            return;
6649        }
6650
6651        let worktree_id = worktree_handle.read(cx).id();
6652        let mut language_server_ids = self
6653            .language_server_ids
6654            .iter()
6655            .filter_map(|((server_worktree_id, _), server_id)| {
6656                (*server_worktree_id == worktree_id).then_some(*server_id)
6657            })
6658            .collect::<Vec<_>>();
6659        language_server_ids.sort();
6660        language_server_ids.dedup();
6661
6662        let abs_path = worktree_handle.read(cx).abs_path();
6663        for server_id in &language_server_ids {
6664            if let Some(LanguageServerState::Running {
6665                server,
6666                watched_paths,
6667                ..
6668            }) = self.language_servers.get(server_id)
6669            {
6670                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6671                    let params = lsp::DidChangeWatchedFilesParams {
6672                        changes: changes
6673                            .iter()
6674                            .filter_map(|(path, _, change)| {
6675                                if !watched_paths.is_match(&path) {
6676                                    return None;
6677                                }
6678                                let typ = match change {
6679                                    PathChange::Loaded => return None,
6680                                    PathChange::Added => lsp::FileChangeType::CREATED,
6681                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6682                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6683                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6684                                };
6685                                Some(lsp::FileEvent {
6686                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6687                                    typ,
6688                                })
6689                            })
6690                            .collect(),
6691                    };
6692
6693                    if !params.changes.is_empty() {
6694                        server
6695                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6696                            .log_err();
6697                    }
6698                }
6699            }
6700        }
6701    }
6702
6703    fn update_local_worktree_buffers_git_repos(
6704        &mut self,
6705        worktree_handle: Model<Worktree>,
6706        changed_repos: &UpdatedGitRepositoriesSet,
6707        cx: &mut ModelContext<Self>,
6708    ) {
6709        debug_assert!(worktree_handle.read(cx).is_local());
6710
6711        // Identify the loading buffers whose containing repository that has changed.
6712        let future_buffers = self
6713            .loading_buffers_by_path
6714            .iter()
6715            .filter_map(|(project_path, receiver)| {
6716                if project_path.worktree_id != worktree_handle.read(cx).id() {
6717                    return None;
6718                }
6719                let path = &project_path.path;
6720                changed_repos
6721                    .iter()
6722                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6723                let receiver = receiver.clone();
6724                let path = path.clone();
6725                Some(async move {
6726                    wait_for_loading_buffer(receiver)
6727                        .await
6728                        .ok()
6729                        .map(|buffer| (buffer, path))
6730                })
6731            })
6732            .collect::<FuturesUnordered<_>>();
6733
6734        // Identify the current buffers whose containing repository has changed.
6735        let current_buffers = self
6736            .opened_buffers
6737            .values()
6738            .filter_map(|buffer| {
6739                let buffer = buffer.upgrade()?;
6740                let file = File::from_dyn(buffer.read(cx).file())?;
6741                if file.worktree != worktree_handle {
6742                    return None;
6743                }
6744                let path = file.path();
6745                changed_repos
6746                    .iter()
6747                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6748                Some((buffer, path.clone()))
6749            })
6750            .collect::<Vec<_>>();
6751
6752        if future_buffers.len() + current_buffers.len() == 0 {
6753            return;
6754        }
6755
6756        let remote_id = self.remote_id();
6757        let client = self.client.clone();
6758        cx.spawn(move |_, mut cx| async move {
6759            // Wait for all of the buffers to load.
6760            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6761
6762            // Reload the diff base for every buffer whose containing git repository has changed.
6763            let snapshot =
6764                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6765            let diff_bases_by_buffer = cx
6766                .background_executor()
6767                .spawn(async move {
6768                    future_buffers
6769                        .into_iter()
6770                        .filter_map(|e| e)
6771                        .chain(current_buffers)
6772                        .filter_map(|(buffer, path)| {
6773                            let (work_directory, repo) =
6774                                snapshot.repository_and_work_directory_for_path(&path)?;
6775                            let repo = snapshot.get_local_repo(&repo)?;
6776                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6777                            let base_text = repo.repo_ptr.lock().load_index_text(relative_path);
6778                            Some((buffer, base_text))
6779                        })
6780                        .collect::<Vec<_>>()
6781                })
6782                .await;
6783
6784            // Assign the new diff bases on all of the buffers.
6785            for (buffer, diff_base) in diff_bases_by_buffer {
6786                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6787                    buffer.set_diff_base(diff_base.clone(), cx);
6788                    buffer.remote_id().into()
6789                })?;
6790                if let Some(project_id) = remote_id {
6791                    client
6792                        .send(proto::UpdateDiffBase {
6793                            project_id,
6794                            buffer_id,
6795                            diff_base,
6796                        })
6797                        .log_err();
6798                }
6799            }
6800
6801            anyhow::Ok(())
6802        })
6803        .detach();
6804    }
6805
6806    fn update_local_worktree_settings(
6807        &mut self,
6808        worktree: &Model<Worktree>,
6809        changes: &UpdatedEntriesSet,
6810        cx: &mut ModelContext<Self>,
6811    ) {
6812        let project_id = self.remote_id();
6813        let worktree_id = worktree.entity_id();
6814        let worktree = worktree.read(cx).as_local().unwrap();
6815        let remote_worktree_id = worktree.id();
6816
6817        let mut settings_contents = Vec::new();
6818        for (path, _, change) in changes.iter() {
6819            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6820                let settings_dir = Arc::from(
6821                    path.ancestors()
6822                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6823                        .unwrap(),
6824                );
6825                let fs = self.fs.clone();
6826                let removed = *change == PathChange::Removed;
6827                let abs_path = worktree.absolutize(path);
6828                settings_contents.push(async move {
6829                    (
6830                        settings_dir,
6831                        if removed {
6832                            None
6833                        } else {
6834                            Some(async move { fs.load(&abs_path?).await }.await)
6835                        },
6836                    )
6837                });
6838            }
6839        }
6840
6841        if settings_contents.is_empty() {
6842            return;
6843        }
6844
6845        let client = self.client.clone();
6846        cx.spawn(move |_, cx| async move {
6847            let settings_contents: Vec<(Arc<Path>, _)> =
6848                futures::future::join_all(settings_contents).await;
6849            cx.update(|cx| {
6850                cx.update_global::<SettingsStore, _>(|store, cx| {
6851                    for (directory, file_content) in settings_contents {
6852                        let file_content = file_content.and_then(|content| content.log_err());
6853                        store
6854                            .set_local_settings(
6855                                worktree_id.as_u64() as usize,
6856                                directory.clone(),
6857                                file_content.as_ref().map(String::as_str),
6858                                cx,
6859                            )
6860                            .log_err();
6861                        if let Some(remote_id) = project_id {
6862                            client
6863                                .send(proto::UpdateWorktreeSettings {
6864                                    project_id: remote_id,
6865                                    worktree_id: remote_worktree_id.to_proto(),
6866                                    path: directory.to_string_lossy().into_owned(),
6867                                    content: file_content,
6868                                })
6869                                .log_err();
6870                        }
6871                    }
6872                });
6873            })
6874            .ok();
6875        })
6876        .detach();
6877    }
6878
6879    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6880        let new_active_entry = entry.and_then(|project_path| {
6881            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6882            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6883            Some(entry.id)
6884        });
6885        if new_active_entry != self.active_entry {
6886            self.active_entry = new_active_entry;
6887            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6888        }
6889    }
6890
6891    pub fn language_servers_running_disk_based_diagnostics(
6892        &self,
6893    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6894        self.language_server_statuses
6895            .iter()
6896            .filter_map(|(id, status)| {
6897                if status.has_pending_diagnostic_updates {
6898                    Some(*id)
6899                } else {
6900                    None
6901                }
6902            })
6903    }
6904
6905    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
6906        let mut summary = DiagnosticSummary::default();
6907        for (_, _, path_summary) in
6908            self.diagnostic_summaries(include_ignored, cx)
6909                .filter(|(path, _, _)| {
6910                    let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
6911                    include_ignored || worktree == Some(false)
6912                })
6913        {
6914            summary.error_count += path_summary.error_count;
6915            summary.warning_count += path_summary.warning_count;
6916        }
6917        summary
6918    }
6919
6920    pub fn diagnostic_summaries<'a>(
6921        &'a self,
6922        include_ignored: bool,
6923        cx: &'a AppContext,
6924    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6925        self.visible_worktrees(cx)
6926            .flat_map(move |worktree| {
6927                let worktree = worktree.read(cx);
6928                let worktree_id = worktree.id();
6929                worktree
6930                    .diagnostic_summaries()
6931                    .map(move |(path, server_id, summary)| {
6932                        (ProjectPath { worktree_id, path }, server_id, summary)
6933                    })
6934            })
6935            .filter(move |(path, _, _)| {
6936                let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
6937                include_ignored || worktree == Some(false)
6938            })
6939    }
6940
6941    pub fn disk_based_diagnostics_started(
6942        &mut self,
6943        language_server_id: LanguageServerId,
6944        cx: &mut ModelContext<Self>,
6945    ) {
6946        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6947    }
6948
6949    pub fn disk_based_diagnostics_finished(
6950        &mut self,
6951        language_server_id: LanguageServerId,
6952        cx: &mut ModelContext<Self>,
6953    ) {
6954        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6955    }
6956
6957    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6958        self.active_entry
6959    }
6960
6961    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6962        self.worktree_for_id(path.worktree_id, cx)?
6963            .read(cx)
6964            .entry_for_path(&path.path)
6965            .cloned()
6966    }
6967
6968    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6969        let worktree = self.worktree_for_entry(entry_id, cx)?;
6970        let worktree = worktree.read(cx);
6971        let worktree_id = worktree.id();
6972        let path = worktree.entry_for_id(entry_id)?.path.clone();
6973        Some(ProjectPath { worktree_id, path })
6974    }
6975
6976    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6977        let workspace_root = self
6978            .worktree_for_id(project_path.worktree_id, cx)?
6979            .read(cx)
6980            .abs_path();
6981        let project_path = project_path.path.as_ref();
6982
6983        Some(if project_path == Path::new("") {
6984            workspace_root.to_path_buf()
6985        } else {
6986            workspace_root.join(project_path)
6987        })
6988    }
6989
6990    // RPC message handlers
6991
6992    async fn handle_unshare_project(
6993        this: Model<Self>,
6994        _: TypedEnvelope<proto::UnshareProject>,
6995        _: Arc<Client>,
6996        mut cx: AsyncAppContext,
6997    ) -> Result<()> {
6998        this.update(&mut cx, |this, cx| {
6999            if this.is_local() {
7000                this.unshare(cx)?;
7001            } else {
7002                this.disconnected_from_host(cx);
7003            }
7004            Ok(())
7005        })?
7006    }
7007
7008    async fn handle_add_collaborator(
7009        this: Model<Self>,
7010        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
7011        _: Arc<Client>,
7012        mut cx: AsyncAppContext,
7013    ) -> Result<()> {
7014        let collaborator = envelope
7015            .payload
7016            .collaborator
7017            .take()
7018            .ok_or_else(|| anyhow!("empty collaborator"))?;
7019
7020        let collaborator = Collaborator::from_proto(collaborator)?;
7021        this.update(&mut cx, |this, cx| {
7022            this.shared_buffers.remove(&collaborator.peer_id);
7023            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
7024            this.collaborators
7025                .insert(collaborator.peer_id, collaborator);
7026            cx.notify();
7027        })?;
7028
7029        Ok(())
7030    }
7031
7032    async fn handle_update_project_collaborator(
7033        this: Model<Self>,
7034        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
7035        _: Arc<Client>,
7036        mut cx: AsyncAppContext,
7037    ) -> Result<()> {
7038        let old_peer_id = envelope
7039            .payload
7040            .old_peer_id
7041            .ok_or_else(|| anyhow!("missing old peer id"))?;
7042        let new_peer_id = envelope
7043            .payload
7044            .new_peer_id
7045            .ok_or_else(|| anyhow!("missing new peer id"))?;
7046        this.update(&mut cx, |this, cx| {
7047            let collaborator = this
7048                .collaborators
7049                .remove(&old_peer_id)
7050                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
7051            let is_host = collaborator.replica_id == 0;
7052            this.collaborators.insert(new_peer_id, collaborator);
7053
7054            let buffers = this.shared_buffers.remove(&old_peer_id);
7055            log::info!(
7056                "peer {} became {}. moving buffers {:?}",
7057                old_peer_id,
7058                new_peer_id,
7059                &buffers
7060            );
7061            if let Some(buffers) = buffers {
7062                this.shared_buffers.insert(new_peer_id, buffers);
7063            }
7064
7065            if is_host {
7066                this.opened_buffers
7067                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
7068                this.buffer_ordered_messages_tx
7069                    .unbounded_send(BufferOrderedMessage::Resync)
7070                    .unwrap();
7071            }
7072
7073            cx.emit(Event::CollaboratorUpdated {
7074                old_peer_id,
7075                new_peer_id,
7076            });
7077            cx.notify();
7078            Ok(())
7079        })?
7080    }
7081
7082    async fn handle_remove_collaborator(
7083        this: Model<Self>,
7084        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
7085        _: Arc<Client>,
7086        mut cx: AsyncAppContext,
7087    ) -> Result<()> {
7088        this.update(&mut cx, |this, cx| {
7089            let peer_id = envelope
7090                .payload
7091                .peer_id
7092                .ok_or_else(|| anyhow!("invalid peer id"))?;
7093            let replica_id = this
7094                .collaborators
7095                .remove(&peer_id)
7096                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7097                .replica_id;
7098            for buffer in this.opened_buffers.values() {
7099                if let Some(buffer) = buffer.upgrade() {
7100                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7101                }
7102            }
7103            this.shared_buffers.remove(&peer_id);
7104
7105            cx.emit(Event::CollaboratorLeft(peer_id));
7106            cx.notify();
7107            Ok(())
7108        })?
7109    }
7110
7111    async fn handle_update_project(
7112        this: Model<Self>,
7113        envelope: TypedEnvelope<proto::UpdateProject>,
7114        _: Arc<Client>,
7115        mut cx: AsyncAppContext,
7116    ) -> Result<()> {
7117        this.update(&mut cx, |this, cx| {
7118            // Don't handle messages that were sent before the response to us joining the project
7119            if envelope.message_id > this.join_project_response_message_id {
7120                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7121            }
7122            Ok(())
7123        })?
7124    }
7125
7126    async fn handle_update_worktree(
7127        this: Model<Self>,
7128        envelope: TypedEnvelope<proto::UpdateWorktree>,
7129        _: Arc<Client>,
7130        mut cx: AsyncAppContext,
7131    ) -> Result<()> {
7132        this.update(&mut cx, |this, cx| {
7133            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7134            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7135                worktree.update(cx, |worktree, _| {
7136                    let worktree = worktree.as_remote_mut().unwrap();
7137                    worktree.update_from_remote(envelope.payload);
7138                });
7139            }
7140            Ok(())
7141        })?
7142    }
7143
7144    async fn handle_update_worktree_settings(
7145        this: Model<Self>,
7146        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7147        _: Arc<Client>,
7148        mut cx: AsyncAppContext,
7149    ) -> Result<()> {
7150        this.update(&mut cx, |this, cx| {
7151            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7152            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7153                cx.update_global::<SettingsStore, _>(|store, cx| {
7154                    store
7155                        .set_local_settings(
7156                            worktree.entity_id().as_u64() as usize,
7157                            PathBuf::from(&envelope.payload.path).into(),
7158                            envelope.payload.content.as_ref().map(String::as_str),
7159                            cx,
7160                        )
7161                        .log_err();
7162                });
7163            }
7164            Ok(())
7165        })?
7166    }
7167
7168    async fn handle_create_project_entry(
7169        this: Model<Self>,
7170        envelope: TypedEnvelope<proto::CreateProjectEntry>,
7171        _: Arc<Client>,
7172        mut cx: AsyncAppContext,
7173    ) -> Result<proto::ProjectEntryResponse> {
7174        let worktree = this.update(&mut cx, |this, cx| {
7175            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7176            this.worktree_for_id(worktree_id, cx)
7177                .ok_or_else(|| anyhow!("worktree not found"))
7178        })??;
7179        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7180        let entry = worktree
7181            .update(&mut cx, |worktree, cx| {
7182                let worktree = worktree.as_local_mut().unwrap();
7183                let path = PathBuf::from(envelope.payload.path);
7184                worktree.create_entry(path, envelope.payload.is_directory, cx)
7185            })?
7186            .await?;
7187        Ok(proto::ProjectEntryResponse {
7188            entry: entry.as_ref().map(|e| e.into()),
7189            worktree_scan_id: worktree_scan_id as u64,
7190        })
7191    }
7192
7193    async fn handle_rename_project_entry(
7194        this: Model<Self>,
7195        envelope: TypedEnvelope<proto::RenameProjectEntry>,
7196        _: Arc<Client>,
7197        mut cx: AsyncAppContext,
7198    ) -> Result<proto::ProjectEntryResponse> {
7199        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7200        let worktree = this.update(&mut cx, |this, cx| {
7201            this.worktree_for_entry(entry_id, cx)
7202                .ok_or_else(|| anyhow!("worktree not found"))
7203        })??;
7204        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7205        let entry = worktree
7206            .update(&mut cx, |worktree, cx| {
7207                let new_path = PathBuf::from(envelope.payload.new_path);
7208                worktree
7209                    .as_local_mut()
7210                    .unwrap()
7211                    .rename_entry(entry_id, new_path, cx)
7212            })?
7213            .await?;
7214        Ok(proto::ProjectEntryResponse {
7215            entry: entry.as_ref().map(|e| e.into()),
7216            worktree_scan_id: worktree_scan_id as u64,
7217        })
7218    }
7219
7220    async fn handle_copy_project_entry(
7221        this: Model<Self>,
7222        envelope: TypedEnvelope<proto::CopyProjectEntry>,
7223        _: Arc<Client>,
7224        mut cx: AsyncAppContext,
7225    ) -> Result<proto::ProjectEntryResponse> {
7226        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7227        let worktree = this.update(&mut cx, |this, cx| {
7228            this.worktree_for_entry(entry_id, cx)
7229                .ok_or_else(|| anyhow!("worktree not found"))
7230        })??;
7231        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7232        let entry = worktree
7233            .update(&mut cx, |worktree, cx| {
7234                let new_path = PathBuf::from(envelope.payload.new_path);
7235                worktree
7236                    .as_local_mut()
7237                    .unwrap()
7238                    .copy_entry(entry_id, new_path, cx)
7239            })?
7240            .await?;
7241        Ok(proto::ProjectEntryResponse {
7242            entry: entry.as_ref().map(|e| e.into()),
7243            worktree_scan_id: worktree_scan_id as u64,
7244        })
7245    }
7246
7247    async fn handle_delete_project_entry(
7248        this: Model<Self>,
7249        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7250        _: Arc<Client>,
7251        mut cx: AsyncAppContext,
7252    ) -> Result<proto::ProjectEntryResponse> {
7253        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7254
7255        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7256
7257        let worktree = this.update(&mut cx, |this, cx| {
7258            this.worktree_for_entry(entry_id, cx)
7259                .ok_or_else(|| anyhow!("worktree not found"))
7260        })??;
7261        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7262        worktree
7263            .update(&mut cx, |worktree, cx| {
7264                worktree
7265                    .as_local_mut()
7266                    .unwrap()
7267                    .delete_entry(entry_id, cx)
7268                    .ok_or_else(|| anyhow!("invalid entry"))
7269            })??
7270            .await?;
7271        Ok(proto::ProjectEntryResponse {
7272            entry: None,
7273            worktree_scan_id: worktree_scan_id as u64,
7274        })
7275    }
7276
7277    async fn handle_expand_project_entry(
7278        this: Model<Self>,
7279        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7280        _: Arc<Client>,
7281        mut cx: AsyncAppContext,
7282    ) -> Result<proto::ExpandProjectEntryResponse> {
7283        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7284        let worktree = this
7285            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7286            .ok_or_else(|| anyhow!("invalid request"))?;
7287        worktree
7288            .update(&mut cx, |worktree, cx| {
7289                worktree
7290                    .as_local_mut()
7291                    .unwrap()
7292                    .expand_entry(entry_id, cx)
7293                    .ok_or_else(|| anyhow!("invalid entry"))
7294            })??
7295            .await?;
7296        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7297        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7298    }
7299
7300    async fn handle_update_diagnostic_summary(
7301        this: Model<Self>,
7302        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7303        _: Arc<Client>,
7304        mut cx: AsyncAppContext,
7305    ) -> Result<()> {
7306        this.update(&mut cx, |this, cx| {
7307            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7308            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7309                if let Some(summary) = envelope.payload.summary {
7310                    let project_path = ProjectPath {
7311                        worktree_id,
7312                        path: Path::new(&summary.path).into(),
7313                    };
7314                    worktree.update(cx, |worktree, _| {
7315                        worktree
7316                            .as_remote_mut()
7317                            .unwrap()
7318                            .update_diagnostic_summary(project_path.path.clone(), &summary);
7319                    });
7320                    cx.emit(Event::DiagnosticsUpdated {
7321                        language_server_id: LanguageServerId(summary.language_server_id as usize),
7322                        path: project_path,
7323                    });
7324                }
7325            }
7326            Ok(())
7327        })?
7328    }
7329
7330    async fn handle_start_language_server(
7331        this: Model<Self>,
7332        envelope: TypedEnvelope<proto::StartLanguageServer>,
7333        _: Arc<Client>,
7334        mut cx: AsyncAppContext,
7335    ) -> Result<()> {
7336        let server = envelope
7337            .payload
7338            .server
7339            .ok_or_else(|| anyhow!("invalid server"))?;
7340        this.update(&mut cx, |this, cx| {
7341            this.language_server_statuses.insert(
7342                LanguageServerId(server.id as usize),
7343                LanguageServerStatus {
7344                    name: server.name,
7345                    pending_work: Default::default(),
7346                    has_pending_diagnostic_updates: false,
7347                    progress_tokens: Default::default(),
7348                },
7349            );
7350            cx.notify();
7351        })?;
7352        Ok(())
7353    }
7354
7355    async fn handle_update_language_server(
7356        this: Model<Self>,
7357        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7358        _: Arc<Client>,
7359        mut cx: AsyncAppContext,
7360    ) -> Result<()> {
7361        this.update(&mut cx, |this, cx| {
7362            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7363
7364            match envelope
7365                .payload
7366                .variant
7367                .ok_or_else(|| anyhow!("invalid variant"))?
7368            {
7369                proto::update_language_server::Variant::WorkStart(payload) => {
7370                    this.on_lsp_work_start(
7371                        language_server_id,
7372                        payload.token,
7373                        LanguageServerProgress {
7374                            message: payload.message,
7375                            percentage: payload.percentage.map(|p| p as usize),
7376                            last_update_at: Instant::now(),
7377                        },
7378                        cx,
7379                    );
7380                }
7381
7382                proto::update_language_server::Variant::WorkProgress(payload) => {
7383                    this.on_lsp_work_progress(
7384                        language_server_id,
7385                        payload.token,
7386                        LanguageServerProgress {
7387                            message: payload.message,
7388                            percentage: payload.percentage.map(|p| p as usize),
7389                            last_update_at: Instant::now(),
7390                        },
7391                        cx,
7392                    );
7393                }
7394
7395                proto::update_language_server::Variant::WorkEnd(payload) => {
7396                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7397                }
7398
7399                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7400                    this.disk_based_diagnostics_started(language_server_id, cx);
7401                }
7402
7403                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7404                    this.disk_based_diagnostics_finished(language_server_id, cx)
7405                }
7406            }
7407
7408            Ok(())
7409        })?
7410    }
7411
7412    async fn handle_update_buffer(
7413        this: Model<Self>,
7414        envelope: TypedEnvelope<proto::UpdateBuffer>,
7415        _: Arc<Client>,
7416        mut cx: AsyncAppContext,
7417    ) -> Result<proto::Ack> {
7418        this.update(&mut cx, |this, cx| {
7419            let payload = envelope.payload.clone();
7420            let buffer_id = BufferId::new(payload.buffer_id)?;
7421            let ops = payload
7422                .operations
7423                .into_iter()
7424                .map(language::proto::deserialize_operation)
7425                .collect::<Result<Vec<_>, _>>()?;
7426            let is_remote = this.is_remote();
7427            match this.opened_buffers.entry(buffer_id) {
7428                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7429                    OpenBuffer::Strong(buffer) => {
7430                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7431                    }
7432                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7433                    OpenBuffer::Weak(_) => {}
7434                },
7435                hash_map::Entry::Vacant(e) => {
7436                    assert!(
7437                        is_remote,
7438                        "received buffer update from {:?}",
7439                        envelope.original_sender_id
7440                    );
7441                    e.insert(OpenBuffer::Operations(ops));
7442                }
7443            }
7444            Ok(proto::Ack {})
7445        })?
7446    }
7447
7448    async fn handle_create_buffer_for_peer(
7449        this: Model<Self>,
7450        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7451        _: Arc<Client>,
7452        mut cx: AsyncAppContext,
7453    ) -> Result<()> {
7454        this.update(&mut cx, |this, cx| {
7455            match envelope
7456                .payload
7457                .variant
7458                .ok_or_else(|| anyhow!("missing variant"))?
7459            {
7460                proto::create_buffer_for_peer::Variant::State(mut state) => {
7461                    let mut buffer_file = None;
7462                    if let Some(file) = state.file.take() {
7463                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7464                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7465                            anyhow!("no worktree found for id {}", file.worktree_id)
7466                        })?;
7467                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7468                            as Arc<dyn language::File>);
7469                    }
7470
7471                    let buffer_id = BufferId::new(state.id)?;
7472                    let buffer = cx.new_model(|_| {
7473                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7474                            .unwrap()
7475                    });
7476                    this.incomplete_remote_buffers
7477                        .insert(buffer_id, Some(buffer));
7478                }
7479                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7480                    let buffer_id = BufferId::new(chunk.buffer_id)?;
7481                    let buffer = this
7482                        .incomplete_remote_buffers
7483                        .get(&buffer_id)
7484                        .cloned()
7485                        .flatten()
7486                        .ok_or_else(|| {
7487                            anyhow!(
7488                                "received chunk for buffer {} without initial state",
7489                                chunk.buffer_id
7490                            )
7491                        })?;
7492                    let operations = chunk
7493                        .operations
7494                        .into_iter()
7495                        .map(language::proto::deserialize_operation)
7496                        .collect::<Result<Vec<_>>>()?;
7497                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7498
7499                    if chunk.is_last {
7500                        this.incomplete_remote_buffers.remove(&buffer_id);
7501                        this.register_buffer(&buffer, cx)?;
7502                    }
7503                }
7504            }
7505
7506            Ok(())
7507        })?
7508    }
7509
7510    async fn handle_update_diff_base(
7511        this: Model<Self>,
7512        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7513        _: Arc<Client>,
7514        mut cx: AsyncAppContext,
7515    ) -> Result<()> {
7516        this.update(&mut cx, |this, cx| {
7517            let buffer_id = envelope.payload.buffer_id;
7518            let buffer_id = BufferId::new(buffer_id)?;
7519            let diff_base = envelope.payload.diff_base;
7520            if let Some(buffer) = this
7521                .opened_buffers
7522                .get_mut(&buffer_id)
7523                .and_then(|b| b.upgrade())
7524                .or_else(|| {
7525                    this.incomplete_remote_buffers
7526                        .get(&buffer_id)
7527                        .cloned()
7528                        .flatten()
7529                })
7530            {
7531                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7532            }
7533            Ok(())
7534        })?
7535    }
7536
7537    async fn handle_update_buffer_file(
7538        this: Model<Self>,
7539        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7540        _: Arc<Client>,
7541        mut cx: AsyncAppContext,
7542    ) -> Result<()> {
7543        let buffer_id = envelope.payload.buffer_id;
7544        let buffer_id = BufferId::new(buffer_id)?;
7545
7546        this.update(&mut cx, |this, cx| {
7547            let payload = envelope.payload.clone();
7548            if let Some(buffer) = this
7549                .opened_buffers
7550                .get(&buffer_id)
7551                .and_then(|b| b.upgrade())
7552                .or_else(|| {
7553                    this.incomplete_remote_buffers
7554                        .get(&buffer_id)
7555                        .cloned()
7556                        .flatten()
7557                })
7558            {
7559                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7560                let worktree = this
7561                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7562                    .ok_or_else(|| anyhow!("no such worktree"))?;
7563                let file = File::from_proto(file, worktree, cx)?;
7564                buffer.update(cx, |buffer, cx| {
7565                    buffer.file_updated(Arc::new(file), cx);
7566                });
7567                this.detect_language_for_buffer(&buffer, cx);
7568            }
7569            Ok(())
7570        })?
7571    }
7572
7573    async fn handle_save_buffer(
7574        this: Model<Self>,
7575        envelope: TypedEnvelope<proto::SaveBuffer>,
7576        _: Arc<Client>,
7577        mut cx: AsyncAppContext,
7578    ) -> Result<proto::BufferSaved> {
7579        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7580        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7581            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7582            let buffer = this
7583                .opened_buffers
7584                .get(&buffer_id)
7585                .and_then(|buffer| buffer.upgrade())
7586                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7587            anyhow::Ok((project_id, buffer))
7588        })??;
7589        buffer
7590            .update(&mut cx, |buffer, _| {
7591                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7592            })?
7593            .await?;
7594        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7595
7596        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7597            .await?;
7598        Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7599            project_id,
7600            buffer_id: buffer_id.into(),
7601            version: serialize_version(buffer.saved_version()),
7602            mtime: Some(buffer.saved_mtime().into()),
7603            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7604        })?)
7605    }
7606
7607    async fn handle_reload_buffers(
7608        this: Model<Self>,
7609        envelope: TypedEnvelope<proto::ReloadBuffers>,
7610        _: Arc<Client>,
7611        mut cx: AsyncAppContext,
7612    ) -> Result<proto::ReloadBuffersResponse> {
7613        let sender_id = envelope.original_sender_id()?;
7614        let reload = this.update(&mut cx, |this, cx| {
7615            let mut buffers = HashSet::default();
7616            for buffer_id in &envelope.payload.buffer_ids {
7617                let buffer_id = BufferId::new(*buffer_id)?;
7618                buffers.insert(
7619                    this.opened_buffers
7620                        .get(&buffer_id)
7621                        .and_then(|buffer| buffer.upgrade())
7622                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7623                );
7624            }
7625            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7626        })??;
7627
7628        let project_transaction = reload.await?;
7629        let project_transaction = this.update(&mut cx, |this, cx| {
7630            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7631        })?;
7632        Ok(proto::ReloadBuffersResponse {
7633            transaction: Some(project_transaction),
7634        })
7635    }
7636
7637    async fn handle_synchronize_buffers(
7638        this: Model<Self>,
7639        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7640        _: Arc<Client>,
7641        mut cx: AsyncAppContext,
7642    ) -> Result<proto::SynchronizeBuffersResponse> {
7643        let project_id = envelope.payload.project_id;
7644        let mut response = proto::SynchronizeBuffersResponse {
7645            buffers: Default::default(),
7646        };
7647
7648        this.update(&mut cx, |this, cx| {
7649            let Some(guest_id) = envelope.original_sender_id else {
7650                error!("missing original_sender_id on SynchronizeBuffers request");
7651                bail!("missing original_sender_id on SynchronizeBuffers request");
7652            };
7653
7654            this.shared_buffers.entry(guest_id).or_default().clear();
7655            for buffer in envelope.payload.buffers {
7656                let buffer_id = BufferId::new(buffer.id)?;
7657                let remote_version = language::proto::deserialize_version(&buffer.version);
7658                if let Some(buffer) = this.buffer_for_id(buffer_id) {
7659                    this.shared_buffers
7660                        .entry(guest_id)
7661                        .or_default()
7662                        .insert(buffer_id);
7663
7664                    let buffer = buffer.read(cx);
7665                    response.buffers.push(proto::BufferVersion {
7666                        id: buffer_id.into(),
7667                        version: language::proto::serialize_version(&buffer.version),
7668                    });
7669
7670                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7671                    let client = this.client.clone();
7672                    if let Some(file) = buffer.file() {
7673                        client
7674                            .send(proto::UpdateBufferFile {
7675                                project_id,
7676                                buffer_id: buffer_id.into(),
7677                                file: Some(file.to_proto()),
7678                            })
7679                            .log_err();
7680                    }
7681
7682                    client
7683                        .send(proto::UpdateDiffBase {
7684                            project_id,
7685                            buffer_id: buffer_id.into(),
7686                            diff_base: buffer.diff_base().map(Into::into),
7687                        })
7688                        .log_err();
7689
7690                    client
7691                        .send(proto::BufferReloaded {
7692                            project_id,
7693                            buffer_id: buffer_id.into(),
7694                            version: language::proto::serialize_version(buffer.saved_version()),
7695                            mtime: Some(buffer.saved_mtime().into()),
7696                            fingerprint: language::proto::serialize_fingerprint(
7697                                buffer.saved_version_fingerprint(),
7698                            ),
7699                            line_ending: language::proto::serialize_line_ending(
7700                                buffer.line_ending(),
7701                            ) as i32,
7702                        })
7703                        .log_err();
7704
7705                    cx.background_executor()
7706                        .spawn(
7707                            async move {
7708                                let operations = operations.await;
7709                                for chunk in split_operations(operations) {
7710                                    client
7711                                        .request(proto::UpdateBuffer {
7712                                            project_id,
7713                                            buffer_id: buffer_id.into(),
7714                                            operations: chunk,
7715                                        })
7716                                        .await?;
7717                                }
7718                                anyhow::Ok(())
7719                            }
7720                            .log_err(),
7721                        )
7722                        .detach();
7723                }
7724            }
7725            Ok(())
7726        })??;
7727
7728        Ok(response)
7729    }
7730
7731    async fn handle_format_buffers(
7732        this: Model<Self>,
7733        envelope: TypedEnvelope<proto::FormatBuffers>,
7734        _: Arc<Client>,
7735        mut cx: AsyncAppContext,
7736    ) -> Result<proto::FormatBuffersResponse> {
7737        let sender_id = envelope.original_sender_id()?;
7738        let format = this.update(&mut cx, |this, cx| {
7739            let mut buffers = HashSet::default();
7740            for buffer_id in &envelope.payload.buffer_ids {
7741                let buffer_id = BufferId::new(*buffer_id)?;
7742                buffers.insert(
7743                    this.opened_buffers
7744                        .get(&buffer_id)
7745                        .and_then(|buffer| buffer.upgrade())
7746                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7747                );
7748            }
7749            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7750            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7751        })??;
7752
7753        let project_transaction = format.await?;
7754        let project_transaction = this.update(&mut cx, |this, cx| {
7755            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7756        })?;
7757        Ok(proto::FormatBuffersResponse {
7758            transaction: Some(project_transaction),
7759        })
7760    }
7761
7762    async fn handle_apply_additional_edits_for_completion(
7763        this: Model<Self>,
7764        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7765        _: Arc<Client>,
7766        mut cx: AsyncAppContext,
7767    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7768        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7769            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7770            let buffer = this
7771                .opened_buffers
7772                .get(&buffer_id)
7773                .and_then(|buffer| buffer.upgrade())
7774                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7775            let language = buffer.read(cx).language();
7776            let completion = language::proto::deserialize_completion(
7777                envelope
7778                    .payload
7779                    .completion
7780                    .ok_or_else(|| anyhow!("invalid completion"))?,
7781                language.cloned(),
7782            );
7783            Ok::<_, anyhow::Error>((buffer, completion))
7784        })??;
7785
7786        let completion = completion.await?;
7787
7788        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7789            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7790        })?;
7791
7792        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7793            transaction: apply_additional_edits
7794                .await?
7795                .as_ref()
7796                .map(language::proto::serialize_transaction),
7797        })
7798    }
7799
7800    async fn handle_resolve_completion_documentation(
7801        this: Model<Self>,
7802        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7803        _: Arc<Client>,
7804        mut cx: AsyncAppContext,
7805    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7806        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7807
7808        let completion = this
7809            .read_with(&mut cx, |this, _| {
7810                let id = LanguageServerId(envelope.payload.language_server_id as usize);
7811                let Some(server) = this.language_server_for_id(id) else {
7812                    return Err(anyhow!("No language server {id}"));
7813                };
7814
7815                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
7816            })??
7817            .await?;
7818
7819        let mut is_markdown = false;
7820        let text = match completion.documentation {
7821            Some(lsp::Documentation::String(text)) => text,
7822
7823            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7824                is_markdown = kind == lsp::MarkupKind::Markdown;
7825                value
7826            }
7827
7828            _ => String::new(),
7829        };
7830
7831        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
7832    }
7833
7834    async fn handle_apply_code_action(
7835        this: Model<Self>,
7836        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7837        _: Arc<Client>,
7838        mut cx: AsyncAppContext,
7839    ) -> Result<proto::ApplyCodeActionResponse> {
7840        let sender_id = envelope.original_sender_id()?;
7841        let action = language::proto::deserialize_code_action(
7842            envelope
7843                .payload
7844                .action
7845                .ok_or_else(|| anyhow!("invalid action"))?,
7846        )?;
7847        let apply_code_action = this.update(&mut cx, |this, cx| {
7848            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7849            let buffer = this
7850                .opened_buffers
7851                .get(&buffer_id)
7852                .and_then(|buffer| buffer.upgrade())
7853                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7854            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7855        })??;
7856
7857        let project_transaction = apply_code_action.await?;
7858        let project_transaction = this.update(&mut cx, |this, cx| {
7859            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7860        })?;
7861        Ok(proto::ApplyCodeActionResponse {
7862            transaction: Some(project_transaction),
7863        })
7864    }
7865
7866    async fn handle_on_type_formatting(
7867        this: Model<Self>,
7868        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7869        _: Arc<Client>,
7870        mut cx: AsyncAppContext,
7871    ) -> Result<proto::OnTypeFormattingResponse> {
7872        let on_type_formatting = this.update(&mut cx, |this, cx| {
7873            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7874            let buffer = this
7875                .opened_buffers
7876                .get(&buffer_id)
7877                .and_then(|buffer| buffer.upgrade())
7878                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7879            let position = envelope
7880                .payload
7881                .position
7882                .and_then(deserialize_anchor)
7883                .ok_or_else(|| anyhow!("invalid position"))?;
7884            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7885                buffer,
7886                position,
7887                envelope.payload.trigger.clone(),
7888                cx,
7889            ))
7890        })??;
7891
7892        let transaction = on_type_formatting
7893            .await?
7894            .as_ref()
7895            .map(language::proto::serialize_transaction);
7896        Ok(proto::OnTypeFormattingResponse { transaction })
7897    }
7898
7899    async fn handle_inlay_hints(
7900        this: Model<Self>,
7901        envelope: TypedEnvelope<proto::InlayHints>,
7902        _: Arc<Client>,
7903        mut cx: AsyncAppContext,
7904    ) -> Result<proto::InlayHintsResponse> {
7905        let sender_id = envelope.original_sender_id()?;
7906        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7907        let buffer = this.update(&mut cx, |this, _| {
7908            this.opened_buffers
7909                .get(&buffer_id)
7910                .and_then(|buffer| buffer.upgrade())
7911                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7912        })??;
7913        let buffer_version = deserialize_version(&envelope.payload.version);
7914
7915        buffer
7916            .update(&mut cx, |buffer, _| {
7917                buffer.wait_for_version(buffer_version.clone())
7918            })?
7919            .await
7920            .with_context(|| {
7921                format!(
7922                    "waiting for version {:?} for buffer {}",
7923                    buffer_version,
7924                    buffer.entity_id()
7925                )
7926            })?;
7927
7928        let start = envelope
7929            .payload
7930            .start
7931            .and_then(deserialize_anchor)
7932            .context("missing range start")?;
7933        let end = envelope
7934            .payload
7935            .end
7936            .and_then(deserialize_anchor)
7937            .context("missing range end")?;
7938        let buffer_hints = this
7939            .update(&mut cx, |project, cx| {
7940                project.inlay_hints(buffer, start..end, cx)
7941            })?
7942            .await
7943            .context("inlay hints fetch")?;
7944
7945        Ok(this.update(&mut cx, |project, cx| {
7946            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7947        })?)
7948    }
7949
7950    async fn handle_resolve_inlay_hint(
7951        this: Model<Self>,
7952        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7953        _: Arc<Client>,
7954        mut cx: AsyncAppContext,
7955    ) -> Result<proto::ResolveInlayHintResponse> {
7956        let proto_hint = envelope
7957            .payload
7958            .hint
7959            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7960        let hint = InlayHints::proto_to_project_hint(proto_hint)
7961            .context("resolved proto inlay hint conversion")?;
7962        let buffer = this.update(&mut cx, |this, _cx| {
7963            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7964            this.opened_buffers
7965                .get(&buffer_id)
7966                .and_then(|buffer| buffer.upgrade())
7967                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7968        })??;
7969        let response_hint = this
7970            .update(&mut cx, |project, cx| {
7971                project.resolve_inlay_hint(
7972                    hint,
7973                    buffer,
7974                    LanguageServerId(envelope.payload.language_server_id as usize),
7975                    cx,
7976                )
7977            })?
7978            .await
7979            .context("inlay hints fetch")?;
7980        Ok(proto::ResolveInlayHintResponse {
7981            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7982        })
7983    }
7984
7985    async fn handle_refresh_inlay_hints(
7986        this: Model<Self>,
7987        _: TypedEnvelope<proto::RefreshInlayHints>,
7988        _: Arc<Client>,
7989        mut cx: AsyncAppContext,
7990    ) -> Result<proto::Ack> {
7991        this.update(&mut cx, |_, cx| {
7992            cx.emit(Event::RefreshInlayHints);
7993        })?;
7994        Ok(proto::Ack {})
7995    }
7996
7997    async fn handle_lsp_command<T: LspCommand>(
7998        this: Model<Self>,
7999        envelope: TypedEnvelope<T::ProtoRequest>,
8000        _: Arc<Client>,
8001        mut cx: AsyncAppContext,
8002    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
8003    where
8004        <T::LspRequest as lsp::request::Request>::Params: Send,
8005        <T::LspRequest as lsp::request::Request>::Result: Send,
8006    {
8007        let sender_id = envelope.original_sender_id()?;
8008        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
8009        let buffer_handle = this.update(&mut cx, |this, _cx| {
8010            this.opened_buffers
8011                .get(&buffer_id)
8012                .and_then(|buffer| buffer.upgrade())
8013                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8014        })??;
8015        let request = T::from_proto(
8016            envelope.payload,
8017            this.clone(),
8018            buffer_handle.clone(),
8019            cx.clone(),
8020        )
8021        .await?;
8022        let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
8023        let response = this
8024            .update(&mut cx, |this, cx| {
8025                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
8026            })?
8027            .await?;
8028        this.update(&mut cx, |this, cx| {
8029            Ok(T::response_to_proto(
8030                response,
8031                this,
8032                sender_id,
8033                &buffer_version,
8034                cx,
8035            ))
8036        })?
8037    }
8038
8039    async fn handle_get_project_symbols(
8040        this: Model<Self>,
8041        envelope: TypedEnvelope<proto::GetProjectSymbols>,
8042        _: Arc<Client>,
8043        mut cx: AsyncAppContext,
8044    ) -> Result<proto::GetProjectSymbolsResponse> {
8045        let symbols = this
8046            .update(&mut cx, |this, cx| {
8047                this.symbols(&envelope.payload.query, cx)
8048            })?
8049            .await?;
8050
8051        Ok(proto::GetProjectSymbolsResponse {
8052            symbols: symbols.iter().map(serialize_symbol).collect(),
8053        })
8054    }
8055
8056    async fn handle_search_project(
8057        this: Model<Self>,
8058        envelope: TypedEnvelope<proto::SearchProject>,
8059        _: Arc<Client>,
8060        mut cx: AsyncAppContext,
8061    ) -> Result<proto::SearchProjectResponse> {
8062        let peer_id = envelope.original_sender_id()?;
8063        let query = SearchQuery::from_proto(envelope.payload)?;
8064        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
8065
8066        cx.spawn(move |mut cx| async move {
8067            let mut locations = Vec::new();
8068            while let Some((buffer, ranges)) = result.next().await {
8069                for range in ranges {
8070                    let start = serialize_anchor(&range.start);
8071                    let end = serialize_anchor(&range.end);
8072                    let buffer_id = this.update(&mut cx, |this, cx| {
8073                        this.create_buffer_for_peer(&buffer, peer_id, cx).into()
8074                    })?;
8075                    locations.push(proto::Location {
8076                        buffer_id,
8077                        start: Some(start),
8078                        end: Some(end),
8079                    });
8080                }
8081            }
8082            Ok(proto::SearchProjectResponse { locations })
8083        })
8084        .await
8085    }
8086
8087    async fn handle_open_buffer_for_symbol(
8088        this: Model<Self>,
8089        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8090        _: Arc<Client>,
8091        mut cx: AsyncAppContext,
8092    ) -> Result<proto::OpenBufferForSymbolResponse> {
8093        let peer_id = envelope.original_sender_id()?;
8094        let symbol = envelope
8095            .payload
8096            .symbol
8097            .ok_or_else(|| anyhow!("invalid symbol"))?;
8098        let symbol = this
8099            .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8100            .await?;
8101        let symbol = this.update(&mut cx, |this, _| {
8102            let signature = this.symbol_signature(&symbol.path);
8103            if signature == symbol.signature {
8104                Ok(symbol)
8105            } else {
8106                Err(anyhow!("invalid symbol signature"))
8107            }
8108        })??;
8109        let buffer = this
8110            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8111            .await?;
8112
8113        this.update(&mut cx, |this, cx| {
8114            let is_private = buffer
8115                .read(cx)
8116                .file()
8117                .map(|f| f.is_private())
8118                .unwrap_or_default();
8119            if is_private {
8120                Err(anyhow!(ErrorCode::UnsharedItem))
8121            } else {
8122                Ok(proto::OpenBufferForSymbolResponse {
8123                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8124                })
8125            }
8126        })?
8127    }
8128
8129    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8130        let mut hasher = Sha256::new();
8131        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8132        hasher.update(project_path.path.to_string_lossy().as_bytes());
8133        hasher.update(self.nonce.to_be_bytes());
8134        hasher.finalize().as_slice().try_into().unwrap()
8135    }
8136
8137    async fn handle_open_buffer_by_id(
8138        this: Model<Self>,
8139        envelope: TypedEnvelope<proto::OpenBufferById>,
8140        _: Arc<Client>,
8141        mut cx: AsyncAppContext,
8142    ) -> Result<proto::OpenBufferResponse> {
8143        let peer_id = envelope.original_sender_id()?;
8144        let buffer_id = BufferId::new(envelope.payload.id)?;
8145        let buffer = this
8146            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
8147            .await?;
8148        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8149    }
8150
8151    async fn handle_open_buffer_by_path(
8152        this: Model<Self>,
8153        envelope: TypedEnvelope<proto::OpenBufferByPath>,
8154        _: Arc<Client>,
8155        mut cx: AsyncAppContext,
8156    ) -> Result<proto::OpenBufferResponse> {
8157        let peer_id = envelope.original_sender_id()?;
8158        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8159        let open_buffer = this.update(&mut cx, |this, cx| {
8160            this.open_buffer(
8161                ProjectPath {
8162                    worktree_id,
8163                    path: PathBuf::from(envelope.payload.path).into(),
8164                },
8165                cx,
8166            )
8167        })?;
8168
8169        let buffer = open_buffer.await?;
8170        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8171    }
8172
8173    fn respond_to_open_buffer_request(
8174        this: Model<Self>,
8175        buffer: Model<Buffer>,
8176        peer_id: proto::PeerId,
8177        cx: &mut AsyncAppContext,
8178    ) -> Result<proto::OpenBufferResponse> {
8179        this.update(cx, |this, cx| {
8180            let is_private = buffer
8181                .read(cx)
8182                .file()
8183                .map(|f| f.is_private())
8184                .unwrap_or_default();
8185            if is_private {
8186                Err(anyhow!(ErrorCode::UnsharedItem))
8187            } else {
8188                Ok(proto::OpenBufferResponse {
8189                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8190                })
8191            }
8192        })?
8193    }
8194
8195    fn serialize_project_transaction_for_peer(
8196        &mut self,
8197        project_transaction: ProjectTransaction,
8198        peer_id: proto::PeerId,
8199        cx: &mut AppContext,
8200    ) -> proto::ProjectTransaction {
8201        let mut serialized_transaction = proto::ProjectTransaction {
8202            buffer_ids: Default::default(),
8203            transactions: Default::default(),
8204        };
8205        for (buffer, transaction) in project_transaction.0 {
8206            serialized_transaction
8207                .buffer_ids
8208                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
8209            serialized_transaction
8210                .transactions
8211                .push(language::proto::serialize_transaction(&transaction));
8212        }
8213        serialized_transaction
8214    }
8215
8216    fn deserialize_project_transaction(
8217        &mut self,
8218        message: proto::ProjectTransaction,
8219        push_to_history: bool,
8220        cx: &mut ModelContext<Self>,
8221    ) -> Task<Result<ProjectTransaction>> {
8222        cx.spawn(move |this, mut cx| async move {
8223            let mut project_transaction = ProjectTransaction::default();
8224            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8225            {
8226                let buffer_id = BufferId::new(buffer_id)?;
8227                let buffer = this
8228                    .update(&mut cx, |this, cx| {
8229                        this.wait_for_remote_buffer(buffer_id, cx)
8230                    })?
8231                    .await?;
8232                let transaction = language::proto::deserialize_transaction(transaction)?;
8233                project_transaction.0.insert(buffer, transaction);
8234            }
8235
8236            for (buffer, transaction) in &project_transaction.0 {
8237                buffer
8238                    .update(&mut cx, |buffer, _| {
8239                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8240                    })?
8241                    .await?;
8242
8243                if push_to_history {
8244                    buffer.update(&mut cx, |buffer, _| {
8245                        buffer.push_transaction(transaction.clone(), Instant::now());
8246                    })?;
8247                }
8248            }
8249
8250            Ok(project_transaction)
8251        })
8252    }
8253
8254    fn create_buffer_for_peer(
8255        &mut self,
8256        buffer: &Model<Buffer>,
8257        peer_id: proto::PeerId,
8258        cx: &mut AppContext,
8259    ) -> BufferId {
8260        let buffer_id = buffer.read(cx).remote_id();
8261        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8262            updates_tx
8263                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8264                .ok();
8265        }
8266        buffer_id
8267    }
8268
8269    fn wait_for_remote_buffer(
8270        &mut self,
8271        id: BufferId,
8272        cx: &mut ModelContext<Self>,
8273    ) -> Task<Result<Model<Buffer>>> {
8274        let mut opened_buffer_rx = self.opened_buffer.1.clone();
8275
8276        cx.spawn(move |this, mut cx| async move {
8277            let buffer = loop {
8278                let Some(this) = this.upgrade() else {
8279                    return Err(anyhow!("project dropped"));
8280                };
8281
8282                let buffer = this.update(&mut cx, |this, _cx| {
8283                    this.opened_buffers
8284                        .get(&id)
8285                        .and_then(|buffer| buffer.upgrade())
8286                })?;
8287
8288                if let Some(buffer) = buffer {
8289                    break buffer;
8290                } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8291                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
8292                }
8293
8294                this.update(&mut cx, |this, _| {
8295                    this.incomplete_remote_buffers.entry(id).or_default();
8296                })?;
8297                drop(this);
8298
8299                opened_buffer_rx
8300                    .next()
8301                    .await
8302                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8303            };
8304
8305            Ok(buffer)
8306        })
8307    }
8308
8309    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8310        let project_id = match self.client_state {
8311            ProjectClientState::Remote {
8312                sharing_has_stopped,
8313                remote_id,
8314                ..
8315            } => {
8316                if sharing_has_stopped {
8317                    return Task::ready(Err(anyhow!(
8318                        "can't synchronize remote buffers on a readonly project"
8319                    )));
8320                } else {
8321                    remote_id
8322                }
8323            }
8324            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8325                return Task::ready(Err(anyhow!(
8326                    "can't synchronize remote buffers on a local project"
8327                )))
8328            }
8329        };
8330
8331        let client = self.client.clone();
8332        cx.spawn(move |this, mut cx| async move {
8333            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8334                let buffers = this
8335                    .opened_buffers
8336                    .iter()
8337                    .filter_map(|(id, buffer)| {
8338                        let buffer = buffer.upgrade()?;
8339                        Some(proto::BufferVersion {
8340                            id: (*id).into(),
8341                            version: language::proto::serialize_version(&buffer.read(cx).version),
8342                        })
8343                    })
8344                    .collect();
8345                let incomplete_buffer_ids = this
8346                    .incomplete_remote_buffers
8347                    .keys()
8348                    .copied()
8349                    .collect::<Vec<_>>();
8350
8351                (buffers, incomplete_buffer_ids)
8352            })?;
8353            let response = client
8354                .request(proto::SynchronizeBuffers {
8355                    project_id,
8356                    buffers,
8357                })
8358                .await?;
8359
8360            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8361                response
8362                    .buffers
8363                    .into_iter()
8364                    .map(|buffer| {
8365                        let client = client.clone();
8366                        let buffer_id = match BufferId::new(buffer.id) {
8367                            Ok(id) => id,
8368                            Err(e) => {
8369                                return Task::ready(Err(e));
8370                            }
8371                        };
8372                        let remote_version = language::proto::deserialize_version(&buffer.version);
8373                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
8374                            let operations =
8375                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
8376                            cx.background_executor().spawn(async move {
8377                                let operations = operations.await;
8378                                for chunk in split_operations(operations) {
8379                                    client
8380                                        .request(proto::UpdateBuffer {
8381                                            project_id,
8382                                            buffer_id: buffer_id.into(),
8383                                            operations: chunk,
8384                                        })
8385                                        .await?;
8386                                }
8387                                anyhow::Ok(())
8388                            })
8389                        } else {
8390                            Task::ready(Ok(()))
8391                        }
8392                    })
8393                    .collect::<Vec<_>>()
8394            })?;
8395
8396            // Any incomplete buffers have open requests waiting. Request that the host sends
8397            // creates these buffers for us again to unblock any waiting futures.
8398            for id in incomplete_buffer_ids {
8399                cx.background_executor()
8400                    .spawn(client.request(proto::OpenBufferById {
8401                        project_id,
8402                        id: id.into(),
8403                    }))
8404                    .detach();
8405            }
8406
8407            futures::future::join_all(send_updates_for_buffers)
8408                .await
8409                .into_iter()
8410                .collect()
8411        })
8412    }
8413
8414    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8415        self.worktrees()
8416            .map(|worktree| {
8417                let worktree = worktree.read(cx);
8418                proto::WorktreeMetadata {
8419                    id: worktree.id().to_proto(),
8420                    root_name: worktree.root_name().into(),
8421                    visible: worktree.is_visible(),
8422                    abs_path: worktree.abs_path().to_string_lossy().into(),
8423                }
8424            })
8425            .collect()
8426    }
8427
8428    fn set_worktrees_from_proto(
8429        &mut self,
8430        worktrees: Vec<proto::WorktreeMetadata>,
8431        cx: &mut ModelContext<Project>,
8432    ) -> Result<()> {
8433        let replica_id = self.replica_id();
8434        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8435
8436        let mut old_worktrees_by_id = self
8437            .worktrees
8438            .drain(..)
8439            .filter_map(|worktree| {
8440                let worktree = worktree.upgrade()?;
8441                Some((worktree.read(cx).id(), worktree))
8442            })
8443            .collect::<HashMap<_, _>>();
8444
8445        for worktree in worktrees {
8446            if let Some(old_worktree) =
8447                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8448            {
8449                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8450            } else {
8451                let worktree =
8452                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8453                let _ = self.add_worktree(&worktree, cx);
8454            }
8455        }
8456
8457        self.metadata_changed(cx);
8458        for id in old_worktrees_by_id.keys() {
8459            cx.emit(Event::WorktreeRemoved(*id));
8460        }
8461
8462        Ok(())
8463    }
8464
8465    fn set_collaborators_from_proto(
8466        &mut self,
8467        messages: Vec<proto::Collaborator>,
8468        cx: &mut ModelContext<Self>,
8469    ) -> Result<()> {
8470        let mut collaborators = HashMap::default();
8471        for message in messages {
8472            let collaborator = Collaborator::from_proto(message)?;
8473            collaborators.insert(collaborator.peer_id, collaborator);
8474        }
8475        for old_peer_id in self.collaborators.keys() {
8476            if !collaborators.contains_key(old_peer_id) {
8477                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8478            }
8479        }
8480        self.collaborators = collaborators;
8481        Ok(())
8482    }
8483
8484    fn deserialize_symbol(
8485        &self,
8486        serialized_symbol: proto::Symbol,
8487    ) -> impl Future<Output = Result<Symbol>> {
8488        let languages = self.languages.clone();
8489        async move {
8490            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8491            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8492            let start = serialized_symbol
8493                .start
8494                .ok_or_else(|| anyhow!("invalid start"))?;
8495            let end = serialized_symbol
8496                .end
8497                .ok_or_else(|| anyhow!("invalid end"))?;
8498            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8499            let path = ProjectPath {
8500                worktree_id,
8501                path: PathBuf::from(serialized_symbol.path).into(),
8502            };
8503            let language = languages
8504                .language_for_file(&path.path, None)
8505                .await
8506                .log_err();
8507            Ok(Symbol {
8508                language_server_name: LanguageServerName(
8509                    serialized_symbol.language_server_name.into(),
8510                ),
8511                source_worktree_id,
8512                path,
8513                label: {
8514                    match language {
8515                        Some(language) => {
8516                            language
8517                                .label_for_symbol(&serialized_symbol.name, kind)
8518                                .await
8519                        }
8520                        None => None,
8521                    }
8522                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8523                },
8524
8525                name: serialized_symbol.name,
8526                range: Unclipped(PointUtf16::new(start.row, start.column))
8527                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8528                kind,
8529                signature: serialized_symbol
8530                    .signature
8531                    .try_into()
8532                    .map_err(|_| anyhow!("invalid signature"))?,
8533            })
8534        }
8535    }
8536
8537    async fn handle_buffer_saved(
8538        this: Model<Self>,
8539        envelope: TypedEnvelope<proto::BufferSaved>,
8540        _: Arc<Client>,
8541        mut cx: AsyncAppContext,
8542    ) -> Result<()> {
8543        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8544        let version = deserialize_version(&envelope.payload.version);
8545        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8546        let mtime = envelope
8547            .payload
8548            .mtime
8549            .ok_or_else(|| anyhow!("missing mtime"))?
8550            .into();
8551
8552        this.update(&mut cx, |this, cx| {
8553            let buffer = this
8554                .opened_buffers
8555                .get(&buffer_id)
8556                .and_then(|buffer| buffer.upgrade())
8557                .or_else(|| {
8558                    this.incomplete_remote_buffers
8559                        .get(&buffer_id)
8560                        .and_then(|b| b.clone())
8561                });
8562            if let Some(buffer) = buffer {
8563                buffer.update(cx, |buffer, cx| {
8564                    buffer.did_save(version, fingerprint, mtime, cx);
8565                });
8566            }
8567            Ok(())
8568        })?
8569    }
8570
8571    async fn handle_buffer_reloaded(
8572        this: Model<Self>,
8573        envelope: TypedEnvelope<proto::BufferReloaded>,
8574        _: Arc<Client>,
8575        mut cx: AsyncAppContext,
8576    ) -> Result<()> {
8577        let payload = envelope.payload;
8578        let version = deserialize_version(&payload.version);
8579        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8580        let line_ending = deserialize_line_ending(
8581            proto::LineEnding::from_i32(payload.line_ending)
8582                .ok_or_else(|| anyhow!("missing line ending"))?,
8583        );
8584        let mtime = payload
8585            .mtime
8586            .ok_or_else(|| anyhow!("missing mtime"))?
8587            .into();
8588        let buffer_id = BufferId::new(payload.buffer_id)?;
8589        this.update(&mut cx, |this, cx| {
8590            let buffer = this
8591                .opened_buffers
8592                .get(&buffer_id)
8593                .and_then(|buffer| buffer.upgrade())
8594                .or_else(|| {
8595                    this.incomplete_remote_buffers
8596                        .get(&buffer_id)
8597                        .cloned()
8598                        .flatten()
8599                });
8600            if let Some(buffer) = buffer {
8601                buffer.update(cx, |buffer, cx| {
8602                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8603                });
8604            }
8605            Ok(())
8606        })?
8607    }
8608
8609    #[allow(clippy::type_complexity)]
8610    fn edits_from_lsp(
8611        &mut self,
8612        buffer: &Model<Buffer>,
8613        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8614        server_id: LanguageServerId,
8615        version: Option<i32>,
8616        cx: &mut ModelContext<Self>,
8617    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8618        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8619        cx.background_executor().spawn(async move {
8620            let snapshot = snapshot?;
8621            let mut lsp_edits = lsp_edits
8622                .into_iter()
8623                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8624                .collect::<Vec<_>>();
8625            lsp_edits.sort_by_key(|(range, _)| range.start);
8626
8627            let mut lsp_edits = lsp_edits.into_iter().peekable();
8628            let mut edits = Vec::new();
8629            while let Some((range, mut new_text)) = lsp_edits.next() {
8630                // Clip invalid ranges provided by the language server.
8631                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8632                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8633
8634                // Combine any LSP edits that are adjacent.
8635                //
8636                // Also, combine LSP edits that are separated from each other by only
8637                // a newline. This is important because for some code actions,
8638                // Rust-analyzer rewrites the entire buffer via a series of edits that
8639                // are separated by unchanged newline characters.
8640                //
8641                // In order for the diffing logic below to work properly, any edits that
8642                // cancel each other out must be combined into one.
8643                while let Some((next_range, next_text)) = lsp_edits.peek() {
8644                    if next_range.start.0 > range.end {
8645                        if next_range.start.0.row > range.end.row + 1
8646                            || next_range.start.0.column > 0
8647                            || snapshot.clip_point_utf16(
8648                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8649                                Bias::Left,
8650                            ) > range.end
8651                        {
8652                            break;
8653                        }
8654                        new_text.push('\n');
8655                    }
8656                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8657                    new_text.push_str(next_text);
8658                    lsp_edits.next();
8659                }
8660
8661                // For multiline edits, perform a diff of the old and new text so that
8662                // we can identify the changes more precisely, preserving the locations
8663                // of any anchors positioned in the unchanged regions.
8664                if range.end.row > range.start.row {
8665                    let mut offset = range.start.to_offset(&snapshot);
8666                    let old_text = snapshot.text_for_range(range).collect::<String>();
8667
8668                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8669                    let mut moved_since_edit = true;
8670                    for change in diff.iter_all_changes() {
8671                        let tag = change.tag();
8672                        let value = change.value();
8673                        match tag {
8674                            ChangeTag::Equal => {
8675                                offset += value.len();
8676                                moved_since_edit = true;
8677                            }
8678                            ChangeTag::Delete => {
8679                                let start = snapshot.anchor_after(offset);
8680                                let end = snapshot.anchor_before(offset + value.len());
8681                                if moved_since_edit {
8682                                    edits.push((start..end, String::new()));
8683                                } else {
8684                                    edits.last_mut().unwrap().0.end = end;
8685                                }
8686                                offset += value.len();
8687                                moved_since_edit = false;
8688                            }
8689                            ChangeTag::Insert => {
8690                                if moved_since_edit {
8691                                    let anchor = snapshot.anchor_after(offset);
8692                                    edits.push((anchor..anchor, value.to_string()));
8693                                } else {
8694                                    edits.last_mut().unwrap().1.push_str(value);
8695                                }
8696                                moved_since_edit = false;
8697                            }
8698                        }
8699                    }
8700                } else if range.end == range.start {
8701                    let anchor = snapshot.anchor_after(range.start);
8702                    edits.push((anchor..anchor, new_text));
8703                } else {
8704                    let edit_start = snapshot.anchor_after(range.start);
8705                    let edit_end = snapshot.anchor_before(range.end);
8706                    edits.push((edit_start..edit_end, new_text));
8707                }
8708            }
8709
8710            Ok(edits)
8711        })
8712    }
8713
8714    fn buffer_snapshot_for_lsp_version(
8715        &mut self,
8716        buffer: &Model<Buffer>,
8717        server_id: LanguageServerId,
8718        version: Option<i32>,
8719        cx: &AppContext,
8720    ) -> Result<TextBufferSnapshot> {
8721        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8722
8723        if let Some(version) = version {
8724            let buffer_id = buffer.read(cx).remote_id();
8725            let snapshots = self
8726                .buffer_snapshots
8727                .get_mut(&buffer_id)
8728                .and_then(|m| m.get_mut(&server_id))
8729                .ok_or_else(|| {
8730                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8731                })?;
8732
8733            let found_snapshot = snapshots
8734                .binary_search_by_key(&version, |e| e.version)
8735                .map(|ix| snapshots[ix].snapshot.clone())
8736                .map_err(|_| {
8737                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8738                })?;
8739
8740            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8741            Ok(found_snapshot)
8742        } else {
8743            Ok((buffer.read(cx)).text_snapshot())
8744        }
8745    }
8746
8747    pub fn language_servers(
8748        &self,
8749    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8750        self.language_server_ids
8751            .iter()
8752            .map(|((worktree_id, server_name), server_id)| {
8753                (*server_id, server_name.clone(), *worktree_id)
8754            })
8755    }
8756
8757    pub fn supplementary_language_servers(
8758        &self,
8759    ) -> impl '_
8760           + Iterator<
8761        Item = (
8762            &LanguageServerId,
8763            &(LanguageServerName, Arc<LanguageServer>),
8764        ),
8765    > {
8766        self.supplementary_language_servers.iter()
8767    }
8768
8769    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8770        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8771            Some(server.clone())
8772        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8773            Some(Arc::clone(server))
8774        } else {
8775            None
8776        }
8777    }
8778
8779    pub fn language_servers_for_buffer(
8780        &self,
8781        buffer: &Buffer,
8782        cx: &AppContext,
8783    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8784        self.language_server_ids_for_buffer(buffer, cx)
8785            .into_iter()
8786            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8787                LanguageServerState::Running {
8788                    adapter, server, ..
8789                } => Some((adapter, server)),
8790                _ => None,
8791            })
8792    }
8793
8794    fn primary_language_server_for_buffer(
8795        &self,
8796        buffer: &Buffer,
8797        cx: &AppContext,
8798    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8799        self.language_servers_for_buffer(buffer, cx).next()
8800    }
8801
8802    pub fn language_server_for_buffer(
8803        &self,
8804        buffer: &Buffer,
8805        server_id: LanguageServerId,
8806        cx: &AppContext,
8807    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8808        self.language_servers_for_buffer(buffer, cx)
8809            .find(|(_, s)| s.server_id() == server_id)
8810    }
8811
8812    fn language_server_ids_for_buffer(
8813        &self,
8814        buffer: &Buffer,
8815        cx: &AppContext,
8816    ) -> Vec<LanguageServerId> {
8817        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8818            let worktree_id = file.worktree_id(cx);
8819            language
8820                .lsp_adapters()
8821                .iter()
8822                .flat_map(|adapter| {
8823                    let key = (worktree_id, adapter.name.clone());
8824                    self.language_server_ids.get(&key).copied()
8825                })
8826                .collect()
8827        } else {
8828            Vec::new()
8829        }
8830    }
8831}
8832
8833fn subscribe_for_copilot_events(
8834    copilot: &Model<Copilot>,
8835    cx: &mut ModelContext<'_, Project>,
8836) -> gpui::Subscription {
8837    cx.subscribe(
8838        copilot,
8839        |project, copilot, copilot_event, cx| match copilot_event {
8840            copilot::Event::CopilotLanguageServerStarted => {
8841                match copilot.read(cx).language_server() {
8842                    Some((name, copilot_server)) => {
8843                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8844                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8845                            let new_server_id = copilot_server.server_id();
8846                            let weak_project = cx.weak_model();
8847                            let copilot_log_subscription = copilot_server
8848                                .on_notification::<copilot::request::LogMessage, _>(
8849                                    move |params, mut cx| {
8850                                        weak_project.update(&mut cx, |_, cx| {
8851                                            cx.emit(Event::LanguageServerLog(
8852                                                new_server_id,
8853                                                params.message,
8854                                            ));
8855                                        }).ok();
8856                                    },
8857                                );
8858                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8859                            project.copilot_log_subscription = Some(copilot_log_subscription);
8860                            cx.emit(Event::LanguageServerAdded(new_server_id));
8861                        }
8862                    }
8863                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8864                }
8865            }
8866        },
8867    )
8868}
8869
8870fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8871    let mut literal_end = 0;
8872    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8873        if part.contains(&['*', '?', '{', '}']) {
8874            break;
8875        } else {
8876            if i > 0 {
8877                // Account for separator prior to this part
8878                literal_end += path::MAIN_SEPARATOR.len_utf8();
8879            }
8880            literal_end += part.len();
8881        }
8882    }
8883    &glob[..literal_end]
8884}
8885
8886impl WorktreeHandle {
8887    pub fn upgrade(&self) -> Option<Model<Worktree>> {
8888        match self {
8889            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8890            WorktreeHandle::Weak(handle) => handle.upgrade(),
8891        }
8892    }
8893
8894    pub fn handle_id(&self) -> usize {
8895        match self {
8896            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
8897            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
8898        }
8899    }
8900}
8901
8902impl OpenBuffer {
8903    pub fn upgrade(&self) -> Option<Model<Buffer>> {
8904        match self {
8905            OpenBuffer::Strong(handle) => Some(handle.clone()),
8906            OpenBuffer::Weak(handle) => handle.upgrade(),
8907            OpenBuffer::Operations(_) => None,
8908        }
8909    }
8910}
8911
8912pub struct PathMatchCandidateSet {
8913    pub snapshot: Snapshot,
8914    pub include_ignored: bool,
8915    pub include_root_name: bool,
8916}
8917
8918impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8919    type Candidates = PathMatchCandidateSetIter<'a>;
8920
8921    fn id(&self) -> usize {
8922        self.snapshot.id().to_usize()
8923    }
8924
8925    fn len(&self) -> usize {
8926        if self.include_ignored {
8927            self.snapshot.file_count()
8928        } else {
8929            self.snapshot.visible_file_count()
8930        }
8931    }
8932
8933    fn prefix(&self) -> Arc<str> {
8934        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8935            self.snapshot.root_name().into()
8936        } else if self.include_root_name {
8937            format!("{}/", self.snapshot.root_name()).into()
8938        } else {
8939            "".into()
8940        }
8941    }
8942
8943    fn candidates(&'a self, start: usize) -> Self::Candidates {
8944        PathMatchCandidateSetIter {
8945            traversal: self.snapshot.files(self.include_ignored, start),
8946        }
8947    }
8948}
8949
8950pub struct PathMatchCandidateSetIter<'a> {
8951    traversal: Traversal<'a>,
8952}
8953
8954impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8955    type Item = fuzzy::PathMatchCandidate<'a>;
8956
8957    fn next(&mut self) -> Option<Self::Item> {
8958        self.traversal.next().map(|entry| {
8959            if let EntryKind::File(char_bag) = entry.kind {
8960                fuzzy::PathMatchCandidate {
8961                    path: &entry.path,
8962                    char_bag,
8963                }
8964            } else {
8965                unreachable!()
8966            }
8967        })
8968    }
8969}
8970
8971impl EventEmitter<Event> for Project {}
8972
8973impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8974    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8975        Self {
8976            worktree_id,
8977            path: path.as_ref().into(),
8978        }
8979    }
8980}
8981
8982impl ProjectLspAdapterDelegate {
8983    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8984        Arc::new(Self {
8985            project: cx.handle(),
8986            http_client: project.client.http_client(),
8987        })
8988    }
8989}
8990
8991impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8992    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8993        self.project
8994            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8995    }
8996
8997    fn http_client(&self) -> Arc<dyn HttpClient> {
8998        self.http_client.clone()
8999    }
9000}
9001
9002fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9003    proto::Symbol {
9004        language_server_name: symbol.language_server_name.0.to_string(),
9005        source_worktree_id: symbol.source_worktree_id.to_proto(),
9006        worktree_id: symbol.path.worktree_id.to_proto(),
9007        path: symbol.path.path.to_string_lossy().to_string(),
9008        name: symbol.name.clone(),
9009        kind: unsafe { mem::transmute(symbol.kind) },
9010        start: Some(proto::PointUtf16 {
9011            row: symbol.range.start.0.row,
9012            column: symbol.range.start.0.column,
9013        }),
9014        end: Some(proto::PointUtf16 {
9015            row: symbol.range.end.0.row,
9016            column: symbol.range.end.0.column,
9017        }),
9018        signature: symbol.signature.to_vec(),
9019    }
9020}
9021
9022fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9023    let mut path_components = path.components();
9024    let mut base_components = base.components();
9025    let mut components: Vec<Component> = Vec::new();
9026    loop {
9027        match (path_components.next(), base_components.next()) {
9028            (None, None) => break,
9029            (Some(a), None) => {
9030                components.push(a);
9031                components.extend(path_components.by_ref());
9032                break;
9033            }
9034            (None, _) => components.push(Component::ParentDir),
9035            (Some(a), Some(b)) if components.is_empty() && a == b => (),
9036            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
9037            (Some(a), Some(_)) => {
9038                components.push(Component::ParentDir);
9039                for _ in base_components {
9040                    components.push(Component::ParentDir);
9041                }
9042                components.push(a);
9043                components.extend(path_components.by_ref());
9044                break;
9045            }
9046        }
9047    }
9048    components.iter().map(|c| c.as_os_str()).collect()
9049}
9050
9051fn resolve_path(base: &Path, path: &Path) -> PathBuf {
9052    let mut result = base.to_path_buf();
9053    for component in path.components() {
9054        match component {
9055            Component::ParentDir => {
9056                result.pop();
9057            }
9058            Component::CurDir => (),
9059            _ => result.push(component),
9060        }
9061    }
9062    result
9063}
9064
9065impl Item for Buffer {
9066    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9067        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9068    }
9069
9070    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9071        File::from_dyn(self.file()).map(|file| ProjectPath {
9072            worktree_id: file.worktree_id(cx),
9073            path: file.path().clone(),
9074        })
9075    }
9076}
9077
9078async fn wait_for_loading_buffer(
9079    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
9080) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
9081    loop {
9082        if let Some(result) = receiver.borrow().as_ref() {
9083            match result {
9084                Ok(buffer) => return Ok(buffer.to_owned()),
9085                Err(e) => return Err(e.to_owned()),
9086            }
9087        }
9088        receiver.next().await;
9089    }
9090}
9091
9092fn include_text(server: &lsp::LanguageServer) -> bool {
9093    server
9094        .capabilities()
9095        .text_document_sync
9096        .as_ref()
9097        .and_then(|sync| match sync {
9098            lsp::TextDocumentSyncCapability::Kind(_) => None,
9099            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9100        })
9101        .and_then(|save_options| match save_options {
9102            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9103            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9104        })
9105        .unwrap_or(false)
9106}