project.rs

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