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