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