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