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