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