project2.rs

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