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