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