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