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