project.rs

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