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