project.rs

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