project.rs

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