project.rs

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