project.rs

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