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