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