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