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