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