project.rs

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