project.rs

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