project.rs

    1pub mod connection_manager;
    2pub mod debounced_delay;
    3pub mod lsp_command;
    4pub mod lsp_ext_command;
    5mod prettier_support;
    6pub mod project_settings;
    7pub mod search;
    8mod task_inventory;
    9pub mod terminals;
   10
   11#[cfg(test)]
   12mod project_tests;
   13pub mod search_history;
   14
   15use anyhow::{anyhow, bail, Context as _, Result};
   16use async_trait::async_trait;
   17use client::{
   18    proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
   19    TypedEnvelope, UserStore,
   20};
   21use clock::ReplicaId;
   22use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
   23use debounced_delay::DebouncedDelay;
   24use futures::{
   25    channel::{
   26        mpsc::{self, UnboundedReceiver},
   27        oneshot,
   28    },
   29    future::{join_all, try_join_all, Shared},
   30    select,
   31    stream::FuturesUnordered,
   32    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
   33};
   34use fuzzy::CharBag;
   35use git::{blame::Blame, repository::GitRepository};
   36use globset::{Glob, GlobSet, GlobSetBuilder};
   37use gpui::{
   38    AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, BorrowAppContext, Context, Entity,
   39    EventEmitter, Model, ModelContext, PromptLevel, Task, WeakModel,
   40};
   41use itertools::Itertools;
   42use language::{
   43    language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
   44    markdown, point_to_lsp, prepare_completion_documentation,
   45    proto::{
   46        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
   47        serialize_version, split_operations,
   48    },
   49    range_from_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability, CodeLabel,
   50    Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Documentation, Event as BufferEvent,
   51    File as _, Language, LanguageRegistry, LanguageServerName, LocalFile, LspAdapterDelegate,
   52    Operation, Patch, PendingLanguageServer, PointUtf16, TextBufferSnapshot, ToOffset,
   53    ToPointUtf16, Transaction, Unclipped,
   54};
   55use log::error;
   56use lsp::{
   57    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
   58    DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId,
   59    LspRequestFuture, MessageActionItem, OneOf, ServerCapabilities, ServerHealthStatus,
   60    ServerStatus,
   61};
   62use lsp_command::*;
   63use node_runtime::NodeRuntime;
   64use parking_lot::{Mutex, RwLock};
   65use postage::watch;
   66use prettier_support::{DefaultPrettier, PrettierInstance};
   67use project_settings::{LspSettings, ProjectSettings};
   68use rand::prelude::*;
   69use search_history::SearchHistory;
   70use worktree::LocalSnapshot;
   71
   72use rpc::{ErrorCode, ErrorExt as _};
   73use search::SearchQuery;
   74use serde::Serialize;
   75use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
   76use sha2::{Digest, Sha256};
   77use similar::{ChangeTag, TextDiff};
   78use smol::channel::{Receiver, Sender};
   79use smol::lock::Semaphore;
   80use std::{
   81    cmp::{self, Ordering},
   82    convert::TryInto,
   83    env,
   84    ffi::OsStr,
   85    hash::Hash,
   86    io, iter, mem,
   87    num::NonZeroU32,
   88    ops::Range,
   89    path::{self, Component, Path, PathBuf},
   90    process::Stdio,
   91    str::{self, FromStr},
   92    sync::{
   93        atomic::{AtomicUsize, Ordering::SeqCst},
   94        Arc,
   95    },
   96    time::{Duration, Instant},
   97};
   98use task::static_source::{StaticSource, TrackedFile};
   99use terminals::Terminals;
  100use text::{Anchor, BufferId, LineEnding};
  101use util::{
  102    debug_panic, defer,
  103    http::{HttpClient, Url},
  104    maybe, merge_json_value_into, parse_env_output,
  105    paths::{
  106        LOCAL_SETTINGS_RELATIVE_PATH, LOCAL_TASKS_RELATIVE_PATH, LOCAL_VSCODE_TASKS_RELATIVE_PATH,
  107    },
  108    post_inc, ResultExt, TryFutureExt as _,
  109};
  110use worktree::{Snapshot, Traversal};
  111
  112pub use fs::*;
  113pub use language::Location;
  114#[cfg(any(test, feature = "test-support"))]
  115pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  116pub use task_inventory::{Inventory, TaskSourceKind};
  117pub use worktree::{
  118    DiagnosticSummary, Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId,
  119    RepositoryEntry, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId,
  120    WorktreeSettings, FS_WATCH_LATENCY,
  121};
  122
  123const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  124const SERVER_REINSTALL_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  125const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
  126pub const SERVER_PROGRESS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  127
  128const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
  129
  130pub trait Item {
  131    fn try_open(
  132        project: &Model<Project>,
  133        path: &ProjectPath,
  134        cx: &mut AppContext,
  135    ) -> Option<Task<Result<Model<Self>>>>
  136    where
  137        Self: Sized;
  138    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  139    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
  140}
  141
  142#[derive(Clone)]
  143pub enum OpenedBufferEvent {
  144    Disconnected,
  145    Ok(BufferId),
  146    Err(BufferId, Arc<anyhow::Error>),
  147}
  148
  149/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
  150/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
  151/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
  152///
  153/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
  154pub struct Project {
  155    worktrees: Vec<WorktreeHandle>,
  156    active_entry: Option<ProjectEntryId>,
  157    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
  158    pending_language_server_update: Option<BufferOrderedMessage>,
  159    flush_language_server_update: Option<Task<()>>,
  160
  161    languages: Arc<LanguageRegistry>,
  162    supplementary_language_servers:
  163        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
  164    language_servers: HashMap<LanguageServerId, LanguageServerState>,
  165    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
  166    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
  167    last_formatting_failure: Option<String>,
  168    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
  169    language_server_watched_paths: HashMap<LanguageServerId, HashMap<WorktreeId, GlobSet>>,
  170    client: Arc<client::Client>,
  171    next_entry_id: Arc<AtomicUsize>,
  172    join_project_response_message_id: u32,
  173    next_diagnostic_group_id: usize,
  174    user_store: Model<UserStore>,
  175    fs: Arc<dyn Fs>,
  176    client_state: ProjectClientState,
  177    collaborators: HashMap<proto::PeerId, Collaborator>,
  178    client_subscriptions: Vec<client::Subscription>,
  179    _subscriptions: Vec<gpui::Subscription>,
  180    loading_buffers: HashMap<BufferId, Vec<oneshot::Sender<Result<Model<Buffer>, anyhow::Error>>>>,
  181    incomplete_remote_buffers: HashMap<BufferId, Model<Buffer>>,
  182    shared_buffers: HashMap<proto::PeerId, HashSet<BufferId>>,
  183    #[allow(clippy::type_complexity)]
  184    loading_buffers_by_path: HashMap<
  185        ProjectPath,
  186        postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
  187    >,
  188    #[allow(clippy::type_complexity)]
  189    loading_local_worktrees:
  190        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
  191    opened_buffers: HashMap<BufferId, OpenBuffer>,
  192    local_buffer_ids_by_path: HashMap<ProjectPath, BufferId>,
  193    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  194    buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
  195    buffers_being_formatted: HashSet<BufferId>,
  196    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
  197    git_diff_debouncer: DebouncedDelay,
  198    nonce: u128,
  199    _maintain_buffer_languages: Task<()>,
  200    _maintain_workspace_config: Task<Result<()>>,
  201    terminals: Terminals,
  202    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
  203    node: Option<Arc<dyn NodeRuntime>>,
  204    default_prettier: DefaultPrettier,
  205    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
  206    prettier_instances: HashMap<PathBuf, PrettierInstance>,
  207    tasks: Model<Inventory>,
  208    hosted_project_id: Option<ProjectId>,
  209    dev_server_project_id: Option<client::DevServerProjectId>,
  210    search_history: SearchHistory,
  211}
  212
  213pub enum LanguageServerToQuery {
  214    Primary,
  215    Other(LanguageServerId),
  216}
  217
  218struct LspBufferSnapshot {
  219    version: i32,
  220    snapshot: TextBufferSnapshot,
  221}
  222
  223/// Message ordered with respect to buffer operations
  224#[derive(Debug)]
  225enum BufferOrderedMessage {
  226    Operation {
  227        buffer_id: BufferId,
  228        operation: proto::Operation,
  229    },
  230    LanguageServerUpdate {
  231        language_server_id: LanguageServerId,
  232        message: proto::update_language_server::Variant,
  233    },
  234    Resync,
  235}
  236
  237#[derive(Debug)]
  238enum LocalProjectUpdate {
  239    WorktreesChanged,
  240    CreateBufferForPeer {
  241        peer_id: proto::PeerId,
  242        buffer_id: BufferId,
  243    },
  244}
  245
  246enum OpenBuffer {
  247    Strong(Model<Buffer>),
  248    Weak(WeakModel<Buffer>),
  249    Operations(Vec<Operation>),
  250}
  251
  252#[derive(Clone)]
  253enum WorktreeHandle {
  254    Strong(Model<Worktree>),
  255    Weak(WeakModel<Worktree>),
  256}
  257
  258#[derive(Debug)]
  259enum ProjectClientState {
  260    Local,
  261    Shared {
  262        remote_id: u64,
  263        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
  264        _send_updates: Task<Result<()>>,
  265    },
  266    Remote {
  267        sharing_has_stopped: bool,
  268        capability: Capability,
  269        remote_id: u64,
  270        replica_id: ReplicaId,
  271        in_room: bool,
  272    },
  273}
  274
  275/// A prompt requested by LSP server.
  276#[derive(Clone, Debug)]
  277pub struct LanguageServerPromptRequest {
  278    pub level: PromptLevel,
  279    pub message: String,
  280    pub actions: Vec<MessageActionItem>,
  281    pub lsp_name: String,
  282    response_channel: Sender<MessageActionItem>,
  283}
  284
  285impl LanguageServerPromptRequest {
  286    pub async fn respond(self, index: usize) -> Option<()> {
  287        if let Some(response) = self.actions.into_iter().nth(index) {
  288            self.response_channel.send(response).await.ok()
  289        } else {
  290            None
  291        }
  292    }
  293}
  294impl PartialEq for LanguageServerPromptRequest {
  295    fn eq(&self, other: &Self) -> bool {
  296        self.message == other.message && self.actions == other.actions
  297    }
  298}
  299
  300#[derive(Clone, Debug, PartialEq)]
  301pub enum Event {
  302    LanguageServerAdded(LanguageServerId),
  303    LanguageServerRemoved(LanguageServerId),
  304    LanguageServerLog(LanguageServerId, String),
  305    Notification(String),
  306    LanguageServerPrompt(LanguageServerPromptRequest),
  307    LanguageNotFound(Model<Buffer>),
  308    ActiveEntryChanged(Option<ProjectEntryId>),
  309    ActivateProjectPanel,
  310    WorktreeAdded,
  311    WorktreeRemoved(WorktreeId),
  312    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
  313    WorktreeUpdatedGitRepositories,
  314    DiskBasedDiagnosticsStarted {
  315        language_server_id: LanguageServerId,
  316    },
  317    DiskBasedDiagnosticsFinished {
  318        language_server_id: LanguageServerId,
  319    },
  320    DiagnosticsUpdated {
  321        path: ProjectPath,
  322        language_server_id: LanguageServerId,
  323    },
  324    RemoteIdChanged(Option<u64>),
  325    DisconnectedFromHost,
  326    Closed,
  327    DeletedEntry(ProjectEntryId),
  328    CollaboratorUpdated {
  329        old_peer_id: proto::PeerId,
  330        new_peer_id: proto::PeerId,
  331    },
  332    CollaboratorJoined(proto::PeerId),
  333    CollaboratorLeft(proto::PeerId),
  334    RefreshInlayHints,
  335    RevealInProjectPanel(ProjectEntryId),
  336}
  337
  338pub enum LanguageServerState {
  339    Starting(Task<Option<Arc<LanguageServer>>>),
  340
  341    Running {
  342        language: Arc<Language>,
  343        adapter: Arc<CachedLspAdapter>,
  344        server: Arc<LanguageServer>,
  345        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
  346    },
  347}
  348
  349#[derive(Clone, Debug, Serialize)]
  350pub struct LanguageServerStatus {
  351    pub name: String,
  352    pub pending_work: BTreeMap<String, LanguageServerProgress>,
  353    pub has_pending_diagnostic_updates: bool,
  354    progress_tokens: HashSet<String>,
  355}
  356
  357#[derive(Clone, Debug, Serialize)]
  358pub struct LanguageServerProgress {
  359    pub message: Option<String>,
  360    pub percentage: Option<usize>,
  361    #[serde(skip_serializing)]
  362    pub last_update_at: Instant,
  363}
  364
  365#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
  366pub struct ProjectPath {
  367    pub worktree_id: WorktreeId,
  368    pub path: Arc<Path>,
  369}
  370
  371impl ProjectPath {
  372    pub fn from_proto(p: proto::ProjectPath) -> Self {
  373        Self {
  374            worktree_id: WorktreeId::from_proto(p.worktree_id),
  375            path: Arc::from(PathBuf::from(p.path)),
  376        }
  377    }
  378
  379    pub fn to_proto(&self) -> proto::ProjectPath {
  380        proto::ProjectPath {
  381            worktree_id: self.worktree_id.to_proto(),
  382            path: self.path.to_string_lossy().to_string(),
  383        }
  384    }
  385}
  386
  387#[derive(Debug, Clone, PartialEq, Eq)]
  388pub struct InlayHint {
  389    pub position: language::Anchor,
  390    pub label: InlayHintLabel,
  391    pub kind: Option<InlayHintKind>,
  392    pub padding_left: bool,
  393    pub padding_right: bool,
  394    pub tooltip: Option<InlayHintTooltip>,
  395    pub resolve_state: ResolveState,
  396}
  397
  398/// A completion provided by a language server
  399#[derive(Clone, Debug)]
  400pub struct Completion {
  401    /// The range of the buffer that will be replaced.
  402    pub old_range: Range<Anchor>,
  403    /// The new text that will be inserted.
  404    pub new_text: String,
  405    /// A label for this completion that is shown in the menu.
  406    pub label: CodeLabel,
  407    /// The id of the language server that produced this completion.
  408    pub server_id: LanguageServerId,
  409    /// The documentation for this completion.
  410    pub documentation: Option<Documentation>,
  411    /// The raw completion provided by the language server.
  412    pub lsp_completion: lsp::CompletionItem,
  413}
  414
  415/// A completion provided by a language server
  416#[derive(Clone, Debug)]
  417struct CoreCompletion {
  418    old_range: Range<Anchor>,
  419    new_text: String,
  420    server_id: LanguageServerId,
  421    lsp_completion: lsp::CompletionItem,
  422}
  423
  424/// A code action provided by a language server.
  425#[derive(Clone, Debug)]
  426pub struct CodeAction {
  427    /// The id of the language server that produced this code action.
  428    pub server_id: LanguageServerId,
  429    /// The range of the buffer where this code action is applicable.
  430    pub range: Range<Anchor>,
  431    /// The raw code action provided by the language server.
  432    pub lsp_action: lsp::CodeAction,
  433}
  434
  435#[derive(Debug, Clone, PartialEq, Eq)]
  436pub enum ResolveState {
  437    Resolved,
  438    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
  439    Resolving,
  440}
  441
  442impl InlayHint {
  443    pub fn text(&self) -> String {
  444        match &self.label {
  445            InlayHintLabel::String(s) => s.to_owned(),
  446            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
  447        }
  448    }
  449}
  450
  451#[derive(Debug, Clone, PartialEq, Eq)]
  452pub enum InlayHintLabel {
  453    String(String),
  454    LabelParts(Vec<InlayHintLabelPart>),
  455}
  456
  457#[derive(Debug, Clone, PartialEq, Eq)]
  458pub struct InlayHintLabelPart {
  459    pub value: String,
  460    pub tooltip: Option<InlayHintLabelPartTooltip>,
  461    pub location: Option<(LanguageServerId, lsp::Location)>,
  462}
  463
  464#[derive(Debug, Clone, PartialEq, Eq)]
  465pub enum InlayHintTooltip {
  466    String(String),
  467    MarkupContent(MarkupContent),
  468}
  469
  470#[derive(Debug, Clone, PartialEq, Eq)]
  471pub enum InlayHintLabelPartTooltip {
  472    String(String),
  473    MarkupContent(MarkupContent),
  474}
  475
  476#[derive(Debug, Clone, PartialEq, Eq)]
  477pub struct MarkupContent {
  478    pub kind: HoverBlockKind,
  479    pub value: String,
  480}
  481
  482#[derive(Debug, Clone)]
  483pub struct LocationLink {
  484    pub origin: Option<Location>,
  485    pub target: Location,
  486}
  487
  488#[derive(Debug)]
  489pub struct DocumentHighlight {
  490    pub range: Range<language::Anchor>,
  491    pub kind: DocumentHighlightKind,
  492}
  493
  494#[derive(Clone, Debug)]
  495pub struct Symbol {
  496    pub language_server_name: LanguageServerName,
  497    pub source_worktree_id: WorktreeId,
  498    pub path: ProjectPath,
  499    pub label: CodeLabel,
  500    pub name: String,
  501    pub kind: lsp::SymbolKind,
  502    pub range: Range<Unclipped<PointUtf16>>,
  503    pub signature: [u8; 32],
  504}
  505
  506#[derive(Clone, Debug)]
  507struct CoreSymbol {
  508    pub language_server_name: LanguageServerName,
  509    pub source_worktree_id: WorktreeId,
  510    pub path: ProjectPath,
  511    pub name: String,
  512    pub kind: lsp::SymbolKind,
  513    pub range: Range<Unclipped<PointUtf16>>,
  514    pub signature: [u8; 32],
  515}
  516
  517#[derive(Clone, Debug, PartialEq)]
  518pub struct HoverBlock {
  519    pub text: String,
  520    pub kind: HoverBlockKind,
  521}
  522
  523#[derive(Clone, Debug, PartialEq, Eq)]
  524pub enum HoverBlockKind {
  525    PlainText,
  526    Markdown,
  527    Code { language: String },
  528}
  529
  530#[derive(Debug, Clone)]
  531pub struct Hover {
  532    pub contents: Vec<HoverBlock>,
  533    pub range: Option<Range<language::Anchor>>,
  534    pub language: Option<Arc<Language>>,
  535}
  536
  537impl Hover {
  538    pub fn is_empty(&self) -> bool {
  539        self.contents.iter().all(|block| block.text.is_empty())
  540    }
  541}
  542
  543#[derive(Default)]
  544pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
  545
  546#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  547pub enum FormatTrigger {
  548    Save,
  549    Manual,
  550}
  551
  552// Currently, formatting operations are represented differently depending on
  553// whether they come from a language server or an external command.
  554enum FormatOperation {
  555    Lsp(Vec<(Range<Anchor>, String)>),
  556    External(Diff),
  557    Prettier(Diff),
  558}
  559
  560impl FormatTrigger {
  561    fn from_proto(value: i32) -> FormatTrigger {
  562        match value {
  563            0 => FormatTrigger::Save,
  564            1 => FormatTrigger::Manual,
  565            _ => FormatTrigger::Save,
  566        }
  567    }
  568}
  569
  570#[derive(Clone, Debug, PartialEq)]
  571enum SearchMatchCandidate {
  572    OpenBuffer {
  573        buffer: Model<Buffer>,
  574        // This might be an unnamed file without representation on filesystem
  575        path: Option<Arc<Path>>,
  576    },
  577    Path {
  578        worktree_id: WorktreeId,
  579        is_ignored: bool,
  580        path: Arc<Path>,
  581    },
  582}
  583
  584impl SearchMatchCandidate {
  585    fn path(&self) -> Option<Arc<Path>> {
  586        match self {
  587            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
  588            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
  589        }
  590    }
  591
  592    fn is_ignored(&self) -> bool {
  593        matches!(
  594            self,
  595            SearchMatchCandidate::Path {
  596                is_ignored: true,
  597                ..
  598            }
  599        )
  600    }
  601}
  602
  603pub enum SearchResult {
  604    Buffer {
  605        buffer: Model<Buffer>,
  606        ranges: Vec<Range<Anchor>>,
  607    },
  608    LimitReached,
  609}
  610
  611impl Project {
  612    pub fn init_settings(cx: &mut AppContext) {
  613        WorktreeSettings::register(cx);
  614        ProjectSettings::register(cx);
  615    }
  616
  617    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
  618        connection_manager::init(client.clone(), cx);
  619        Self::init_settings(cx);
  620
  621        client.add_model_message_handler(Self::handle_add_collaborator);
  622        client.add_model_message_handler(Self::handle_update_project_collaborator);
  623        client.add_model_message_handler(Self::handle_remove_collaborator);
  624        client.add_model_message_handler(Self::handle_buffer_reloaded);
  625        client.add_model_message_handler(Self::handle_buffer_saved);
  626        client.add_model_message_handler(Self::handle_start_language_server);
  627        client.add_model_message_handler(Self::handle_update_language_server);
  628        client.add_model_message_handler(Self::handle_update_project);
  629        client.add_model_message_handler(Self::handle_unshare_project);
  630        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
  631        client.add_model_message_handler(Self::handle_update_buffer_file);
  632        client.add_model_request_handler(Self::handle_update_buffer);
  633        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
  634        client.add_model_message_handler(Self::handle_update_worktree);
  635        client.add_model_message_handler(Self::handle_update_worktree_settings);
  636        client.add_model_request_handler(Self::handle_create_project_entry);
  637        client.add_model_request_handler(Self::handle_rename_project_entry);
  638        client.add_model_request_handler(Self::handle_copy_project_entry);
  639        client.add_model_request_handler(Self::handle_delete_project_entry);
  640        client.add_model_request_handler(Self::handle_expand_project_entry);
  641        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
  642        client.add_model_request_handler(Self::handle_resolve_completion_documentation);
  643        client.add_model_request_handler(Self::handle_apply_code_action);
  644        client.add_model_request_handler(Self::handle_on_type_formatting);
  645        client.add_model_request_handler(Self::handle_inlay_hints);
  646        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
  647        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
  648        client.add_model_request_handler(Self::handle_reload_buffers);
  649        client.add_model_request_handler(Self::handle_synchronize_buffers);
  650        client.add_model_request_handler(Self::handle_format_buffers);
  651        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
  652        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
  653        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
  654        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
  655        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
  656        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
  657        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
  658        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
  659        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
  660        client.add_model_request_handler(Self::handle_search_project);
  661        client.add_model_request_handler(Self::handle_get_project_symbols);
  662        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
  663        client.add_model_request_handler(Self::handle_open_buffer_by_id);
  664        client.add_model_request_handler(Self::handle_open_buffer_by_path);
  665        client.add_model_request_handler(Self::handle_open_new_buffer);
  666        client.add_model_request_handler(Self::handle_save_buffer);
  667        client.add_model_message_handler(Self::handle_update_diff_base);
  668        client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
  669        client.add_model_request_handler(Self::handle_blame_buffer);
  670        client.add_model_request_handler(Self::handle_multi_lsp_query);
  671    }
  672
  673    pub fn local(
  674        client: Arc<Client>,
  675        node: Arc<dyn NodeRuntime>,
  676        user_store: Model<UserStore>,
  677        languages: Arc<LanguageRegistry>,
  678        fs: Arc<dyn Fs>,
  679        cx: &mut AppContext,
  680    ) -> Model<Self> {
  681        cx.new_model(|cx: &mut ModelContext<Self>| {
  682            let (tx, rx) = mpsc::unbounded();
  683            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  684                .detach();
  685            let tasks = Inventory::new(cx);
  686
  687            Self {
  688                worktrees: Vec::new(),
  689                buffer_ordered_messages_tx: tx,
  690                flush_language_server_update: None,
  691                pending_language_server_update: None,
  692                collaborators: Default::default(),
  693                opened_buffers: Default::default(),
  694                shared_buffers: Default::default(),
  695                loading_buffers_by_path: Default::default(),
  696                loading_local_worktrees: Default::default(),
  697                local_buffer_ids_by_path: Default::default(),
  698                local_buffer_ids_by_entry_id: Default::default(),
  699                buffer_snapshots: Default::default(),
  700                join_project_response_message_id: 0,
  701                client_state: ProjectClientState::Local,
  702                loading_buffers: HashMap::default(),
  703                incomplete_remote_buffers: HashMap::default(),
  704                client_subscriptions: Vec::new(),
  705                _subscriptions: vec![
  706                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
  707                    cx.on_release(Self::release),
  708                    cx.on_app_quit(Self::shutdown_language_servers),
  709                ],
  710                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  711                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  712                active_entry: None,
  713                languages,
  714                client,
  715                user_store,
  716                fs,
  717                next_entry_id: Default::default(),
  718                next_diagnostic_group_id: Default::default(),
  719                supplementary_language_servers: HashMap::default(),
  720                language_servers: Default::default(),
  721                language_server_ids: HashMap::default(),
  722                language_server_statuses: Default::default(),
  723                last_formatting_failure: None,
  724                last_workspace_edits_by_language_server: Default::default(),
  725                language_server_watched_paths: HashMap::default(),
  726                buffers_being_formatted: Default::default(),
  727                buffers_needing_diff: Default::default(),
  728                git_diff_debouncer: DebouncedDelay::new(),
  729                nonce: StdRng::from_entropy().gen(),
  730                terminals: Terminals {
  731                    local_handles: Vec::new(),
  732                },
  733                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  734                node: Some(node),
  735                default_prettier: DefaultPrettier::default(),
  736                prettiers_per_worktree: HashMap::default(),
  737                prettier_instances: HashMap::default(),
  738                tasks,
  739                hosted_project_id: None,
  740                dev_server_project_id: None,
  741                search_history: Self::new_search_history(),
  742            }
  743        })
  744    }
  745
  746    pub async fn remote(
  747        remote_id: u64,
  748        client: Arc<Client>,
  749        user_store: Model<UserStore>,
  750        languages: Arc<LanguageRegistry>,
  751        fs: Arc<dyn Fs>,
  752        cx: AsyncAppContext,
  753    ) -> Result<Model<Self>> {
  754        let project =
  755            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
  756        cx.update(|cx| {
  757            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
  758                manager.maintain_project_connection(&project, cx)
  759            })
  760        })?;
  761        Ok(project)
  762    }
  763
  764    pub async fn in_room(
  765        remote_id: u64,
  766        client: Arc<Client>,
  767        user_store: Model<UserStore>,
  768        languages: Arc<LanguageRegistry>,
  769        fs: Arc<dyn Fs>,
  770        cx: AsyncAppContext,
  771    ) -> Result<Model<Self>> {
  772        client.authenticate_and_connect(true, &cx).await?;
  773
  774        let subscription = client.subscribe_to_entity(remote_id)?;
  775        let response = client
  776            .request_envelope(proto::JoinProject {
  777                project_id: remote_id,
  778            })
  779            .await?;
  780        Self::from_join_project_response(
  781            response,
  782            subscription,
  783            client,
  784            user_store,
  785            languages,
  786            fs,
  787            cx,
  788        )
  789        .await
  790    }
  791
  792    async fn from_join_project_response(
  793        response: TypedEnvelope<proto::JoinProjectResponse>,
  794        subscription: PendingEntitySubscription<Project>,
  795        client: Arc<Client>,
  796        user_store: Model<UserStore>,
  797        languages: Arc<LanguageRegistry>,
  798        fs: Arc<dyn Fs>,
  799        mut cx: AsyncAppContext,
  800    ) -> Result<Model<Self>> {
  801        let remote_id = response.payload.project_id;
  802        let role = response.payload.role();
  803        let this = cx.new_model(|cx| {
  804            let replica_id = response.payload.replica_id as ReplicaId;
  805            let tasks = Inventory::new(cx);
  806            // BIG CAUTION NOTE: The order in which we initialize fields here matters and it should match what's done in Self::local.
  807            // Otherwise, you might run into issues where worktree id on remote is different than what's on local host.
  808            // That's because Worktree's identifier is entity id, which should probably be changed.
  809            let mut worktrees = Vec::new();
  810            for worktree in response.payload.worktrees {
  811                let worktree =
  812                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
  813                worktrees.push(worktree);
  814            }
  815
  816            let (tx, rx) = mpsc::unbounded();
  817            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  818                .detach();
  819            let mut this = Self {
  820                worktrees: Vec::new(),
  821                buffer_ordered_messages_tx: tx,
  822                pending_language_server_update: None,
  823                flush_language_server_update: None,
  824                loading_buffers_by_path: Default::default(),
  825                loading_buffers: Default::default(),
  826                shared_buffers: Default::default(),
  827                incomplete_remote_buffers: Default::default(),
  828                loading_local_worktrees: Default::default(),
  829                local_buffer_ids_by_path: Default::default(),
  830                local_buffer_ids_by_entry_id: Default::default(),
  831                active_entry: None,
  832                collaborators: Default::default(),
  833                join_project_response_message_id: response.message_id,
  834                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  835                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  836                languages,
  837                user_store: user_store.clone(),
  838                fs,
  839                next_entry_id: Default::default(),
  840                next_diagnostic_group_id: Default::default(),
  841                client_subscriptions: Default::default(),
  842                _subscriptions: vec![
  843                    cx.on_release(Self::release),
  844                    cx.on_app_quit(Self::shutdown_language_servers),
  845                ],
  846                client: client.clone(),
  847                client_state: ProjectClientState::Remote {
  848                    sharing_has_stopped: false,
  849                    capability: Capability::ReadWrite,
  850                    remote_id,
  851                    replica_id,
  852                    in_room: response.payload.dev_server_project_id.is_none(),
  853                },
  854                supplementary_language_servers: HashMap::default(),
  855                language_servers: Default::default(),
  856                language_server_ids: HashMap::default(),
  857                language_server_statuses: response
  858                    .payload
  859                    .language_servers
  860                    .into_iter()
  861                    .map(|server| {
  862                        (
  863                            LanguageServerId(server.id as usize),
  864                            LanguageServerStatus {
  865                                name: server.name,
  866                                pending_work: Default::default(),
  867                                has_pending_diagnostic_updates: false,
  868                                progress_tokens: Default::default(),
  869                            },
  870                        )
  871                    })
  872                    .collect(),
  873                last_formatting_failure: None,
  874                last_workspace_edits_by_language_server: Default::default(),
  875                language_server_watched_paths: HashMap::default(),
  876                opened_buffers: Default::default(),
  877                buffers_being_formatted: Default::default(),
  878                buffers_needing_diff: Default::default(),
  879                git_diff_debouncer: DebouncedDelay::new(),
  880                buffer_snapshots: Default::default(),
  881                nonce: StdRng::from_entropy().gen(),
  882                terminals: Terminals {
  883                    local_handles: Vec::new(),
  884                },
  885                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  886                node: None,
  887                default_prettier: DefaultPrettier::default(),
  888                prettiers_per_worktree: HashMap::default(),
  889                prettier_instances: HashMap::default(),
  890                tasks,
  891                hosted_project_id: None,
  892                dev_server_project_id: response
  893                    .payload
  894                    .dev_server_project_id
  895                    .map(|dev_server_project_id| DevServerProjectId(dev_server_project_id)),
  896                search_history: Self::new_search_history(),
  897            };
  898            this.set_role(role, cx);
  899            for worktree in worktrees {
  900                let _ = this.add_worktree(&worktree, cx);
  901            }
  902            this
  903        })?;
  904        let subscription = subscription.set_model(&this, &mut cx);
  905
  906        let user_ids = response
  907            .payload
  908            .collaborators
  909            .iter()
  910            .map(|peer| peer.user_id)
  911            .collect();
  912        user_store
  913            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
  914            .await?;
  915
  916        this.update(&mut cx, |this, cx| {
  917            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
  918            this.client_subscriptions.push(subscription);
  919            anyhow::Ok(())
  920        })??;
  921
  922        Ok(this)
  923    }
  924
  925    pub async fn hosted(
  926        remote_id: ProjectId,
  927        user_store: Model<UserStore>,
  928        client: Arc<Client>,
  929        languages: Arc<LanguageRegistry>,
  930        fs: Arc<dyn Fs>,
  931        cx: AsyncAppContext,
  932    ) -> Result<Model<Self>> {
  933        client.authenticate_and_connect(true, &cx).await?;
  934
  935        let subscription = client.subscribe_to_entity(remote_id.0)?;
  936        let response = client
  937            .request_envelope(proto::JoinHostedProject {
  938                project_id: remote_id.0,
  939            })
  940            .await?;
  941        Self::from_join_project_response(
  942            response,
  943            subscription,
  944            client,
  945            user_store,
  946            languages,
  947            fs,
  948            cx,
  949        )
  950        .await
  951    }
  952
  953    fn new_search_history() -> SearchHistory {
  954        SearchHistory::new(
  955            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
  956            search_history::QueryInsertionBehavior::AlwaysInsert,
  957        )
  958    }
  959
  960    fn release(&mut self, cx: &mut AppContext) {
  961        match &self.client_state {
  962            ProjectClientState::Local => {}
  963            ProjectClientState::Shared { .. } => {
  964                let _ = self.unshare_internal(cx);
  965            }
  966            ProjectClientState::Remote { remote_id, .. } => {
  967                let _ = self.client.send(proto::LeaveProject {
  968                    project_id: *remote_id,
  969                });
  970                self.disconnected_from_host_internal(cx);
  971            }
  972        }
  973    }
  974
  975    fn shutdown_language_servers(
  976        &mut self,
  977        _cx: &mut ModelContext<Self>,
  978    ) -> impl Future<Output = ()> {
  979        let shutdown_futures = self
  980            .language_servers
  981            .drain()
  982            .map(|(_, server_state)| async {
  983                use LanguageServerState::*;
  984                match server_state {
  985                    Running { server, .. } => server.shutdown()?.await,
  986                    Starting(task) => task.await?.shutdown()?.await,
  987                }
  988            })
  989            .collect::<Vec<_>>();
  990
  991        async move {
  992            futures::future::join_all(shutdown_futures).await;
  993        }
  994    }
  995
  996    #[cfg(any(test, feature = "test-support"))]
  997    pub async fn example(
  998        root_paths: impl IntoIterator<Item = &Path>,
  999        cx: &mut AsyncAppContext,
 1000    ) -> Model<Project> {
 1001        use clock::FakeSystemClock;
 1002
 1003        let fs = Arc::new(RealFs::default());
 1004        let languages = LanguageRegistry::test(cx.background_executor().clone());
 1005        let clock = Arc::new(FakeSystemClock::default());
 1006        let http_client = util::http::FakeHttpClient::with_404_response();
 1007        let client = cx
 1008            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
 1009            .unwrap();
 1010        let user_store = cx
 1011            .new_model(|cx| UserStore::new(client.clone(), cx))
 1012            .unwrap();
 1013        let project = cx
 1014            .update(|cx| {
 1015                Project::local(
 1016                    client,
 1017                    node_runtime::FakeNodeRuntime::new(),
 1018                    user_store,
 1019                    Arc::new(languages),
 1020                    fs,
 1021                    cx,
 1022                )
 1023            })
 1024            .unwrap();
 1025        for path in root_paths {
 1026            let (tree, _) = project
 1027                .update(cx, |project, cx| {
 1028                    project.find_or_create_local_worktree(path, true, cx)
 1029                })
 1030                .unwrap()
 1031                .await
 1032                .unwrap();
 1033            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 1034                .unwrap()
 1035                .await;
 1036        }
 1037        project
 1038    }
 1039
 1040    #[cfg(any(test, feature = "test-support"))]
 1041    pub async fn test(
 1042        fs: Arc<dyn Fs>,
 1043        root_paths: impl IntoIterator<Item = &Path>,
 1044        cx: &mut gpui::TestAppContext,
 1045    ) -> Model<Project> {
 1046        use clock::FakeSystemClock;
 1047
 1048        let languages = LanguageRegistry::test(cx.executor());
 1049        let clock = Arc::new(FakeSystemClock::default());
 1050        let http_client = util::http::FakeHttpClient::with_404_response();
 1051        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
 1052        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
 1053        let project = cx.update(|cx| {
 1054            Project::local(
 1055                client,
 1056                node_runtime::FakeNodeRuntime::new(),
 1057                user_store,
 1058                Arc::new(languages),
 1059                fs,
 1060                cx,
 1061            )
 1062        });
 1063        for path in root_paths {
 1064            let (tree, _) = project
 1065                .update(cx, |project, cx| {
 1066                    project.find_or_create_local_worktree(path, true, cx)
 1067                })
 1068                .await
 1069                .unwrap();
 1070            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 1071                .await;
 1072        }
 1073        project
 1074    }
 1075
 1076    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 1077        let mut language_servers_to_start = Vec::new();
 1078        let mut language_formatters_to_check = Vec::new();
 1079        for buffer in self.opened_buffers.values() {
 1080            if let Some(buffer) = buffer.upgrade() {
 1081                let buffer = buffer.read(cx);
 1082                let buffer_file = File::from_dyn(buffer.file());
 1083                let buffer_language = buffer.language();
 1084                let settings = language_settings(buffer_language, buffer.file(), cx);
 1085                if let Some(language) = buffer_language {
 1086                    if settings.enable_language_server {
 1087                        if let Some(file) = buffer_file {
 1088                            language_servers_to_start
 1089                                .push((file.worktree.clone(), Arc::clone(language)));
 1090                        }
 1091                    }
 1092                    language_formatters_to_check.push((
 1093                        buffer_file.map(|f| f.worktree_id(cx)),
 1094                        Arc::clone(language),
 1095                        settings.clone(),
 1096                    ));
 1097                }
 1098            }
 1099        }
 1100
 1101        let mut language_servers_to_stop = Vec::new();
 1102        let mut language_servers_to_restart = Vec::new();
 1103        let languages = self.languages.to_vec();
 1104
 1105        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
 1106        let current_lsp_settings = &self.current_lsp_settings;
 1107        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 1108            let language = languages.iter().find_map(|l| {
 1109                let adapter = self
 1110                    .languages
 1111                    .lsp_adapters(l)
 1112                    .iter()
 1113                    .find(|adapter| &adapter.name == started_lsp_name)?
 1114                    .clone();
 1115                Some((l, adapter))
 1116            });
 1117            if let Some((language, adapter)) = language {
 1118                let worktree = self.worktree_for_id(*worktree_id, cx);
 1119                let file = worktree.as_ref().and_then(|tree| {
 1120                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 1121                });
 1122                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 1123                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 1124                } else if let Some(worktree) = worktree {
 1125                    let server_name = &adapter.name.0;
 1126                    match (
 1127                        current_lsp_settings.get(server_name),
 1128                        new_lsp_settings.get(server_name),
 1129                    ) {
 1130                        (None, None) => {}
 1131                        (Some(_), None) | (None, Some(_)) => {
 1132                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 1133                        }
 1134                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 1135                            if current_lsp_settings != new_lsp_settings {
 1136                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 1137                            }
 1138                        }
 1139                    }
 1140                }
 1141            }
 1142        }
 1143        self.current_lsp_settings = new_lsp_settings;
 1144
 1145        // Stop all newly-disabled language servers.
 1146        for (worktree_id, adapter_name) in language_servers_to_stop {
 1147            self.stop_language_server(worktree_id, adapter_name, cx)
 1148                .detach();
 1149        }
 1150
 1151        let mut prettier_plugins_by_worktree = HashMap::default();
 1152        for (worktree, language, settings) in language_formatters_to_check {
 1153            if let Some(plugins) =
 1154                prettier_support::prettier_plugins_for_language(&language, &settings)
 1155            {
 1156                prettier_plugins_by_worktree
 1157                    .entry(worktree)
 1158                    .or_insert_with(|| HashSet::default())
 1159                    .extend(plugins.iter().cloned());
 1160            }
 1161        }
 1162        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
 1163            self.install_default_prettier(worktree, prettier_plugins.into_iter(), cx);
 1164        }
 1165
 1166        // Start all the newly-enabled language servers.
 1167        for (worktree, language) in language_servers_to_start {
 1168            self.start_language_servers(&worktree, language, cx);
 1169        }
 1170
 1171        // Restart all language servers with changed initialization options.
 1172        for (worktree, language) in language_servers_to_restart {
 1173            self.restart_language_servers(worktree, language, cx);
 1174        }
 1175
 1176        cx.notify();
 1177    }
 1178
 1179    pub fn buffer_for_id(&self, remote_id: BufferId) -> Option<Model<Buffer>> {
 1180        self.opened_buffers
 1181            .get(&remote_id)
 1182            .and_then(|buffer| buffer.upgrade())
 1183    }
 1184
 1185    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 1186        &self.languages
 1187    }
 1188
 1189    pub fn client(&self) -> Arc<Client> {
 1190        self.client.clone()
 1191    }
 1192
 1193    pub fn user_store(&self) -> Model<UserStore> {
 1194        self.user_store.clone()
 1195    }
 1196
 1197    pub fn node_runtime(&self) -> Option<&Arc<dyn NodeRuntime>> {
 1198        self.node.as_ref()
 1199    }
 1200
 1201    pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
 1202        self.opened_buffers
 1203            .values()
 1204            .filter_map(|b| b.upgrade())
 1205            .collect()
 1206    }
 1207
 1208    #[cfg(any(test, feature = "test-support"))]
 1209    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 1210        let path = path.into();
 1211        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 1212            self.opened_buffers.iter().any(|(_, buffer)| {
 1213                if let Some(buffer) = buffer.upgrade() {
 1214                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 1215                        if file.worktree == worktree && file.path() == &path.path {
 1216                            return true;
 1217                        }
 1218                    }
 1219                }
 1220                false
 1221            })
 1222        } else {
 1223            false
 1224        }
 1225    }
 1226
 1227    pub fn fs(&self) -> &Arc<dyn Fs> {
 1228        &self.fs
 1229    }
 1230
 1231    pub fn remote_id(&self) -> Option<u64> {
 1232        match self.client_state {
 1233            ProjectClientState::Local => None,
 1234            ProjectClientState::Shared { remote_id, .. }
 1235            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
 1236        }
 1237    }
 1238
 1239    pub fn hosted_project_id(&self) -> Option<ProjectId> {
 1240        self.hosted_project_id
 1241    }
 1242
 1243    pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
 1244        self.dev_server_project_id
 1245    }
 1246
 1247    pub fn replica_id(&self) -> ReplicaId {
 1248        match self.client_state {
 1249            ProjectClientState::Remote { replica_id, .. } => replica_id,
 1250            _ => 0,
 1251        }
 1252    }
 1253
 1254    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
 1255        if let ProjectClientState::Shared { updates_tx, .. } = &mut self.client_state {
 1256            updates_tx
 1257                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
 1258                .ok();
 1259        }
 1260        cx.notify();
 1261    }
 1262
 1263    pub fn task_inventory(&self) -> &Model<Inventory> {
 1264        &self.tasks
 1265    }
 1266
 1267    pub fn search_history(&self) -> &SearchHistory {
 1268        &self.search_history
 1269    }
 1270
 1271    pub fn search_history_mut(&mut self) -> &mut SearchHistory {
 1272        &mut self.search_history
 1273    }
 1274
 1275    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 1276        &self.collaborators
 1277    }
 1278
 1279    pub fn host(&self) -> Option<&Collaborator> {
 1280        self.collaborators.values().find(|c| c.replica_id == 0)
 1281    }
 1282
 1283    /// Collect all worktrees, including ones that don't appear in the project panel
 1284    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
 1285        self.worktrees
 1286            .iter()
 1287            .filter_map(move |worktree| worktree.upgrade())
 1288    }
 1289
 1290    /// Collect all user-visible worktrees, the ones that appear in the project panel
 1291    pub fn visible_worktrees<'a>(
 1292        &'a self,
 1293        cx: &'a AppContext,
 1294    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
 1295        self.worktrees.iter().filter_map(|worktree| {
 1296            worktree.upgrade().and_then(|worktree| {
 1297                if worktree.read(cx).is_visible() {
 1298                    Some(worktree)
 1299                } else {
 1300                    None
 1301                }
 1302            })
 1303        })
 1304    }
 1305
 1306    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 1307        self.visible_worktrees(cx)
 1308            .map(|tree| tree.read(cx).root_name())
 1309    }
 1310
 1311    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
 1312        self.worktrees()
 1313            .find(|worktree| worktree.read(cx).id() == id)
 1314    }
 1315
 1316    pub fn worktree_for_entry(
 1317        &self,
 1318        entry_id: ProjectEntryId,
 1319        cx: &AppContext,
 1320    ) -> Option<Model<Worktree>> {
 1321        self.worktrees()
 1322            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 1323    }
 1324
 1325    pub fn worktree_id_for_entry(
 1326        &self,
 1327        entry_id: ProjectEntryId,
 1328        cx: &AppContext,
 1329    ) -> Option<WorktreeId> {
 1330        self.worktree_for_entry(entry_id, cx)
 1331            .map(|worktree| worktree.read(cx).id())
 1332    }
 1333
 1334    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
 1335        paths
 1336            .iter()
 1337            .map(|path| self.visibility_for_path(path, cx))
 1338            .max()
 1339            .flatten()
 1340    }
 1341
 1342    pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
 1343        self.worktrees()
 1344            .filter_map(|worktree| {
 1345                let worktree = worktree.read(cx);
 1346                worktree
 1347                    .as_local()?
 1348                    .contains_abs_path(path)
 1349                    .then(|| worktree.is_visible())
 1350            })
 1351            .max()
 1352    }
 1353
 1354    pub fn create_entry(
 1355        &mut self,
 1356        project_path: impl Into<ProjectPath>,
 1357        is_directory: bool,
 1358        cx: &mut ModelContext<Self>,
 1359    ) -> Task<Result<Option<Entry>>> {
 1360        let project_path = project_path.into();
 1361        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
 1362            return Task::ready(Ok(None));
 1363        };
 1364        if self.is_local() {
 1365            worktree.update(cx, |worktree, cx| {
 1366                worktree
 1367                    .as_local_mut()
 1368                    .unwrap()
 1369                    .create_entry(project_path.path, is_directory, cx)
 1370            })
 1371        } else {
 1372            let client = self.client.clone();
 1373            let project_id = self.remote_id().unwrap();
 1374            cx.spawn(move |_, mut cx| async move {
 1375                let response = client
 1376                    .request(proto::CreateProjectEntry {
 1377                        worktree_id: project_path.worktree_id.to_proto(),
 1378                        project_id,
 1379                        path: project_path.path.to_string_lossy().into(),
 1380                        is_directory,
 1381                    })
 1382                    .await?;
 1383                match response.entry {
 1384                    Some(entry) => worktree
 1385                        .update(&mut cx, |worktree, cx| {
 1386                            worktree.as_remote_mut().unwrap().insert_entry(
 1387                                entry,
 1388                                response.worktree_scan_id as usize,
 1389                                cx,
 1390                            )
 1391                        })?
 1392                        .await
 1393                        .map(Some),
 1394                    None => Ok(None),
 1395                }
 1396            })
 1397        }
 1398    }
 1399
 1400    pub fn copy_entry(
 1401        &mut self,
 1402        entry_id: ProjectEntryId,
 1403        new_path: impl Into<Arc<Path>>,
 1404        cx: &mut ModelContext<Self>,
 1405    ) -> Task<Result<Option<Entry>>> {
 1406        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1407            return Task::ready(Ok(None));
 1408        };
 1409        let new_path = new_path.into();
 1410        if self.is_local() {
 1411            worktree.update(cx, |worktree, cx| {
 1412                worktree
 1413                    .as_local_mut()
 1414                    .unwrap()
 1415                    .copy_entry(entry_id, new_path, cx)
 1416            })
 1417        } else {
 1418            let client = self.client.clone();
 1419            let project_id = self.remote_id().unwrap();
 1420
 1421            cx.spawn(move |_, mut cx| async move {
 1422                let response = client
 1423                    .request(proto::CopyProjectEntry {
 1424                        project_id,
 1425                        entry_id: entry_id.to_proto(),
 1426                        new_path: new_path.to_string_lossy().into(),
 1427                    })
 1428                    .await?;
 1429                match response.entry {
 1430                    Some(entry) => worktree
 1431                        .update(&mut cx, |worktree, cx| {
 1432                            worktree.as_remote_mut().unwrap().insert_entry(
 1433                                entry,
 1434                                response.worktree_scan_id as usize,
 1435                                cx,
 1436                            )
 1437                        })?
 1438                        .await
 1439                        .map(Some),
 1440                    None => Ok(None),
 1441                }
 1442            })
 1443        }
 1444    }
 1445
 1446    pub fn rename_entry(
 1447        &mut self,
 1448        entry_id: ProjectEntryId,
 1449        new_path: impl Into<Arc<Path>>,
 1450        cx: &mut ModelContext<Self>,
 1451    ) -> Task<Result<Option<Entry>>> {
 1452        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1453            return Task::ready(Ok(None));
 1454        };
 1455        let new_path = new_path.into();
 1456        if self.is_local() {
 1457            worktree.update(cx, |worktree, cx| {
 1458                worktree
 1459                    .as_local_mut()
 1460                    .unwrap()
 1461                    .rename_entry(entry_id, new_path, cx)
 1462            })
 1463        } else {
 1464            let client = self.client.clone();
 1465            let project_id = self.remote_id().unwrap();
 1466
 1467            cx.spawn(move |_, mut cx| async move {
 1468                let response = client
 1469                    .request(proto::RenameProjectEntry {
 1470                        project_id,
 1471                        entry_id: entry_id.to_proto(),
 1472                        new_path: new_path.to_string_lossy().into(),
 1473                    })
 1474                    .await?;
 1475                match response.entry {
 1476                    Some(entry) => worktree
 1477                        .update(&mut cx, |worktree, cx| {
 1478                            worktree.as_remote_mut().unwrap().insert_entry(
 1479                                entry,
 1480                                response.worktree_scan_id as usize,
 1481                                cx,
 1482                            )
 1483                        })?
 1484                        .await
 1485                        .map(Some),
 1486                    None => Ok(None),
 1487                }
 1488            })
 1489        }
 1490    }
 1491
 1492    pub fn delete_entry(
 1493        &mut self,
 1494        entry_id: ProjectEntryId,
 1495        trash: bool,
 1496        cx: &mut ModelContext<Self>,
 1497    ) -> Option<Task<Result<()>>> {
 1498        let worktree = self.worktree_for_entry(entry_id, cx)?;
 1499
 1500        cx.emit(Event::DeletedEntry(entry_id));
 1501
 1502        if self.is_local() {
 1503            worktree.update(cx, |worktree, cx| {
 1504                worktree
 1505                    .as_local_mut()
 1506                    .unwrap()
 1507                    .delete_entry(entry_id, trash, cx)
 1508            })
 1509        } else {
 1510            let client = self.client.clone();
 1511            let project_id = self.remote_id().unwrap();
 1512            Some(cx.spawn(move |_, mut cx| async move {
 1513                let response = client
 1514                    .request(proto::DeleteProjectEntry {
 1515                        project_id,
 1516                        entry_id: entry_id.to_proto(),
 1517                        use_trash: trash,
 1518                    })
 1519                    .await?;
 1520                worktree
 1521                    .update(&mut cx, move |worktree, cx| {
 1522                        worktree.as_remote_mut().unwrap().delete_entry(
 1523                            entry_id,
 1524                            response.worktree_scan_id as usize,
 1525                            cx,
 1526                        )
 1527                    })?
 1528                    .await
 1529            }))
 1530        }
 1531    }
 1532
 1533    pub fn expand_entry(
 1534        &mut self,
 1535        worktree_id: WorktreeId,
 1536        entry_id: ProjectEntryId,
 1537        cx: &mut ModelContext<Self>,
 1538    ) -> Option<Task<Result<()>>> {
 1539        let worktree = self.worktree_for_id(worktree_id, cx)?;
 1540        if self.is_local() {
 1541            worktree.update(cx, |worktree, cx| {
 1542                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
 1543            })
 1544        } else {
 1545            let worktree = worktree.downgrade();
 1546            let request = self.client.request(proto::ExpandProjectEntry {
 1547                project_id: self.remote_id().unwrap(),
 1548                entry_id: entry_id.to_proto(),
 1549            });
 1550            Some(cx.spawn(move |_, mut cx| async move {
 1551                let response = request.await?;
 1552                if let Some(worktree) = worktree.upgrade() {
 1553                    worktree
 1554                        .update(&mut cx, |worktree, _| {
 1555                            worktree
 1556                                .as_remote_mut()
 1557                                .unwrap()
 1558                                .wait_for_snapshot(response.worktree_scan_id as usize)
 1559                        })?
 1560                        .await?;
 1561                }
 1562                Ok(())
 1563            }))
 1564        }
 1565    }
 1566
 1567    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
 1568        if !matches!(self.client_state, ProjectClientState::Local) {
 1569            if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
 1570                if *in_room || self.dev_server_project_id.is_none() {
 1571                    return Err(anyhow!("project was already shared"));
 1572                } else {
 1573                    *in_room = true;
 1574                    return Ok(());
 1575                }
 1576            } else {
 1577                return Err(anyhow!("project was already shared"));
 1578            }
 1579        }
 1580        self.client_subscriptions.push(
 1581            self.client
 1582                .subscribe_to_entity(project_id)?
 1583                .set_model(&cx.handle(), &mut cx.to_async()),
 1584        );
 1585
 1586        for open_buffer in self.opened_buffers.values_mut() {
 1587            match open_buffer {
 1588                OpenBuffer::Strong(_) => {}
 1589                OpenBuffer::Weak(buffer) => {
 1590                    if let Some(buffer) = buffer.upgrade() {
 1591                        *open_buffer = OpenBuffer::Strong(buffer);
 1592                    }
 1593                }
 1594                OpenBuffer::Operations(_) => unreachable!(),
 1595            }
 1596        }
 1597
 1598        for worktree_handle in self.worktrees.iter_mut() {
 1599            match worktree_handle {
 1600                WorktreeHandle::Strong(_) => {}
 1601                WorktreeHandle::Weak(worktree) => {
 1602                    if let Some(worktree) = worktree.upgrade() {
 1603                        *worktree_handle = WorktreeHandle::Strong(worktree);
 1604                    }
 1605                }
 1606            }
 1607        }
 1608
 1609        for (server_id, status) in &self.language_server_statuses {
 1610            self.client
 1611                .send(proto::StartLanguageServer {
 1612                    project_id,
 1613                    server: Some(proto::LanguageServer {
 1614                        id: server_id.0 as u64,
 1615                        name: status.name.clone(),
 1616                    }),
 1617                })
 1618                .log_err();
 1619        }
 1620
 1621        let store = cx.global::<SettingsStore>();
 1622        for worktree in self.worktrees() {
 1623            let worktree_id = worktree.read(cx).id().to_proto();
 1624            for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
 1625                self.client
 1626                    .send(proto::UpdateWorktreeSettings {
 1627                        project_id,
 1628                        worktree_id,
 1629                        path: path.to_string_lossy().into(),
 1630                        content: Some(content),
 1631                    })
 1632                    .log_err();
 1633            }
 1634        }
 1635
 1636        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 1637        let client = self.client.clone();
 1638        self.client_state = ProjectClientState::Shared {
 1639            remote_id: project_id,
 1640            updates_tx,
 1641            _send_updates: cx.spawn(move |this, mut cx| async move {
 1642                while let Some(update) = updates_rx.next().await {
 1643                    match update {
 1644                        LocalProjectUpdate::WorktreesChanged => {
 1645                            let worktrees = this.update(&mut cx, |this, _cx| {
 1646                                this.worktrees().collect::<Vec<_>>()
 1647                            })?;
 1648                            let update_project = this
 1649                                .update(&mut cx, |this, cx| {
 1650                                    this.client.request(proto::UpdateProject {
 1651                                        project_id,
 1652                                        worktrees: this.worktree_metadata_protos(cx),
 1653                                    })
 1654                                })?
 1655                                .await;
 1656                            if update_project.log_err().is_some() {
 1657                                for worktree in worktrees {
 1658                                    worktree.update(&mut cx, |worktree, cx| {
 1659                                        let worktree = worktree.as_local_mut().unwrap();
 1660                                        worktree.share(project_id, cx).detach_and_log_err(cx)
 1661                                    })?;
 1662                                }
 1663                            }
 1664                        }
 1665                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
 1666                            let buffer = this.update(&mut cx, |this, _| {
 1667                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
 1668                                let shared_buffers =
 1669                                    this.shared_buffers.entry(peer_id).or_default();
 1670                                if shared_buffers.insert(buffer_id) {
 1671                                    if let OpenBuffer::Strong(buffer) = buffer {
 1672                                        Some(buffer.clone())
 1673                                    } else {
 1674                                        None
 1675                                    }
 1676                                } else {
 1677                                    None
 1678                                }
 1679                            })?;
 1680
 1681                            let Some(buffer) = buffer else { continue };
 1682                            let operations =
 1683                                buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
 1684                            let operations = operations.await;
 1685                            let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
 1686
 1687                            let initial_state = proto::CreateBufferForPeer {
 1688                                project_id,
 1689                                peer_id: Some(peer_id),
 1690                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
 1691                            };
 1692                            if client.send(initial_state).log_err().is_some() {
 1693                                let client = client.clone();
 1694                                cx.background_executor()
 1695                                    .spawn(async move {
 1696                                        let mut chunks = split_operations(operations).peekable();
 1697                                        while let Some(chunk) = chunks.next() {
 1698                                            let is_last = chunks.peek().is_none();
 1699                                            client.send(proto::CreateBufferForPeer {
 1700                                                project_id,
 1701                                                peer_id: Some(peer_id),
 1702                                                variant: Some(
 1703                                                    proto::create_buffer_for_peer::Variant::Chunk(
 1704                                                        proto::BufferChunk {
 1705                                                            buffer_id: buffer_id.into(),
 1706                                                            operations: chunk,
 1707                                                            is_last,
 1708                                                        },
 1709                                                    ),
 1710                                                ),
 1711                                            })?;
 1712                                        }
 1713                                        anyhow::Ok(())
 1714                                    })
 1715                                    .await
 1716                                    .log_err();
 1717                            }
 1718                        }
 1719                    }
 1720                }
 1721                Ok(())
 1722            }),
 1723        };
 1724
 1725        self.metadata_changed(cx);
 1726        cx.emit(Event::RemoteIdChanged(Some(project_id)));
 1727        cx.notify();
 1728        Ok(())
 1729    }
 1730
 1731    pub fn reshared(
 1732        &mut self,
 1733        message: proto::ResharedProject,
 1734        cx: &mut ModelContext<Self>,
 1735    ) -> Result<()> {
 1736        self.shared_buffers.clear();
 1737        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1738        self.metadata_changed(cx);
 1739        Ok(())
 1740    }
 1741
 1742    pub fn rejoined(
 1743        &mut self,
 1744        message: proto::RejoinedProject,
 1745        message_id: u32,
 1746        cx: &mut ModelContext<Self>,
 1747    ) -> Result<()> {
 1748        cx.update_global::<SettingsStore, _>(|store, cx| {
 1749            for worktree in &self.worktrees {
 1750                store
 1751                    .clear_local_settings(worktree.handle_id(), cx)
 1752                    .log_err();
 1753            }
 1754        });
 1755
 1756        self.join_project_response_message_id = message_id;
 1757        self.set_worktrees_from_proto(message.worktrees, cx)?;
 1758        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1759        self.language_server_statuses = message
 1760            .language_servers
 1761            .into_iter()
 1762            .map(|server| {
 1763                (
 1764                    LanguageServerId(server.id as usize),
 1765                    LanguageServerStatus {
 1766                        name: server.name,
 1767                        pending_work: Default::default(),
 1768                        has_pending_diagnostic_updates: false,
 1769                        progress_tokens: Default::default(),
 1770                    },
 1771                )
 1772            })
 1773            .collect();
 1774        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 1775            .unwrap();
 1776        cx.notify();
 1777        Ok(())
 1778    }
 1779
 1780    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
 1781        self.unshare_internal(cx)?;
 1782        self.metadata_changed(cx);
 1783        cx.notify();
 1784        Ok(())
 1785    }
 1786
 1787    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
 1788        if self.is_remote() {
 1789            if self.dev_server_project_id().is_some() {
 1790                if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
 1791                    *in_room = false
 1792                }
 1793                return Ok(());
 1794            } else {
 1795                return Err(anyhow!("attempted to unshare a remote project"));
 1796            }
 1797        }
 1798
 1799        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
 1800            self.client_state = ProjectClientState::Local;
 1801            self.collaborators.clear();
 1802            self.shared_buffers.clear();
 1803            self.client_subscriptions.clear();
 1804
 1805            for worktree_handle in self.worktrees.iter_mut() {
 1806                if let WorktreeHandle::Strong(worktree) = worktree_handle {
 1807                    let is_visible = worktree.update(cx, |worktree, _| {
 1808                        worktree.as_local_mut().unwrap().unshare();
 1809                        worktree.is_visible()
 1810                    });
 1811                    if !is_visible {
 1812                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 1813                    }
 1814                }
 1815            }
 1816
 1817            for open_buffer in self.opened_buffers.values_mut() {
 1818                // Wake up any tasks waiting for peers' edits to this buffer.
 1819                if let Some(buffer) = open_buffer.upgrade() {
 1820                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1821                }
 1822
 1823                if let OpenBuffer::Strong(buffer) = open_buffer {
 1824                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1825                }
 1826            }
 1827
 1828            self.client.send(proto::UnshareProject {
 1829                project_id: remote_id,
 1830            })?;
 1831
 1832            Ok(())
 1833        } else {
 1834            Err(anyhow!("attempted to unshare an unshared project"))
 1835        }
 1836    }
 1837
 1838    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
 1839        self.disconnected_from_host_internal(cx);
 1840        cx.emit(Event::DisconnectedFromHost);
 1841        cx.notify();
 1842    }
 1843
 1844    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
 1845        let new_capability =
 1846            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
 1847                Capability::ReadWrite
 1848            } else {
 1849                Capability::ReadOnly
 1850            };
 1851        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
 1852            if *capability == new_capability {
 1853                return;
 1854            }
 1855
 1856            *capability = new_capability;
 1857            for buffer in self.opened_buffers() {
 1858                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
 1859            }
 1860        }
 1861    }
 1862
 1863    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
 1864        if let ProjectClientState::Remote {
 1865            sharing_has_stopped,
 1866            ..
 1867        } = &mut self.client_state
 1868        {
 1869            *sharing_has_stopped = true;
 1870
 1871            self.collaborators.clear();
 1872
 1873            for worktree in &self.worktrees {
 1874                if let Some(worktree) = worktree.upgrade() {
 1875                    worktree.update(cx, |worktree, _| {
 1876                        if let Some(worktree) = worktree.as_remote_mut() {
 1877                            worktree.disconnected_from_host();
 1878                        }
 1879                    });
 1880                }
 1881            }
 1882
 1883            for open_buffer in self.opened_buffers.values_mut() {
 1884                // Wake up any tasks waiting for peers' edits to this buffer.
 1885                if let Some(buffer) = open_buffer.upgrade() {
 1886                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1887                }
 1888
 1889                if let OpenBuffer::Strong(buffer) = open_buffer {
 1890                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1891                }
 1892            }
 1893
 1894            // Wake up all futures currently waiting on a buffer to get opened,
 1895            // to give them a chance to fail now that we've disconnected.
 1896            self.loading_buffers.clear();
 1897            // self.opened_buffer.send(OpenedBufferEvent::Disconnected);
 1898        }
 1899    }
 1900
 1901    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 1902        cx.emit(Event::Closed);
 1903    }
 1904
 1905    pub fn is_disconnected(&self) -> bool {
 1906        match &self.client_state {
 1907            ProjectClientState::Remote {
 1908                sharing_has_stopped,
 1909                ..
 1910            } => *sharing_has_stopped,
 1911            _ => false,
 1912        }
 1913    }
 1914
 1915    pub fn capability(&self) -> Capability {
 1916        match &self.client_state {
 1917            ProjectClientState::Remote { capability, .. } => *capability,
 1918            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
 1919        }
 1920    }
 1921
 1922    pub fn is_read_only(&self) -> bool {
 1923        self.is_disconnected() || self.capability() == Capability::ReadOnly
 1924    }
 1925
 1926    pub fn is_local(&self) -> bool {
 1927        match &self.client_state {
 1928            ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
 1929            ProjectClientState::Remote { .. } => false,
 1930        }
 1931    }
 1932
 1933    pub fn is_remote(&self) -> bool {
 1934        !self.is_local()
 1935    }
 1936
 1937    pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
 1938        if self.is_remote() {
 1939            let create = self.client.request(proto::OpenNewBuffer {
 1940                project_id: self.remote_id().unwrap(),
 1941            });
 1942            cx.spawn(|this, mut cx| async move {
 1943                let response = create.await?;
 1944                let buffer_id = BufferId::new(response.buffer_id)?;
 1945
 1946                this.update(&mut cx, |this, cx| {
 1947                    this.wait_for_remote_buffer(buffer_id, cx)
 1948                })?
 1949                .await
 1950            })
 1951        } else {
 1952            Task::ready(Ok(self.create_local_buffer("", None, cx)))
 1953        }
 1954    }
 1955
 1956    pub fn create_local_buffer(
 1957        &mut self,
 1958        text: &str,
 1959        language: Option<Arc<Language>>,
 1960        cx: &mut ModelContext<Self>,
 1961    ) -> Model<Buffer> {
 1962        if self.is_remote() {
 1963            panic!("called create_local_buffer on a remote project")
 1964        }
 1965        let buffer = cx.new_model(|cx| {
 1966            Buffer::local(text, cx)
 1967                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
 1968        });
 1969        self.register_buffer(&buffer, cx)
 1970            .expect("creating local buffers always succeeds");
 1971        buffer
 1972    }
 1973
 1974    pub fn open_path(
 1975        &mut self,
 1976        path: ProjectPath,
 1977        cx: &mut ModelContext<Self>,
 1978    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
 1979        let task = self.open_buffer(path.clone(), cx);
 1980        cx.spawn(move |_, cx| async move {
 1981            let buffer = task.await?;
 1982            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
 1983                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
 1984            })?;
 1985
 1986            let buffer: &AnyModel = &buffer;
 1987            Ok((project_entry_id, buffer.clone()))
 1988        })
 1989    }
 1990
 1991    pub fn open_local_buffer(
 1992        &mut self,
 1993        abs_path: impl AsRef<Path>,
 1994        cx: &mut ModelContext<Self>,
 1995    ) -> Task<Result<Model<Buffer>>> {
 1996        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
 1997            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
 1998        } else {
 1999            Task::ready(Err(anyhow!("no such path")))
 2000        }
 2001    }
 2002
 2003    pub fn open_buffer(
 2004        &mut self,
 2005        path: impl Into<ProjectPath>,
 2006        cx: &mut ModelContext<Self>,
 2007    ) -> Task<Result<Model<Buffer>>> {
 2008        let project_path = path.into();
 2009        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
 2010            worktree
 2011        } else {
 2012            return Task::ready(Err(anyhow!("no such worktree")));
 2013        };
 2014
 2015        // If there is already a buffer for the given path, then return it.
 2016        let existing_buffer = self.get_open_buffer(&project_path, cx);
 2017        if let Some(existing_buffer) = existing_buffer {
 2018            return Task::ready(Ok(existing_buffer));
 2019        }
 2020
 2021        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
 2022            // If the given path is already being loaded, then wait for that existing
 2023            // task to complete and return the same buffer.
 2024            hash_map::Entry::Occupied(e) => e.get().clone(),
 2025
 2026            // Otherwise, record the fact that this path is now being loaded.
 2027            hash_map::Entry::Vacant(entry) => {
 2028                let (mut tx, rx) = postage::watch::channel();
 2029                entry.insert(rx.clone());
 2030
 2031                let project_path = project_path.clone();
 2032                let load_buffer = if worktree.read(cx).is_local() {
 2033                    self.open_local_buffer_internal(project_path.path.clone(), worktree, cx)
 2034                } else {
 2035                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
 2036                };
 2037
 2038                cx.spawn(move |this, mut cx| async move {
 2039                    let load_result = load_buffer.await;
 2040                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
 2041                        // Record the fact that the buffer is no longer loading.
 2042                        this.loading_buffers_by_path.remove(&project_path);
 2043                        let buffer = load_result.map_err(Arc::new)?;
 2044                        Ok(buffer)
 2045                    })?);
 2046                    anyhow::Ok(())
 2047                })
 2048                .detach();
 2049                rx
 2050            }
 2051        };
 2052
 2053        cx.background_executor().spawn(async move {
 2054            wait_for_loading_buffer(loading_watch)
 2055                .await
 2056                .map_err(|e| e.cloned())
 2057        })
 2058    }
 2059
 2060    fn open_local_buffer_internal(
 2061        &mut self,
 2062        path: Arc<Path>,
 2063        worktree: Model<Worktree>,
 2064        cx: &mut ModelContext<Self>,
 2065    ) -> Task<Result<Model<Buffer>>> {
 2066        let load_buffer = worktree.update(cx, |worktree, cx| {
 2067            let worktree = worktree.as_local_mut().unwrap();
 2068            worktree.load_buffer(&path, cx)
 2069        });
 2070        fn is_not_found_error(error: &anyhow::Error) -> bool {
 2071            error
 2072                .root_cause()
 2073                .downcast_ref::<io::Error>()
 2074                .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
 2075        }
 2076        cx.spawn(move |this, mut cx| async move {
 2077            let buffer = match load_buffer.await {
 2078                Ok(buffer) => Ok(buffer),
 2079                Err(error) if is_not_found_error(&error) => {
 2080                    worktree.update(&mut cx, |worktree, cx| {
 2081                        let worktree = worktree.as_local_mut().unwrap();
 2082                        worktree.new_buffer(path, cx)
 2083                    })
 2084                }
 2085                Err(e) => Err(e),
 2086            }?;
 2087            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
 2088            Ok(buffer)
 2089        })
 2090    }
 2091
 2092    fn open_remote_buffer_internal(
 2093        &mut self,
 2094        path: &Arc<Path>,
 2095        worktree: &Model<Worktree>,
 2096        cx: &mut ModelContext<Self>,
 2097    ) -> Task<Result<Model<Buffer>>> {
 2098        let rpc = self.client.clone();
 2099        let project_id = self.remote_id().unwrap();
 2100        let remote_worktree_id = worktree.read(cx).id();
 2101        let path = path.clone();
 2102        let path_string = path.to_string_lossy().to_string();
 2103        cx.spawn(move |this, mut cx| async move {
 2104            let response = rpc
 2105                .request(proto::OpenBufferByPath {
 2106                    project_id,
 2107                    worktree_id: remote_worktree_id.to_proto(),
 2108                    path: path_string,
 2109                })
 2110                .await?;
 2111            let buffer_id = BufferId::new(response.buffer_id)?;
 2112            this.update(&mut cx, |this, cx| {
 2113                this.wait_for_remote_buffer(buffer_id, cx)
 2114            })?
 2115            .await
 2116        })
 2117    }
 2118
 2119    /// LanguageServerName is owned, because it is inserted into a map
 2120    pub fn open_local_buffer_via_lsp(
 2121        &mut self,
 2122        abs_path: lsp::Url,
 2123        language_server_id: LanguageServerId,
 2124        language_server_name: LanguageServerName,
 2125        cx: &mut ModelContext<Self>,
 2126    ) -> Task<Result<Model<Buffer>>> {
 2127        cx.spawn(move |this, mut cx| async move {
 2128            let abs_path = abs_path
 2129                .to_file_path()
 2130                .map_err(|_| anyhow!("can't convert URI to path"))?;
 2131            let (worktree, relative_path) = if let Some(result) =
 2132                this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
 2133            {
 2134                result
 2135            } else {
 2136                let worktree = this
 2137                    .update(&mut cx, |this, cx| {
 2138                        this.create_local_worktree(&abs_path, false, cx)
 2139                    })?
 2140                    .await?;
 2141                this.update(&mut cx, |this, cx| {
 2142                    this.language_server_ids.insert(
 2143                        (worktree.read(cx).id(), language_server_name),
 2144                        language_server_id,
 2145                    );
 2146                })
 2147                .ok();
 2148                (worktree, PathBuf::new())
 2149            };
 2150
 2151            let project_path = ProjectPath {
 2152                worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
 2153                path: relative_path.into(),
 2154            };
 2155            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
 2156                .await
 2157        })
 2158    }
 2159
 2160    pub fn open_buffer_by_id(
 2161        &mut self,
 2162        id: BufferId,
 2163        cx: &mut ModelContext<Self>,
 2164    ) -> Task<Result<Model<Buffer>>> {
 2165        if let Some(buffer) = self.buffer_for_id(id) {
 2166            Task::ready(Ok(buffer))
 2167        } else if self.is_local() {
 2168            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
 2169        } else if let Some(project_id) = self.remote_id() {
 2170            let request = self.client.request(proto::OpenBufferById {
 2171                project_id,
 2172                id: id.into(),
 2173            });
 2174            cx.spawn(move |this, mut cx| async move {
 2175                let buffer_id = BufferId::new(request.await?.buffer_id)?;
 2176                this.update(&mut cx, |this, cx| {
 2177                    this.wait_for_remote_buffer(buffer_id, cx)
 2178                })?
 2179                .await
 2180            })
 2181        } else {
 2182            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
 2183        }
 2184    }
 2185
 2186    pub fn save_buffers(
 2187        &self,
 2188        buffers: HashSet<Model<Buffer>>,
 2189        cx: &mut ModelContext<Self>,
 2190    ) -> Task<Result<()>> {
 2191        cx.spawn(move |this, mut cx| async move {
 2192            let save_tasks = buffers.into_iter().filter_map(|buffer| {
 2193                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
 2194                    .ok()
 2195            });
 2196            try_join_all(save_tasks).await?;
 2197            Ok(())
 2198        })
 2199    }
 2200
 2201    pub fn save_buffer(
 2202        &self,
 2203        buffer: Model<Buffer>,
 2204        cx: &mut ModelContext<Self>,
 2205    ) -> Task<Result<()>> {
 2206        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2207            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 2208        };
 2209        let worktree = file.worktree.clone();
 2210        let path = file.path.clone();
 2211        worktree.update(cx, |worktree, cx| match worktree {
 2212            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
 2213            Worktree::Remote(worktree) => worktree.save_buffer(buffer, None, cx),
 2214        })
 2215    }
 2216
 2217    pub fn save_buffer_as(
 2218        &mut self,
 2219        buffer: Model<Buffer>,
 2220        path: ProjectPath,
 2221        cx: &mut ModelContext<Self>,
 2222    ) -> Task<Result<()>> {
 2223        let old_file = File::from_dyn(buffer.read(cx).file())
 2224            .filter(|f| f.is_local())
 2225            .cloned();
 2226        let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) else {
 2227            return Task::ready(Err(anyhow!("worktree does not exist")));
 2228        };
 2229
 2230        cx.spawn(move |this, mut cx| async move {
 2231            if let Some(old_file) = &old_file {
 2232                this.update(&mut cx, |this, cx| {
 2233                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
 2234                })?;
 2235            }
 2236            worktree
 2237                .update(&mut cx, |worktree, cx| match worktree {
 2238                    Worktree::Local(worktree) => {
 2239                        worktree.save_buffer(buffer.clone(), path.path, true, cx)
 2240                    }
 2241                    Worktree::Remote(worktree) => {
 2242                        worktree.save_buffer(buffer.clone(), Some(path.to_proto()), cx)
 2243                    }
 2244                })?
 2245                .await?;
 2246
 2247            this.update(&mut cx, |this, cx| {
 2248                this.detect_language_for_buffer(&buffer, cx);
 2249                this.register_buffer_with_language_servers(&buffer, cx);
 2250            })?;
 2251            Ok(())
 2252        })
 2253    }
 2254
 2255    pub fn get_open_buffer(
 2256        &mut self,
 2257        path: &ProjectPath,
 2258        cx: &mut ModelContext<Self>,
 2259    ) -> Option<Model<Buffer>> {
 2260        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
 2261        self.opened_buffers.values().find_map(|buffer| {
 2262            let buffer = buffer.upgrade()?;
 2263            let file = File::from_dyn(buffer.read(cx).file())?;
 2264            if file.worktree == worktree && file.path() == &path.path {
 2265                Some(buffer)
 2266            } else {
 2267                None
 2268            }
 2269        })
 2270    }
 2271
 2272    fn register_buffer(
 2273        &mut self,
 2274        buffer: &Model<Buffer>,
 2275        cx: &mut ModelContext<Self>,
 2276    ) -> Result<()> {
 2277        self.request_buffer_diff_recalculation(buffer, cx);
 2278        buffer.update(cx, |buffer, _| {
 2279            buffer.set_language_registry(self.languages.clone())
 2280        });
 2281
 2282        let remote_id = buffer.read(cx).remote_id();
 2283        let is_remote = self.is_remote();
 2284        let open_buffer = if is_remote || self.is_shared() {
 2285            OpenBuffer::Strong(buffer.clone())
 2286        } else {
 2287            OpenBuffer::Weak(buffer.downgrade())
 2288        };
 2289
 2290        match self.opened_buffers.entry(remote_id) {
 2291            hash_map::Entry::Vacant(entry) => {
 2292                entry.insert(open_buffer);
 2293            }
 2294            hash_map::Entry::Occupied(mut entry) => {
 2295                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 2296                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
 2297                } else if entry.get().upgrade().is_some() {
 2298                    if is_remote {
 2299                        return Ok(());
 2300                    } else {
 2301                        debug_panic!("buffer {} was already registered", remote_id);
 2302                        Err(anyhow!("buffer {} was already registered", remote_id))?;
 2303                    }
 2304                }
 2305                entry.insert(open_buffer);
 2306            }
 2307        }
 2308        cx.subscribe(buffer, |this, buffer, event, cx| {
 2309            this.on_buffer_event(buffer, event, cx);
 2310        })
 2311        .detach();
 2312
 2313        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 2314            if file.is_local {
 2315                self.local_buffer_ids_by_path.insert(
 2316                    ProjectPath {
 2317                        worktree_id: file.worktree_id(cx),
 2318                        path: file.path.clone(),
 2319                    },
 2320                    remote_id,
 2321                );
 2322
 2323                if let Some(entry_id) = file.entry_id {
 2324                    self.local_buffer_ids_by_entry_id
 2325                        .insert(entry_id, remote_id);
 2326                }
 2327            }
 2328        }
 2329
 2330        self.detect_language_for_buffer(buffer, cx);
 2331        self.register_buffer_with_language_servers(buffer, cx);
 2332        // self.register_buffer_with_copilot(buffer, cx);
 2333        cx.observe_release(buffer, |this, buffer, cx| {
 2334            if let Some(file) = File::from_dyn(buffer.file()) {
 2335                if file.is_local() {
 2336                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 2337                    for server in this.language_servers_for_buffer(buffer, cx) {
 2338                        server
 2339                            .1
 2340                            .notify::<lsp::notification::DidCloseTextDocument>(
 2341                                lsp::DidCloseTextDocumentParams {
 2342                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
 2343                                },
 2344                            )
 2345                            .log_err();
 2346                    }
 2347                }
 2348            }
 2349        })
 2350        .detach();
 2351
 2352        if let Some(senders) = self.loading_buffers.remove(&remote_id) {
 2353            for sender in senders {
 2354                sender.send(Ok(buffer.clone())).ok();
 2355            }
 2356        }
 2357        Ok(())
 2358    }
 2359
 2360    fn register_buffer_with_language_servers(
 2361        &mut self,
 2362        buffer_handle: &Model<Buffer>,
 2363        cx: &mut ModelContext<Self>,
 2364    ) {
 2365        let buffer = buffer_handle.read(cx);
 2366        let buffer_id = buffer.remote_id();
 2367
 2368        if let Some(file) = File::from_dyn(buffer.file()) {
 2369            if !file.is_local() {
 2370                return;
 2371            }
 2372
 2373            let abs_path = file.abs_path(cx);
 2374            let uri = lsp::Url::from_file_path(&abs_path)
 2375                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
 2376            let initial_snapshot = buffer.text_snapshot();
 2377            let language = buffer.language().cloned();
 2378            let worktree_id = file.worktree_id(cx);
 2379
 2380            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
 2381                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
 2382                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
 2383                        .log_err();
 2384                }
 2385            }
 2386
 2387            if let Some(language) = language {
 2388                for adapter in self.languages.lsp_adapters(&language) {
 2389                    let server = self
 2390                        .language_server_ids
 2391                        .get(&(worktree_id, adapter.name.clone()))
 2392                        .and_then(|id| self.language_servers.get(id))
 2393                        .and_then(|server_state| {
 2394                            if let LanguageServerState::Running { server, .. } = server_state {
 2395                                Some(server.clone())
 2396                            } else {
 2397                                None
 2398                            }
 2399                        });
 2400                    let server = match server {
 2401                        Some(server) => server,
 2402                        None => continue,
 2403                    };
 2404
 2405                    server
 2406                        .notify::<lsp::notification::DidOpenTextDocument>(
 2407                            lsp::DidOpenTextDocumentParams {
 2408                                text_document: lsp::TextDocumentItem::new(
 2409                                    uri.clone(),
 2410                                    adapter.language_id(&language),
 2411                                    0,
 2412                                    initial_snapshot.text(),
 2413                                ),
 2414                            },
 2415                        )
 2416                        .log_err();
 2417
 2418                    buffer_handle.update(cx, |buffer, cx| {
 2419                        buffer.set_completion_triggers(
 2420                            server
 2421                                .capabilities()
 2422                                .completion_provider
 2423                                .as_ref()
 2424                                .and_then(|provider| provider.trigger_characters.clone())
 2425                                .unwrap_or_default(),
 2426                            cx,
 2427                        );
 2428                    });
 2429
 2430                    let snapshot = LspBufferSnapshot {
 2431                        version: 0,
 2432                        snapshot: initial_snapshot.clone(),
 2433                    };
 2434                    self.buffer_snapshots
 2435                        .entry(buffer_id)
 2436                        .or_default()
 2437                        .insert(server.server_id(), vec![snapshot]);
 2438                }
 2439            }
 2440        }
 2441    }
 2442
 2443    fn unregister_buffer_from_language_servers(
 2444        &mut self,
 2445        buffer: &Model<Buffer>,
 2446        old_file: &File,
 2447        cx: &mut ModelContext<Self>,
 2448    ) {
 2449        let old_path = match old_file.as_local() {
 2450            Some(local) => local.abs_path(cx),
 2451            None => return,
 2452        };
 2453
 2454        buffer.update(cx, |buffer, cx| {
 2455            let worktree_id = old_file.worktree_id(cx);
 2456            let ids = &self.language_server_ids;
 2457
 2458            if let Some(language) = buffer.language().cloned() {
 2459                for adapter in self.languages.lsp_adapters(&language) {
 2460                    if let Some(server_id) = ids.get(&(worktree_id, adapter.name.clone())) {
 2461                        buffer.update_diagnostics(*server_id, Default::default(), cx);
 2462                    }
 2463                }
 2464            }
 2465
 2466            self.buffer_snapshots.remove(&buffer.remote_id());
 2467            let file_url = lsp::Url::from_file_path(old_path).unwrap();
 2468            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
 2469                language_server
 2470                    .notify::<lsp::notification::DidCloseTextDocument>(
 2471                        lsp::DidCloseTextDocumentParams {
 2472                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
 2473                        },
 2474                    )
 2475                    .log_err();
 2476            }
 2477        });
 2478    }
 2479
 2480    // fn register_buffer_with_copilot(
 2481    //     &self,
 2482    //     buffer_handle: &Model<Buffer>,
 2483    //     cx: &mut ModelContext<Self>,
 2484    // ) {
 2485    //     if let Some(copilot) = Copilot::global(cx) {
 2486    //         copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
 2487    //     }
 2488    // }
 2489
 2490    async fn send_buffer_ordered_messages(
 2491        this: WeakModel<Self>,
 2492        rx: UnboundedReceiver<BufferOrderedMessage>,
 2493        mut cx: AsyncAppContext,
 2494    ) -> Result<()> {
 2495        const MAX_BATCH_SIZE: usize = 128;
 2496
 2497        let mut operations_by_buffer_id = HashMap::default();
 2498        async fn flush_operations(
 2499            this: &WeakModel<Project>,
 2500            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
 2501            needs_resync_with_host: &mut bool,
 2502            is_local: bool,
 2503            cx: &mut AsyncAppContext,
 2504        ) -> Result<()> {
 2505            for (buffer_id, operations) in operations_by_buffer_id.drain() {
 2506                let request = this.update(cx, |this, _| {
 2507                    let project_id = this.remote_id()?;
 2508                    Some(this.client.request(proto::UpdateBuffer {
 2509                        buffer_id: buffer_id.into(),
 2510                        project_id,
 2511                        operations,
 2512                    }))
 2513                })?;
 2514                if let Some(request) = request {
 2515                    if request.await.is_err() && !is_local {
 2516                        *needs_resync_with_host = true;
 2517                        break;
 2518                    }
 2519                }
 2520            }
 2521            Ok(())
 2522        }
 2523
 2524        let mut needs_resync_with_host = false;
 2525        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
 2526
 2527        while let Some(changes) = changes.next().await {
 2528            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
 2529
 2530            for change in changes {
 2531                match change {
 2532                    BufferOrderedMessage::Operation {
 2533                        buffer_id,
 2534                        operation,
 2535                    } => {
 2536                        if needs_resync_with_host {
 2537                            continue;
 2538                        }
 2539
 2540                        operations_by_buffer_id
 2541                            .entry(buffer_id)
 2542                            .or_insert(Vec::new())
 2543                            .push(operation);
 2544                    }
 2545
 2546                    BufferOrderedMessage::Resync => {
 2547                        operations_by_buffer_id.clear();
 2548                        if this
 2549                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
 2550                            .await
 2551                            .is_ok()
 2552                        {
 2553                            needs_resync_with_host = false;
 2554                        }
 2555                    }
 2556
 2557                    BufferOrderedMessage::LanguageServerUpdate {
 2558                        language_server_id,
 2559                        message,
 2560                    } => {
 2561                        flush_operations(
 2562                            &this,
 2563                            &mut operations_by_buffer_id,
 2564                            &mut needs_resync_with_host,
 2565                            is_local,
 2566                            &mut cx,
 2567                        )
 2568                        .await?;
 2569
 2570                        this.update(&mut cx, |this, _| {
 2571                            if let Some(project_id) = this.remote_id() {
 2572                                this.client
 2573                                    .send(proto::UpdateLanguageServer {
 2574                                        project_id,
 2575                                        language_server_id: language_server_id.0 as u64,
 2576                                        variant: Some(message),
 2577                                    })
 2578                                    .log_err();
 2579                            }
 2580                        })?;
 2581                    }
 2582                }
 2583            }
 2584
 2585            flush_operations(
 2586                &this,
 2587                &mut operations_by_buffer_id,
 2588                &mut needs_resync_with_host,
 2589                is_local,
 2590                &mut cx,
 2591            )
 2592            .await?;
 2593        }
 2594
 2595        Ok(())
 2596    }
 2597
 2598    fn on_buffer_event(
 2599        &mut self,
 2600        buffer: Model<Buffer>,
 2601        event: &BufferEvent,
 2602        cx: &mut ModelContext<Self>,
 2603    ) -> Option<()> {
 2604        if matches!(
 2605            event,
 2606            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
 2607        ) {
 2608            self.request_buffer_diff_recalculation(&buffer, cx);
 2609        }
 2610
 2611        match event {
 2612            BufferEvent::Operation(operation) => {
 2613                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
 2614                    buffer_id: buffer.read(cx).remote_id(),
 2615                    operation: language::proto::serialize_operation(operation),
 2616                })
 2617                .ok();
 2618            }
 2619
 2620            BufferEvent::Edited { .. } => {
 2621                let buffer = buffer.read(cx);
 2622                let file = File::from_dyn(buffer.file())?;
 2623                let abs_path = file.as_local()?.abs_path(cx);
 2624                let uri = lsp::Url::from_file_path(abs_path).unwrap();
 2625                let next_snapshot = buffer.text_snapshot();
 2626
 2627                let language_servers: Vec<_> = self
 2628                    .language_servers_for_buffer(buffer, cx)
 2629                    .map(|i| i.1.clone())
 2630                    .collect();
 2631
 2632                for language_server in language_servers {
 2633                    let language_server = language_server.clone();
 2634
 2635                    let buffer_snapshots = self
 2636                        .buffer_snapshots
 2637                        .get_mut(&buffer.remote_id())
 2638                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
 2639                    let previous_snapshot = buffer_snapshots.last()?;
 2640
 2641                    let build_incremental_change = || {
 2642                        buffer
 2643                            .edits_since::<(PointUtf16, usize)>(
 2644                                previous_snapshot.snapshot.version(),
 2645                            )
 2646                            .map(|edit| {
 2647                                let edit_start = edit.new.start.0;
 2648                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 2649                                let new_text = next_snapshot
 2650                                    .text_for_range(edit.new.start.1..edit.new.end.1)
 2651                                    .collect();
 2652                                lsp::TextDocumentContentChangeEvent {
 2653                                    range: Some(lsp::Range::new(
 2654                                        point_to_lsp(edit_start),
 2655                                        point_to_lsp(edit_end),
 2656                                    )),
 2657                                    range_length: None,
 2658                                    text: new_text,
 2659                                }
 2660                            })
 2661                            .collect()
 2662                    };
 2663
 2664                    let document_sync_kind = language_server
 2665                        .capabilities()
 2666                        .text_document_sync
 2667                        .as_ref()
 2668                        .and_then(|sync| match sync {
 2669                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
 2670                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
 2671                        });
 2672
 2673                    let content_changes: Vec<_> = match document_sync_kind {
 2674                        Some(lsp::TextDocumentSyncKind::FULL) => {
 2675                            vec![lsp::TextDocumentContentChangeEvent {
 2676                                range: None,
 2677                                range_length: None,
 2678                                text: next_snapshot.text(),
 2679                            }]
 2680                        }
 2681                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
 2682                        _ => {
 2683                            #[cfg(any(test, feature = "test-support"))]
 2684                            {
 2685                                build_incremental_change()
 2686                            }
 2687
 2688                            #[cfg(not(any(test, feature = "test-support")))]
 2689                            {
 2690                                continue;
 2691                            }
 2692                        }
 2693                    };
 2694
 2695                    let next_version = previous_snapshot.version + 1;
 2696
 2697                    buffer_snapshots.push(LspBufferSnapshot {
 2698                        version: next_version,
 2699                        snapshot: next_snapshot.clone(),
 2700                    });
 2701
 2702                    language_server
 2703                        .notify::<lsp::notification::DidChangeTextDocument>(
 2704                            lsp::DidChangeTextDocumentParams {
 2705                                text_document: lsp::VersionedTextDocumentIdentifier::new(
 2706                                    uri.clone(),
 2707                                    next_version,
 2708                                ),
 2709                                content_changes,
 2710                            },
 2711                        )
 2712                        .log_err();
 2713                }
 2714            }
 2715
 2716            BufferEvent::Saved => {
 2717                let file = File::from_dyn(buffer.read(cx).file())?;
 2718                let worktree_id = file.worktree_id(cx);
 2719                let abs_path = file.as_local()?.abs_path(cx);
 2720                let text_document = lsp::TextDocumentIdentifier {
 2721                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
 2722                };
 2723
 2724                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
 2725                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
 2726                    server
 2727                        .notify::<lsp::notification::DidSaveTextDocument>(
 2728                            lsp::DidSaveTextDocumentParams {
 2729                                text_document: text_document.clone(),
 2730                                text,
 2731                            },
 2732                        )
 2733                        .log_err();
 2734                }
 2735
 2736                for language_server_id in self.language_server_ids_for_buffer(buffer.read(cx), cx) {
 2737                    self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
 2738                }
 2739            }
 2740            BufferEvent::FileHandleChanged => {
 2741                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2742                    return None;
 2743                };
 2744
 2745                let remote_id = buffer.read(cx).remote_id();
 2746                if let Some(entry_id) = file.entry_id {
 2747                    match self.local_buffer_ids_by_entry_id.get(&entry_id) {
 2748                        Some(_) => {
 2749                            return None;
 2750                        }
 2751                        None => {
 2752                            self.local_buffer_ids_by_entry_id
 2753                                .insert(entry_id, remote_id);
 2754                        }
 2755                    }
 2756                };
 2757                self.local_buffer_ids_by_path.insert(
 2758                    ProjectPath {
 2759                        worktree_id: file.worktree_id(cx),
 2760                        path: file.path.clone(),
 2761                    },
 2762                    remote_id,
 2763                );
 2764            }
 2765            _ => {}
 2766        }
 2767
 2768        None
 2769    }
 2770
 2771    // After saving a buffer using a language server that doesn't provide a disk-based progress token,
 2772    // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
 2773    // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
 2774    // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
 2775    // the language server might take some time to publish diagnostics.
 2776    fn simulate_disk_based_diagnostics_events_if_needed(
 2777        &mut self,
 2778        language_server_id: LanguageServerId,
 2779        cx: &mut ModelContext<Self>,
 2780    ) {
 2781        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
 2782
 2783        let Some(LanguageServerState::Running {
 2784            simulate_disk_based_diagnostics_completion,
 2785            adapter,
 2786            ..
 2787        }) = self.language_servers.get_mut(&language_server_id)
 2788        else {
 2789            return;
 2790        };
 2791
 2792        if adapter.disk_based_diagnostics_progress_token.is_some() {
 2793            return;
 2794        }
 2795
 2796        let prev_task = simulate_disk_based_diagnostics_completion.replace(cx.spawn(
 2797            move |this, mut cx| async move {
 2798                cx.background_executor()
 2799                    .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
 2800                    .await;
 2801
 2802                this.update(&mut cx, |this, cx| {
 2803                    this.disk_based_diagnostics_finished(language_server_id, cx);
 2804
 2805                    if let Some(LanguageServerState::Running {
 2806                        simulate_disk_based_diagnostics_completion,
 2807                        ..
 2808                    }) = this.language_servers.get_mut(&language_server_id)
 2809                    {
 2810                        *simulate_disk_based_diagnostics_completion = None;
 2811                    }
 2812                })
 2813                .ok();
 2814            },
 2815        ));
 2816
 2817        if prev_task.is_none() {
 2818            self.disk_based_diagnostics_started(language_server_id, cx);
 2819        }
 2820    }
 2821
 2822    fn request_buffer_diff_recalculation(
 2823        &mut self,
 2824        buffer: &Model<Buffer>,
 2825        cx: &mut ModelContext<Self>,
 2826    ) {
 2827        self.buffers_needing_diff.insert(buffer.downgrade());
 2828        let first_insertion = self.buffers_needing_diff.len() == 1;
 2829
 2830        let settings = ProjectSettings::get_global(cx);
 2831        let delay = if let Some(delay) = settings.git.gutter_debounce {
 2832            delay
 2833        } else {
 2834            if first_insertion {
 2835                let this = cx.weak_model();
 2836                cx.defer(move |cx| {
 2837                    if let Some(this) = this.upgrade() {
 2838                        this.update(cx, |this, cx| {
 2839                            this.recalculate_buffer_diffs(cx).detach();
 2840                        });
 2841                    }
 2842                });
 2843            }
 2844            return;
 2845        };
 2846
 2847        const MIN_DELAY: u64 = 50;
 2848        let delay = delay.max(MIN_DELAY);
 2849        let duration = Duration::from_millis(delay);
 2850
 2851        self.git_diff_debouncer
 2852            .fire_new(duration, cx, move |this, cx| {
 2853                this.recalculate_buffer_diffs(cx)
 2854            });
 2855    }
 2856
 2857    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
 2858        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
 2859        cx.spawn(move |this, mut cx| async move {
 2860            let tasks: Vec<_> = buffers
 2861                .iter()
 2862                .filter_map(|buffer| {
 2863                    let buffer = buffer.upgrade()?;
 2864                    buffer
 2865                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
 2866                        .ok()
 2867                        .flatten()
 2868                })
 2869                .collect();
 2870
 2871            futures::future::join_all(tasks).await;
 2872
 2873            this.update(&mut cx, |this, cx| {
 2874                if this.buffers_needing_diff.is_empty() {
 2875                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
 2876                    for buffer in buffers {
 2877                        if let Some(buffer) = buffer.upgrade() {
 2878                            buffer.update(cx, |_, cx| cx.notify());
 2879                        }
 2880                    }
 2881                } else {
 2882                    this.recalculate_buffer_diffs(cx).detach();
 2883                }
 2884            })
 2885            .ok();
 2886        })
 2887    }
 2888
 2889    fn language_servers_for_worktree(
 2890        &self,
 2891        worktree_id: WorktreeId,
 2892    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
 2893        self.language_server_ids
 2894            .iter()
 2895            .filter_map(move |((language_server_worktree_id, _), id)| {
 2896                if *language_server_worktree_id == worktree_id {
 2897                    if let Some(LanguageServerState::Running {
 2898                        adapter,
 2899                        language,
 2900                        server,
 2901                        ..
 2902                    }) = self.language_servers.get(id)
 2903                    {
 2904                        return Some((adapter, language, server));
 2905                    }
 2906                }
 2907                None
 2908            })
 2909    }
 2910
 2911    fn maintain_buffer_languages(
 2912        languages: Arc<LanguageRegistry>,
 2913        cx: &mut ModelContext<Project>,
 2914    ) -> Task<()> {
 2915        let mut subscription = languages.subscribe();
 2916        let mut prev_reload_count = languages.reload_count();
 2917        cx.spawn(move |project, mut cx| async move {
 2918            while let Some(()) = subscription.next().await {
 2919                if let Some(project) = project.upgrade() {
 2920                    // If the language registry has been reloaded, then remove and
 2921                    // re-assign the languages on all open buffers.
 2922                    let reload_count = languages.reload_count();
 2923                    if reload_count > prev_reload_count {
 2924                        prev_reload_count = reload_count;
 2925                        project
 2926                            .update(&mut cx, |this, cx| {
 2927                                let buffers = this
 2928                                    .opened_buffers
 2929                                    .values()
 2930                                    .filter_map(|b| b.upgrade())
 2931                                    .collect::<Vec<_>>();
 2932                                for buffer in buffers {
 2933                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
 2934                                    {
 2935                                        this.unregister_buffer_from_language_servers(
 2936                                            &buffer, &f, cx,
 2937                                        );
 2938                                        buffer
 2939                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
 2940                                    }
 2941                                }
 2942                            })
 2943                            .ok();
 2944                    }
 2945
 2946                    project
 2947                        .update(&mut cx, |project, cx| {
 2948                            let mut plain_text_buffers = Vec::new();
 2949                            let mut buffers_with_unknown_injections = Vec::new();
 2950                            for buffer in project.opened_buffers.values() {
 2951                                if let Some(handle) = buffer.upgrade() {
 2952                                    let buffer = &handle.read(cx);
 2953                                    if buffer.language().is_none()
 2954                                        || buffer.language() == Some(&*language::PLAIN_TEXT)
 2955                                    {
 2956                                        plain_text_buffers.push(handle);
 2957                                    } else if buffer.contains_unknown_injections() {
 2958                                        buffers_with_unknown_injections.push(handle);
 2959                                    }
 2960                                }
 2961                            }
 2962
 2963                            for buffer in plain_text_buffers {
 2964                                project.detect_language_for_buffer(&buffer, cx);
 2965                                project.register_buffer_with_language_servers(&buffer, cx);
 2966                            }
 2967
 2968                            for buffer in buffers_with_unknown_injections {
 2969                                buffer.update(cx, |buffer, cx| buffer.reparse(cx));
 2970                            }
 2971                        })
 2972                        .ok();
 2973                }
 2974            }
 2975        })
 2976    }
 2977
 2978    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
 2979        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
 2980        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
 2981
 2982        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
 2983            *settings_changed_tx.borrow_mut() = ();
 2984        });
 2985
 2986        cx.spawn(move |this, mut cx| async move {
 2987            while let Some(()) = settings_changed_rx.next().await {
 2988                let servers = this.update(&mut cx, |this, cx| {
 2989                    this.language_server_ids
 2990                        .iter()
 2991                        .filter_map(|((worktree_id, _), server_id)| {
 2992                            let worktree = this.worktree_for_id(*worktree_id, cx)?;
 2993                            let state = this.language_servers.get(server_id)?;
 2994                            let delegate = ProjectLspAdapterDelegate::new(this, &worktree, cx);
 2995                            match state {
 2996                                LanguageServerState::Starting(_) => None,
 2997                                LanguageServerState::Running {
 2998                                    adapter, server, ..
 2999                                } => Some((
 3000                                    adapter.adapter.clone(),
 3001                                    server.clone(),
 3002                                    delegate as Arc<dyn LspAdapterDelegate>,
 3003                                )),
 3004                            }
 3005                        })
 3006                        .collect::<Vec<_>>()
 3007                })?;
 3008
 3009                for (adapter, server, delegate) in servers {
 3010                    let settings = adapter.workspace_configuration(&delegate, &mut cx).await?;
 3011
 3012                    server
 3013                        .notify::<lsp::notification::DidChangeConfiguration>(
 3014                            lsp::DidChangeConfigurationParams { settings },
 3015                        )
 3016                        .ok();
 3017                }
 3018            }
 3019
 3020            drop(settings_observation);
 3021            anyhow::Ok(())
 3022        })
 3023    }
 3024
 3025    fn detect_language_for_buffer(
 3026        &mut self,
 3027        buffer_handle: &Model<Buffer>,
 3028        cx: &mut ModelContext<Self>,
 3029    ) {
 3030        // If the buffer has a language, set it and start the language server if we haven't already.
 3031        let buffer = buffer_handle.read(cx);
 3032        let Some(file) = buffer.file() else {
 3033            return;
 3034        };
 3035        let content = buffer.as_rope();
 3036        let Some(new_language_result) = self
 3037            .languages
 3038            .language_for_file(file, Some(content), cx)
 3039            .now_or_never()
 3040        else {
 3041            return;
 3042        };
 3043
 3044        match new_language_result {
 3045            Err(e) => {
 3046                if e.is::<language::LanguageNotFound>() {
 3047                    cx.emit(Event::LanguageNotFound(buffer_handle.clone()))
 3048                }
 3049            }
 3050            Ok(new_language) => {
 3051                self.set_language_for_buffer(buffer_handle, new_language, cx);
 3052            }
 3053        };
 3054    }
 3055
 3056    pub fn set_language_for_buffer(
 3057        &mut self,
 3058        buffer: &Model<Buffer>,
 3059        new_language: Arc<Language>,
 3060        cx: &mut ModelContext<Self>,
 3061    ) {
 3062        buffer.update(cx, |buffer, cx| {
 3063            if buffer.language().map_or(true, |old_language| {
 3064                !Arc::ptr_eq(old_language, &new_language)
 3065            }) {
 3066                buffer.set_language(Some(new_language.clone()), cx);
 3067            }
 3068        });
 3069
 3070        let buffer_file = buffer.read(cx).file().cloned();
 3071        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
 3072        let buffer_file = File::from_dyn(buffer_file.as_ref());
 3073        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
 3074        if let Some(prettier_plugins) =
 3075            prettier_support::prettier_plugins_for_language(&new_language, &settings)
 3076        {
 3077            self.install_default_prettier(worktree, prettier_plugins.iter().cloned(), cx);
 3078        };
 3079        if let Some(file) = buffer_file {
 3080            let worktree = file.worktree.clone();
 3081            if worktree.read(cx).is_local() {
 3082                self.start_language_servers(&worktree, new_language, cx);
 3083            }
 3084        }
 3085    }
 3086
 3087    fn start_language_servers(
 3088        &mut self,
 3089        worktree: &Model<Worktree>,
 3090        language: Arc<Language>,
 3091        cx: &mut ModelContext<Self>,
 3092    ) {
 3093        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
 3094        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
 3095        if !settings.enable_language_server {
 3096            return;
 3097        }
 3098
 3099        let available_lsp_adapters = self.languages.clone().lsp_adapters(&language);
 3100        let available_language_servers = available_lsp_adapters
 3101            .iter()
 3102            .map(|lsp_adapter| lsp_adapter.name.clone())
 3103            .collect::<Vec<_>>();
 3104
 3105        let desired_language_servers =
 3106            settings.customized_language_servers(&available_language_servers);
 3107
 3108        let mut enabled_lsp_adapters: Vec<Arc<CachedLspAdapter>> = Vec::new();
 3109        for desired_language_server in desired_language_servers {
 3110            if let Some(adapter) = available_lsp_adapters
 3111                .iter()
 3112                .find(|adapter| adapter.name == desired_language_server)
 3113            {
 3114                enabled_lsp_adapters.push(adapter.clone());
 3115                continue;
 3116            }
 3117
 3118            if let Some(adapter) = self
 3119                .languages
 3120                .load_available_lsp_adapter(&desired_language_server)
 3121            {
 3122                self.languages()
 3123                    .register_lsp_adapter(language.name(), adapter.adapter.clone());
 3124                enabled_lsp_adapters.push(adapter);
 3125                continue;
 3126            }
 3127
 3128            log::warn!(
 3129                "no language server found matching '{}'",
 3130                desired_language_server.0
 3131            );
 3132        }
 3133
 3134        log::info!(
 3135            "starting language servers for {language}: {adapters}",
 3136            language = language.name(),
 3137            adapters = enabled_lsp_adapters
 3138                .iter()
 3139                .map(|adapter| adapter.name.0.as_ref())
 3140                .join(", ")
 3141        );
 3142
 3143        for adapter in enabled_lsp_adapters {
 3144            self.start_language_server(worktree, adapter, language.clone(), cx);
 3145        }
 3146    }
 3147
 3148    fn start_language_server(
 3149        &mut self,
 3150        worktree_handle: &Model<Worktree>,
 3151        adapter: Arc<CachedLspAdapter>,
 3152        language: Arc<Language>,
 3153        cx: &mut ModelContext<Self>,
 3154    ) {
 3155        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3156            return;
 3157        }
 3158
 3159        let worktree = worktree_handle.read(cx);
 3160        let worktree_id = worktree.id();
 3161        let worktree_path = worktree.abs_path();
 3162        let key = (worktree_id, adapter.name.clone());
 3163        if self.language_server_ids.contains_key(&key) {
 3164            return;
 3165        }
 3166
 3167        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
 3168        let lsp_adapter_delegate = ProjectLspAdapterDelegate::new(self, worktree_handle, cx);
 3169        let pending_server = match self.languages.create_pending_language_server(
 3170            stderr_capture.clone(),
 3171            language.clone(),
 3172            adapter.clone(),
 3173            Arc::clone(&worktree_path),
 3174            lsp_adapter_delegate.clone(),
 3175            cx,
 3176        ) {
 3177            Some(pending_server) => pending_server,
 3178            None => return,
 3179        };
 3180
 3181        let project_settings = ProjectSettings::get(
 3182            Some(SettingsLocation {
 3183                worktree_id: worktree_id.to_proto() as usize,
 3184                path: Path::new(""),
 3185            }),
 3186            cx,
 3187        );
 3188        let lsp = project_settings.lsp.get(&adapter.name.0);
 3189        let override_options = lsp.and_then(|s| s.initialization_options.clone());
 3190
 3191        let server_id = pending_server.server_id;
 3192        let container_dir = pending_server.container_dir.clone();
 3193        let state = LanguageServerState::Starting({
 3194            let adapter = adapter.clone();
 3195            let server_name = adapter.name.0.clone();
 3196            let language = language.clone();
 3197            let key = key.clone();
 3198
 3199            cx.spawn(move |this, mut cx| async move {
 3200                let result = Self::setup_and_insert_language_server(
 3201                    this.clone(),
 3202                    lsp_adapter_delegate,
 3203                    override_options,
 3204                    pending_server,
 3205                    adapter.clone(),
 3206                    language.clone(),
 3207                    server_id,
 3208                    key,
 3209                    &mut cx,
 3210                )
 3211                .await;
 3212
 3213                match result {
 3214                    Ok(server) => {
 3215                        stderr_capture.lock().take();
 3216                        server
 3217                    }
 3218
 3219                    Err(err) => {
 3220                        log::error!("failed to start language server {server_name:?}: {err}");
 3221                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
 3222
 3223                        let this = this.upgrade()?;
 3224                        let container_dir = container_dir?;
 3225
 3226                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
 3227                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3228                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
 3229                            log::error!("Hit {max} reinstallation attempts for {server_name:?}");
 3230                            return None;
 3231                        }
 3232
 3233                        log::info!(
 3234                            "retrying installation of language server {server_name:?} in {}s",
 3235                            SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
 3236                        );
 3237                        cx.background_executor()
 3238                            .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
 3239                            .await;
 3240
 3241                        let installation_test_binary = adapter
 3242                            .installation_test_binary(container_dir.to_path_buf())
 3243                            .await;
 3244
 3245                        this.update(&mut cx, |_, cx| {
 3246                            Self::check_errored_server(
 3247                                language,
 3248                                adapter,
 3249                                server_id,
 3250                                installation_test_binary,
 3251                                cx,
 3252                            )
 3253                        })
 3254                        .ok();
 3255
 3256                        None
 3257                    }
 3258                }
 3259            })
 3260        });
 3261
 3262        self.language_servers.insert(server_id, state);
 3263        self.language_server_ids.insert(key, server_id);
 3264    }
 3265
 3266    fn reinstall_language_server(
 3267        &mut self,
 3268        language: Arc<Language>,
 3269        adapter: Arc<CachedLspAdapter>,
 3270        server_id: LanguageServerId,
 3271        cx: &mut ModelContext<Self>,
 3272    ) -> Option<Task<()>> {
 3273        log::info!("beginning to reinstall server");
 3274
 3275        let existing_server = match self.language_servers.remove(&server_id) {
 3276            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3277            _ => None,
 3278        };
 3279
 3280        for worktree in &self.worktrees {
 3281            if let Some(worktree) = worktree.upgrade() {
 3282                let key = (worktree.read(cx).id(), adapter.name.clone());
 3283                self.language_server_ids.remove(&key);
 3284            }
 3285        }
 3286
 3287        Some(cx.spawn(move |this, mut cx| async move {
 3288            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
 3289                log::info!("shutting down existing server");
 3290                task.await;
 3291            }
 3292
 3293            // TODO: This is race-safe with regards to preventing new instances from
 3294            // starting while deleting, but existing instances in other projects are going
 3295            // to be very confused and messed up
 3296            let Some(task) = this
 3297                .update(&mut cx, |this, cx| {
 3298                    this.languages.delete_server_container(adapter.clone(), cx)
 3299                })
 3300                .log_err()
 3301            else {
 3302                return;
 3303            };
 3304            task.await;
 3305
 3306            this.update(&mut cx, |this, cx| {
 3307                let worktrees = this.worktrees.clone();
 3308                for worktree in worktrees {
 3309                    if let Some(worktree) = worktree.upgrade() {
 3310                        this.start_language_server(
 3311                            &worktree,
 3312                            adapter.clone(),
 3313                            language.clone(),
 3314                            cx,
 3315                        );
 3316                    }
 3317                }
 3318            })
 3319            .ok();
 3320        }))
 3321    }
 3322
 3323    #[allow(clippy::too_many_arguments)]
 3324    async fn setup_and_insert_language_server(
 3325        this: WeakModel<Self>,
 3326        delegate: Arc<dyn LspAdapterDelegate>,
 3327        override_initialization_options: Option<serde_json::Value>,
 3328        pending_server: PendingLanguageServer,
 3329        adapter: Arc<CachedLspAdapter>,
 3330        language: Arc<Language>,
 3331        server_id: LanguageServerId,
 3332        key: (WorktreeId, LanguageServerName),
 3333        cx: &mut AsyncAppContext,
 3334    ) -> Result<Option<Arc<LanguageServer>>> {
 3335        let language_server = Self::setup_pending_language_server(
 3336            this.clone(),
 3337            override_initialization_options,
 3338            pending_server,
 3339            delegate,
 3340            adapter.clone(),
 3341            server_id,
 3342            cx,
 3343        )
 3344        .await?;
 3345
 3346        let this = match this.upgrade() {
 3347            Some(this) => this,
 3348            None => return Err(anyhow!("failed to upgrade project handle")),
 3349        };
 3350
 3351        this.update(cx, |this, cx| {
 3352            this.insert_newly_running_language_server(
 3353                language,
 3354                adapter,
 3355                language_server.clone(),
 3356                server_id,
 3357                key,
 3358                cx,
 3359            )
 3360        })??;
 3361
 3362        Ok(Some(language_server))
 3363    }
 3364
 3365    async fn setup_pending_language_server(
 3366        this: WeakModel<Self>,
 3367        override_options: Option<serde_json::Value>,
 3368        pending_server: PendingLanguageServer,
 3369        delegate: Arc<dyn LspAdapterDelegate>,
 3370        adapter: Arc<CachedLspAdapter>,
 3371        server_id: LanguageServerId,
 3372        cx: &mut AsyncAppContext,
 3373    ) -> Result<Arc<LanguageServer>> {
 3374        let workspace_config = adapter
 3375            .adapter
 3376            .clone()
 3377            .workspace_configuration(&delegate, cx)
 3378            .await?;
 3379        let (language_server, mut initialization_options) = pending_server.task.await?;
 3380
 3381        let name = language_server.name();
 3382        language_server
 3383            .on_notification::<lsp::notification::PublishDiagnostics, _>({
 3384                let adapter = adapter.clone();
 3385                let this = this.clone();
 3386                move |mut params, mut cx| {
 3387                    let adapter = adapter.clone();
 3388                    if let Some(this) = this.upgrade() {
 3389                        adapter.process_diagnostics(&mut params);
 3390                        this.update(&mut cx, |this, cx| {
 3391                            this.update_diagnostics(
 3392                                server_id,
 3393                                params,
 3394                                &adapter.disk_based_diagnostic_sources,
 3395                                cx,
 3396                            )
 3397                            .log_err();
 3398                        })
 3399                        .ok();
 3400                    }
 3401                }
 3402            })
 3403            .detach();
 3404
 3405        language_server
 3406            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
 3407                let adapter = adapter.adapter.clone();
 3408                let delegate = delegate.clone();
 3409                move |params, mut cx| {
 3410                    let adapter = adapter.clone();
 3411                    let delegate = delegate.clone();
 3412                    async move {
 3413                        let workspace_config =
 3414                            adapter.workspace_configuration(&delegate, &mut cx).await?;
 3415                        Ok(params
 3416                            .items
 3417                            .into_iter()
 3418                            .map(|item| {
 3419                                if let Some(section) = &item.section {
 3420                                    workspace_config
 3421                                        .get(section)
 3422                                        .cloned()
 3423                                        .unwrap_or(serde_json::Value::Null)
 3424                                } else {
 3425                                    workspace_config.clone()
 3426                                }
 3427                            })
 3428                            .collect())
 3429                    }
 3430                }
 3431            })
 3432            .detach();
 3433
 3434        // Even though we don't have handling for these requests, respond to them to
 3435        // avoid stalling any language server like `gopls` which waits for a response
 3436        // to these requests when initializing.
 3437        language_server
 3438            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
 3439                let this = this.clone();
 3440                move |params, mut cx| {
 3441                    let this = this.clone();
 3442                    async move {
 3443                        this.update(&mut cx, |this, _| {
 3444                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
 3445                            {
 3446                                if let lsp::NumberOrString::String(token) = params.token {
 3447                                    status.progress_tokens.insert(token);
 3448                                }
 3449                            }
 3450                        })?;
 3451
 3452                        Ok(())
 3453                    }
 3454                }
 3455            })
 3456            .detach();
 3457
 3458        language_server
 3459            .on_request::<lsp::request::RegisterCapability, _, _>({
 3460                let this = this.clone();
 3461                move |params, mut cx| {
 3462                    let this = this.clone();
 3463                    async move {
 3464                        for reg in params.registrations {
 3465                            if reg.method == "workspace/didChangeWatchedFiles" {
 3466                                if let Some(options) = reg.register_options {
 3467                                    let options = serde_json::from_value(options)?;
 3468                                    this.update(&mut cx, |this, cx| {
 3469                                        this.on_lsp_did_change_watched_files(
 3470                                            server_id, options, cx,
 3471                                        );
 3472                                    })?;
 3473                                }
 3474                            }
 3475                        }
 3476                        Ok(())
 3477                    }
 3478                }
 3479            })
 3480            .detach();
 3481
 3482        language_server
 3483            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
 3484                let adapter = adapter.clone();
 3485                let this = this.clone();
 3486                move |params, cx| {
 3487                    Self::on_lsp_workspace_edit(
 3488                        this.clone(),
 3489                        params,
 3490                        server_id,
 3491                        adapter.clone(),
 3492                        cx,
 3493                    )
 3494                }
 3495            })
 3496            .detach();
 3497
 3498        language_server
 3499            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
 3500                let this = this.clone();
 3501                move |(), mut cx| {
 3502                    let this = this.clone();
 3503                    async move {
 3504                        this.update(&mut cx, |project, cx| {
 3505                            cx.emit(Event::RefreshInlayHints);
 3506                            project.remote_id().map(|project_id| {
 3507                                project.client.send(proto::RefreshInlayHints { project_id })
 3508                            })
 3509                        })?
 3510                        .transpose()?;
 3511                        Ok(())
 3512                    }
 3513                }
 3514            })
 3515            .detach();
 3516
 3517        language_server
 3518            .on_request::<lsp::request::ShowMessageRequest, _, _>({
 3519                let this = this.clone();
 3520                let name = name.to_string();
 3521                move |params, mut cx| {
 3522                    let this = this.clone();
 3523                    let name = name.to_string();
 3524                    async move {
 3525                        if let Some(actions) = params.actions {
 3526                            let (tx, mut rx) = smol::channel::bounded(1);
 3527                            let request = LanguageServerPromptRequest {
 3528                                level: match params.typ {
 3529                                    lsp::MessageType::ERROR => PromptLevel::Critical,
 3530                                    lsp::MessageType::WARNING => PromptLevel::Warning,
 3531                                    _ => PromptLevel::Info,
 3532                                },
 3533                                message: params.message,
 3534                                actions,
 3535                                response_channel: tx,
 3536                                lsp_name: name.clone(),
 3537                            };
 3538
 3539                            if let Ok(_) = this.update(&mut cx, |_, cx| {
 3540                                cx.emit(Event::LanguageServerPrompt(request));
 3541                            }) {
 3542                                let response = rx.next().await;
 3543
 3544                                Ok(response)
 3545                            } else {
 3546                                Ok(None)
 3547                            }
 3548                        } else {
 3549                            Ok(None)
 3550                        }
 3551                    }
 3552                }
 3553            })
 3554            .detach();
 3555
 3556        let disk_based_diagnostics_progress_token =
 3557            adapter.disk_based_diagnostics_progress_token.clone();
 3558
 3559        language_server
 3560            .on_notification::<ServerStatus, _>({
 3561                let this = this.clone();
 3562                let name = name.to_string();
 3563                move |params, mut cx| {
 3564                    let this = this.clone();
 3565                    let name = name.to_string();
 3566                    if let Some(ref message) = params.message {
 3567                        let message = message.trim();
 3568                        if !message.is_empty() {
 3569                            let formatted_message = format!(
 3570                                "Language server {name} (id {server_id}) status update: {message}"
 3571                            );
 3572                            match params.health {
 3573                                ServerHealthStatus::Ok => log::info!("{}", formatted_message),
 3574                                ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
 3575                                ServerHealthStatus::Error => {
 3576                                    log::error!("{}", formatted_message);
 3577                                    let (tx, _rx) = smol::channel::bounded(1);
 3578                                    let request = LanguageServerPromptRequest {
 3579                                        level: PromptLevel::Critical,
 3580                                        message: params.message.unwrap_or_default(),
 3581                                        actions: Vec::new(),
 3582                                        response_channel: tx,
 3583                                        lsp_name: name.clone(),
 3584                                    };
 3585                                    let _ = this
 3586                                        .update(&mut cx, |_, cx| {
 3587                                            cx.emit(Event::LanguageServerPrompt(request));
 3588                                        })
 3589                                        .ok();
 3590                                }
 3591                                ServerHealthStatus::Other(status) => {
 3592                                    log::info!(
 3593                                        "Unknown server health: {status}\n{formatted_message}"
 3594                                    )
 3595                                }
 3596                            }
 3597                        }
 3598                    }
 3599                }
 3600            })
 3601            .detach();
 3602
 3603        language_server
 3604            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
 3605                if let Some(this) = this.upgrade() {
 3606                    this.update(&mut cx, |this, cx| {
 3607                        this.on_lsp_progress(
 3608                            params,
 3609                            server_id,
 3610                            disk_based_diagnostics_progress_token.clone(),
 3611                            cx,
 3612                        );
 3613                    })
 3614                    .ok();
 3615                }
 3616            })
 3617            .detach();
 3618
 3619        match (&mut initialization_options, override_options) {
 3620            (Some(initialization_options), Some(override_options)) => {
 3621                merge_json_value_into(override_options, initialization_options);
 3622            }
 3623            (None, override_options) => initialization_options = override_options,
 3624            _ => {}
 3625        }
 3626        let language_server = cx
 3627            .update(|cx| language_server.initialize(initialization_options, cx))?
 3628            .await?;
 3629
 3630        language_server
 3631            .notify::<lsp::notification::DidChangeConfiguration>(
 3632                lsp::DidChangeConfigurationParams {
 3633                    settings: workspace_config,
 3634                },
 3635            )
 3636            .ok();
 3637
 3638        Ok(language_server)
 3639    }
 3640
 3641    fn insert_newly_running_language_server(
 3642        &mut self,
 3643        language: Arc<Language>,
 3644        adapter: Arc<CachedLspAdapter>,
 3645        language_server: Arc<LanguageServer>,
 3646        server_id: LanguageServerId,
 3647        key: (WorktreeId, LanguageServerName),
 3648        cx: &mut ModelContext<Self>,
 3649    ) -> Result<()> {
 3650        // If the language server for this key doesn't match the server id, don't store the
 3651        // server. Which will cause it to be dropped, killing the process
 3652        if self
 3653            .language_server_ids
 3654            .get(&key)
 3655            .map(|id| id != &server_id)
 3656            .unwrap_or(false)
 3657        {
 3658            return Ok(());
 3659        }
 3660
 3661        // Update language_servers collection with Running variant of LanguageServerState
 3662        // indicating that the server is up and running and ready
 3663        self.language_servers.insert(
 3664            server_id,
 3665            LanguageServerState::Running {
 3666                adapter: adapter.clone(),
 3667                language: language.clone(),
 3668                server: language_server.clone(),
 3669                simulate_disk_based_diagnostics_completion: None,
 3670            },
 3671        );
 3672
 3673        self.language_server_statuses.insert(
 3674            server_id,
 3675            LanguageServerStatus {
 3676                name: language_server.name().to_string(),
 3677                pending_work: Default::default(),
 3678                has_pending_diagnostic_updates: false,
 3679                progress_tokens: Default::default(),
 3680            },
 3681        );
 3682
 3683        cx.emit(Event::LanguageServerAdded(server_id));
 3684
 3685        if let Some(project_id) = self.remote_id() {
 3686            self.client.send(proto::StartLanguageServer {
 3687                project_id,
 3688                server: Some(proto::LanguageServer {
 3689                    id: server_id.0 as u64,
 3690                    name: language_server.name().to_string(),
 3691                }),
 3692            })?;
 3693        }
 3694
 3695        // Tell the language server about every open buffer in the worktree that matches the language.
 3696        for buffer in self.opened_buffers.values() {
 3697            if let Some(buffer_handle) = buffer.upgrade() {
 3698                let buffer = buffer_handle.read(cx);
 3699                let file = match File::from_dyn(buffer.file()) {
 3700                    Some(file) => file,
 3701                    None => continue,
 3702                };
 3703                let language = match buffer.language() {
 3704                    Some(language) => language,
 3705                    None => continue,
 3706                };
 3707
 3708                if file.worktree.read(cx).id() != key.0
 3709                    || !self
 3710                        .languages
 3711                        .lsp_adapters(&language)
 3712                        .iter()
 3713                        .any(|a| a.name == key.1)
 3714                {
 3715                    continue;
 3716                }
 3717
 3718                let file = match file.as_local() {
 3719                    Some(file) => file,
 3720                    None => continue,
 3721                };
 3722
 3723                let versions = self
 3724                    .buffer_snapshots
 3725                    .entry(buffer.remote_id())
 3726                    .or_default()
 3727                    .entry(server_id)
 3728                    .or_insert_with(|| {
 3729                        vec![LspBufferSnapshot {
 3730                            version: 0,
 3731                            snapshot: buffer.text_snapshot(),
 3732                        }]
 3733                    });
 3734
 3735                let snapshot = versions.last().unwrap();
 3736                let version = snapshot.version;
 3737                let initial_snapshot = &snapshot.snapshot;
 3738                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 3739                language_server.notify::<lsp::notification::DidOpenTextDocument>(
 3740                    lsp::DidOpenTextDocumentParams {
 3741                        text_document: lsp::TextDocumentItem::new(
 3742                            uri,
 3743                            adapter.language_id(&language),
 3744                            version,
 3745                            initial_snapshot.text(),
 3746                        ),
 3747                    },
 3748                )?;
 3749
 3750                buffer_handle.update(cx, |buffer, cx| {
 3751                    buffer.set_completion_triggers(
 3752                        language_server
 3753                            .capabilities()
 3754                            .completion_provider
 3755                            .as_ref()
 3756                            .and_then(|provider| provider.trigger_characters.clone())
 3757                            .unwrap_or_default(),
 3758                        cx,
 3759                    )
 3760                });
 3761            }
 3762        }
 3763
 3764        cx.notify();
 3765        Ok(())
 3766    }
 3767
 3768    // Returns a list of all of the worktrees which no longer have a language server and the root path
 3769    // for the stopped server
 3770    fn stop_language_server(
 3771        &mut self,
 3772        worktree_id: WorktreeId,
 3773        adapter_name: LanguageServerName,
 3774        cx: &mut ModelContext<Self>,
 3775    ) -> Task<Vec<WorktreeId>> {
 3776        let key = (worktree_id, adapter_name);
 3777        if let Some(server_id) = self.language_server_ids.remove(&key) {
 3778            let name = key.1 .0;
 3779            log::info!("stopping language server {name}");
 3780
 3781            // Remove other entries for this language server as well
 3782            let mut orphaned_worktrees = vec![worktree_id];
 3783            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
 3784            for other_key in other_keys {
 3785                if self.language_server_ids.get(&other_key) == Some(&server_id) {
 3786                    self.language_server_ids.remove(&other_key);
 3787                    orphaned_worktrees.push(other_key.0);
 3788                }
 3789            }
 3790
 3791            for buffer in self.opened_buffers.values() {
 3792                if let Some(buffer) = buffer.upgrade() {
 3793                    buffer.update(cx, |buffer, cx| {
 3794                        buffer.update_diagnostics(server_id, Default::default(), cx);
 3795                    });
 3796                }
 3797            }
 3798            for worktree in &self.worktrees {
 3799                if let Some(worktree) = worktree.upgrade() {
 3800                    worktree.update(cx, |worktree, cx| {
 3801                        if let Some(worktree) = worktree.as_local_mut() {
 3802                            worktree.clear_diagnostics_for_language_server(server_id, cx);
 3803                        }
 3804                    });
 3805                }
 3806            }
 3807
 3808            self.language_server_watched_paths.remove(&server_id);
 3809            self.language_server_statuses.remove(&server_id);
 3810            cx.notify();
 3811
 3812            let server_state = self.language_servers.remove(&server_id);
 3813            cx.emit(Event::LanguageServerRemoved(server_id));
 3814            cx.spawn(move |_, cx| async move {
 3815                Self::shutdown_language_server(server_state, name, cx).await;
 3816                orphaned_worktrees
 3817            })
 3818        } else {
 3819            Task::ready(Vec::new())
 3820        }
 3821    }
 3822
 3823    async fn shutdown_language_server(
 3824        server_state: Option<LanguageServerState>,
 3825        name: Arc<str>,
 3826        cx: AsyncAppContext,
 3827    ) {
 3828        let server = match server_state {
 3829            Some(LanguageServerState::Starting(task)) => {
 3830                let mut timer = cx
 3831                    .background_executor()
 3832                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
 3833                    .fuse();
 3834
 3835                select! {
 3836                    server = task.fuse() => server,
 3837                    _ = timer => {
 3838                        log::info!(
 3839                            "timeout waiting for language server {} to finish launching before stopping",
 3840                            name
 3841                        );
 3842                        None
 3843                    },
 3844                }
 3845            }
 3846
 3847            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3848
 3849            None => None,
 3850        };
 3851
 3852        if let Some(server) = server {
 3853            if let Some(shutdown) = server.shutdown() {
 3854                shutdown.await;
 3855            }
 3856        }
 3857    }
 3858
 3859    pub fn restart_language_servers_for_buffers(
 3860        &mut self,
 3861        buffers: impl IntoIterator<Item = Model<Buffer>>,
 3862        cx: &mut ModelContext<Self>,
 3863    ) -> Option<()> {
 3864        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
 3865            .into_iter()
 3866            .filter_map(|buffer| {
 3867                let buffer = buffer.read(cx);
 3868                let file = buffer.file()?;
 3869                let worktree = File::from_dyn(Some(file))?.worktree.clone();
 3870                let language = self
 3871                    .languages
 3872                    .language_for_file(file, Some(buffer.as_rope()), cx)
 3873                    .now_or_never()?
 3874                    .ok()?;
 3875                Some((worktree, language))
 3876            })
 3877            .collect();
 3878        for (worktree, language) in language_server_lookup_info {
 3879            self.restart_language_servers(worktree, language, cx);
 3880        }
 3881
 3882        None
 3883    }
 3884
 3885    fn restart_language_servers(
 3886        &mut self,
 3887        worktree: Model<Worktree>,
 3888        language: Arc<Language>,
 3889        cx: &mut ModelContext<Self>,
 3890    ) {
 3891        let worktree_id = worktree.read(cx).id();
 3892
 3893        let stop_tasks = self
 3894            .languages
 3895            .clone()
 3896            .lsp_adapters(&language)
 3897            .iter()
 3898            .map(|adapter| {
 3899                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
 3900                (stop_task, adapter.name.clone())
 3901            })
 3902            .collect::<Vec<_>>();
 3903        if stop_tasks.is_empty() {
 3904            return;
 3905        }
 3906
 3907        cx.spawn(move |this, mut cx| async move {
 3908            // For each stopped language server, record all of the worktrees with which
 3909            // it was associated.
 3910            let mut affected_worktrees = Vec::new();
 3911            for (stop_task, language_server_name) in stop_tasks {
 3912                for affected_worktree_id in stop_task.await {
 3913                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
 3914                }
 3915            }
 3916
 3917            this.update(&mut cx, |this, cx| {
 3918                // Restart the language server for the given worktree.
 3919                this.start_language_servers(&worktree, language.clone(), cx);
 3920
 3921                // Lookup new server ids and set them for each of the orphaned worktrees
 3922                for (affected_worktree_id, language_server_name) in affected_worktrees {
 3923                    if let Some(new_server_id) = this
 3924                        .language_server_ids
 3925                        .get(&(worktree_id, language_server_name.clone()))
 3926                        .cloned()
 3927                    {
 3928                        this.language_server_ids
 3929                            .insert((affected_worktree_id, language_server_name), new_server_id);
 3930                    }
 3931                }
 3932            })
 3933            .ok();
 3934        })
 3935        .detach();
 3936    }
 3937
 3938    fn check_errored_server(
 3939        language: Arc<Language>,
 3940        adapter: Arc<CachedLspAdapter>,
 3941        server_id: LanguageServerId,
 3942        installation_test_binary: Option<LanguageServerBinary>,
 3943        cx: &mut ModelContext<Self>,
 3944    ) {
 3945        if !adapter.can_be_reinstalled() {
 3946            log::info!(
 3947                "Validation check requested for {:?} but it cannot be reinstalled",
 3948                adapter.name.0
 3949            );
 3950            return;
 3951        }
 3952
 3953        cx.spawn(move |this, mut cx| async move {
 3954            log::info!("About to spawn test binary");
 3955
 3956            // A lack of test binary counts as a failure
 3957            let process = installation_test_binary.and_then(|binary| {
 3958                smol::process::Command::new(&binary.path)
 3959                    .current_dir(&binary.path)
 3960                    .args(binary.arguments)
 3961                    .stdin(Stdio::piped())
 3962                    .stdout(Stdio::piped())
 3963                    .stderr(Stdio::inherit())
 3964                    .kill_on_drop(true)
 3965                    .spawn()
 3966                    .ok()
 3967            });
 3968
 3969            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
 3970            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
 3971
 3972            let mut errored = false;
 3973            if let Some(mut process) = process {
 3974                futures::select! {
 3975                    status = process.status().fuse() => match status {
 3976                        Ok(status) => errored = !status.success(),
 3977                        Err(_) => errored = true,
 3978                    },
 3979
 3980                    _ = timeout => {
 3981                        log::info!("test binary time-ed out, this counts as a success");
 3982                        _ = process.kill();
 3983                    }
 3984                }
 3985            } else {
 3986                log::warn!("test binary failed to launch");
 3987                errored = true;
 3988            }
 3989
 3990            if errored {
 3991                log::warn!("test binary check failed");
 3992                let task = this
 3993                    .update(&mut cx, move |this, cx| {
 3994                        this.reinstall_language_server(language, adapter, server_id, cx)
 3995                    })
 3996                    .ok()
 3997                    .flatten();
 3998
 3999                if let Some(task) = task {
 4000                    task.await;
 4001                }
 4002            }
 4003        })
 4004        .detach();
 4005    }
 4006
 4007    fn enqueue_language_server_progress(
 4008        &mut self,
 4009        message: BufferOrderedMessage,
 4010        cx: &mut ModelContext<Self>,
 4011    ) {
 4012        self.pending_language_server_update.replace(message);
 4013        self.flush_language_server_update.get_or_insert_with(|| {
 4014            cx.spawn(|this, mut cx| async move {
 4015                cx.background_executor()
 4016                    .timer(SERVER_PROGRESS_DEBOUNCE_TIMEOUT)
 4017                    .await;
 4018                this.update(&mut cx, |this, _| {
 4019                    this.flush_language_server_update.take();
 4020                    if let Some(update) = this.pending_language_server_update.take() {
 4021                        this.enqueue_buffer_ordered_message(update).ok();
 4022                    }
 4023                })
 4024                .ok();
 4025            })
 4026        });
 4027    }
 4028
 4029    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
 4030        if let Some(pending_message) = self.pending_language_server_update.take() {
 4031            self.flush_language_server_update.take();
 4032            self.buffer_ordered_messages_tx
 4033                .unbounded_send(pending_message)
 4034                .map_err(|e| anyhow!(e))?;
 4035        }
 4036        self.buffer_ordered_messages_tx
 4037            .unbounded_send(message)
 4038            .map_err(|e| anyhow!(e))
 4039    }
 4040
 4041    fn on_lsp_progress(
 4042        &mut self,
 4043        progress: lsp::ProgressParams,
 4044        language_server_id: LanguageServerId,
 4045        disk_based_diagnostics_progress_token: Option<String>,
 4046        cx: &mut ModelContext<Self>,
 4047    ) {
 4048        let token = match progress.token {
 4049            lsp::NumberOrString::String(token) => token,
 4050            lsp::NumberOrString::Number(token) => {
 4051                log::info!("skipping numeric progress token {}", token);
 4052                return;
 4053            }
 4054        };
 4055        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
 4056        let language_server_status =
 4057            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4058                status
 4059            } else {
 4060                return;
 4061            };
 4062
 4063        if !language_server_status.progress_tokens.contains(&token) {
 4064            return;
 4065        }
 4066
 4067        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 4068            .as_ref()
 4069            .map_or(false, |disk_based_token| {
 4070                token.starts_with(disk_based_token)
 4071            });
 4072
 4073        match progress {
 4074            lsp::WorkDoneProgress::Begin(report) => {
 4075                if is_disk_based_diagnostics_progress {
 4076                    self.disk_based_diagnostics_started(language_server_id, cx);
 4077                } else {
 4078                    self.on_lsp_work_start(
 4079                        language_server_id,
 4080                        token.clone(),
 4081                        LanguageServerProgress {
 4082                            message: report.message.clone(),
 4083                            percentage: report.percentage.map(|p| p as usize),
 4084                            last_update_at: Instant::now(),
 4085                        },
 4086                        cx,
 4087                    );
 4088                }
 4089            }
 4090            lsp::WorkDoneProgress::Report(report) => {
 4091                if !is_disk_based_diagnostics_progress {
 4092                    self.on_lsp_work_progress(
 4093                        language_server_id,
 4094                        token.clone(),
 4095                        LanguageServerProgress {
 4096                            message: report.message.clone(),
 4097                            percentage: report.percentage.map(|p| p as usize),
 4098                            last_update_at: Instant::now(),
 4099                        },
 4100                        cx,
 4101                    );
 4102                    self.enqueue_language_server_progress(
 4103                        BufferOrderedMessage::LanguageServerUpdate {
 4104                            language_server_id,
 4105                            message: proto::update_language_server::Variant::WorkProgress(
 4106                                proto::LspWorkProgress {
 4107                                    token,
 4108                                    message: report.message,
 4109                                    percentage: report.percentage,
 4110                                },
 4111                            ),
 4112                        },
 4113                        cx,
 4114                    );
 4115                }
 4116            }
 4117            lsp::WorkDoneProgress::End(_) => {
 4118                language_server_status.progress_tokens.remove(&token);
 4119
 4120                if is_disk_based_diagnostics_progress {
 4121                    self.disk_based_diagnostics_finished(language_server_id, cx);
 4122                } else {
 4123                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
 4124                }
 4125            }
 4126        }
 4127    }
 4128
 4129    fn on_lsp_work_start(
 4130        &mut self,
 4131        language_server_id: LanguageServerId,
 4132        token: String,
 4133        progress: LanguageServerProgress,
 4134        cx: &mut ModelContext<Self>,
 4135    ) {
 4136        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4137            status.pending_work.insert(token.clone(), progress.clone());
 4138            cx.notify();
 4139        }
 4140
 4141        if self.is_local() {
 4142            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4143                language_server_id,
 4144                message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
 4145                    token,
 4146                    message: progress.message,
 4147                    percentage: progress.percentage.map(|p| p as u32),
 4148                }),
 4149            })
 4150            .ok();
 4151        }
 4152    }
 4153
 4154    fn on_lsp_work_progress(
 4155        &mut self,
 4156        language_server_id: LanguageServerId,
 4157        token: String,
 4158        progress: LanguageServerProgress,
 4159        cx: &mut ModelContext<Self>,
 4160    ) {
 4161        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4162            let entry = status
 4163                .pending_work
 4164                .entry(token)
 4165                .or_insert(LanguageServerProgress {
 4166                    message: Default::default(),
 4167                    percentage: Default::default(),
 4168                    last_update_at: progress.last_update_at,
 4169                });
 4170            if progress.message.is_some() {
 4171                entry.message = progress.message;
 4172            }
 4173            if progress.percentage.is_some() {
 4174                entry.percentage = progress.percentage;
 4175            }
 4176            entry.last_update_at = progress.last_update_at;
 4177            cx.notify();
 4178        }
 4179    }
 4180
 4181    fn on_lsp_work_end(
 4182        &mut self,
 4183        language_server_id: LanguageServerId,
 4184        token: String,
 4185        cx: &mut ModelContext<Self>,
 4186    ) {
 4187        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4188            cx.emit(Event::RefreshInlayHints);
 4189            status.pending_work.remove(&token);
 4190            cx.notify();
 4191        }
 4192
 4193        if self.is_local() {
 4194            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4195                language_server_id,
 4196                message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
 4197                    token,
 4198                }),
 4199            })
 4200            .ok();
 4201        }
 4202    }
 4203
 4204    fn on_lsp_did_change_watched_files(
 4205        &mut self,
 4206        language_server_id: LanguageServerId,
 4207        params: DidChangeWatchedFilesRegistrationOptions,
 4208        cx: &mut ModelContext<Self>,
 4209    ) {
 4210        let watched_paths = self
 4211            .language_server_watched_paths
 4212            .entry(language_server_id)
 4213            .or_default();
 4214
 4215        let mut builders = HashMap::default();
 4216        for watcher in params.watchers {
 4217            for worktree in &self.worktrees {
 4218                if let Some(worktree) = worktree.upgrade() {
 4219                    let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
 4220                        if let Some(abs_path) = tree.abs_path().to_str() {
 4221                            let relative_glob_pattern = match &watcher.glob_pattern {
 4222                                lsp::GlobPattern::String(s) => Some(
 4223                                    s.strip_prefix(abs_path)
 4224                                        .unwrap_or(s)
 4225                                        .strip_prefix(std::path::MAIN_SEPARATOR)
 4226                                        .unwrap_or(s),
 4227                                ),
 4228                                lsp::GlobPattern::Relative(rp) => {
 4229                                    let base_uri = match &rp.base_uri {
 4230                                        lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
 4231                                        lsp::OneOf::Right(base_uri) => base_uri,
 4232                                    };
 4233                                    base_uri.to_file_path().ok().and_then(|file_path| {
 4234                                        (file_path.to_str() == Some(abs_path))
 4235                                            .then_some(rp.pattern.as_str())
 4236                                    })
 4237                                }
 4238                            };
 4239                            if let Some(relative_glob_pattern) = relative_glob_pattern {
 4240                                let literal_prefix = glob_literal_prefix(relative_glob_pattern);
 4241                                tree.as_local_mut()
 4242                                    .unwrap()
 4243                                    .add_path_prefix_to_scan(Path::new(literal_prefix).into());
 4244                                if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
 4245                                    builders
 4246                                        .entry(tree.id())
 4247                                        .or_insert_with(|| GlobSetBuilder::new())
 4248                                        .add(glob);
 4249                                }
 4250                                return true;
 4251                            }
 4252                        }
 4253                        false
 4254                    });
 4255                    if glob_is_inside_worktree {
 4256                        break;
 4257                    }
 4258                }
 4259            }
 4260        }
 4261
 4262        watched_paths.clear();
 4263        for (worktree_id, builder) in builders {
 4264            if let Ok(globset) = builder.build() {
 4265                watched_paths.insert(worktree_id, globset);
 4266            }
 4267        }
 4268
 4269        cx.notify();
 4270    }
 4271
 4272    async fn on_lsp_workspace_edit(
 4273        this: WeakModel<Self>,
 4274        params: lsp::ApplyWorkspaceEditParams,
 4275        server_id: LanguageServerId,
 4276        adapter: Arc<CachedLspAdapter>,
 4277        mut cx: AsyncAppContext,
 4278    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
 4279        let this = this
 4280            .upgrade()
 4281            .ok_or_else(|| anyhow!("project project closed"))?;
 4282        let language_server = this
 4283            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
 4284            .ok_or_else(|| anyhow!("language server not found"))?;
 4285        let transaction = Self::deserialize_workspace_edit(
 4286            this.clone(),
 4287            params.edit,
 4288            true,
 4289            adapter.clone(),
 4290            language_server.clone(),
 4291            &mut cx,
 4292        )
 4293        .await
 4294        .log_err();
 4295        this.update(&mut cx, |this, _| {
 4296            if let Some(transaction) = transaction {
 4297                this.last_workspace_edits_by_language_server
 4298                    .insert(server_id, transaction);
 4299            }
 4300        })?;
 4301        Ok(lsp::ApplyWorkspaceEditResponse {
 4302            applied: true,
 4303            failed_change: None,
 4304            failure_reason: None,
 4305        })
 4306    }
 4307
 4308    pub fn language_server_statuses(
 4309        &self,
 4310    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
 4311        self.language_server_statuses.values()
 4312    }
 4313
 4314    pub fn last_formatting_failure(&self) -> Option<&str> {
 4315        self.last_formatting_failure.as_deref()
 4316    }
 4317
 4318    pub fn update_diagnostics(
 4319        &mut self,
 4320        language_server_id: LanguageServerId,
 4321        mut params: lsp::PublishDiagnosticsParams,
 4322        disk_based_sources: &[String],
 4323        cx: &mut ModelContext<Self>,
 4324    ) -> Result<()> {
 4325        let abs_path = params
 4326            .uri
 4327            .to_file_path()
 4328            .map_err(|_| anyhow!("URI is not a file"))?;
 4329        let mut diagnostics = Vec::default();
 4330        let mut primary_diagnostic_group_ids = HashMap::default();
 4331        let mut sources_by_group_id = HashMap::default();
 4332        let mut supporting_diagnostics = HashMap::default();
 4333
 4334        // Ensure that primary diagnostics are always the most severe
 4335        params.diagnostics.sort_by_key(|item| item.severity);
 4336
 4337        for diagnostic in &params.diagnostics {
 4338            let source = diagnostic.source.as_ref();
 4339            let code = diagnostic.code.as_ref().map(|code| match code {
 4340                lsp::NumberOrString::Number(code) => code.to_string(),
 4341                lsp::NumberOrString::String(code) => code.clone(),
 4342            });
 4343            let range = range_from_lsp(diagnostic.range);
 4344            let is_supporting = diagnostic
 4345                .related_information
 4346                .as_ref()
 4347                .map_or(false, |infos| {
 4348                    infos.iter().any(|info| {
 4349                        primary_diagnostic_group_ids.contains_key(&(
 4350                            source,
 4351                            code.clone(),
 4352                            range_from_lsp(info.location.range),
 4353                        ))
 4354                    })
 4355                });
 4356
 4357            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
 4358                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
 4359            });
 4360
 4361            if is_supporting {
 4362                supporting_diagnostics.insert(
 4363                    (source, code.clone(), range),
 4364                    (diagnostic.severity, is_unnecessary),
 4365                );
 4366            } else {
 4367                let group_id = post_inc(&mut self.next_diagnostic_group_id);
 4368                let is_disk_based =
 4369                    source.map_or(false, |source| disk_based_sources.contains(source));
 4370
 4371                sources_by_group_id.insert(group_id, source);
 4372                primary_diagnostic_group_ids
 4373                    .insert((source, code.clone(), range.clone()), group_id);
 4374
 4375                diagnostics.push(DiagnosticEntry {
 4376                    range,
 4377                    diagnostic: Diagnostic {
 4378                        source: diagnostic.source.clone(),
 4379                        code: code.clone(),
 4380                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
 4381                        message: diagnostic.message.trim().to_string(),
 4382                        group_id,
 4383                        is_primary: true,
 4384                        is_disk_based,
 4385                        is_unnecessary,
 4386                    },
 4387                });
 4388                if let Some(infos) = &diagnostic.related_information {
 4389                    for info in infos {
 4390                        if info.location.uri == params.uri && !info.message.is_empty() {
 4391                            let range = range_from_lsp(info.location.range);
 4392                            diagnostics.push(DiagnosticEntry {
 4393                                range,
 4394                                diagnostic: Diagnostic {
 4395                                    source: diagnostic.source.clone(),
 4396                                    code: code.clone(),
 4397                                    severity: DiagnosticSeverity::INFORMATION,
 4398                                    message: info.message.trim().to_string(),
 4399                                    group_id,
 4400                                    is_primary: false,
 4401                                    is_disk_based,
 4402                                    is_unnecessary: false,
 4403                                },
 4404                            });
 4405                        }
 4406                    }
 4407                }
 4408            }
 4409        }
 4410
 4411        for entry in &mut diagnostics {
 4412            let diagnostic = &mut entry.diagnostic;
 4413            if !diagnostic.is_primary {
 4414                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
 4415                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
 4416                    source,
 4417                    diagnostic.code.clone(),
 4418                    entry.range.clone(),
 4419                )) {
 4420                    if let Some(severity) = severity {
 4421                        diagnostic.severity = severity;
 4422                    }
 4423                    diagnostic.is_unnecessary = is_unnecessary;
 4424                }
 4425            }
 4426        }
 4427
 4428        self.update_diagnostic_entries(
 4429            language_server_id,
 4430            abs_path,
 4431            params.version,
 4432            diagnostics,
 4433            cx,
 4434        )?;
 4435        Ok(())
 4436    }
 4437
 4438    pub fn update_diagnostic_entries(
 4439        &mut self,
 4440        server_id: LanguageServerId,
 4441        abs_path: PathBuf,
 4442        version: Option<i32>,
 4443        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4444        cx: &mut ModelContext<Project>,
 4445    ) -> Result<(), anyhow::Error> {
 4446        let (worktree, relative_path) = self
 4447            .find_local_worktree(&abs_path, cx)
 4448            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
 4449
 4450        let project_path = ProjectPath {
 4451            worktree_id: worktree.read(cx).id(),
 4452            path: relative_path.into(),
 4453        };
 4454
 4455        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
 4456            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
 4457        }
 4458
 4459        let updated = worktree.update(cx, |worktree, cx| {
 4460            worktree
 4461                .as_local_mut()
 4462                .ok_or_else(|| anyhow!("not a local worktree"))?
 4463                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
 4464        })?;
 4465        if updated {
 4466            cx.emit(Event::DiagnosticsUpdated {
 4467                language_server_id: server_id,
 4468                path: project_path,
 4469            });
 4470        }
 4471        Ok(())
 4472    }
 4473
 4474    fn update_buffer_diagnostics(
 4475        &mut self,
 4476        buffer: &Model<Buffer>,
 4477        server_id: LanguageServerId,
 4478        version: Option<i32>,
 4479        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4480        cx: &mut ModelContext<Self>,
 4481    ) -> Result<()> {
 4482        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 4483            Ordering::Equal
 4484                .then_with(|| b.is_primary.cmp(&a.is_primary))
 4485                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 4486                .then_with(|| a.severity.cmp(&b.severity))
 4487                .then_with(|| a.message.cmp(&b.message))
 4488        }
 4489
 4490        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
 4491
 4492        diagnostics.sort_unstable_by(|a, b| {
 4493            Ordering::Equal
 4494                .then_with(|| a.range.start.cmp(&b.range.start))
 4495                .then_with(|| b.range.end.cmp(&a.range.end))
 4496                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 4497        });
 4498
 4499        let mut sanitized_diagnostics = Vec::new();
 4500        let edits_since_save = Patch::new(
 4501            snapshot
 4502                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
 4503                .collect(),
 4504        );
 4505        for entry in diagnostics {
 4506            let start;
 4507            let end;
 4508            if entry.diagnostic.is_disk_based {
 4509                // Some diagnostics are based on files on disk instead of buffers'
 4510                // current contents. Adjust these diagnostics' ranges to reflect
 4511                // any unsaved edits.
 4512                start = edits_since_save.old_to_new(entry.range.start);
 4513                end = edits_since_save.old_to_new(entry.range.end);
 4514            } else {
 4515                start = entry.range.start;
 4516                end = entry.range.end;
 4517            }
 4518
 4519            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
 4520                ..snapshot.clip_point_utf16(end, Bias::Right);
 4521
 4522            // Expand empty ranges by one codepoint
 4523            if range.start == range.end {
 4524                // This will be go to the next boundary when being clipped
 4525                range.end.column += 1;
 4526                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
 4527                if range.start == range.end && range.end.column > 0 {
 4528                    range.start.column -= 1;
 4529                    range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
 4530                }
 4531            }
 4532
 4533            sanitized_diagnostics.push(DiagnosticEntry {
 4534                range,
 4535                diagnostic: entry.diagnostic,
 4536            });
 4537        }
 4538        drop(edits_since_save);
 4539
 4540        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
 4541        buffer.update(cx, |buffer, cx| {
 4542            buffer.update_diagnostics(server_id, set, cx)
 4543        });
 4544        Ok(())
 4545    }
 4546
 4547    pub fn reload_buffers(
 4548        &self,
 4549        buffers: HashSet<Model<Buffer>>,
 4550        push_to_history: bool,
 4551        cx: &mut ModelContext<Self>,
 4552    ) -> Task<Result<ProjectTransaction>> {
 4553        let mut local_buffers = Vec::new();
 4554        let mut remote_buffers = None;
 4555        for buffer_handle in buffers {
 4556            let buffer = buffer_handle.read(cx);
 4557            if buffer.is_dirty() {
 4558                if let Some(file) = File::from_dyn(buffer.file()) {
 4559                    if file.is_local() {
 4560                        local_buffers.push(buffer_handle);
 4561                    } else {
 4562                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
 4563                    }
 4564                }
 4565            }
 4566        }
 4567
 4568        let remote_buffers = self.remote_id().zip(remote_buffers);
 4569        let client = self.client.clone();
 4570
 4571        cx.spawn(move |this, mut cx| async move {
 4572            let mut project_transaction = ProjectTransaction::default();
 4573
 4574            if let Some((project_id, remote_buffers)) = remote_buffers {
 4575                let response = client
 4576                    .request(proto::ReloadBuffers {
 4577                        project_id,
 4578                        buffer_ids: remote_buffers
 4579                            .iter()
 4580                            .filter_map(|buffer| {
 4581                                buffer
 4582                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
 4583                                    .ok()
 4584                            })
 4585                            .collect(),
 4586                    })
 4587                    .await?
 4588                    .transaction
 4589                    .ok_or_else(|| anyhow!("missing transaction"))?;
 4590                project_transaction = this
 4591                    .update(&mut cx, |this, cx| {
 4592                        this.deserialize_project_transaction(response, push_to_history, cx)
 4593                    })?
 4594                    .await?;
 4595            }
 4596
 4597            for buffer in local_buffers {
 4598                let transaction = buffer
 4599                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
 4600                    .await?;
 4601                buffer.update(&mut cx, |buffer, cx| {
 4602                    if let Some(transaction) = transaction {
 4603                        if !push_to_history {
 4604                            buffer.forget_transaction(transaction.id);
 4605                        }
 4606                        project_transaction.0.insert(cx.handle(), transaction);
 4607                    }
 4608                })?;
 4609            }
 4610
 4611            Ok(project_transaction)
 4612        })
 4613    }
 4614
 4615    pub fn format(
 4616        &mut self,
 4617        buffers: HashSet<Model<Buffer>>,
 4618        push_to_history: bool,
 4619        trigger: FormatTrigger,
 4620        cx: &mut ModelContext<Project>,
 4621    ) -> Task<anyhow::Result<ProjectTransaction>> {
 4622        if self.is_local() {
 4623            let buffers_with_paths = buffers
 4624                .into_iter()
 4625                .filter_map(|buffer_handle| {
 4626                    let buffer = buffer_handle.read(cx);
 4627                    let file = File::from_dyn(buffer.file())?;
 4628                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
 4629                    Some((buffer_handle, buffer_abs_path))
 4630                })
 4631                .collect::<Vec<_>>();
 4632
 4633            cx.spawn(move |project, mut cx| async move {
 4634                let result = Self::format_locally(
 4635                    project.clone(),
 4636                    buffers_with_paths,
 4637                    push_to_history,
 4638                    trigger,
 4639                    cx.clone(),
 4640                )
 4641                .await;
 4642
 4643                project.update(&mut cx, |project, _| match &result {
 4644                    Ok(_) => project.last_formatting_failure = None,
 4645                    Err(error) => {
 4646                        project.last_formatting_failure.replace(error.to_string());
 4647                    }
 4648                })?;
 4649
 4650                result
 4651            })
 4652        } else {
 4653            let remote_id = self.remote_id();
 4654            let client = self.client.clone();
 4655            cx.spawn(move |this, mut cx| async move {
 4656                let mut project_transaction = ProjectTransaction::default();
 4657                if let Some(project_id) = remote_id {
 4658                    let response = client
 4659                        .request(proto::FormatBuffers {
 4660                            project_id,
 4661                            trigger: trigger as i32,
 4662                            buffer_ids: buffers
 4663                                .iter()
 4664                                .map(|buffer| {
 4665                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
 4666                                })
 4667                                .collect::<Result<_>>()?,
 4668                        })
 4669                        .await?
 4670                        .transaction
 4671                        .ok_or_else(|| anyhow!("missing transaction"))?;
 4672                    project_transaction = this
 4673                        .update(&mut cx, |this, cx| {
 4674                            this.deserialize_project_transaction(response, push_to_history, cx)
 4675                        })?
 4676                        .await?;
 4677                }
 4678                Ok(project_transaction)
 4679            })
 4680        }
 4681    }
 4682
 4683    async fn format_locally(
 4684        project: WeakModel<Project>,
 4685        mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
 4686        push_to_history: bool,
 4687        trigger: FormatTrigger,
 4688        mut cx: AsyncAppContext,
 4689    ) -> anyhow::Result<ProjectTransaction> {
 4690        // Do not allow multiple concurrent formatting requests for the
 4691        // same buffer.
 4692        project.update(&mut cx, |this, cx| {
 4693            buffers_with_paths.retain(|(buffer, _)| {
 4694                this.buffers_being_formatted
 4695                    .insert(buffer.read(cx).remote_id())
 4696            });
 4697        })?;
 4698
 4699        let _cleanup = defer({
 4700            let this = project.clone();
 4701            let mut cx = cx.clone();
 4702            let buffers = &buffers_with_paths;
 4703            move || {
 4704                this.update(&mut cx, |this, cx| {
 4705                    for (buffer, _) in buffers {
 4706                        this.buffers_being_formatted
 4707                            .remove(&buffer.read(cx).remote_id());
 4708                    }
 4709                })
 4710                .ok();
 4711            }
 4712        });
 4713
 4714        let mut project_transaction = ProjectTransaction::default();
 4715        for (buffer, buffer_abs_path) in &buffers_with_paths {
 4716            let (primary_adapter_and_server, adapters_and_servers) =
 4717                project.update(&mut cx, |project, cx| {
 4718                    let buffer = buffer.read(cx);
 4719
 4720                    let adapters_and_servers = project
 4721                        .language_servers_for_buffer(buffer, cx)
 4722                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
 4723                        .collect::<Vec<_>>();
 4724
 4725                    let primary_adapter = project
 4726                        .primary_language_server_for_buffer(buffer, cx)
 4727                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
 4728
 4729                    (primary_adapter, adapters_and_servers)
 4730                })?;
 4731
 4732            let settings = buffer.update(&mut cx, |buffer, cx| {
 4733                language_settings(buffer.language(), buffer.file(), cx).clone()
 4734            })?;
 4735
 4736            let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
 4737            let ensure_final_newline = settings.ensure_final_newline_on_save;
 4738            let tab_size = settings.tab_size;
 4739
 4740            // First, format buffer's whitespace according to the settings.
 4741            let trailing_whitespace_diff = if remove_trailing_whitespace {
 4742                Some(
 4743                    buffer
 4744                        .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
 4745                        .await,
 4746                )
 4747            } else {
 4748                None
 4749            };
 4750            let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
 4751                buffer.finalize_last_transaction();
 4752                buffer.start_transaction();
 4753                if let Some(diff) = trailing_whitespace_diff {
 4754                    buffer.apply_diff(diff, cx);
 4755                }
 4756                if ensure_final_newline {
 4757                    buffer.ensure_final_newline(cx);
 4758                }
 4759                buffer.end_transaction(cx)
 4760            })?;
 4761
 4762            // Apply the `code_actions_on_format` before we run the formatter.
 4763            let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
 4764            #[allow(clippy::nonminimal_bool)]
 4765            if !code_actions.is_empty()
 4766                && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
 4767            {
 4768                Self::execute_code_actions_on_servers(
 4769                    &project,
 4770                    &adapters_and_servers,
 4771                    code_actions,
 4772                    buffer,
 4773                    push_to_history,
 4774                    &mut project_transaction,
 4775                    &mut cx,
 4776                )
 4777                .await?;
 4778            }
 4779
 4780            // Apply language-specific formatting using either the primary language server
 4781            // or external command.
 4782            // Except for code actions, which are applied with all connected language servers.
 4783            let primary_language_server =
 4784                primary_adapter_and_server.map(|(_adapter, server)| server.clone());
 4785            let server_and_buffer = primary_language_server
 4786                .as_ref()
 4787                .zip(buffer_abs_path.as_ref());
 4788
 4789            let mut format_operation = None;
 4790            match (&settings.formatter, &settings.format_on_save) {
 4791                (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
 4792
 4793                (Formatter::CodeActions(code_actions), FormatOnSave::On | FormatOnSave::Off)
 4794                | (_, FormatOnSave::CodeActions(code_actions)) => {
 4795                    let code_actions = deserialize_code_actions(code_actions);
 4796                    if !code_actions.is_empty() {
 4797                        Self::execute_code_actions_on_servers(
 4798                            &project,
 4799                            &adapters_and_servers,
 4800                            code_actions,
 4801                            buffer,
 4802                            push_to_history,
 4803                            &mut project_transaction,
 4804                            &mut cx,
 4805                        )
 4806                        .await?;
 4807                    }
 4808                }
 4809                (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
 4810                | (_, FormatOnSave::LanguageServer) => {
 4811                    if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4812                        format_operation = Some(FormatOperation::Lsp(
 4813                            Self::format_via_lsp(
 4814                                &project,
 4815                                buffer,
 4816                                buffer_abs_path,
 4817                                language_server,
 4818                                tab_size,
 4819                                &mut cx,
 4820                            )
 4821                            .await
 4822                            .context("failed to format via language server")?,
 4823                        ));
 4824                    }
 4825                }
 4826
 4827                (
 4828                    Formatter::External { command, arguments },
 4829                    FormatOnSave::On | FormatOnSave::Off,
 4830                )
 4831                | (_, FormatOnSave::External { command, arguments }) => {
 4832                    if let Some(buffer_abs_path) = buffer_abs_path {
 4833                        format_operation = Self::format_via_external_command(
 4834                            buffer,
 4835                            buffer_abs_path,
 4836                            command,
 4837                            arguments,
 4838                            &mut cx,
 4839                        )
 4840                        .await
 4841                        .context(format!(
 4842                            "failed to format via external command {:?}",
 4843                            command
 4844                        ))?
 4845                        .map(FormatOperation::External);
 4846                    }
 4847                }
 4848                (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
 4849                    let prettier =
 4850                        prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
 4851
 4852                    if let Some(operation) = prettier {
 4853                        format_operation = Some(operation?);
 4854                    } else if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4855                        format_operation = Some(FormatOperation::Lsp(
 4856                            Self::format_via_lsp(
 4857                                &project,
 4858                                buffer,
 4859                                buffer_abs_path,
 4860                                language_server,
 4861                                tab_size,
 4862                                &mut cx,
 4863                            )
 4864                            .await
 4865                            .context("failed to format via language server")?,
 4866                        ));
 4867                    }
 4868                }
 4869                (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
 4870                    let prettier =
 4871                        prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
 4872
 4873                    if let Some(operation) = prettier {
 4874                        format_operation = Some(operation?);
 4875                    }
 4876                }
 4877            };
 4878
 4879            buffer.update(&mut cx, |b, cx| {
 4880                // If the buffer had its whitespace formatted and was edited while the language-specific
 4881                // formatting was being computed, avoid applying the language-specific formatting, because
 4882                // it can't be grouped with the whitespace formatting in the undo history.
 4883                if let Some(transaction_id) = whitespace_transaction_id {
 4884                    if b.peek_undo_stack()
 4885                        .map_or(true, |e| e.transaction_id() != transaction_id)
 4886                    {
 4887                        format_operation.take();
 4888                    }
 4889                }
 4890
 4891                // Apply any language-specific formatting, and group the two formatting operations
 4892                // in the buffer's undo history.
 4893                if let Some(operation) = format_operation {
 4894                    match operation {
 4895                        FormatOperation::Lsp(edits) => {
 4896                            b.edit(edits, None, cx);
 4897                        }
 4898                        FormatOperation::External(diff) => {
 4899                            b.apply_diff(diff, cx);
 4900                        }
 4901                        FormatOperation::Prettier(diff) => {
 4902                            b.apply_diff(diff, cx);
 4903                        }
 4904                    }
 4905
 4906                    if let Some(transaction_id) = whitespace_transaction_id {
 4907                        b.group_until_transaction(transaction_id);
 4908                    } else if let Some(transaction) = project_transaction.0.get(buffer) {
 4909                        b.group_until_transaction(transaction.id)
 4910                    }
 4911                }
 4912
 4913                if let Some(transaction) = b.finalize_last_transaction().cloned() {
 4914                    if !push_to_history {
 4915                        b.forget_transaction(transaction.id);
 4916                    }
 4917                    project_transaction.0.insert(buffer.clone(), transaction);
 4918                }
 4919            })?;
 4920        }
 4921
 4922        Ok(project_transaction)
 4923    }
 4924
 4925    async fn format_via_lsp(
 4926        this: &WeakModel<Self>,
 4927        buffer: &Model<Buffer>,
 4928        abs_path: &Path,
 4929        language_server: &Arc<LanguageServer>,
 4930        tab_size: NonZeroU32,
 4931        cx: &mut AsyncAppContext,
 4932    ) -> Result<Vec<(Range<Anchor>, String)>> {
 4933        let uri = lsp::Url::from_file_path(abs_path)
 4934            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
 4935        let text_document = lsp::TextDocumentIdentifier::new(uri);
 4936        let capabilities = &language_server.capabilities();
 4937
 4938        let formatting_provider = capabilities.document_formatting_provider.as_ref();
 4939        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
 4940
 4941        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 4942            language_server
 4943                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
 4944                    text_document,
 4945                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 4946                    work_done_progress_params: Default::default(),
 4947                })
 4948                .await?
 4949        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 4950            let buffer_start = lsp::Position::new(0, 0);
 4951            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
 4952
 4953            language_server
 4954                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
 4955                    text_document,
 4956                    range: lsp::Range::new(buffer_start, buffer_end),
 4957                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 4958                    work_done_progress_params: Default::default(),
 4959                })
 4960                .await?
 4961        } else {
 4962            None
 4963        };
 4964
 4965        if let Some(lsp_edits) = lsp_edits {
 4966            this.update(cx, |this, cx| {
 4967                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
 4968            })?
 4969            .await
 4970        } else {
 4971            Ok(Vec::new())
 4972        }
 4973    }
 4974
 4975    async fn format_via_external_command(
 4976        buffer: &Model<Buffer>,
 4977        buffer_abs_path: &Path,
 4978        command: &str,
 4979        arguments: &[String],
 4980        cx: &mut AsyncAppContext,
 4981    ) -> Result<Option<Diff>> {
 4982        let working_dir_path = buffer.update(cx, |buffer, cx| {
 4983            let file = File::from_dyn(buffer.file())?;
 4984            let worktree = file.worktree.read(cx).as_local()?;
 4985            let mut worktree_path = worktree.abs_path().to_path_buf();
 4986            if worktree.root_entry()?.is_file() {
 4987                worktree_path.pop();
 4988            }
 4989            Some(worktree_path)
 4990        })?;
 4991
 4992        if let Some(working_dir_path) = working_dir_path {
 4993            let mut child =
 4994                smol::process::Command::new(command)
 4995                    .args(arguments.iter().map(|arg| {
 4996                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
 4997                    }))
 4998                    .current_dir(&working_dir_path)
 4999                    .stdin(smol::process::Stdio::piped())
 5000                    .stdout(smol::process::Stdio::piped())
 5001                    .stderr(smol::process::Stdio::piped())
 5002                    .spawn()?;
 5003            let stdin = child
 5004                .stdin
 5005                .as_mut()
 5006                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
 5007            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
 5008            for chunk in text.chunks() {
 5009                stdin.write_all(chunk.as_bytes()).await?;
 5010            }
 5011            stdin.flush().await?;
 5012
 5013            let output = child.output().await?;
 5014            if !output.status.success() {
 5015                return Err(anyhow!(
 5016                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
 5017                    output.status.code(),
 5018                    String::from_utf8_lossy(&output.stdout),
 5019                    String::from_utf8_lossy(&output.stderr),
 5020                ));
 5021            }
 5022
 5023            let stdout = String::from_utf8(output.stdout)?;
 5024            Ok(Some(
 5025                buffer
 5026                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
 5027                    .await,
 5028            ))
 5029        } else {
 5030            Ok(None)
 5031        }
 5032    }
 5033
 5034    #[inline(never)]
 5035    fn definition_impl(
 5036        &self,
 5037        buffer: &Model<Buffer>,
 5038        position: PointUtf16,
 5039        cx: &mut ModelContext<Self>,
 5040    ) -> Task<Result<Vec<LocationLink>>> {
 5041        self.request_lsp(
 5042            buffer.clone(),
 5043            LanguageServerToQuery::Primary,
 5044            GetDefinition { position },
 5045            cx,
 5046        )
 5047    }
 5048    pub fn definition<T: ToPointUtf16>(
 5049        &self,
 5050        buffer: &Model<Buffer>,
 5051        position: T,
 5052        cx: &mut ModelContext<Self>,
 5053    ) -> Task<Result<Vec<LocationLink>>> {
 5054        let position = position.to_point_utf16(buffer.read(cx));
 5055        self.definition_impl(buffer, position, cx)
 5056    }
 5057
 5058    fn type_definition_impl(
 5059        &self,
 5060        buffer: &Model<Buffer>,
 5061        position: PointUtf16,
 5062        cx: &mut ModelContext<Self>,
 5063    ) -> Task<Result<Vec<LocationLink>>> {
 5064        self.request_lsp(
 5065            buffer.clone(),
 5066            LanguageServerToQuery::Primary,
 5067            GetTypeDefinition { position },
 5068            cx,
 5069        )
 5070    }
 5071
 5072    pub fn type_definition<T: ToPointUtf16>(
 5073        &self,
 5074        buffer: &Model<Buffer>,
 5075        position: T,
 5076        cx: &mut ModelContext<Self>,
 5077    ) -> Task<Result<Vec<LocationLink>>> {
 5078        let position = position.to_point_utf16(buffer.read(cx));
 5079        self.type_definition_impl(buffer, position, cx)
 5080    }
 5081
 5082    fn implementation_impl(
 5083        &self,
 5084        buffer: &Model<Buffer>,
 5085        position: PointUtf16,
 5086        cx: &mut ModelContext<Self>,
 5087    ) -> Task<Result<Vec<LocationLink>>> {
 5088        self.request_lsp(
 5089            buffer.clone(),
 5090            LanguageServerToQuery::Primary,
 5091            GetImplementation { position },
 5092            cx,
 5093        )
 5094    }
 5095
 5096    pub fn implementation<T: ToPointUtf16>(
 5097        &self,
 5098        buffer: &Model<Buffer>,
 5099        position: T,
 5100        cx: &mut ModelContext<Self>,
 5101    ) -> Task<Result<Vec<LocationLink>>> {
 5102        let position = position.to_point_utf16(buffer.read(cx));
 5103        self.implementation_impl(buffer, position, cx)
 5104    }
 5105
 5106    fn references_impl(
 5107        &self,
 5108        buffer: &Model<Buffer>,
 5109        position: PointUtf16,
 5110        cx: &mut ModelContext<Self>,
 5111    ) -> Task<Result<Vec<Location>>> {
 5112        self.request_lsp(
 5113            buffer.clone(),
 5114            LanguageServerToQuery::Primary,
 5115            GetReferences { position },
 5116            cx,
 5117        )
 5118    }
 5119    pub fn references<T: ToPointUtf16>(
 5120        &self,
 5121        buffer: &Model<Buffer>,
 5122        position: T,
 5123        cx: &mut ModelContext<Self>,
 5124    ) -> Task<Result<Vec<Location>>> {
 5125        let position = position.to_point_utf16(buffer.read(cx));
 5126        self.references_impl(buffer, position, cx)
 5127    }
 5128
 5129    fn document_highlights_impl(
 5130        &self,
 5131        buffer: &Model<Buffer>,
 5132        position: PointUtf16,
 5133        cx: &mut ModelContext<Self>,
 5134    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5135        self.request_lsp(
 5136            buffer.clone(),
 5137            LanguageServerToQuery::Primary,
 5138            GetDocumentHighlights { position },
 5139            cx,
 5140        )
 5141    }
 5142
 5143    pub fn document_highlights<T: ToPointUtf16>(
 5144        &self,
 5145        buffer: &Model<Buffer>,
 5146        position: T,
 5147        cx: &mut ModelContext<Self>,
 5148    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5149        let position = position.to_point_utf16(buffer.read(cx));
 5150        self.document_highlights_impl(buffer, position, cx)
 5151    }
 5152
 5153    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
 5154        let language_registry = self.languages.clone();
 5155
 5156        if self.is_local() {
 5157            let mut requests = Vec::new();
 5158            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
 5159                let Some(worktree_handle) = self.worktree_for_id(*worktree_id, cx) else {
 5160                    continue;
 5161                };
 5162                let worktree = worktree_handle.read(cx);
 5163                if !worktree.is_visible() {
 5164                    continue;
 5165                }
 5166                let Some(worktree) = worktree.as_local() else {
 5167                    continue;
 5168                };
 5169                let worktree_abs_path = worktree.abs_path().clone();
 5170
 5171                let (adapter, language, server) = match self.language_servers.get(server_id) {
 5172                    Some(LanguageServerState::Running {
 5173                        adapter,
 5174                        language,
 5175                        server,
 5176                        ..
 5177                    }) => (adapter.clone(), language.clone(), server),
 5178
 5179                    _ => continue,
 5180                };
 5181
 5182                requests.push(
 5183                    server
 5184                        .request::<lsp::request::WorkspaceSymbolRequest>(
 5185                            lsp::WorkspaceSymbolParams {
 5186                                query: query.to_string(),
 5187                                ..Default::default()
 5188                            },
 5189                        )
 5190                        .log_err()
 5191                        .map(move |response| {
 5192                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
 5193                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 5194                                    flat_responses.into_iter().map(|lsp_symbol| {
 5195                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 5196                                    }).collect::<Vec<_>>()
 5197                                }
 5198                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 5199                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
 5200                                        let location = match lsp_symbol.location {
 5201                                            OneOf::Left(location) => location,
 5202                                            OneOf::Right(_) => {
 5203                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 5204                                                return None
 5205                                            }
 5206                                        };
 5207                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
 5208                                    }).collect::<Vec<_>>()
 5209                                }
 5210                            }).unwrap_or_default();
 5211
 5212                            (
 5213                                adapter,
 5214                                language,
 5215                                worktree_handle.downgrade(),
 5216                                worktree_abs_path,
 5217                                lsp_symbols,
 5218                            )
 5219                        }),
 5220                );
 5221            }
 5222
 5223            cx.spawn(move |this, mut cx| async move {
 5224                let responses = futures::future::join_all(requests).await;
 5225                let this = match this.upgrade() {
 5226                    Some(this) => this,
 5227                    None => return Ok(Vec::new()),
 5228                };
 5229
 5230                let mut symbols = Vec::new();
 5231                for (adapter, adapter_language, source_worktree, worktree_abs_path, lsp_symbols) in
 5232                    responses
 5233                {
 5234                    let core_symbols = this.update(&mut cx, |this, cx| {
 5235                        lsp_symbols
 5236                            .into_iter()
 5237                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 5238                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 5239                                let source_worktree = source_worktree.upgrade()?;
 5240                                let source_worktree_id = source_worktree.read(cx).id();
 5241
 5242                                let path;
 5243                                let worktree;
 5244                                if let Some((tree, rel_path)) =
 5245                                    this.find_local_worktree(&abs_path, cx)
 5246                                {
 5247                                    worktree = tree;
 5248                                    path = rel_path;
 5249                                } else {
 5250                                    worktree = source_worktree.clone();
 5251                                    path = relativize_path(&worktree_abs_path, &abs_path);
 5252                                }
 5253
 5254                                let worktree_id = worktree.read(cx).id();
 5255                                let project_path = ProjectPath {
 5256                                    worktree_id,
 5257                                    path: path.into(),
 5258                                };
 5259                                let signature = this.symbol_signature(&project_path);
 5260                                Some(CoreSymbol {
 5261                                    language_server_name: adapter.name.clone(),
 5262                                    source_worktree_id,
 5263                                    path: project_path,
 5264                                    kind: symbol_kind,
 5265                                    name: symbol_name,
 5266                                    range: range_from_lsp(symbol_location.range),
 5267                                    signature,
 5268                                })
 5269                            })
 5270                            .collect()
 5271                    })?;
 5272
 5273                    populate_labels_for_symbols(
 5274                        core_symbols,
 5275                        &language_registry,
 5276                        Some(adapter_language),
 5277                        Some(adapter),
 5278                        &mut symbols,
 5279                    )
 5280                    .await;
 5281                }
 5282
 5283                Ok(symbols)
 5284            })
 5285        } else if let Some(project_id) = self.remote_id() {
 5286            let request = self.client.request(proto::GetProjectSymbols {
 5287                project_id,
 5288                query: query.to_string(),
 5289            });
 5290            cx.foreground_executor().spawn(async move {
 5291                let response = request.await?;
 5292                let mut symbols = Vec::new();
 5293                let core_symbols = response
 5294                    .symbols
 5295                    .into_iter()
 5296                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 5297                    .collect::<Vec<_>>();
 5298                populate_labels_for_symbols(
 5299                    core_symbols,
 5300                    &language_registry,
 5301                    None,
 5302                    None,
 5303                    &mut symbols,
 5304                )
 5305                .await;
 5306                Ok(symbols)
 5307            })
 5308        } else {
 5309            Task::ready(Ok(Default::default()))
 5310        }
 5311    }
 5312
 5313    pub fn open_buffer_for_symbol(
 5314        &mut self,
 5315        symbol: &Symbol,
 5316        cx: &mut ModelContext<Self>,
 5317    ) -> Task<Result<Model<Buffer>>> {
 5318        if self.is_local() {
 5319            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
 5320                symbol.source_worktree_id,
 5321                symbol.language_server_name.clone(),
 5322            )) {
 5323                *id
 5324            } else {
 5325                return Task::ready(Err(anyhow!(
 5326                    "language server for worktree and language not found"
 5327                )));
 5328            };
 5329
 5330            let worktree_abs_path = if let Some(worktree_abs_path) = self
 5331                .worktree_for_id(symbol.path.worktree_id, cx)
 5332                .and_then(|worktree| worktree.read(cx).as_local())
 5333                .map(|local_worktree| local_worktree.abs_path())
 5334            {
 5335                worktree_abs_path
 5336            } else {
 5337                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 5338            };
 5339
 5340            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
 5341            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 5342                uri
 5343            } else {
 5344                return Task::ready(Err(anyhow!("invalid symbol path")));
 5345            };
 5346
 5347            self.open_local_buffer_via_lsp(
 5348                symbol_uri,
 5349                language_server_id,
 5350                symbol.language_server_name.clone(),
 5351                cx,
 5352            )
 5353        } else if let Some(project_id) = self.remote_id() {
 5354            let request = self.client.request(proto::OpenBufferForSymbol {
 5355                project_id,
 5356                symbol: Some(serialize_symbol(symbol)),
 5357            });
 5358            cx.spawn(move |this, mut cx| async move {
 5359                let response = request.await?;
 5360                let buffer_id = BufferId::new(response.buffer_id)?;
 5361                this.update(&mut cx, |this, cx| {
 5362                    this.wait_for_remote_buffer(buffer_id, cx)
 5363                })?
 5364                .await
 5365            })
 5366        } else {
 5367            Task::ready(Err(anyhow!("project does not have a remote id")))
 5368        }
 5369    }
 5370
 5371    fn hover_impl(
 5372        &self,
 5373        buffer: &Model<Buffer>,
 5374        position: PointUtf16,
 5375        cx: &mut ModelContext<Self>,
 5376    ) -> Task<Vec<Hover>> {
 5377        if self.is_local() {
 5378            let all_actions_task = self.request_multiple_lsp_locally(
 5379                &buffer,
 5380                Some(position),
 5381                |server_capabilities| match server_capabilities.hover_provider {
 5382                    Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 5383                    Some(lsp::HoverProviderCapability::Options(_)) => true,
 5384                    None => false,
 5385                },
 5386                GetHover { position },
 5387                cx,
 5388            );
 5389            cx.spawn(|_, _| async move {
 5390                all_actions_task
 5391                    .await
 5392                    .into_iter()
 5393                    .filter_map(|hover| remove_empty_hover_blocks(hover?))
 5394                    .collect()
 5395            })
 5396        } else if let Some(project_id) = self.remote_id() {
 5397            let request_task = self.client().request(proto::MultiLspQuery {
 5398                buffer_id: buffer.read(cx).remote_id().into(),
 5399                version: serialize_version(&buffer.read(cx).version()),
 5400                project_id,
 5401                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5402                    proto::AllLanguageServers {},
 5403                )),
 5404                request: Some(proto::multi_lsp_query::Request::GetHover(
 5405                    GetHover { position }.to_proto(project_id, buffer.read(cx)),
 5406                )),
 5407            });
 5408            let buffer = buffer.clone();
 5409            cx.spawn(|weak_project, cx| async move {
 5410                let Some(project) = weak_project.upgrade() else {
 5411                    return Vec::new();
 5412                };
 5413                join_all(
 5414                    request_task
 5415                        .await
 5416                        .log_err()
 5417                        .map(|response| response.responses)
 5418                        .unwrap_or_default()
 5419                        .into_iter()
 5420                        .filter_map(|lsp_response| match lsp_response.response? {
 5421                            proto::lsp_response::Response::GetHoverResponse(response) => {
 5422                                Some(response)
 5423                            }
 5424                            unexpected => {
 5425                                debug_panic!("Unexpected response: {unexpected:?}");
 5426                                None
 5427                            }
 5428                        })
 5429                        .map(|hover_response| {
 5430                            let response = GetHover { position }.response_from_proto(
 5431                                hover_response,
 5432                                project.clone(),
 5433                                buffer.clone(),
 5434                                cx.clone(),
 5435                            );
 5436                            async move {
 5437                                response
 5438                                    .await
 5439                                    .log_err()
 5440                                    .flatten()
 5441                                    .and_then(remove_empty_hover_blocks)
 5442                            }
 5443                        }),
 5444                )
 5445                .await
 5446                .into_iter()
 5447                .flatten()
 5448                .collect()
 5449            })
 5450        } else {
 5451            log::error!("cannot show hovers: project does not have a remote id");
 5452            Task::ready(Vec::new())
 5453        }
 5454    }
 5455
 5456    pub fn hover<T: ToPointUtf16>(
 5457        &self,
 5458        buffer: &Model<Buffer>,
 5459        position: T,
 5460        cx: &mut ModelContext<Self>,
 5461    ) -> Task<Vec<Hover>> {
 5462        let position = position.to_point_utf16(buffer.read(cx));
 5463        self.hover_impl(buffer, position, cx)
 5464    }
 5465
 5466    #[inline(never)]
 5467    fn completions_impl(
 5468        &self,
 5469        buffer: &Model<Buffer>,
 5470        position: PointUtf16,
 5471        cx: &mut ModelContext<Self>,
 5472    ) -> Task<Result<Vec<Completion>>> {
 5473        let language_registry = self.languages.clone();
 5474
 5475        if self.is_local() {
 5476            let snapshot = buffer.read(cx).snapshot();
 5477            let offset = position.to_offset(&snapshot);
 5478            let scope = snapshot.language_scope_at(offset);
 5479            let language = snapshot.language().cloned();
 5480
 5481            let server_ids: Vec<_> = self
 5482                .language_servers_for_buffer(buffer.read(cx), cx)
 5483                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 5484                .filter(|(adapter, _)| {
 5485                    scope
 5486                        .as_ref()
 5487                        .map(|scope| scope.language_allowed(&adapter.name))
 5488                        .unwrap_or(true)
 5489                })
 5490                .map(|(_, server)| server.server_id())
 5491                .collect();
 5492
 5493            let buffer = buffer.clone();
 5494            cx.spawn(move |this, mut cx| async move {
 5495                let mut tasks = Vec::with_capacity(server_ids.len());
 5496                this.update(&mut cx, |this, cx| {
 5497                    for server_id in server_ids {
 5498                        let lsp_adapter = this.language_server_adapter_for_id(server_id);
 5499                        tasks.push((
 5500                            lsp_adapter,
 5501                            this.request_lsp(
 5502                                buffer.clone(),
 5503                                LanguageServerToQuery::Other(server_id),
 5504                                GetCompletions { position },
 5505                                cx,
 5506                            ),
 5507                        ));
 5508                    }
 5509                })?;
 5510
 5511                let mut completions = Vec::new();
 5512                for (lsp_adapter, task) in tasks {
 5513                    if let Ok(new_completions) = task.await {
 5514                        populate_labels_for_completions(
 5515                            new_completions,
 5516                            &language_registry,
 5517                            language.clone(),
 5518                            lsp_adapter,
 5519                            &mut completions,
 5520                        )
 5521                        .await;
 5522                    }
 5523                }
 5524
 5525                Ok(completions)
 5526            })
 5527        } else if let Some(project_id) = self.remote_id() {
 5528            let task = self.send_lsp_proto_request(
 5529                buffer.clone(),
 5530                project_id,
 5531                GetCompletions { position },
 5532                cx,
 5533            );
 5534            let language = buffer.read(cx).language().cloned();
 5535
 5536            // In the future, we should provide project guests with the names of LSP adapters,
 5537            // so that they can use the correct LSP adapter when computing labels. For now,
 5538            // guests just use the first LSP adapter associated with the buffer's language.
 5539            let lsp_adapter = language
 5540                .as_ref()
 5541                .and_then(|language| language_registry.lsp_adapters(language).first().cloned());
 5542
 5543            cx.foreground_executor().spawn(async move {
 5544                let completions = task.await?;
 5545                let mut result = Vec::new();
 5546                populate_labels_for_completions(
 5547                    completions,
 5548                    &language_registry,
 5549                    language,
 5550                    lsp_adapter,
 5551                    &mut result,
 5552                )
 5553                .await;
 5554                Ok(result)
 5555            })
 5556        } else {
 5557            Task::ready(Ok(Default::default()))
 5558        }
 5559    }
 5560
 5561    pub fn completions<T: ToOffset + ToPointUtf16>(
 5562        &self,
 5563        buffer: &Model<Buffer>,
 5564        position: T,
 5565        cx: &mut ModelContext<Self>,
 5566    ) -> Task<Result<Vec<Completion>>> {
 5567        let position = position.to_point_utf16(buffer.read(cx));
 5568        self.completions_impl(buffer, position, cx)
 5569    }
 5570
 5571    pub fn resolve_completions(
 5572        &self,
 5573        buffer: Model<Buffer>,
 5574        completion_indices: Vec<usize>,
 5575        completions: Arc<RwLock<Box<[Completion]>>>,
 5576        cx: &mut ModelContext<Self>,
 5577    ) -> Task<Result<bool>> {
 5578        let client = self.client();
 5579        let language_registry = self.languages().clone();
 5580
 5581        let is_remote = self.is_remote();
 5582        let project_id = self.remote_id();
 5583
 5584        let buffer_id = buffer.read(cx).remote_id();
 5585        let buffer_snapshot = buffer.read(cx).snapshot();
 5586
 5587        cx.spawn(move |this, mut cx| async move {
 5588            let mut did_resolve = false;
 5589            if is_remote {
 5590                let project_id =
 5591                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
 5592
 5593                for completion_index in completion_indices {
 5594                    let (server_id, completion) = {
 5595                        let completions_guard = completions.read();
 5596                        let completion = &completions_guard[completion_index];
 5597                        if completion.documentation.is_some() {
 5598                            continue;
 5599                        }
 5600
 5601                        did_resolve = true;
 5602                        let server_id = completion.server_id;
 5603                        let completion = completion.lsp_completion.clone();
 5604
 5605                        (server_id, completion)
 5606                    };
 5607
 5608                    Self::resolve_completion_remote(
 5609                        project_id,
 5610                        server_id,
 5611                        buffer_id,
 5612                        completions.clone(),
 5613                        completion_index,
 5614                        completion,
 5615                        client.clone(),
 5616                        language_registry.clone(),
 5617                    )
 5618                    .await;
 5619                }
 5620            } else {
 5621                for completion_index in completion_indices {
 5622                    let (server_id, completion) = {
 5623                        let completions_guard = completions.read();
 5624                        let completion = &completions_guard[completion_index];
 5625                        if completion.documentation.is_some() {
 5626                            continue;
 5627                        }
 5628
 5629                        let server_id = completion.server_id;
 5630                        let completion = completion.lsp_completion.clone();
 5631
 5632                        (server_id, completion)
 5633                    };
 5634
 5635                    let server = this
 5636                        .read_with(&mut cx, |project, _| {
 5637                            project.language_server_for_id(server_id)
 5638                        })
 5639                        .ok()
 5640                        .flatten();
 5641                    let Some(server) = server else {
 5642                        continue;
 5643                    };
 5644
 5645                    did_resolve = true;
 5646                    Self::resolve_completion_local(
 5647                        server,
 5648                        &buffer_snapshot,
 5649                        completions.clone(),
 5650                        completion_index,
 5651                        completion,
 5652                        language_registry.clone(),
 5653                    )
 5654                    .await;
 5655                }
 5656            }
 5657
 5658            Ok(did_resolve)
 5659        })
 5660    }
 5661
 5662    async fn resolve_completion_local(
 5663        server: Arc<lsp::LanguageServer>,
 5664        snapshot: &BufferSnapshot,
 5665        completions: Arc<RwLock<Box<[Completion]>>>,
 5666        completion_index: usize,
 5667        completion: lsp::CompletionItem,
 5668        language_registry: Arc<LanguageRegistry>,
 5669    ) {
 5670        let can_resolve = server
 5671            .capabilities()
 5672            .completion_provider
 5673            .as_ref()
 5674            .and_then(|options| options.resolve_provider)
 5675            .unwrap_or(false);
 5676        if !can_resolve {
 5677            return;
 5678        }
 5679
 5680        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 5681        let Some(completion_item) = request.await.log_err() else {
 5682            return;
 5683        };
 5684
 5685        if let Some(lsp_documentation) = completion_item.documentation.as_ref() {
 5686            let documentation = language::prepare_completion_documentation(
 5687                lsp_documentation,
 5688                &language_registry,
 5689                None, // TODO: Try to reasonably work out which language the completion is for
 5690            )
 5691            .await;
 5692
 5693            let mut completions = completions.write();
 5694            let completion = &mut completions[completion_index];
 5695            completion.documentation = Some(documentation);
 5696        } else {
 5697            let mut completions = completions.write();
 5698            let completion = &mut completions[completion_index];
 5699            completion.documentation = Some(Documentation::Undocumented);
 5700        }
 5701
 5702        if let Some(text_edit) = completion_item.text_edit.as_ref() {
 5703            // Technically we don't have to parse the whole `text_edit`, since the only
 5704            // language server we currently use that does update `text_edit` in `completionItem/resolve`
 5705            // is `typescript-language-server` and they only update `text_edit.new_text`.
 5706            // But we should not rely on that.
 5707            let edit = parse_completion_text_edit(text_edit, snapshot);
 5708
 5709            if let Some((old_range, mut new_text)) = edit {
 5710                LineEnding::normalize(&mut new_text);
 5711
 5712                let mut completions = completions.write();
 5713                let completion = &mut completions[completion_index];
 5714
 5715                completion.new_text = new_text;
 5716                completion.old_range = old_range;
 5717            }
 5718        }
 5719    }
 5720
 5721    #[allow(clippy::too_many_arguments)]
 5722    async fn resolve_completion_remote(
 5723        project_id: u64,
 5724        server_id: LanguageServerId,
 5725        buffer_id: BufferId,
 5726        completions: Arc<RwLock<Box<[Completion]>>>,
 5727        completion_index: usize,
 5728        completion: lsp::CompletionItem,
 5729        client: Arc<Client>,
 5730        language_registry: Arc<LanguageRegistry>,
 5731    ) {
 5732        let request = proto::ResolveCompletionDocumentation {
 5733            project_id,
 5734            language_server_id: server_id.0 as u64,
 5735            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 5736            buffer_id: buffer_id.into(),
 5737        };
 5738
 5739        let Some(response) = client
 5740            .request(request)
 5741            .await
 5742            .context("completion documentation resolve proto request")
 5743            .log_err()
 5744        else {
 5745            return;
 5746        };
 5747
 5748        let documentation = if response.documentation.is_empty() {
 5749            Documentation::Undocumented
 5750        } else if response.documentation_is_markdown {
 5751            Documentation::MultiLineMarkdown(
 5752                markdown::parse_markdown(&response.documentation, &language_registry, None).await,
 5753            )
 5754        } else if response.documentation.lines().count() <= 1 {
 5755            Documentation::SingleLine(response.documentation)
 5756        } else {
 5757            Documentation::MultiLinePlainText(response.documentation)
 5758        };
 5759
 5760        let mut completions = completions.write();
 5761        let completion = &mut completions[completion_index];
 5762        completion.documentation = Some(documentation);
 5763
 5764        let old_range = response
 5765            .old_start
 5766            .and_then(deserialize_anchor)
 5767            .zip(response.old_end.and_then(deserialize_anchor));
 5768        if let Some((old_start, old_end)) = old_range {
 5769            if !response.new_text.is_empty() {
 5770                completion.new_text = response.new_text;
 5771                completion.old_range = old_start..old_end;
 5772            }
 5773        }
 5774    }
 5775
 5776    pub fn apply_additional_edits_for_completion(
 5777        &self,
 5778        buffer_handle: Model<Buffer>,
 5779        completion: Completion,
 5780        push_to_history: bool,
 5781        cx: &mut ModelContext<Self>,
 5782    ) -> Task<Result<Option<Transaction>>> {
 5783        let buffer = buffer_handle.read(cx);
 5784        let buffer_id = buffer.remote_id();
 5785
 5786        if self.is_local() {
 5787            let server_id = completion.server_id;
 5788            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
 5789                Some((_, server)) => server.clone(),
 5790                _ => return Task::ready(Ok(Default::default())),
 5791            };
 5792
 5793            cx.spawn(move |this, mut cx| async move {
 5794                let can_resolve = lang_server
 5795                    .capabilities()
 5796                    .completion_provider
 5797                    .as_ref()
 5798                    .and_then(|options| options.resolve_provider)
 5799                    .unwrap_or(false);
 5800                let additional_text_edits = if can_resolve {
 5801                    lang_server
 5802                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
 5803                        .await?
 5804                        .additional_text_edits
 5805                } else {
 5806                    completion.lsp_completion.additional_text_edits
 5807                };
 5808                if let Some(edits) = additional_text_edits {
 5809                    let edits = this
 5810                        .update(&mut cx, |this, cx| {
 5811                            this.edits_from_lsp(
 5812                                &buffer_handle,
 5813                                edits,
 5814                                lang_server.server_id(),
 5815                                None,
 5816                                cx,
 5817                            )
 5818                        })?
 5819                        .await?;
 5820
 5821                    buffer_handle.update(&mut cx, |buffer, cx| {
 5822                        buffer.finalize_last_transaction();
 5823                        buffer.start_transaction();
 5824
 5825                        for (range, text) in edits {
 5826                            let primary = &completion.old_range;
 5827                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 5828                                && primary.end.cmp(&range.start, buffer).is_ge();
 5829                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 5830                                && range.end.cmp(&primary.end, buffer).is_ge();
 5831
 5832                            //Skip additional edits which overlap with the primary completion edit
 5833                            //https://github.com/zed-industries/zed/pull/1871
 5834                            if !start_within && !end_within {
 5835                                buffer.edit([(range, text)], None, cx);
 5836                            }
 5837                        }
 5838
 5839                        let transaction = if buffer.end_transaction(cx).is_some() {
 5840                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 5841                            if !push_to_history {
 5842                                buffer.forget_transaction(transaction.id);
 5843                            }
 5844                            Some(transaction)
 5845                        } else {
 5846                            None
 5847                        };
 5848                        Ok(transaction)
 5849                    })?
 5850                } else {
 5851                    Ok(None)
 5852                }
 5853            })
 5854        } else if let Some(project_id) = self.remote_id() {
 5855            let client = self.client.clone();
 5856            cx.spawn(move |_, mut cx| async move {
 5857                let response = client
 5858                    .request(proto::ApplyCompletionAdditionalEdits {
 5859                        project_id,
 5860                        buffer_id: buffer_id.into(),
 5861                        completion: Some(Self::serialize_completion(&CoreCompletion {
 5862                            old_range: completion.old_range,
 5863                            new_text: completion.new_text,
 5864                            server_id: completion.server_id,
 5865                            lsp_completion: completion.lsp_completion,
 5866                        })),
 5867                    })
 5868                    .await?;
 5869
 5870                if let Some(transaction) = response.transaction {
 5871                    let transaction = language::proto::deserialize_transaction(transaction)?;
 5872                    buffer_handle
 5873                        .update(&mut cx, |buffer, _| {
 5874                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 5875                        })?
 5876                        .await?;
 5877                    if push_to_history {
 5878                        buffer_handle.update(&mut cx, |buffer, _| {
 5879                            buffer.push_transaction(transaction.clone(), Instant::now());
 5880                        })?;
 5881                    }
 5882                    Ok(Some(transaction))
 5883                } else {
 5884                    Ok(None)
 5885                }
 5886            })
 5887        } else {
 5888            Task::ready(Err(anyhow!("project does not have a remote id")))
 5889        }
 5890    }
 5891
 5892    fn code_actions_impl(
 5893        &mut self,
 5894        buffer_handle: &Model<Buffer>,
 5895        range: Range<Anchor>,
 5896        cx: &mut ModelContext<Self>,
 5897    ) -> Task<Vec<CodeAction>> {
 5898        if self.is_local() {
 5899            let all_actions_task = self.request_multiple_lsp_locally(
 5900                &buffer_handle,
 5901                Some(range.start),
 5902                GetCodeActions::supports_code_actions,
 5903                GetCodeActions {
 5904                    range: range.clone(),
 5905                    kinds: None,
 5906                },
 5907                cx,
 5908            );
 5909            cx.spawn(|_, _| async move { all_actions_task.await.into_iter().flatten().collect() })
 5910        } else if let Some(project_id) = self.remote_id() {
 5911            let request_task = self.client().request(proto::MultiLspQuery {
 5912                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5913                version: serialize_version(&buffer_handle.read(cx).version()),
 5914                project_id,
 5915                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5916                    proto::AllLanguageServers {},
 5917                )),
 5918                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 5919                    GetCodeActions {
 5920                        range: range.clone(),
 5921                        kinds: None,
 5922                    }
 5923                    .to_proto(project_id, buffer_handle.read(cx)),
 5924                )),
 5925            });
 5926            let buffer = buffer_handle.clone();
 5927            cx.spawn(|weak_project, cx| async move {
 5928                let Some(project) = weak_project.upgrade() else {
 5929                    return Vec::new();
 5930                };
 5931                join_all(
 5932                    request_task
 5933                        .await
 5934                        .log_err()
 5935                        .map(|response| response.responses)
 5936                        .unwrap_or_default()
 5937                        .into_iter()
 5938                        .filter_map(|lsp_response| match lsp_response.response? {
 5939                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 5940                                Some(response)
 5941                            }
 5942                            unexpected => {
 5943                                debug_panic!("Unexpected response: {unexpected:?}");
 5944                                None
 5945                            }
 5946                        })
 5947                        .map(|code_actions_response| {
 5948                            let response = GetCodeActions {
 5949                                range: range.clone(),
 5950                                kinds: None,
 5951                            }
 5952                            .response_from_proto(
 5953                                code_actions_response,
 5954                                project.clone(),
 5955                                buffer.clone(),
 5956                                cx.clone(),
 5957                            );
 5958                            async move { response.await.log_err().unwrap_or_default() }
 5959                        }),
 5960                )
 5961                .await
 5962                .into_iter()
 5963                .flatten()
 5964                .collect()
 5965            })
 5966        } else {
 5967            log::error!("cannot fetch actions: project does not have a remote id");
 5968            Task::ready(Vec::new())
 5969        }
 5970    }
 5971
 5972    pub fn code_actions<T: Clone + ToOffset>(
 5973        &mut self,
 5974        buffer_handle: &Model<Buffer>,
 5975        range: Range<T>,
 5976        cx: &mut ModelContext<Self>,
 5977    ) -> Task<Vec<CodeAction>> {
 5978        let buffer = buffer_handle.read(cx);
 5979        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 5980        self.code_actions_impl(buffer_handle, range, cx)
 5981    }
 5982
 5983    pub fn apply_code_action(
 5984        &self,
 5985        buffer_handle: Model<Buffer>,
 5986        mut action: CodeAction,
 5987        push_to_history: bool,
 5988        cx: &mut ModelContext<Self>,
 5989    ) -> Task<Result<ProjectTransaction>> {
 5990        if self.is_local() {
 5991            let buffer = buffer_handle.read(cx);
 5992            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
 5993                self.language_server_for_buffer(buffer, action.server_id, cx)
 5994            {
 5995                (adapter.clone(), server.clone())
 5996            } else {
 5997                return Task::ready(Ok(Default::default()));
 5998            };
 5999            cx.spawn(move |this, mut cx| async move {
 6000                Self::try_resolve_code_action(&lang_server, &mut action)
 6001                    .await
 6002                    .context("resolving a code action")?;
 6003                if let Some(edit) = action.lsp_action.edit {
 6004                    if edit.changes.is_some() || edit.document_changes.is_some() {
 6005                        return Self::deserialize_workspace_edit(
 6006                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
 6007                            edit,
 6008                            push_to_history,
 6009                            lsp_adapter.clone(),
 6010                            lang_server.clone(),
 6011                            &mut cx,
 6012                        )
 6013                        .await;
 6014                    }
 6015                }
 6016
 6017                if let Some(command) = action.lsp_action.command {
 6018                    this.update(&mut cx, |this, _| {
 6019                        this.last_workspace_edits_by_language_server
 6020                            .remove(&lang_server.server_id());
 6021                    })?;
 6022
 6023                    let result = lang_server
 6024                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 6025                            command: command.command,
 6026                            arguments: command.arguments.unwrap_or_default(),
 6027                            ..Default::default()
 6028                        })
 6029                        .await;
 6030
 6031                    if let Err(err) = result {
 6032                        // TODO: LSP ERROR
 6033                        return Err(err);
 6034                    }
 6035
 6036                    return this.update(&mut cx, |this, _| {
 6037                        this.last_workspace_edits_by_language_server
 6038                            .remove(&lang_server.server_id())
 6039                            .unwrap_or_default()
 6040                    });
 6041                }
 6042
 6043                Ok(ProjectTransaction::default())
 6044            })
 6045        } else if let Some(project_id) = self.remote_id() {
 6046            let client = self.client.clone();
 6047            let request = proto::ApplyCodeAction {
 6048                project_id,
 6049                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6050                action: Some(Self::serialize_code_action(&action)),
 6051            };
 6052            cx.spawn(move |this, mut cx| async move {
 6053                let response = client
 6054                    .request(request)
 6055                    .await?
 6056                    .transaction
 6057                    .ok_or_else(|| anyhow!("missing transaction"))?;
 6058                this.update(&mut cx, |this, cx| {
 6059                    this.deserialize_project_transaction(response, push_to_history, cx)
 6060                })?
 6061                .await
 6062            })
 6063        } else {
 6064            Task::ready(Err(anyhow!("project does not have a remote id")))
 6065        }
 6066    }
 6067
 6068    fn apply_on_type_formatting(
 6069        &self,
 6070        buffer: Model<Buffer>,
 6071        position: Anchor,
 6072        trigger: String,
 6073        cx: &mut ModelContext<Self>,
 6074    ) -> Task<Result<Option<Transaction>>> {
 6075        if self.is_local() {
 6076            cx.spawn(move |this, mut cx| async move {
 6077                // Do not allow multiple concurrent formatting requests for the
 6078                // same buffer.
 6079                this.update(&mut cx, |this, cx| {
 6080                    this.buffers_being_formatted
 6081                        .insert(buffer.read(cx).remote_id())
 6082                })?;
 6083
 6084                let _cleanup = defer({
 6085                    let this = this.clone();
 6086                    let mut cx = cx.clone();
 6087                    let closure_buffer = buffer.clone();
 6088                    move || {
 6089                        this.update(&mut cx, |this, cx| {
 6090                            this.buffers_being_formatted
 6091                                .remove(&closure_buffer.read(cx).remote_id());
 6092                        })
 6093                        .ok();
 6094                    }
 6095                });
 6096
 6097                buffer
 6098                    .update(&mut cx, |buffer, _| {
 6099                        buffer.wait_for_edits(Some(position.timestamp))
 6100                    })?
 6101                    .await?;
 6102                this.update(&mut cx, |this, cx| {
 6103                    let position = position.to_point_utf16(buffer.read(cx));
 6104                    this.on_type_format(buffer, position, trigger, false, cx)
 6105                })?
 6106                .await
 6107            })
 6108        } else if let Some(project_id) = self.remote_id() {
 6109            let client = self.client.clone();
 6110            let request = proto::OnTypeFormatting {
 6111                project_id,
 6112                buffer_id: buffer.read(cx).remote_id().into(),
 6113                position: Some(serialize_anchor(&position)),
 6114                trigger,
 6115                version: serialize_version(&buffer.read(cx).version()),
 6116            };
 6117            cx.spawn(move |_, _| async move {
 6118                client
 6119                    .request(request)
 6120                    .await?
 6121                    .transaction
 6122                    .map(language::proto::deserialize_transaction)
 6123                    .transpose()
 6124            })
 6125        } else {
 6126            Task::ready(Err(anyhow!("project does not have a remote id")))
 6127        }
 6128    }
 6129
 6130    async fn deserialize_edits(
 6131        this: Model<Self>,
 6132        buffer_to_edit: Model<Buffer>,
 6133        edits: Vec<lsp::TextEdit>,
 6134        push_to_history: bool,
 6135        _: Arc<CachedLspAdapter>,
 6136        language_server: Arc<LanguageServer>,
 6137        cx: &mut AsyncAppContext,
 6138    ) -> Result<Option<Transaction>> {
 6139        let edits = this
 6140            .update(cx, |this, cx| {
 6141                this.edits_from_lsp(
 6142                    &buffer_to_edit,
 6143                    edits,
 6144                    language_server.server_id(),
 6145                    None,
 6146                    cx,
 6147                )
 6148            })?
 6149            .await?;
 6150
 6151        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6152            buffer.finalize_last_transaction();
 6153            buffer.start_transaction();
 6154            for (range, text) in edits {
 6155                buffer.edit([(range, text)], None, cx);
 6156            }
 6157
 6158            if buffer.end_transaction(cx).is_some() {
 6159                let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6160                if !push_to_history {
 6161                    buffer.forget_transaction(transaction.id);
 6162                }
 6163                Some(transaction)
 6164            } else {
 6165                None
 6166            }
 6167        })?;
 6168
 6169        Ok(transaction)
 6170    }
 6171
 6172    async fn deserialize_workspace_edit(
 6173        this: Model<Self>,
 6174        edit: lsp::WorkspaceEdit,
 6175        push_to_history: bool,
 6176        lsp_adapter: Arc<CachedLspAdapter>,
 6177        language_server: Arc<LanguageServer>,
 6178        cx: &mut AsyncAppContext,
 6179    ) -> Result<ProjectTransaction> {
 6180        let fs = this.update(cx, |this, _| this.fs.clone())?;
 6181        let mut operations = Vec::new();
 6182        if let Some(document_changes) = edit.document_changes {
 6183            match document_changes {
 6184                lsp::DocumentChanges::Edits(edits) => {
 6185                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
 6186                }
 6187                lsp::DocumentChanges::Operations(ops) => operations = ops,
 6188            }
 6189        } else if let Some(changes) = edit.changes {
 6190            operations.extend(changes.into_iter().map(|(uri, edits)| {
 6191                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
 6192                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
 6193                        uri,
 6194                        version: None,
 6195                    },
 6196                    edits: edits.into_iter().map(OneOf::Left).collect(),
 6197                })
 6198            }));
 6199        }
 6200
 6201        let mut project_transaction = ProjectTransaction::default();
 6202        for operation in operations {
 6203            match operation {
 6204                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
 6205                    let abs_path = op
 6206                        .uri
 6207                        .to_file_path()
 6208                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6209
 6210                    if let Some(parent_path) = abs_path.parent() {
 6211                        fs.create_dir(parent_path).await?;
 6212                    }
 6213                    if abs_path.ends_with("/") {
 6214                        fs.create_dir(&abs_path).await?;
 6215                    } else {
 6216                        fs.create_file(
 6217                            &abs_path,
 6218                            op.options
 6219                                .map(|options| fs::CreateOptions {
 6220                                    overwrite: options.overwrite.unwrap_or(false),
 6221                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6222                                })
 6223                                .unwrap_or_default(),
 6224                        )
 6225                        .await?;
 6226                    }
 6227                }
 6228
 6229                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
 6230                    let source_abs_path = op
 6231                        .old_uri
 6232                        .to_file_path()
 6233                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6234                    let target_abs_path = op
 6235                        .new_uri
 6236                        .to_file_path()
 6237                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6238                    fs.rename(
 6239                        &source_abs_path,
 6240                        &target_abs_path,
 6241                        op.options
 6242                            .map(|options| fs::RenameOptions {
 6243                                overwrite: options.overwrite.unwrap_or(false),
 6244                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6245                            })
 6246                            .unwrap_or_default(),
 6247                    )
 6248                    .await?;
 6249                }
 6250
 6251                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
 6252                    let abs_path = op
 6253                        .uri
 6254                        .to_file_path()
 6255                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6256                    let options = op
 6257                        .options
 6258                        .map(|options| fs::RemoveOptions {
 6259                            recursive: options.recursive.unwrap_or(false),
 6260                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
 6261                        })
 6262                        .unwrap_or_default();
 6263                    if abs_path.ends_with("/") {
 6264                        fs.remove_dir(&abs_path, options).await?;
 6265                    } else {
 6266                        fs.remove_file(&abs_path, options).await?;
 6267                    }
 6268                }
 6269
 6270                lsp::DocumentChangeOperation::Edit(op) => {
 6271                    let buffer_to_edit = this
 6272                        .update(cx, |this, cx| {
 6273                            this.open_local_buffer_via_lsp(
 6274                                op.text_document.uri,
 6275                                language_server.server_id(),
 6276                                lsp_adapter.name.clone(),
 6277                                cx,
 6278                            )
 6279                        })?
 6280                        .await?;
 6281
 6282                    let edits = this
 6283                        .update(cx, |this, cx| {
 6284                            let edits = op.edits.into_iter().map(|edit| match edit {
 6285                                OneOf::Left(edit) => edit,
 6286                                OneOf::Right(edit) => edit.text_edit,
 6287                            });
 6288                            this.edits_from_lsp(
 6289                                &buffer_to_edit,
 6290                                edits,
 6291                                language_server.server_id(),
 6292                                op.text_document.version,
 6293                                cx,
 6294                            )
 6295                        })?
 6296                        .await?;
 6297
 6298                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6299                        buffer.finalize_last_transaction();
 6300                        buffer.start_transaction();
 6301                        for (range, text) in edits {
 6302                            buffer.edit([(range, text)], None, cx);
 6303                        }
 6304                        let transaction = if buffer.end_transaction(cx).is_some() {
 6305                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6306                            if !push_to_history {
 6307                                buffer.forget_transaction(transaction.id);
 6308                            }
 6309                            Some(transaction)
 6310                        } else {
 6311                            None
 6312                        };
 6313
 6314                        transaction
 6315                    })?;
 6316                    if let Some(transaction) = transaction {
 6317                        project_transaction.0.insert(buffer_to_edit, transaction);
 6318                    }
 6319                }
 6320            }
 6321        }
 6322
 6323        Ok(project_transaction)
 6324    }
 6325
 6326    fn prepare_rename_impl(
 6327        &mut self,
 6328        buffer: Model<Buffer>,
 6329        position: PointUtf16,
 6330        cx: &mut ModelContext<Self>,
 6331    ) -> Task<Result<Option<Range<Anchor>>>> {
 6332        self.request_lsp(
 6333            buffer,
 6334            LanguageServerToQuery::Primary,
 6335            PrepareRename { position },
 6336            cx,
 6337        )
 6338    }
 6339    pub fn prepare_rename<T: ToPointUtf16>(
 6340        &mut self,
 6341        buffer: Model<Buffer>,
 6342        position: T,
 6343        cx: &mut ModelContext<Self>,
 6344    ) -> Task<Result<Option<Range<Anchor>>>> {
 6345        let position = position.to_point_utf16(buffer.read(cx));
 6346        self.prepare_rename_impl(buffer, position, cx)
 6347    }
 6348
 6349    fn perform_rename_impl(
 6350        &mut self,
 6351        buffer: Model<Buffer>,
 6352        position: PointUtf16,
 6353        new_name: String,
 6354        push_to_history: bool,
 6355        cx: &mut ModelContext<Self>,
 6356    ) -> Task<Result<ProjectTransaction>> {
 6357        let position = position.to_point_utf16(buffer.read(cx));
 6358        self.request_lsp(
 6359            buffer,
 6360            LanguageServerToQuery::Primary,
 6361            PerformRename {
 6362                position,
 6363                new_name,
 6364                push_to_history,
 6365            },
 6366            cx,
 6367        )
 6368    }
 6369    pub fn perform_rename<T: ToPointUtf16>(
 6370        &mut self,
 6371        buffer: Model<Buffer>,
 6372        position: T,
 6373        new_name: String,
 6374        push_to_history: bool,
 6375        cx: &mut ModelContext<Self>,
 6376    ) -> Task<Result<ProjectTransaction>> {
 6377        let position = position.to_point_utf16(buffer.read(cx));
 6378        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
 6379    }
 6380
 6381    pub fn on_type_format_impl(
 6382        &mut self,
 6383        buffer: Model<Buffer>,
 6384        position: PointUtf16,
 6385        trigger: String,
 6386        push_to_history: bool,
 6387        cx: &mut ModelContext<Self>,
 6388    ) -> Task<Result<Option<Transaction>>> {
 6389        let tab_size = buffer.update(cx, |buffer, cx| {
 6390            language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
 6391        });
 6392        self.request_lsp(
 6393            buffer.clone(),
 6394            LanguageServerToQuery::Primary,
 6395            OnTypeFormatting {
 6396                position,
 6397                trigger,
 6398                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
 6399                push_to_history,
 6400            },
 6401            cx,
 6402        )
 6403    }
 6404
 6405    pub fn on_type_format<T: ToPointUtf16>(
 6406        &mut self,
 6407        buffer: Model<Buffer>,
 6408        position: T,
 6409        trigger: String,
 6410        push_to_history: bool,
 6411        cx: &mut ModelContext<Self>,
 6412    ) -> Task<Result<Option<Transaction>>> {
 6413        let position = position.to_point_utf16(buffer.read(cx));
 6414        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 6415    }
 6416
 6417    pub fn inlay_hints<T: ToOffset>(
 6418        &mut self,
 6419        buffer_handle: Model<Buffer>,
 6420        range: Range<T>,
 6421        cx: &mut ModelContext<Self>,
 6422    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6423        let buffer = buffer_handle.read(cx);
 6424        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 6425        self.inlay_hints_impl(buffer_handle, range, cx)
 6426    }
 6427    fn inlay_hints_impl(
 6428        &mut self,
 6429        buffer_handle: Model<Buffer>,
 6430        range: Range<Anchor>,
 6431        cx: &mut ModelContext<Self>,
 6432    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6433        let buffer = buffer_handle.read(cx);
 6434        let range_start = range.start;
 6435        let range_end = range.end;
 6436        let buffer_id = buffer.remote_id().into();
 6437        let lsp_request = InlayHints { range };
 6438
 6439        if self.is_local() {
 6440            let lsp_request_task = self.request_lsp(
 6441                buffer_handle.clone(),
 6442                LanguageServerToQuery::Primary,
 6443                lsp_request,
 6444                cx,
 6445            );
 6446            cx.spawn(move |_, mut cx| async move {
 6447                buffer_handle
 6448                    .update(&mut cx, |buffer, _| {
 6449                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 6450                    })?
 6451                    .await
 6452                    .context("waiting for inlay hint request range edits")?;
 6453                lsp_request_task.await.context("inlay hints LSP request")
 6454            })
 6455        } else if let Some(project_id) = self.remote_id() {
 6456            let client = self.client.clone();
 6457            let request = proto::InlayHints {
 6458                project_id,
 6459                buffer_id,
 6460                start: Some(serialize_anchor(&range_start)),
 6461                end: Some(serialize_anchor(&range_end)),
 6462                version: serialize_version(&buffer_handle.read(cx).version()),
 6463            };
 6464            cx.spawn(move |project, cx| async move {
 6465                let response = client
 6466                    .request(request)
 6467                    .await
 6468                    .context("inlay hints proto request")?;
 6469                LspCommand::response_from_proto(
 6470                    lsp_request,
 6471                    response,
 6472                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
 6473                    buffer_handle.clone(),
 6474                    cx.clone(),
 6475                )
 6476                .await
 6477                .context("inlay hints proto response conversion")
 6478            })
 6479        } else {
 6480            Task::ready(Err(anyhow!("project does not have a remote id")))
 6481        }
 6482    }
 6483
 6484    pub fn resolve_inlay_hint(
 6485        &self,
 6486        hint: InlayHint,
 6487        buffer_handle: Model<Buffer>,
 6488        server_id: LanguageServerId,
 6489        cx: &mut ModelContext<Self>,
 6490    ) -> Task<anyhow::Result<InlayHint>> {
 6491        if self.is_local() {
 6492            let buffer = buffer_handle.read(cx);
 6493            let (_, lang_server) = if let Some((adapter, server)) =
 6494                self.language_server_for_buffer(buffer, server_id, cx)
 6495            {
 6496                (adapter.clone(), server.clone())
 6497            } else {
 6498                return Task::ready(Ok(hint));
 6499            };
 6500            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
 6501                return Task::ready(Ok(hint));
 6502            }
 6503
 6504            let buffer_snapshot = buffer.snapshot();
 6505            cx.spawn(move |_, mut cx| async move {
 6506                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
 6507                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
 6508                );
 6509                let resolved_hint = resolve_task
 6510                    .await
 6511                    .context("inlay hint resolve LSP request")?;
 6512                let resolved_hint = InlayHints::lsp_to_project_hint(
 6513                    resolved_hint,
 6514                    &buffer_handle,
 6515                    server_id,
 6516                    ResolveState::Resolved,
 6517                    false,
 6518                    &mut cx,
 6519                )
 6520                .await?;
 6521                Ok(resolved_hint)
 6522            })
 6523        } else if let Some(project_id) = self.remote_id() {
 6524            let client = self.client.clone();
 6525            let request = proto::ResolveInlayHint {
 6526                project_id,
 6527                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6528                language_server_id: server_id.0 as u64,
 6529                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
 6530            };
 6531            cx.spawn(move |_, _| async move {
 6532                let response = client
 6533                    .request(request)
 6534                    .await
 6535                    .context("inlay hints proto request")?;
 6536                match response.hint {
 6537                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
 6538                        .context("inlay hints proto resolve response conversion"),
 6539                    None => Ok(hint),
 6540                }
 6541            })
 6542        } else {
 6543            Task::ready(Err(anyhow!("project does not have a remote id")))
 6544        }
 6545    }
 6546
 6547    #[allow(clippy::type_complexity)]
 6548    pub fn search(
 6549        &self,
 6550        query: SearchQuery,
 6551        cx: &mut ModelContext<Self>,
 6552    ) -> Receiver<SearchResult> {
 6553        if self.is_local() {
 6554            self.search_local(query, cx)
 6555        } else if let Some(project_id) = self.remote_id() {
 6556            let (tx, rx) = smol::channel::unbounded();
 6557            let request = self.client.request(query.to_proto(project_id));
 6558            cx.spawn(move |this, mut cx| async move {
 6559                let response = request.await?;
 6560                let mut result = HashMap::default();
 6561                for location in response.locations {
 6562                    let buffer_id = BufferId::new(location.buffer_id)?;
 6563                    let target_buffer = this
 6564                        .update(&mut cx, |this, cx| {
 6565                            this.wait_for_remote_buffer(buffer_id, cx)
 6566                        })?
 6567                        .await?;
 6568                    let start = location
 6569                        .start
 6570                        .and_then(deserialize_anchor)
 6571                        .ok_or_else(|| anyhow!("missing target start"))?;
 6572                    let end = location
 6573                        .end
 6574                        .and_then(deserialize_anchor)
 6575                        .ok_or_else(|| anyhow!("missing target end"))?;
 6576                    result
 6577                        .entry(target_buffer)
 6578                        .or_insert(Vec::new())
 6579                        .push(start..end)
 6580                }
 6581                for (buffer, ranges) in result {
 6582                    let _ = tx.send(SearchResult::Buffer { buffer, ranges }).await;
 6583                }
 6584
 6585                if response.limit_reached {
 6586                    let _ = tx.send(SearchResult::LimitReached).await;
 6587                }
 6588
 6589                Result::<(), anyhow::Error>::Ok(())
 6590            })
 6591            .detach_and_log_err(cx);
 6592            rx
 6593        } else {
 6594            unimplemented!();
 6595        }
 6596    }
 6597
 6598    pub fn search_local(
 6599        &self,
 6600        query: SearchQuery,
 6601        cx: &mut ModelContext<Self>,
 6602    ) -> Receiver<SearchResult> {
 6603        // Local search is split into several phases.
 6604        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
 6605        // and the second phase that finds positions of all the matches found in the candidate files.
 6606        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
 6607        //
 6608        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
 6609        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
 6610        //
 6611        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
 6612        //    Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
 6613        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
 6614        // 2. At this point, we have a list of all potentially matching buffers/files.
 6615        //    We sort that list by buffer path - this list is retained for later use.
 6616        //    We ensure that all buffers are now opened and available in project.
 6617        // 3. We run a scan over all the candidate buffers on multiple background threads.
 6618        //    We cannot assume that there will even be a match - while at least one match
 6619        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
 6620        //    There is also an auxiliary background thread responsible for result gathering.
 6621        //    This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
 6622        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
 6623        //    As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
 6624        //    entry - which might already be available thanks to out-of-order processing.
 6625        //
 6626        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
 6627        // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
 6628        // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
 6629        // in face of constantly updating list of sorted matches.
 6630        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
 6631        let snapshots = self
 6632            .visible_worktrees(cx)
 6633            .filter_map(|tree| {
 6634                let tree = tree.read(cx).as_local()?;
 6635                Some(tree.snapshot())
 6636            })
 6637            .collect::<Vec<_>>();
 6638        let include_root = snapshots.len() > 1;
 6639
 6640        let background = cx.background_executor().clone();
 6641        let path_count: usize = snapshots
 6642            .iter()
 6643            .map(|s| {
 6644                if query.include_ignored() {
 6645                    s.file_count()
 6646                } else {
 6647                    s.visible_file_count()
 6648                }
 6649            })
 6650            .sum();
 6651        if path_count == 0 {
 6652            let (_, rx) = smol::channel::bounded(1024);
 6653            return rx;
 6654        }
 6655        let workers = background.num_cpus().min(path_count);
 6656        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
 6657        let mut unnamed_files = vec![];
 6658        let opened_buffers = self
 6659            .opened_buffers
 6660            .iter()
 6661            .filter_map(|(_, b)| {
 6662                let buffer = b.upgrade()?;
 6663                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
 6664                    let is_ignored = buffer
 6665                        .project_path(cx)
 6666                        .and_then(|path| self.entry_for_path(&path, cx))
 6667                        .map_or(false, |entry| entry.is_ignored);
 6668                    (is_ignored, buffer.snapshot())
 6669                });
 6670                if is_ignored && !query.include_ignored() {
 6671                    return None;
 6672                } else if let Some(file) = snapshot.file() {
 6673                    let matched_path = if include_root {
 6674                        query.file_matches(Some(&file.full_path(cx)))
 6675                    } else {
 6676                        query.file_matches(Some(file.path()))
 6677                    };
 6678
 6679                    if matched_path {
 6680                        Some((file.path().clone(), (buffer, snapshot)))
 6681                    } else {
 6682                        None
 6683                    }
 6684                } else {
 6685                    unnamed_files.push(buffer);
 6686                    None
 6687                }
 6688            })
 6689            .collect();
 6690        cx.background_executor()
 6691            .spawn(Self::background_search(
 6692                unnamed_files,
 6693                opened_buffers,
 6694                cx.background_executor().clone(),
 6695                self.fs.clone(),
 6696                workers,
 6697                query.clone(),
 6698                include_root,
 6699                path_count,
 6700                snapshots,
 6701                matching_paths_tx,
 6702            ))
 6703            .detach();
 6704
 6705        let (result_tx, result_rx) = smol::channel::bounded(1024);
 6706
 6707        cx.spawn(|this, mut cx| async move {
 6708            const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 6709            const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 6710
 6711            let mut matching_paths = matching_paths_rx
 6712                .take(MAX_SEARCH_RESULT_FILES + 1)
 6713                .collect::<Vec<_>>()
 6714                .await;
 6715            let mut limit_reached = if matching_paths.len() > MAX_SEARCH_RESULT_FILES {
 6716                matching_paths.pop();
 6717                true
 6718            } else {
 6719                false
 6720            };
 6721            matching_paths.sort_by_key(|candidate| (candidate.is_ignored(), candidate.path()));
 6722
 6723            let mut range_count = 0;
 6724            let query = Arc::new(query);
 6725
 6726            // Now that we know what paths match the query, we will load at most
 6727            // 64 buffers at a time to avoid overwhelming the main thread. For each
 6728            // opened buffer, we will spawn a background task that retrieves all the
 6729            // ranges in the buffer matched by the query.
 6730            'outer: for matching_paths_chunk in matching_paths.chunks(64) {
 6731                let mut chunk_results = Vec::new();
 6732                for matching_path in matching_paths_chunk {
 6733                    let query = query.clone();
 6734                    let buffer = match matching_path {
 6735                        SearchMatchCandidate::OpenBuffer { buffer, .. } => {
 6736                            Task::ready(Ok(buffer.clone()))
 6737                        }
 6738                        SearchMatchCandidate::Path {
 6739                            worktree_id, path, ..
 6740                        } => this.update(&mut cx, |this, cx| {
 6741                            this.open_buffer((*worktree_id, path.clone()), cx)
 6742                        })?,
 6743                    };
 6744
 6745                    chunk_results.push(cx.spawn(|cx| async move {
 6746                        let buffer = buffer.await?;
 6747                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
 6748                        let ranges = cx
 6749                            .background_executor()
 6750                            .spawn(async move {
 6751                                query
 6752                                    .search(&snapshot, None)
 6753                                    .await
 6754                                    .iter()
 6755                                    .map(|range| {
 6756                                        snapshot.anchor_before(range.start)
 6757                                            ..snapshot.anchor_after(range.end)
 6758                                    })
 6759                                    .collect::<Vec<_>>()
 6760                            })
 6761                            .await;
 6762                        anyhow::Ok((buffer, ranges))
 6763                    }));
 6764                }
 6765
 6766                let chunk_results = futures::future::join_all(chunk_results).await;
 6767                for result in chunk_results {
 6768                    if let Some((buffer, ranges)) = result.log_err() {
 6769                        range_count += ranges.len();
 6770                        result_tx
 6771                            .send(SearchResult::Buffer { buffer, ranges })
 6772                            .await?;
 6773                        if range_count > MAX_SEARCH_RESULT_RANGES {
 6774                            limit_reached = true;
 6775                            break 'outer;
 6776                        }
 6777                    }
 6778                }
 6779            }
 6780
 6781            if limit_reached {
 6782                result_tx.send(SearchResult::LimitReached).await?;
 6783            }
 6784
 6785            anyhow::Ok(())
 6786        })
 6787        .detach();
 6788
 6789        result_rx
 6790    }
 6791
 6792    /// Pick paths that might potentially contain a match of a given search query.
 6793    #[allow(clippy::too_many_arguments)]
 6794    async fn background_search(
 6795        unnamed_buffers: Vec<Model<Buffer>>,
 6796        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
 6797        executor: BackgroundExecutor,
 6798        fs: Arc<dyn Fs>,
 6799        workers: usize,
 6800        query: SearchQuery,
 6801        include_root: bool,
 6802        path_count: usize,
 6803        snapshots: Vec<LocalSnapshot>,
 6804        matching_paths_tx: Sender<SearchMatchCandidate>,
 6805    ) {
 6806        let fs = &fs;
 6807        let query = &query;
 6808        let matching_paths_tx = &matching_paths_tx;
 6809        let snapshots = &snapshots;
 6810        for buffer in unnamed_buffers {
 6811            matching_paths_tx
 6812                .send(SearchMatchCandidate::OpenBuffer {
 6813                    buffer: buffer.clone(),
 6814                    path: None,
 6815                })
 6816                .await
 6817                .log_err();
 6818        }
 6819        for (path, (buffer, _)) in opened_buffers.iter() {
 6820            matching_paths_tx
 6821                .send(SearchMatchCandidate::OpenBuffer {
 6822                    buffer: buffer.clone(),
 6823                    path: Some(path.clone()),
 6824                })
 6825                .await
 6826                .log_err();
 6827        }
 6828
 6829        let paths_per_worker = (path_count + workers - 1) / workers;
 6830
 6831        executor
 6832            .scoped(|scope| {
 6833                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
 6834
 6835                for worker_ix in 0..workers {
 6836                    let worker_start_ix = worker_ix * paths_per_worker;
 6837                    let worker_end_ix = worker_start_ix + paths_per_worker;
 6838                    let opened_buffers = opened_buffers.clone();
 6839                    let limiter = Arc::clone(&max_concurrent_workers);
 6840                    scope.spawn({
 6841                        async move {
 6842                            let _guard = limiter.acquire().await;
 6843                            search_snapshots(
 6844                                snapshots,
 6845                                worker_start_ix,
 6846                                worker_end_ix,
 6847                                query,
 6848                                matching_paths_tx,
 6849                                &opened_buffers,
 6850                                include_root,
 6851                                fs,
 6852                            )
 6853                            .await;
 6854                        }
 6855                    });
 6856                }
 6857
 6858                if query.include_ignored() {
 6859                    for snapshot in snapshots {
 6860                        for ignored_entry in snapshot.entries(true).filter(|e| e.is_ignored) {
 6861                            let limiter = Arc::clone(&max_concurrent_workers);
 6862                            scope.spawn(async move {
 6863                                let _guard = limiter.acquire().await;
 6864                                search_ignored_entry(
 6865                                    snapshot,
 6866                                    ignored_entry,
 6867                                    fs,
 6868                                    query,
 6869                                    matching_paths_tx,
 6870                                )
 6871                                .await;
 6872                            });
 6873                        }
 6874                    }
 6875                }
 6876            })
 6877            .await;
 6878    }
 6879
 6880    pub fn request_lsp<R: LspCommand>(
 6881        &self,
 6882        buffer_handle: Model<Buffer>,
 6883        server: LanguageServerToQuery,
 6884        request: R,
 6885        cx: &mut ModelContext<Self>,
 6886    ) -> Task<Result<R::Response>>
 6887    where
 6888        <R::LspRequest as lsp::request::Request>::Result: Send,
 6889        <R::LspRequest as lsp::request::Request>::Params: Send,
 6890    {
 6891        let buffer = buffer_handle.read(cx);
 6892        if self.is_local() {
 6893            let language_server = match server {
 6894                LanguageServerToQuery::Primary => {
 6895                    match self.primary_language_server_for_buffer(buffer, cx) {
 6896                        Some((_, server)) => Some(Arc::clone(server)),
 6897                        None => return Task::ready(Ok(Default::default())),
 6898                    }
 6899                }
 6900                LanguageServerToQuery::Other(id) => self
 6901                    .language_server_for_buffer(buffer, id, cx)
 6902                    .map(|(_, server)| Arc::clone(server)),
 6903            };
 6904            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 6905            if let (Some(file), Some(language_server)) = (file, language_server) {
 6906                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
 6907                let status = request.status();
 6908                return cx.spawn(move |this, cx| async move {
 6909                    if !request.check_capabilities(language_server.capabilities()) {
 6910                        return Ok(Default::default());
 6911                    }
 6912
 6913                    let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
 6914
 6915                    let id = lsp_request.id();
 6916                    let _cleanup = if status.is_some() {
 6917                        cx.update(|cx| {
 6918                            this.update(cx, |this, cx| {
 6919                                this.on_lsp_work_start(
 6920                                    language_server.server_id(),
 6921                                    id.to_string(),
 6922                                    LanguageServerProgress {
 6923                                        message: status.clone(),
 6924                                        percentage: None,
 6925                                        last_update_at: Instant::now(),
 6926                                    },
 6927                                    cx,
 6928                                );
 6929                            })
 6930                        })
 6931                        .log_err();
 6932
 6933                        Some(defer(|| {
 6934                            cx.update(|cx| {
 6935                                this.update(cx, |this, cx| {
 6936                                    this.on_lsp_work_end(
 6937                                        language_server.server_id(),
 6938                                        id.to_string(),
 6939                                        cx,
 6940                                    );
 6941                                })
 6942                            })
 6943                            .log_err();
 6944                        }))
 6945                    } else {
 6946                        None
 6947                    };
 6948
 6949                    let result = lsp_request.await;
 6950
 6951                    let response = result.map_err(|err| {
 6952                        log::warn!(
 6953                            "Generic lsp request to {} failed: {}",
 6954                            language_server.name(),
 6955                            err
 6956                        );
 6957                        err
 6958                    })?;
 6959
 6960                    request
 6961                        .response_from_lsp(
 6962                            response,
 6963                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 6964                            buffer_handle,
 6965                            language_server.server_id(),
 6966                            cx.clone(),
 6967                        )
 6968                        .await
 6969                });
 6970            }
 6971        } else if let Some(project_id) = self.remote_id() {
 6972            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
 6973        }
 6974
 6975        Task::ready(Ok(Default::default()))
 6976    }
 6977
 6978    fn request_multiple_lsp_locally<P, R>(
 6979        &self,
 6980        buffer: &Model<Buffer>,
 6981        position: Option<P>,
 6982        server_capabilities_check: fn(&ServerCapabilities) -> bool,
 6983        request: R,
 6984        cx: &mut ModelContext<'_, Self>,
 6985    ) -> Task<Vec<R::Response>>
 6986    where
 6987        P: ToOffset,
 6988        R: LspCommand + Clone,
 6989        <R::LspRequest as lsp::request::Request>::Result: Send,
 6990        <R::LspRequest as lsp::request::Request>::Params: Send,
 6991    {
 6992        if !self.is_local() {
 6993            debug_panic!("Should not request multiple lsp commands in non-local project");
 6994            return Task::ready(Vec::new());
 6995        }
 6996        let snapshot = buffer.read(cx).snapshot();
 6997        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 6998        let mut response_results = self
 6999            .language_servers_for_buffer(buffer.read(cx), cx)
 7000            .filter(|(_, server)| server_capabilities_check(server.capabilities()))
 7001            .filter(|(adapter, _)| {
 7002                scope
 7003                    .as_ref()
 7004                    .map(|scope| scope.language_allowed(&adapter.name))
 7005                    .unwrap_or(true)
 7006            })
 7007            .map(|(_, server)| server.server_id())
 7008            .map(|server_id| {
 7009                self.request_lsp(
 7010                    buffer.clone(),
 7011                    LanguageServerToQuery::Other(server_id),
 7012                    request.clone(),
 7013                    cx,
 7014                )
 7015            })
 7016            .collect::<FuturesUnordered<_>>();
 7017
 7018        return cx.spawn(|_, _| async move {
 7019            let mut responses = Vec::with_capacity(response_results.len());
 7020            while let Some(response_result) = response_results.next().await {
 7021                if let Some(response) = response_result.log_err() {
 7022                    responses.push(response);
 7023                }
 7024            }
 7025            responses
 7026        });
 7027    }
 7028
 7029    fn send_lsp_proto_request<R: LspCommand>(
 7030        &self,
 7031        buffer: Model<Buffer>,
 7032        project_id: u64,
 7033        request: R,
 7034        cx: &mut ModelContext<'_, Project>,
 7035    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
 7036        let rpc = self.client.clone();
 7037        let message = request.to_proto(project_id, buffer.read(cx));
 7038        cx.spawn(move |this, mut cx| async move {
 7039            // Ensure the project is still alive by the time the task
 7040            // is scheduled.
 7041            this.upgrade().context("project dropped")?;
 7042            let response = rpc.request(message).await?;
 7043            let this = this.upgrade().context("project dropped")?;
 7044            if this.update(&mut cx, |this, _| this.is_disconnected())? {
 7045                Err(anyhow!("disconnected before completing request"))
 7046            } else {
 7047                request
 7048                    .response_from_proto(response, this, buffer, cx)
 7049                    .await
 7050            }
 7051        })
 7052    }
 7053
 7054    pub fn find_or_create_local_worktree(
 7055        &mut self,
 7056        abs_path: impl AsRef<Path>,
 7057        visible: bool,
 7058        cx: &mut ModelContext<Self>,
 7059    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
 7060        let abs_path = abs_path.as_ref();
 7061        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
 7062            Task::ready(Ok((tree, relative_path)))
 7063        } else {
 7064            let worktree = self.create_local_worktree(abs_path, visible, cx);
 7065            cx.background_executor()
 7066                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
 7067        }
 7068    }
 7069
 7070    pub fn find_local_worktree(
 7071        &self,
 7072        abs_path: &Path,
 7073        cx: &AppContext,
 7074    ) -> Option<(Model<Worktree>, PathBuf)> {
 7075        for tree in &self.worktrees {
 7076            if let Some(tree) = tree.upgrade() {
 7077                if let Some(relative_path) = tree
 7078                    .read(cx)
 7079                    .as_local()
 7080                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 7081                {
 7082                    return Some((tree.clone(), relative_path.into()));
 7083                }
 7084            }
 7085        }
 7086        None
 7087    }
 7088
 7089    pub fn is_shared(&self) -> bool {
 7090        match &self.client_state {
 7091            ProjectClientState::Shared { .. } => true,
 7092            ProjectClientState::Local => false,
 7093            ProjectClientState::Remote { in_room, .. } => *in_room,
 7094        }
 7095    }
 7096
 7097    fn create_local_worktree(
 7098        &mut self,
 7099        abs_path: impl AsRef<Path>,
 7100        visible: bool,
 7101        cx: &mut ModelContext<Self>,
 7102    ) -> Task<Result<Model<Worktree>>> {
 7103        let fs = self.fs.clone();
 7104        let client = self.client.clone();
 7105        let next_entry_id = self.next_entry_id.clone();
 7106        let path: Arc<Path> = abs_path.as_ref().into();
 7107        let task = self
 7108            .loading_local_worktrees
 7109            .entry(path.clone())
 7110            .or_insert_with(|| {
 7111                cx.spawn(move |project, mut cx| {
 7112                    async move {
 7113                        let worktree = Worktree::local(
 7114                            client.clone(),
 7115                            path.clone(),
 7116                            visible,
 7117                            fs,
 7118                            next_entry_id,
 7119                            &mut cx,
 7120                        )
 7121                        .await;
 7122
 7123                        project.update(&mut cx, |project, _| {
 7124                            project.loading_local_worktrees.remove(&path);
 7125                        })?;
 7126
 7127                        let worktree = worktree?;
 7128                        project
 7129                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
 7130
 7131                        if visible {
 7132                            cx.update(|cx| {
 7133                                cx.add_recent_document(&path);
 7134                            })
 7135                            .log_err();
 7136                        }
 7137
 7138                        Ok(worktree)
 7139                    }
 7140                    .map_err(Arc::new)
 7141                })
 7142                .shared()
 7143            })
 7144            .clone();
 7145        cx.background_executor().spawn(async move {
 7146            match task.await {
 7147                Ok(worktree) => Ok(worktree),
 7148                Err(err) => Err(anyhow!("{}", err)),
 7149            }
 7150        })
 7151    }
 7152
 7153    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
 7154        let mut servers_to_remove = HashMap::default();
 7155        let mut servers_to_preserve = HashSet::default();
 7156        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
 7157            if worktree_id == &id_to_remove {
 7158                servers_to_remove.insert(server_id, server_name.clone());
 7159            } else {
 7160                servers_to_preserve.insert(server_id);
 7161            }
 7162        }
 7163        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
 7164        for (server_id_to_remove, server_name) in servers_to_remove {
 7165            self.language_server_ids
 7166                .remove(&(id_to_remove, server_name));
 7167            self.language_server_statuses.remove(&server_id_to_remove);
 7168            self.language_server_watched_paths
 7169                .remove(&server_id_to_remove);
 7170            self.last_workspace_edits_by_language_server
 7171                .remove(&server_id_to_remove);
 7172            self.language_servers.remove(&server_id_to_remove);
 7173            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
 7174        }
 7175
 7176        let mut prettier_instances_to_clean = FuturesUnordered::new();
 7177        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
 7178            for path in prettier_paths.iter().flatten() {
 7179                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
 7180                    prettier_instances_to_clean.push(async move {
 7181                        prettier_instance
 7182                            .server()
 7183                            .await
 7184                            .map(|server| server.server_id())
 7185                    });
 7186                }
 7187            }
 7188        }
 7189        cx.spawn(|project, mut cx| async move {
 7190            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
 7191                if let Some(prettier_server_id) = prettier_server_id {
 7192                    project
 7193                        .update(&mut cx, |project, cx| {
 7194                            project
 7195                                .supplementary_language_servers
 7196                                .remove(&prettier_server_id);
 7197                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
 7198                        })
 7199                        .ok();
 7200                }
 7201            }
 7202        })
 7203        .detach();
 7204
 7205        self.task_inventory().update(cx, |inventory, _| {
 7206            inventory.remove_worktree_sources(id_to_remove);
 7207        });
 7208
 7209        self.worktrees.retain(|worktree| {
 7210            if let Some(worktree) = worktree.upgrade() {
 7211                let id = worktree.read(cx).id();
 7212                if id == id_to_remove {
 7213                    cx.emit(Event::WorktreeRemoved(id));
 7214                    false
 7215                } else {
 7216                    true
 7217                }
 7218            } else {
 7219                false
 7220            }
 7221        });
 7222        self.metadata_changed(cx);
 7223    }
 7224
 7225    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
 7226        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
 7227        cx.subscribe(worktree, |this, worktree, event, cx| {
 7228            let is_local = worktree.read(cx).is_local();
 7229            match event {
 7230                worktree::Event::UpdatedEntries(changes) => {
 7231                    if is_local {
 7232                        this.update_local_worktree_buffers(&worktree, changes, cx);
 7233                        this.update_local_worktree_language_servers(&worktree, changes, cx);
 7234                        this.update_local_worktree_settings(&worktree, changes, cx);
 7235                        this.update_prettier_settings(&worktree, changes, cx);
 7236                    }
 7237
 7238                    cx.emit(Event::WorktreeUpdatedEntries(
 7239                        worktree.read(cx).id(),
 7240                        changes.clone(),
 7241                    ));
 7242                }
 7243                worktree::Event::UpdatedGitRepositories(updated_repos) => {
 7244                    if is_local {
 7245                        this.update_local_worktree_buffers_git_repos(
 7246                            worktree.clone(),
 7247                            updated_repos,
 7248                            cx,
 7249                        )
 7250                    }
 7251                    cx.emit(Event::WorktreeUpdatedGitRepositories);
 7252                }
 7253            }
 7254        })
 7255        .detach();
 7256
 7257        let push_strong_handle = {
 7258            let worktree = worktree.read(cx);
 7259            self.is_shared() || worktree.is_visible() || worktree.is_remote()
 7260        };
 7261        if push_strong_handle {
 7262            self.worktrees
 7263                .push(WorktreeHandle::Strong(worktree.clone()));
 7264        } else {
 7265            self.worktrees
 7266                .push(WorktreeHandle::Weak(worktree.downgrade()));
 7267        }
 7268
 7269        let handle_id = worktree.entity_id();
 7270        cx.observe_release(worktree, move |this, worktree, cx| {
 7271            let _ = this.remove_worktree(worktree.id(), cx);
 7272            cx.update_global::<SettingsStore, _>(|store, cx| {
 7273                store
 7274                    .clear_local_settings(handle_id.as_u64() as usize, cx)
 7275                    .log_err()
 7276            });
 7277        })
 7278        .detach();
 7279
 7280        cx.emit(Event::WorktreeAdded);
 7281        self.metadata_changed(cx);
 7282    }
 7283
 7284    fn update_local_worktree_buffers(
 7285        &mut self,
 7286        worktree_handle: &Model<Worktree>,
 7287        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7288        cx: &mut ModelContext<Self>,
 7289    ) {
 7290        let snapshot = worktree_handle.read(cx).snapshot();
 7291
 7292        let mut renamed_buffers = Vec::new();
 7293        for (path, entry_id, _) in changes {
 7294            let worktree_id = worktree_handle.read(cx).id();
 7295            let project_path = ProjectPath {
 7296                worktree_id,
 7297                path: path.clone(),
 7298            };
 7299
 7300            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
 7301                Some(&buffer_id) => buffer_id,
 7302                None => match self.local_buffer_ids_by_path.get(&project_path) {
 7303                    Some(&buffer_id) => buffer_id,
 7304                    None => {
 7305                        continue;
 7306                    }
 7307                },
 7308            };
 7309
 7310            let open_buffer = self.opened_buffers.get(&buffer_id);
 7311            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
 7312                buffer
 7313            } else {
 7314                self.opened_buffers.remove(&buffer_id);
 7315                self.local_buffer_ids_by_path.remove(&project_path);
 7316                self.local_buffer_ids_by_entry_id.remove(entry_id);
 7317                continue;
 7318            };
 7319
 7320            buffer.update(cx, |buffer, cx| {
 7321                if let Some(old_file) = File::from_dyn(buffer.file()) {
 7322                    if old_file.worktree != *worktree_handle {
 7323                        return;
 7324                    }
 7325
 7326                    let new_file = if let Some(entry) = old_file
 7327                        .entry_id
 7328                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 7329                    {
 7330                        File {
 7331                            is_local: true,
 7332                            entry_id: Some(entry.id),
 7333                            mtime: entry.mtime,
 7334                            path: entry.path.clone(),
 7335                            worktree: worktree_handle.clone(),
 7336                            is_deleted: false,
 7337                            is_private: entry.is_private,
 7338                        }
 7339                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
 7340                        File {
 7341                            is_local: true,
 7342                            entry_id: Some(entry.id),
 7343                            mtime: entry.mtime,
 7344                            path: entry.path.clone(),
 7345                            worktree: worktree_handle.clone(),
 7346                            is_deleted: false,
 7347                            is_private: entry.is_private,
 7348                        }
 7349                    } else {
 7350                        File {
 7351                            is_local: true,
 7352                            entry_id: old_file.entry_id,
 7353                            path: old_file.path().clone(),
 7354                            mtime: old_file.mtime(),
 7355                            worktree: worktree_handle.clone(),
 7356                            is_deleted: true,
 7357                            is_private: old_file.is_private,
 7358                        }
 7359                    };
 7360
 7361                    let old_path = old_file.abs_path(cx);
 7362                    if new_file.abs_path(cx) != old_path {
 7363                        renamed_buffers.push((cx.handle(), old_file.clone()));
 7364                        self.local_buffer_ids_by_path.remove(&project_path);
 7365                        self.local_buffer_ids_by_path.insert(
 7366                            ProjectPath {
 7367                                worktree_id,
 7368                                path: path.clone(),
 7369                            },
 7370                            buffer_id,
 7371                        );
 7372                    }
 7373
 7374                    if new_file.entry_id != Some(*entry_id) {
 7375                        self.local_buffer_ids_by_entry_id.remove(entry_id);
 7376                        if let Some(entry_id) = new_file.entry_id {
 7377                            self.local_buffer_ids_by_entry_id
 7378                                .insert(entry_id, buffer_id);
 7379                        }
 7380                    }
 7381
 7382                    if new_file != *old_file {
 7383                        if let Some(project_id) = self.remote_id() {
 7384                            self.client
 7385                                .send(proto::UpdateBufferFile {
 7386                                    project_id,
 7387                                    buffer_id: buffer_id.into(),
 7388                                    file: Some(new_file.to_proto()),
 7389                                })
 7390                                .log_err();
 7391                        }
 7392
 7393                        buffer.file_updated(Arc::new(new_file), cx);
 7394                    }
 7395                }
 7396            });
 7397        }
 7398
 7399        for (buffer, old_file) in renamed_buffers {
 7400            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
 7401            self.detect_language_for_buffer(&buffer, cx);
 7402            self.register_buffer_with_language_servers(&buffer, cx);
 7403        }
 7404    }
 7405
 7406    fn update_local_worktree_language_servers(
 7407        &mut self,
 7408        worktree_handle: &Model<Worktree>,
 7409        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7410        cx: &mut ModelContext<Self>,
 7411    ) {
 7412        if changes.is_empty() {
 7413            return;
 7414        }
 7415
 7416        let worktree_id = worktree_handle.read(cx).id();
 7417        let mut language_server_ids = self
 7418            .language_server_ids
 7419            .iter()
 7420            .filter_map(|((server_worktree_id, _), server_id)| {
 7421                (*server_worktree_id == worktree_id).then_some(*server_id)
 7422            })
 7423            .collect::<Vec<_>>();
 7424        language_server_ids.sort();
 7425        language_server_ids.dedup();
 7426
 7427        let abs_path = worktree_handle.read(cx).abs_path();
 7428        for server_id in &language_server_ids {
 7429            if let Some(LanguageServerState::Running { server, .. }) =
 7430                self.language_servers.get(server_id)
 7431            {
 7432                if let Some(watched_paths) = self
 7433                    .language_server_watched_paths
 7434                    .get(&server_id)
 7435                    .and_then(|paths| paths.get(&worktree_id))
 7436                {
 7437                    let params = lsp::DidChangeWatchedFilesParams {
 7438                        changes: changes
 7439                            .iter()
 7440                            .filter_map(|(path, _, change)| {
 7441                                if !watched_paths.is_match(&path) {
 7442                                    return None;
 7443                                }
 7444                                let typ = match change {
 7445                                    PathChange::Loaded => return None,
 7446                                    PathChange::Added => lsp::FileChangeType::CREATED,
 7447                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 7448                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 7449                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 7450                                };
 7451                                Some(lsp::FileEvent {
 7452                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
 7453                                    typ,
 7454                                })
 7455                            })
 7456                            .collect(),
 7457                    };
 7458                    if !params.changes.is_empty() {
 7459                        server
 7460                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
 7461                            .log_err();
 7462                    }
 7463                }
 7464            }
 7465        }
 7466    }
 7467
 7468    fn update_local_worktree_buffers_git_repos(
 7469        &mut self,
 7470        worktree_handle: Model<Worktree>,
 7471        changed_repos: &UpdatedGitRepositoriesSet,
 7472        cx: &mut ModelContext<Self>,
 7473    ) {
 7474        debug_assert!(worktree_handle.read(cx).is_local());
 7475
 7476        // Identify the loading buffers whose containing repository that has changed.
 7477        let future_buffers = self
 7478            .loading_buffers_by_path
 7479            .iter()
 7480            .filter_map(|(project_path, receiver)| {
 7481                if project_path.worktree_id != worktree_handle.read(cx).id() {
 7482                    return None;
 7483                }
 7484                let path = &project_path.path;
 7485                changed_repos
 7486                    .iter()
 7487                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7488                let receiver = receiver.clone();
 7489                let path = path.clone();
 7490                let abs_path = worktree_handle.read(cx).absolutize(&path).ok()?;
 7491                Some(async move {
 7492                    wait_for_loading_buffer(receiver)
 7493                        .await
 7494                        .ok()
 7495                        .map(|buffer| (buffer, path, abs_path))
 7496                })
 7497            })
 7498            .collect::<FuturesUnordered<_>>();
 7499
 7500        // Identify the current buffers whose containing repository has changed.
 7501        let current_buffers = self
 7502            .opened_buffers
 7503            .values()
 7504            .filter_map(|buffer| {
 7505                let buffer = buffer.upgrade()?;
 7506                let file = File::from_dyn(buffer.read(cx).file())?;
 7507                if file.worktree != worktree_handle {
 7508                    return None;
 7509                }
 7510                let path = file.path();
 7511                changed_repos
 7512                    .iter()
 7513                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7514                Some((buffer, path.clone(), file.abs_path(cx)))
 7515            })
 7516            .collect::<Vec<_>>();
 7517
 7518        if future_buffers.len() + current_buffers.len() == 0 {
 7519            return;
 7520        }
 7521
 7522        let remote_id = self.remote_id();
 7523        let client = self.client.clone();
 7524        let fs = self.fs.clone();
 7525        cx.spawn(move |_, mut cx| async move {
 7526            // Wait for all of the buffers to load.
 7527            let future_buffers = future_buffers.collect::<Vec<_>>().await;
 7528
 7529            // Reload the diff base for every buffer whose containing git repository has changed.
 7530            let snapshot =
 7531                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
 7532            let diff_bases_by_buffer = cx
 7533                .background_executor()
 7534                .spawn(async move {
 7535                    let mut diff_base_tasks = future_buffers
 7536                        .into_iter()
 7537                        .flatten()
 7538                        .chain(current_buffers)
 7539                        .filter_map(|(buffer, path, abs_path)| {
 7540                            let (work_directory, repo) =
 7541                                snapshot.repository_and_work_directory_for_path(&path)?;
 7542                            let repo_entry = snapshot.get_local_repo(&repo)?;
 7543                            Some((buffer, path, abs_path, work_directory, repo_entry))
 7544                        })
 7545                        .map(|(buffer, path, abs_path, work_directory, repo_entry)| {
 7546                            let fs = fs.clone();
 7547                            async move {
 7548                                let abs_path_metadata = fs
 7549                                    .metadata(&abs_path)
 7550                                    .await
 7551                                    .with_context(|| {
 7552                                        format!("loading file and FS metadata for {path:?}")
 7553                                    })
 7554                                    .log_err()
 7555                                    .flatten()?;
 7556                                let base_text = if abs_path_metadata.is_dir
 7557                                    || abs_path_metadata.is_symlink
 7558                                {
 7559                                    None
 7560                                } else {
 7561                                    let relative_path = path.strip_prefix(&work_directory).ok()?;
 7562                                    repo_entry.repo().lock().load_index_text(relative_path)
 7563                                };
 7564                                Some((buffer, base_text))
 7565                            }
 7566                        })
 7567                        .collect::<FuturesUnordered<_>>();
 7568
 7569                    let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
 7570                    while let Some(diff_base) = diff_base_tasks.next().await {
 7571                        if let Some(diff_base) = diff_base {
 7572                            diff_bases.push(diff_base);
 7573                        }
 7574                    }
 7575                    diff_bases
 7576                })
 7577                .await;
 7578
 7579            // Assign the new diff bases on all of the buffers.
 7580            for (buffer, diff_base) in diff_bases_by_buffer {
 7581                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
 7582                    buffer.set_diff_base(diff_base.clone(), cx);
 7583                    buffer.remote_id().into()
 7584                })?;
 7585                if let Some(project_id) = remote_id {
 7586                    client
 7587                        .send(proto::UpdateDiffBase {
 7588                            project_id,
 7589                            buffer_id,
 7590                            diff_base,
 7591                        })
 7592                        .log_err();
 7593                }
 7594            }
 7595
 7596            anyhow::Ok(())
 7597        })
 7598        .detach();
 7599    }
 7600
 7601    fn update_local_worktree_settings(
 7602        &mut self,
 7603        worktree: &Model<Worktree>,
 7604        changes: &UpdatedEntriesSet,
 7605        cx: &mut ModelContext<Self>,
 7606    ) {
 7607        if worktree.read(cx).as_local().is_none() {
 7608            return;
 7609        }
 7610        let project_id = self.remote_id();
 7611        let worktree_id = worktree.entity_id();
 7612        let remote_worktree_id = worktree.read(cx).id();
 7613
 7614        let mut settings_contents = Vec::new();
 7615        for (path, _, change) in changes.iter() {
 7616            let removed = change == &PathChange::Removed;
 7617            let abs_path = match worktree.read(cx).absolutize(path) {
 7618                Ok(abs_path) => abs_path,
 7619                Err(e) => {
 7620                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 7621                    continue;
 7622                }
 7623            };
 7624
 7625            if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
 7626                let settings_dir = Arc::from(
 7627                    path.ancestors()
 7628                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
 7629                        .unwrap(),
 7630                );
 7631                let fs = self.fs.clone();
 7632                settings_contents.push(async move {
 7633                    (
 7634                        settings_dir,
 7635                        if removed {
 7636                            None
 7637                        } else {
 7638                            Some(async move { fs.load(&abs_path).await }.await)
 7639                        },
 7640                    )
 7641                });
 7642            } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
 7643                self.task_inventory().update(cx, |task_inventory, cx| {
 7644                    if removed {
 7645                        task_inventory.remove_local_static_source(&abs_path);
 7646                    } else {
 7647                        let fs = self.fs.clone();
 7648                        let task_abs_path = abs_path.clone();
 7649                        let tasks_file_rx =
 7650                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7651                        task_inventory.add_source(
 7652                            TaskSourceKind::Worktree {
 7653                                id: remote_worktree_id,
 7654                                abs_path,
 7655                                id_base: "local_tasks_for_worktree",
 7656                            },
 7657                            StaticSource::new(TrackedFile::new(tasks_file_rx, cx)),
 7658                            cx,
 7659                        );
 7660                    }
 7661                })
 7662            } else if abs_path.ends_with(&*LOCAL_VSCODE_TASKS_RELATIVE_PATH) {
 7663                self.task_inventory().update(cx, |task_inventory, cx| {
 7664                    if removed {
 7665                        task_inventory.remove_local_static_source(&abs_path);
 7666                    } else {
 7667                        let fs = self.fs.clone();
 7668                        let task_abs_path = abs_path.clone();
 7669                        let tasks_file_rx =
 7670                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7671                        task_inventory.add_source(
 7672                            TaskSourceKind::Worktree {
 7673                                id: remote_worktree_id,
 7674                                abs_path,
 7675                                id_base: "local_vscode_tasks_for_worktree",
 7676                            },
 7677                            StaticSource::new(
 7678                                TrackedFile::new_convertible::<task::VsCodeTaskFile>(
 7679                                    tasks_file_rx,
 7680                                    cx,
 7681                                ),
 7682                            ),
 7683                            cx,
 7684                        );
 7685                    }
 7686                })
 7687            }
 7688        }
 7689
 7690        if settings_contents.is_empty() {
 7691            return;
 7692        }
 7693
 7694        let client = self.client.clone();
 7695        cx.spawn(move |_, cx| async move {
 7696            let settings_contents: Vec<(Arc<Path>, _)> =
 7697                futures::future::join_all(settings_contents).await;
 7698            cx.update(|cx| {
 7699                cx.update_global::<SettingsStore, _>(|store, cx| {
 7700                    for (directory, file_content) in settings_contents {
 7701                        let file_content = file_content.and_then(|content| content.log_err());
 7702                        store
 7703                            .set_local_settings(
 7704                                worktree_id.as_u64() as usize,
 7705                                directory.clone(),
 7706                                file_content.as_deref(),
 7707                                cx,
 7708                            )
 7709                            .log_err();
 7710                        if let Some(remote_id) = project_id {
 7711                            client
 7712                                .send(proto::UpdateWorktreeSettings {
 7713                                    project_id: remote_id,
 7714                                    worktree_id: remote_worktree_id.to_proto(),
 7715                                    path: directory.to_string_lossy().into_owned(),
 7716                                    content: file_content,
 7717                                })
 7718                                .log_err();
 7719                        }
 7720                    }
 7721                });
 7722            })
 7723            .ok();
 7724        })
 7725        .detach();
 7726    }
 7727
 7728    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 7729        let new_active_entry = entry.and_then(|project_path| {
 7730            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 7731            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 7732            Some(entry.id)
 7733        });
 7734        if new_active_entry != self.active_entry {
 7735            self.active_entry = new_active_entry;
 7736            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 7737        }
 7738    }
 7739
 7740    pub fn language_servers_running_disk_based_diagnostics(
 7741        &self,
 7742    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 7743        self.language_server_statuses
 7744            .iter()
 7745            .filter_map(|(id, status)| {
 7746                if status.has_pending_diagnostic_updates {
 7747                    Some(*id)
 7748                } else {
 7749                    None
 7750                }
 7751            })
 7752    }
 7753
 7754    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 7755        let mut summary = DiagnosticSummary::default();
 7756        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 7757            summary.error_count += path_summary.error_count;
 7758            summary.warning_count += path_summary.warning_count;
 7759        }
 7760        summary
 7761    }
 7762
 7763    pub fn diagnostic_summaries<'a>(
 7764        &'a self,
 7765        include_ignored: bool,
 7766        cx: &'a AppContext,
 7767    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 7768        self.visible_worktrees(cx).flat_map(move |worktree| {
 7769            let worktree = worktree.read(cx);
 7770            let worktree_id = worktree.id();
 7771            worktree
 7772                .diagnostic_summaries()
 7773                .filter_map(move |(path, server_id, summary)| {
 7774                    if include_ignored
 7775                        || worktree
 7776                            .entry_for_path(path.as_ref())
 7777                            .map_or(false, |entry| !entry.is_ignored)
 7778                    {
 7779                        Some((ProjectPath { worktree_id, path }, server_id, summary))
 7780                    } else {
 7781                        None
 7782                    }
 7783                })
 7784        })
 7785    }
 7786
 7787    pub fn disk_based_diagnostics_started(
 7788        &mut self,
 7789        language_server_id: LanguageServerId,
 7790        cx: &mut ModelContext<Self>,
 7791    ) {
 7792        if let Some(language_server_status) =
 7793            self.language_server_statuses.get_mut(&language_server_id)
 7794        {
 7795            language_server_status.has_pending_diagnostic_updates = true;
 7796        }
 7797
 7798        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 7799        if self.is_local() {
 7800            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 7801                language_server_id,
 7802                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 7803                    Default::default(),
 7804                ),
 7805            })
 7806            .ok();
 7807        }
 7808    }
 7809
 7810    pub fn disk_based_diagnostics_finished(
 7811        &mut self,
 7812        language_server_id: LanguageServerId,
 7813        cx: &mut ModelContext<Self>,
 7814    ) {
 7815        if let Some(language_server_status) =
 7816            self.language_server_statuses.get_mut(&language_server_id)
 7817        {
 7818            language_server_status.has_pending_diagnostic_updates = false;
 7819        }
 7820
 7821        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 7822
 7823        if self.is_local() {
 7824            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 7825                language_server_id,
 7826                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 7827                    Default::default(),
 7828                ),
 7829            })
 7830            .ok();
 7831        }
 7832    }
 7833
 7834    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 7835        self.active_entry
 7836    }
 7837
 7838    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 7839        self.worktree_for_id(path.worktree_id, cx)?
 7840            .read(cx)
 7841            .entry_for_path(&path.path)
 7842            .cloned()
 7843    }
 7844
 7845    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 7846        let worktree = self.worktree_for_entry(entry_id, cx)?;
 7847        let worktree = worktree.read(cx);
 7848        let worktree_id = worktree.id();
 7849        let path = worktree.entry_for_id(entry_id)?.path.clone();
 7850        Some(ProjectPath { worktree_id, path })
 7851    }
 7852
 7853    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 7854        let workspace_root = self
 7855            .worktree_for_id(project_path.worktree_id, cx)?
 7856            .read(cx)
 7857            .abs_path();
 7858        let project_path = project_path.path.as_ref();
 7859
 7860        Some(if project_path == Path::new("") {
 7861            workspace_root.to_path_buf()
 7862        } else {
 7863            workspace_root.join(project_path)
 7864        })
 7865    }
 7866
 7867    pub fn project_path_for_absolute_path(
 7868        &self,
 7869        abs_path: &Path,
 7870        cx: &AppContext,
 7871    ) -> Option<ProjectPath> {
 7872        self.find_local_worktree(abs_path, cx)
 7873            .map(|(worktree, relative_path)| ProjectPath {
 7874                worktree_id: worktree.read(cx).id(),
 7875                path: relative_path.into(),
 7876            })
 7877    }
 7878
 7879    pub fn get_workspace_root(
 7880        &self,
 7881        project_path: &ProjectPath,
 7882        cx: &AppContext,
 7883    ) -> Option<PathBuf> {
 7884        Some(
 7885            self.worktree_for_id(project_path.worktree_id, cx)?
 7886                .read(cx)
 7887                .abs_path()
 7888                .to_path_buf(),
 7889        )
 7890    }
 7891
 7892    pub fn get_repo(
 7893        &self,
 7894        project_path: &ProjectPath,
 7895        cx: &AppContext,
 7896    ) -> Option<Arc<Mutex<dyn GitRepository>>> {
 7897        self.worktree_for_id(project_path.worktree_id, cx)?
 7898            .read(cx)
 7899            .as_local()?
 7900            .snapshot()
 7901            .local_git_repo(&project_path.path)
 7902    }
 7903
 7904    pub fn blame_buffer(
 7905        &self,
 7906        buffer: &Model<Buffer>,
 7907        version: Option<clock::Global>,
 7908        cx: &AppContext,
 7909    ) -> Task<Result<Blame>> {
 7910        if self.is_local() {
 7911            let blame_params = maybe!({
 7912                let buffer = buffer.read(cx);
 7913                let buffer_project_path = buffer
 7914                    .project_path(cx)
 7915                    .context("failed to get buffer project path")?;
 7916
 7917                let worktree = self
 7918                    .worktree_for_id(buffer_project_path.worktree_id, cx)
 7919                    .context("failed to get worktree")?
 7920                    .read(cx)
 7921                    .as_local()
 7922                    .context("worktree was not local")?
 7923                    .snapshot();
 7924
 7925                let (work_directory, repo) = match worktree
 7926                    .repository_and_work_directory_for_path(&buffer_project_path.path)
 7927                {
 7928                    Some(work_dir_repo) => work_dir_repo,
 7929                    None => anyhow::bail!(NoRepositoryError {}),
 7930                };
 7931
 7932                let repo_entry = match worktree.get_local_repo(&repo) {
 7933                    Some(repo_entry) => repo_entry,
 7934                    None => anyhow::bail!(NoRepositoryError {}),
 7935                };
 7936
 7937                let repo = repo_entry.repo().clone();
 7938
 7939                let relative_path = buffer_project_path
 7940                    .path
 7941                    .strip_prefix(&work_directory)?
 7942                    .to_path_buf();
 7943
 7944                let content = match version {
 7945                    Some(version) => buffer.rope_for_version(&version).clone(),
 7946                    None => buffer.as_rope().clone(),
 7947                };
 7948
 7949                anyhow::Ok((repo, relative_path, content))
 7950            });
 7951
 7952            cx.background_executor().spawn(async move {
 7953                let (repo, relative_path, content) = blame_params?;
 7954                let lock = repo.lock();
 7955                lock.blame(&relative_path, content)
 7956                    .with_context(|| format!("Failed to blame {relative_path:?}"))
 7957            })
 7958        } else {
 7959            let project_id = self.remote_id();
 7960            let buffer_id = buffer.read(cx).remote_id();
 7961            let client = self.client.clone();
 7962            let version = buffer.read(cx).version();
 7963
 7964            cx.spawn(|_| async move {
 7965                let project_id = project_id.context("unable to get project id for buffer")?;
 7966                let response = client
 7967                    .request(proto::BlameBuffer {
 7968                        project_id,
 7969                        buffer_id: buffer_id.into(),
 7970                        version: serialize_version(&version),
 7971                    })
 7972                    .await?;
 7973
 7974                Ok(deserialize_blame_buffer_response(response))
 7975            })
 7976        }
 7977    }
 7978
 7979    // RPC message handlers
 7980
 7981    async fn handle_blame_buffer(
 7982        this: Model<Self>,
 7983        envelope: TypedEnvelope<proto::BlameBuffer>,
 7984        _: Arc<Client>,
 7985        mut cx: AsyncAppContext,
 7986    ) -> Result<proto::BlameBufferResponse> {
 7987        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7988        let version = deserialize_version(&envelope.payload.version);
 7989
 7990        let buffer = this.update(&mut cx, |this, _cx| {
 7991            this.opened_buffers
 7992                .get(&buffer_id)
 7993                .and_then(|buffer| buffer.upgrade())
 7994                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 7995        })??;
 7996
 7997        buffer
 7998            .update(&mut cx, |buffer, _| {
 7999                buffer.wait_for_version(version.clone())
 8000            })?
 8001            .await?;
 8002
 8003        let blame = this
 8004            .update(&mut cx, |this, cx| {
 8005                this.blame_buffer(&buffer, Some(version), cx)
 8006            })?
 8007            .await?;
 8008
 8009        Ok(serialize_blame_buffer_response(blame))
 8010    }
 8011
 8012    async fn handle_multi_lsp_query(
 8013        project: Model<Self>,
 8014        envelope: TypedEnvelope<proto::MultiLspQuery>,
 8015        _: Arc<Client>,
 8016        mut cx: AsyncAppContext,
 8017    ) -> Result<proto::MultiLspQueryResponse> {
 8018        let sender_id = envelope.original_sender_id()?;
 8019        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8020        let version = deserialize_version(&envelope.payload.version);
 8021        let buffer = project.update(&mut cx, |project, _cx| {
 8022            project
 8023                .opened_buffers
 8024                .get(&buffer_id)
 8025                .and_then(|buffer| buffer.upgrade())
 8026                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8027        })??;
 8028        buffer
 8029            .update(&mut cx, |buffer, _| {
 8030                buffer.wait_for_version(version.clone())
 8031            })?
 8032            .await?;
 8033        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 8034        match envelope
 8035            .payload
 8036            .strategy
 8037            .context("invalid request without the strategy")?
 8038        {
 8039            proto::multi_lsp_query::Strategy::All(_) => {
 8040                // currently, there's only one multiple language servers query strategy,
 8041                // so just ensure it's specified correctly
 8042            }
 8043        }
 8044        match envelope.payload.request {
 8045            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 8046                let get_hover =
 8047                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 8048                        .await?;
 8049                let all_hovers = project
 8050                    .update(&mut cx, |project, cx| {
 8051                        project.request_multiple_lsp_locally(
 8052                            &buffer,
 8053                            Some(get_hover.position),
 8054                            |server_capabilities| match server_capabilities.hover_provider {
 8055                                Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 8056                                Some(lsp::HoverProviderCapability::Options(_)) => true,
 8057                                None => false,
 8058                            },
 8059                            get_hover,
 8060                            cx,
 8061                        )
 8062                    })?
 8063                    .await
 8064                    .into_iter()
 8065                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 8066                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8067                    responses: all_hovers
 8068                        .map(|hover| proto::LspResponse {
 8069                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 8070                                GetHover::response_to_proto(
 8071                                    Some(hover),
 8072                                    project,
 8073                                    sender_id,
 8074                                    &buffer_version,
 8075                                    cx,
 8076                                ),
 8077                            )),
 8078                        })
 8079                        .collect(),
 8080                })
 8081            }
 8082            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 8083                let get_code_actions = GetCodeActions::from_proto(
 8084                    get_code_actions,
 8085                    project.clone(),
 8086                    buffer.clone(),
 8087                    cx.clone(),
 8088                )
 8089                .await?;
 8090
 8091                let all_actions = project
 8092                    .update(&mut cx, |project, cx| {
 8093                        project.request_multiple_lsp_locally(
 8094                            &buffer,
 8095                            Some(get_code_actions.range.start),
 8096                            GetCodeActions::supports_code_actions,
 8097                            get_code_actions,
 8098                            cx,
 8099                        )
 8100                    })?
 8101                    .await
 8102                    .into_iter();
 8103
 8104                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8105                    responses: all_actions
 8106                        .map(|code_actions| proto::LspResponse {
 8107                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8108                                GetCodeActions::response_to_proto(
 8109                                    code_actions,
 8110                                    project,
 8111                                    sender_id,
 8112                                    &buffer_version,
 8113                                    cx,
 8114                                ),
 8115                            )),
 8116                        })
 8117                        .collect(),
 8118                })
 8119            }
 8120            None => anyhow::bail!("empty multi lsp query request"),
 8121        }
 8122    }
 8123
 8124    async fn handle_unshare_project(
 8125        this: Model<Self>,
 8126        _: TypedEnvelope<proto::UnshareProject>,
 8127        _: Arc<Client>,
 8128        mut cx: AsyncAppContext,
 8129    ) -> Result<()> {
 8130        this.update(&mut cx, |this, cx| {
 8131            if this.is_local() {
 8132                this.unshare(cx)?;
 8133            } else {
 8134                this.disconnected_from_host(cx);
 8135            }
 8136            Ok(())
 8137        })?
 8138    }
 8139
 8140    async fn handle_add_collaborator(
 8141        this: Model<Self>,
 8142        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 8143        _: Arc<Client>,
 8144        mut cx: AsyncAppContext,
 8145    ) -> Result<()> {
 8146        let collaborator = envelope
 8147            .payload
 8148            .collaborator
 8149            .take()
 8150            .ok_or_else(|| anyhow!("empty collaborator"))?;
 8151
 8152        let collaborator = Collaborator::from_proto(collaborator)?;
 8153        this.update(&mut cx, |this, cx| {
 8154            this.shared_buffers.remove(&collaborator.peer_id);
 8155            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 8156            this.collaborators
 8157                .insert(collaborator.peer_id, collaborator);
 8158            cx.notify();
 8159        })?;
 8160
 8161        Ok(())
 8162    }
 8163
 8164    async fn handle_update_project_collaborator(
 8165        this: Model<Self>,
 8166        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 8167        _: Arc<Client>,
 8168        mut cx: AsyncAppContext,
 8169    ) -> Result<()> {
 8170        let old_peer_id = envelope
 8171            .payload
 8172            .old_peer_id
 8173            .ok_or_else(|| anyhow!("missing old peer id"))?;
 8174        let new_peer_id = envelope
 8175            .payload
 8176            .new_peer_id
 8177            .ok_or_else(|| anyhow!("missing new peer id"))?;
 8178        this.update(&mut cx, |this, cx| {
 8179            let collaborator = this
 8180                .collaborators
 8181                .remove(&old_peer_id)
 8182                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 8183            let is_host = collaborator.replica_id == 0;
 8184            this.collaborators.insert(new_peer_id, collaborator);
 8185
 8186            let buffers = this.shared_buffers.remove(&old_peer_id);
 8187            log::info!(
 8188                "peer {} became {}. moving buffers {:?}",
 8189                old_peer_id,
 8190                new_peer_id,
 8191                &buffers
 8192            );
 8193            if let Some(buffers) = buffers {
 8194                this.shared_buffers.insert(new_peer_id, buffers);
 8195            }
 8196
 8197            if is_host {
 8198                this.opened_buffers
 8199                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
 8200                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 8201                    .unwrap();
 8202            }
 8203
 8204            cx.emit(Event::CollaboratorUpdated {
 8205                old_peer_id,
 8206                new_peer_id,
 8207            });
 8208            cx.notify();
 8209            Ok(())
 8210        })?
 8211    }
 8212
 8213    async fn handle_remove_collaborator(
 8214        this: Model<Self>,
 8215        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 8216        _: Arc<Client>,
 8217        mut cx: AsyncAppContext,
 8218    ) -> Result<()> {
 8219        this.update(&mut cx, |this, cx| {
 8220            let peer_id = envelope
 8221                .payload
 8222                .peer_id
 8223                .ok_or_else(|| anyhow!("invalid peer id"))?;
 8224            let replica_id = this
 8225                .collaborators
 8226                .remove(&peer_id)
 8227                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 8228                .replica_id;
 8229            for buffer in this.opened_buffers.values() {
 8230                if let Some(buffer) = buffer.upgrade() {
 8231                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 8232                }
 8233            }
 8234            this.shared_buffers.remove(&peer_id);
 8235
 8236            cx.emit(Event::CollaboratorLeft(peer_id));
 8237            cx.notify();
 8238            Ok(())
 8239        })?
 8240    }
 8241
 8242    async fn handle_update_project(
 8243        this: Model<Self>,
 8244        envelope: TypedEnvelope<proto::UpdateProject>,
 8245        _: Arc<Client>,
 8246        mut cx: AsyncAppContext,
 8247    ) -> Result<()> {
 8248        this.update(&mut cx, |this, cx| {
 8249            // Don't handle messages that were sent before the response to us joining the project
 8250            if envelope.message_id > this.join_project_response_message_id {
 8251                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 8252            }
 8253            Ok(())
 8254        })?
 8255    }
 8256
 8257    async fn handle_update_worktree(
 8258        this: Model<Self>,
 8259        envelope: TypedEnvelope<proto::UpdateWorktree>,
 8260        _: Arc<Client>,
 8261        mut cx: AsyncAppContext,
 8262    ) -> Result<()> {
 8263        this.update(&mut cx, |this, cx| {
 8264            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8265            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8266                worktree.update(cx, |worktree, _| {
 8267                    let worktree = worktree.as_remote_mut().unwrap();
 8268                    worktree.update_from_remote(envelope.payload);
 8269                });
 8270            }
 8271            Ok(())
 8272        })?
 8273    }
 8274
 8275    async fn handle_update_worktree_settings(
 8276        this: Model<Self>,
 8277        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 8278        _: Arc<Client>,
 8279        mut cx: AsyncAppContext,
 8280    ) -> Result<()> {
 8281        this.update(&mut cx, |this, cx| {
 8282            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8283            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8284                cx.update_global::<SettingsStore, _>(|store, cx| {
 8285                    store
 8286                        .set_local_settings(
 8287                            worktree.entity_id().as_u64() as usize,
 8288                            PathBuf::from(&envelope.payload.path).into(),
 8289                            envelope.payload.content.as_deref(),
 8290                            cx,
 8291                        )
 8292                        .log_err();
 8293                });
 8294            }
 8295            Ok(())
 8296        })?
 8297    }
 8298
 8299    async fn handle_create_project_entry(
 8300        this: Model<Self>,
 8301        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 8302        _: Arc<Client>,
 8303        mut cx: AsyncAppContext,
 8304    ) -> Result<proto::ProjectEntryResponse> {
 8305        let worktree = this.update(&mut cx, |this, cx| {
 8306            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8307            this.worktree_for_id(worktree_id, cx)
 8308                .ok_or_else(|| anyhow!("worktree not found"))
 8309        })??;
 8310        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8311        let entry = worktree
 8312            .update(&mut cx, |worktree, cx| {
 8313                let worktree = worktree.as_local_mut().unwrap();
 8314                let path = PathBuf::from(envelope.payload.path);
 8315                worktree.create_entry(path, envelope.payload.is_directory, cx)
 8316            })?
 8317            .await?;
 8318        Ok(proto::ProjectEntryResponse {
 8319            entry: entry.as_ref().map(|e| e.into()),
 8320            worktree_scan_id: worktree_scan_id as u64,
 8321        })
 8322    }
 8323
 8324    async fn handle_rename_project_entry(
 8325        this: Model<Self>,
 8326        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8327        _: Arc<Client>,
 8328        mut cx: AsyncAppContext,
 8329    ) -> Result<proto::ProjectEntryResponse> {
 8330        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8331        let worktree = this.update(&mut cx, |this, cx| {
 8332            this.worktree_for_entry(entry_id, cx)
 8333                .ok_or_else(|| anyhow!("worktree not found"))
 8334        })??;
 8335        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8336        let entry = worktree
 8337            .update(&mut cx, |worktree, cx| {
 8338                let new_path = PathBuf::from(envelope.payload.new_path);
 8339                worktree
 8340                    .as_local_mut()
 8341                    .unwrap()
 8342                    .rename_entry(entry_id, new_path, cx)
 8343            })?
 8344            .await?;
 8345        Ok(proto::ProjectEntryResponse {
 8346            entry: entry.as_ref().map(|e| e.into()),
 8347            worktree_scan_id: worktree_scan_id as u64,
 8348        })
 8349    }
 8350
 8351    async fn handle_copy_project_entry(
 8352        this: Model<Self>,
 8353        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 8354        _: Arc<Client>,
 8355        mut cx: AsyncAppContext,
 8356    ) -> Result<proto::ProjectEntryResponse> {
 8357        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8358        let worktree = this.update(&mut cx, |this, cx| {
 8359            this.worktree_for_entry(entry_id, cx)
 8360                .ok_or_else(|| anyhow!("worktree not found"))
 8361        })??;
 8362        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8363        let entry = worktree
 8364            .update(&mut cx, |worktree, cx| {
 8365                let new_path = PathBuf::from(envelope.payload.new_path);
 8366                worktree
 8367                    .as_local_mut()
 8368                    .unwrap()
 8369                    .copy_entry(entry_id, new_path, cx)
 8370            })?
 8371            .await?;
 8372        Ok(proto::ProjectEntryResponse {
 8373            entry: entry.as_ref().map(|e| e.into()),
 8374            worktree_scan_id: worktree_scan_id as u64,
 8375        })
 8376    }
 8377
 8378    async fn handle_delete_project_entry(
 8379        this: Model<Self>,
 8380        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 8381        _: Arc<Client>,
 8382        mut cx: AsyncAppContext,
 8383    ) -> Result<proto::ProjectEntryResponse> {
 8384        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8385        let trash = envelope.payload.use_trash;
 8386
 8387        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
 8388
 8389        let worktree = this.update(&mut cx, |this, cx| {
 8390            this.worktree_for_entry(entry_id, cx)
 8391                .ok_or_else(|| anyhow!("worktree not found"))
 8392        })??;
 8393        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8394        worktree
 8395            .update(&mut cx, |worktree, cx| {
 8396                worktree
 8397                    .as_local_mut()
 8398                    .unwrap()
 8399                    .delete_entry(entry_id, trash, cx)
 8400                    .ok_or_else(|| anyhow!("invalid entry"))
 8401            })??
 8402            .await?;
 8403        Ok(proto::ProjectEntryResponse {
 8404            entry: None,
 8405            worktree_scan_id: worktree_scan_id as u64,
 8406        })
 8407    }
 8408
 8409    async fn handle_expand_project_entry(
 8410        this: Model<Self>,
 8411        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
 8412        _: Arc<Client>,
 8413        mut cx: AsyncAppContext,
 8414    ) -> Result<proto::ExpandProjectEntryResponse> {
 8415        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8416        let worktree = this
 8417            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
 8418            .ok_or_else(|| anyhow!("invalid request"))?;
 8419        worktree
 8420            .update(&mut cx, |worktree, cx| {
 8421                worktree
 8422                    .as_local_mut()
 8423                    .unwrap()
 8424                    .expand_entry(entry_id, cx)
 8425                    .ok_or_else(|| anyhow!("invalid entry"))
 8426            })??
 8427            .await?;
 8428        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
 8429        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
 8430    }
 8431
 8432    async fn handle_update_diagnostic_summary(
 8433        this: Model<Self>,
 8434        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8435        _: Arc<Client>,
 8436        mut cx: AsyncAppContext,
 8437    ) -> Result<()> {
 8438        this.update(&mut cx, |this, cx| {
 8439            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8440            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8441                if let Some(summary) = envelope.payload.summary {
 8442                    let project_path = ProjectPath {
 8443                        worktree_id,
 8444                        path: Path::new(&summary.path).into(),
 8445                    };
 8446                    worktree.update(cx, |worktree, _| {
 8447                        worktree
 8448                            .as_remote_mut()
 8449                            .unwrap()
 8450                            .update_diagnostic_summary(project_path.path.clone(), &summary);
 8451                    });
 8452                    cx.emit(Event::DiagnosticsUpdated {
 8453                        language_server_id: LanguageServerId(summary.language_server_id as usize),
 8454                        path: project_path,
 8455                    });
 8456                }
 8457            }
 8458            Ok(())
 8459        })?
 8460    }
 8461
 8462    async fn handle_start_language_server(
 8463        this: Model<Self>,
 8464        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8465        _: Arc<Client>,
 8466        mut cx: AsyncAppContext,
 8467    ) -> Result<()> {
 8468        let server = envelope
 8469            .payload
 8470            .server
 8471            .ok_or_else(|| anyhow!("invalid server"))?;
 8472        this.update(&mut cx, |this, cx| {
 8473            this.language_server_statuses.insert(
 8474                LanguageServerId(server.id as usize),
 8475                LanguageServerStatus {
 8476                    name: server.name,
 8477                    pending_work: Default::default(),
 8478                    has_pending_diagnostic_updates: false,
 8479                    progress_tokens: Default::default(),
 8480                },
 8481            );
 8482            cx.notify();
 8483        })?;
 8484        Ok(())
 8485    }
 8486
 8487    async fn handle_update_language_server(
 8488        this: Model<Self>,
 8489        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8490        _: Arc<Client>,
 8491        mut cx: AsyncAppContext,
 8492    ) -> Result<()> {
 8493        this.update(&mut cx, |this, cx| {
 8494            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8495
 8496            match envelope
 8497                .payload
 8498                .variant
 8499                .ok_or_else(|| anyhow!("invalid variant"))?
 8500            {
 8501                proto::update_language_server::Variant::WorkStart(payload) => {
 8502                    this.on_lsp_work_start(
 8503                        language_server_id,
 8504                        payload.token,
 8505                        LanguageServerProgress {
 8506                            message: payload.message,
 8507                            percentage: payload.percentage.map(|p| p as usize),
 8508                            last_update_at: Instant::now(),
 8509                        },
 8510                        cx,
 8511                    );
 8512                }
 8513
 8514                proto::update_language_server::Variant::WorkProgress(payload) => {
 8515                    this.on_lsp_work_progress(
 8516                        language_server_id,
 8517                        payload.token,
 8518                        LanguageServerProgress {
 8519                            message: payload.message,
 8520                            percentage: payload.percentage.map(|p| p as usize),
 8521                            last_update_at: Instant::now(),
 8522                        },
 8523                        cx,
 8524                    );
 8525                }
 8526
 8527                proto::update_language_server::Variant::WorkEnd(payload) => {
 8528                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 8529                }
 8530
 8531                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8532                    this.disk_based_diagnostics_started(language_server_id, cx);
 8533                }
 8534
 8535                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8536                    this.disk_based_diagnostics_finished(language_server_id, cx)
 8537                }
 8538            }
 8539
 8540            Ok(())
 8541        })?
 8542    }
 8543
 8544    async fn handle_update_buffer(
 8545        this: Model<Self>,
 8546        envelope: TypedEnvelope<proto::UpdateBuffer>,
 8547        _: Arc<Client>,
 8548        mut cx: AsyncAppContext,
 8549    ) -> Result<proto::Ack> {
 8550        this.update(&mut cx, |this, cx| {
 8551            let payload = envelope.payload.clone();
 8552            let buffer_id = BufferId::new(payload.buffer_id)?;
 8553            let ops = payload
 8554                .operations
 8555                .into_iter()
 8556                .map(language::proto::deserialize_operation)
 8557                .collect::<Result<Vec<_>, _>>()?;
 8558            let is_remote = this.is_remote();
 8559            match this.opened_buffers.entry(buffer_id) {
 8560                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
 8561                    OpenBuffer::Strong(buffer) => {
 8562                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 8563                    }
 8564                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
 8565                    OpenBuffer::Weak(_) => {}
 8566                },
 8567                hash_map::Entry::Vacant(e) => {
 8568                    if !is_remote {
 8569                        debug_panic!(
 8570                            "received buffer update from {:?}",
 8571                            envelope.original_sender_id
 8572                        );
 8573                        return Err(anyhow!("received buffer update for non-remote project"));
 8574                    }
 8575                    e.insert(OpenBuffer::Operations(ops));
 8576                }
 8577            }
 8578            Ok(proto::Ack {})
 8579        })?
 8580    }
 8581
 8582    async fn handle_create_buffer_for_peer(
 8583        this: Model<Self>,
 8584        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 8585        _: Arc<Client>,
 8586        mut cx: AsyncAppContext,
 8587    ) -> Result<()> {
 8588        this.update(&mut cx, |this, cx| {
 8589            match envelope
 8590                .payload
 8591                .variant
 8592                .ok_or_else(|| anyhow!("missing variant"))?
 8593            {
 8594                proto::create_buffer_for_peer::Variant::State(mut state) => {
 8595                    let buffer_id = BufferId::new(state.id)?;
 8596
 8597                    let buffer_result = maybe!({
 8598                        let mut buffer_file = None;
 8599                        if let Some(file) = state.file.take() {
 8600                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
 8601                            let worktree =
 8602                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
 8603                                    anyhow!("no worktree found for id {}", file.worktree_id)
 8604                                })?;
 8605                            buffer_file =
 8606                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
 8607                                    as Arc<dyn language::File>);
 8608                        }
 8609                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
 8610                    });
 8611
 8612                    match buffer_result {
 8613                        Ok(buffer) => {
 8614                            let buffer = cx.new_model(|_| buffer);
 8615                            this.incomplete_remote_buffers.insert(buffer_id, buffer);
 8616                        }
 8617                        Err(error) => {
 8618                            if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8619                                for listener in listeners {
 8620                                    listener.send(Err(anyhow!(error.cloned()))).ok();
 8621                                }
 8622                            }
 8623                        }
 8624                    };
 8625                }
 8626                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 8627                    let buffer_id = BufferId::new(chunk.buffer_id)?;
 8628                    let buffer = this
 8629                        .incomplete_remote_buffers
 8630                        .get(&buffer_id)
 8631                        .cloned()
 8632                        .ok_or_else(|| {
 8633                            anyhow!(
 8634                                "received chunk for buffer {} without initial state",
 8635                                chunk.buffer_id
 8636                            )
 8637                        })?;
 8638
 8639                    let result = maybe!({
 8640                        let operations = chunk
 8641                            .operations
 8642                            .into_iter()
 8643                            .map(language::proto::deserialize_operation)
 8644                            .collect::<Result<Vec<_>>>()?;
 8645                        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))
 8646                    });
 8647
 8648                    if let Err(error) = result {
 8649                        this.incomplete_remote_buffers.remove(&buffer_id);
 8650                        if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8651                            for listener in listeners {
 8652                                listener.send(Err(error.cloned())).ok();
 8653                            }
 8654                        }
 8655                    } else {
 8656                        if chunk.is_last {
 8657                            this.incomplete_remote_buffers.remove(&buffer_id);
 8658                            this.register_buffer(&buffer, cx)?;
 8659                        }
 8660                    }
 8661                }
 8662            }
 8663
 8664            Ok(())
 8665        })?
 8666    }
 8667
 8668    async fn handle_update_diff_base(
 8669        this: Model<Self>,
 8670        envelope: TypedEnvelope<proto::UpdateDiffBase>,
 8671        _: Arc<Client>,
 8672        mut cx: AsyncAppContext,
 8673    ) -> Result<()> {
 8674        this.update(&mut cx, |this, cx| {
 8675            let buffer_id = envelope.payload.buffer_id;
 8676            let buffer_id = BufferId::new(buffer_id)?;
 8677            if let Some(buffer) = this
 8678                .opened_buffers
 8679                .get_mut(&buffer_id)
 8680                .and_then(|b| b.upgrade())
 8681                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8682            {
 8683                buffer.update(cx, |buffer, cx| {
 8684                    buffer.set_diff_base(envelope.payload.diff_base, cx)
 8685                });
 8686            }
 8687            Ok(())
 8688        })?
 8689    }
 8690
 8691    async fn handle_update_buffer_file(
 8692        this: Model<Self>,
 8693        envelope: TypedEnvelope<proto::UpdateBufferFile>,
 8694        _: Arc<Client>,
 8695        mut cx: AsyncAppContext,
 8696    ) -> Result<()> {
 8697        let buffer_id = envelope.payload.buffer_id;
 8698        let buffer_id = BufferId::new(buffer_id)?;
 8699
 8700        this.update(&mut cx, |this, cx| {
 8701            let payload = envelope.payload.clone();
 8702            if let Some(buffer) = this
 8703                .opened_buffers
 8704                .get(&buffer_id)
 8705                .and_then(|b| b.upgrade())
 8706                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8707            {
 8708                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
 8709                let worktree = this
 8710                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
 8711                    .ok_or_else(|| anyhow!("no such worktree"))?;
 8712                let file = File::from_proto(file, worktree, cx)?;
 8713                buffer.update(cx, |buffer, cx| {
 8714                    buffer.file_updated(Arc::new(file), cx);
 8715                });
 8716                this.detect_language_for_buffer(&buffer, cx);
 8717            }
 8718            Ok(())
 8719        })?
 8720    }
 8721
 8722    async fn handle_save_buffer(
 8723        this: Model<Self>,
 8724        envelope: TypedEnvelope<proto::SaveBuffer>,
 8725        _: Arc<Client>,
 8726        mut cx: AsyncAppContext,
 8727    ) -> Result<proto::BufferSaved> {
 8728        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8729        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
 8730            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
 8731            let buffer = this
 8732                .opened_buffers
 8733                .get(&buffer_id)
 8734                .and_then(|buffer| buffer.upgrade())
 8735                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8736            anyhow::Ok((project_id, buffer))
 8737        })??;
 8738        buffer
 8739            .update(&mut cx, |buffer, _| {
 8740                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 8741            })?
 8742            .await?;
 8743        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
 8744
 8745        if let Some(new_path) = envelope.payload.new_path {
 8746            let new_path = ProjectPath::from_proto(new_path);
 8747            this.update(&mut cx, |this, cx| {
 8748                this.save_buffer_as(buffer.clone(), new_path, cx)
 8749            })?
 8750            .await?;
 8751        } else {
 8752            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
 8753                .await?;
 8754        }
 8755
 8756        buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
 8757            project_id,
 8758            buffer_id: buffer_id.into(),
 8759            version: serialize_version(buffer.saved_version()),
 8760            mtime: buffer.saved_mtime().map(|time| time.into()),
 8761        })
 8762    }
 8763
 8764    async fn handle_reload_buffers(
 8765        this: Model<Self>,
 8766        envelope: TypedEnvelope<proto::ReloadBuffers>,
 8767        _: Arc<Client>,
 8768        mut cx: AsyncAppContext,
 8769    ) -> Result<proto::ReloadBuffersResponse> {
 8770        let sender_id = envelope.original_sender_id()?;
 8771        let reload = this.update(&mut cx, |this, cx| {
 8772            let mut buffers = HashSet::default();
 8773            for buffer_id in &envelope.payload.buffer_ids {
 8774                let buffer_id = BufferId::new(*buffer_id)?;
 8775                buffers.insert(
 8776                    this.opened_buffers
 8777                        .get(&buffer_id)
 8778                        .and_then(|buffer| buffer.upgrade())
 8779                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 8780                );
 8781            }
 8782            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 8783        })??;
 8784
 8785        let project_transaction = reload.await?;
 8786        let project_transaction = this.update(&mut cx, |this, cx| {
 8787            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8788        })?;
 8789        Ok(proto::ReloadBuffersResponse {
 8790            transaction: Some(project_transaction),
 8791        })
 8792    }
 8793
 8794    async fn handle_synchronize_buffers(
 8795        this: Model<Self>,
 8796        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 8797        _: Arc<Client>,
 8798        mut cx: AsyncAppContext,
 8799    ) -> Result<proto::SynchronizeBuffersResponse> {
 8800        let project_id = envelope.payload.project_id;
 8801        let mut response = proto::SynchronizeBuffersResponse {
 8802            buffers: Default::default(),
 8803        };
 8804
 8805        this.update(&mut cx, |this, cx| {
 8806            let Some(guest_id) = envelope.original_sender_id else {
 8807                error!("missing original_sender_id on SynchronizeBuffers request");
 8808                bail!("missing original_sender_id on SynchronizeBuffers request");
 8809            };
 8810
 8811            this.shared_buffers.entry(guest_id).or_default().clear();
 8812            for buffer in envelope.payload.buffers {
 8813                let buffer_id = BufferId::new(buffer.id)?;
 8814                let remote_version = language::proto::deserialize_version(&buffer.version);
 8815                if let Some(buffer) = this.buffer_for_id(buffer_id) {
 8816                    this.shared_buffers
 8817                        .entry(guest_id)
 8818                        .or_default()
 8819                        .insert(buffer_id);
 8820
 8821                    let buffer = buffer.read(cx);
 8822                    response.buffers.push(proto::BufferVersion {
 8823                        id: buffer_id.into(),
 8824                        version: language::proto::serialize_version(&buffer.version),
 8825                    });
 8826
 8827                    let operations = buffer.serialize_ops(Some(remote_version), cx);
 8828                    let client = this.client.clone();
 8829                    if let Some(file) = buffer.file() {
 8830                        client
 8831                            .send(proto::UpdateBufferFile {
 8832                                project_id,
 8833                                buffer_id: buffer_id.into(),
 8834                                file: Some(file.to_proto()),
 8835                            })
 8836                            .log_err();
 8837                    }
 8838
 8839                    client
 8840                        .send(proto::UpdateDiffBase {
 8841                            project_id,
 8842                            buffer_id: buffer_id.into(),
 8843                            diff_base: buffer.diff_base().map(ToString::to_string),
 8844                        })
 8845                        .log_err();
 8846
 8847                    client
 8848                        .send(proto::BufferReloaded {
 8849                            project_id,
 8850                            buffer_id: buffer_id.into(),
 8851                            version: language::proto::serialize_version(buffer.saved_version()),
 8852                            mtime: buffer.saved_mtime().map(|time| time.into()),
 8853                            line_ending: language::proto::serialize_line_ending(
 8854                                buffer.line_ending(),
 8855                            ) as i32,
 8856                        })
 8857                        .log_err();
 8858
 8859                    cx.background_executor()
 8860                        .spawn(
 8861                            async move {
 8862                                let operations = operations.await;
 8863                                for chunk in split_operations(operations) {
 8864                                    client
 8865                                        .request(proto::UpdateBuffer {
 8866                                            project_id,
 8867                                            buffer_id: buffer_id.into(),
 8868                                            operations: chunk,
 8869                                        })
 8870                                        .await?;
 8871                                }
 8872                                anyhow::Ok(())
 8873                            }
 8874                            .log_err(),
 8875                        )
 8876                        .detach();
 8877                }
 8878            }
 8879            Ok(())
 8880        })??;
 8881
 8882        Ok(response)
 8883    }
 8884
 8885    async fn handle_format_buffers(
 8886        this: Model<Self>,
 8887        envelope: TypedEnvelope<proto::FormatBuffers>,
 8888        _: Arc<Client>,
 8889        mut cx: AsyncAppContext,
 8890    ) -> Result<proto::FormatBuffersResponse> {
 8891        let sender_id = envelope.original_sender_id()?;
 8892        let format = this.update(&mut cx, |this, cx| {
 8893            let mut buffers = HashSet::default();
 8894            for buffer_id in &envelope.payload.buffer_ids {
 8895                let buffer_id = BufferId::new(*buffer_id)?;
 8896                buffers.insert(
 8897                    this.opened_buffers
 8898                        .get(&buffer_id)
 8899                        .and_then(|buffer| buffer.upgrade())
 8900                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 8901                );
 8902            }
 8903            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 8904            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 8905        })??;
 8906
 8907        let project_transaction = format.await?;
 8908        let project_transaction = this.update(&mut cx, |this, cx| {
 8909            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8910        })?;
 8911        Ok(proto::FormatBuffersResponse {
 8912            transaction: Some(project_transaction),
 8913        })
 8914    }
 8915
 8916    async fn handle_apply_additional_edits_for_completion(
 8917        this: Model<Self>,
 8918        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 8919        _: Arc<Client>,
 8920        mut cx: AsyncAppContext,
 8921    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 8922        let (buffer, completion) = this.update(&mut cx, |this, _| {
 8923            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8924            let buffer = this
 8925                .opened_buffers
 8926                .get(&buffer_id)
 8927                .and_then(|buffer| buffer.upgrade())
 8928                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8929            let completion = Self::deserialize_completion(
 8930                envelope
 8931                    .payload
 8932                    .completion
 8933                    .ok_or_else(|| anyhow!("invalid completion"))?,
 8934            )?;
 8935            anyhow::Ok((buffer, completion))
 8936        })??;
 8937
 8938        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 8939            this.apply_additional_edits_for_completion(
 8940                buffer,
 8941                Completion {
 8942                    old_range: completion.old_range,
 8943                    new_text: completion.new_text,
 8944                    lsp_completion: completion.lsp_completion,
 8945                    server_id: completion.server_id,
 8946                    documentation: None,
 8947                    label: CodeLabel {
 8948                        text: Default::default(),
 8949                        runs: Default::default(),
 8950                        filter_range: Default::default(),
 8951                    },
 8952                },
 8953                false,
 8954                cx,
 8955            )
 8956        })?;
 8957
 8958        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 8959            transaction: apply_additional_edits
 8960                .await?
 8961                .as_ref()
 8962                .map(language::proto::serialize_transaction),
 8963        })
 8964    }
 8965
 8966    async fn handle_resolve_completion_documentation(
 8967        this: Model<Self>,
 8968        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 8969        _: Arc<Client>,
 8970        mut cx: AsyncAppContext,
 8971    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 8972        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 8973
 8974        let completion = this
 8975            .read_with(&mut cx, |this, _| {
 8976                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 8977                let Some(server) = this.language_server_for_id(id) else {
 8978                    return Err(anyhow!("No language server {id}"));
 8979                };
 8980
 8981                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 8982            })??
 8983            .await?;
 8984
 8985        let mut documentation_is_markdown = false;
 8986        let documentation = match completion.documentation {
 8987            Some(lsp::Documentation::String(text)) => text,
 8988
 8989            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 8990                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 8991                value
 8992            }
 8993
 8994            _ => String::new(),
 8995        };
 8996
 8997        // If we have a new buffer_id, that means we're talking to a new client
 8998        // and want to check for new text_edits in the completion too.
 8999        let mut old_start = None;
 9000        let mut old_end = None;
 9001        let mut new_text = String::default();
 9002        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 9003            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 9004                let buffer = this
 9005                    .opened_buffers
 9006                    .get(&buffer_id)
 9007                    .and_then(|buffer| buffer.upgrade())
 9008                    .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9009                anyhow::Ok(buffer.read(cx).snapshot())
 9010            })??;
 9011
 9012            if let Some(text_edit) = completion.text_edit.as_ref() {
 9013                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 9014
 9015                if let Some((old_range, mut text_edit_new_text)) = edit {
 9016                    LineEnding::normalize(&mut text_edit_new_text);
 9017
 9018                    new_text = text_edit_new_text;
 9019                    old_start = Some(serialize_anchor(&old_range.start));
 9020                    old_end = Some(serialize_anchor(&old_range.end));
 9021                }
 9022            }
 9023        }
 9024
 9025        Ok(proto::ResolveCompletionDocumentationResponse {
 9026            documentation,
 9027            documentation_is_markdown,
 9028            old_start,
 9029            old_end,
 9030            new_text,
 9031        })
 9032    }
 9033
 9034    async fn handle_apply_code_action(
 9035        this: Model<Self>,
 9036        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 9037        _: Arc<Client>,
 9038        mut cx: AsyncAppContext,
 9039    ) -> Result<proto::ApplyCodeActionResponse> {
 9040        let sender_id = envelope.original_sender_id()?;
 9041        let action = Self::deserialize_code_action(
 9042            envelope
 9043                .payload
 9044                .action
 9045                .ok_or_else(|| anyhow!("invalid action"))?,
 9046        )?;
 9047        let apply_code_action = this.update(&mut cx, |this, cx| {
 9048            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9049            let buffer = this
 9050                .opened_buffers
 9051                .get(&buffer_id)
 9052                .and_then(|buffer| buffer.upgrade())
 9053                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
 9054            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
 9055        })??;
 9056
 9057        let project_transaction = apply_code_action.await?;
 9058        let project_transaction = this.update(&mut cx, |this, cx| {
 9059            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9060        })?;
 9061        Ok(proto::ApplyCodeActionResponse {
 9062            transaction: Some(project_transaction),
 9063        })
 9064    }
 9065
 9066    async fn handle_on_type_formatting(
 9067        this: Model<Self>,
 9068        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 9069        _: Arc<Client>,
 9070        mut cx: AsyncAppContext,
 9071    ) -> Result<proto::OnTypeFormattingResponse> {
 9072        let on_type_formatting = this.update(&mut cx, |this, cx| {
 9073            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9074            let buffer = this
 9075                .opened_buffers
 9076                .get(&buffer_id)
 9077                .and_then(|buffer| buffer.upgrade())
 9078                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9079            let position = envelope
 9080                .payload
 9081                .position
 9082                .and_then(deserialize_anchor)
 9083                .ok_or_else(|| anyhow!("invalid position"))?;
 9084            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 9085                buffer,
 9086                position,
 9087                envelope.payload.trigger.clone(),
 9088                cx,
 9089            ))
 9090        })??;
 9091
 9092        let transaction = on_type_formatting
 9093            .await?
 9094            .as_ref()
 9095            .map(language::proto::serialize_transaction);
 9096        Ok(proto::OnTypeFormattingResponse { transaction })
 9097    }
 9098
 9099    async fn handle_inlay_hints(
 9100        this: Model<Self>,
 9101        envelope: TypedEnvelope<proto::InlayHints>,
 9102        _: Arc<Client>,
 9103        mut cx: AsyncAppContext,
 9104    ) -> Result<proto::InlayHintsResponse> {
 9105        let sender_id = envelope.original_sender_id()?;
 9106        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9107        let buffer = this.update(&mut cx, |this, _| {
 9108            this.opened_buffers
 9109                .get(&buffer_id)
 9110                .and_then(|buffer| buffer.upgrade())
 9111                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
 9112        })??;
 9113        buffer
 9114            .update(&mut cx, |buffer, _| {
 9115                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9116            })?
 9117            .await
 9118            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 9119
 9120        let start = envelope
 9121            .payload
 9122            .start
 9123            .and_then(deserialize_anchor)
 9124            .context("missing range start")?;
 9125        let end = envelope
 9126            .payload
 9127            .end
 9128            .and_then(deserialize_anchor)
 9129            .context("missing range end")?;
 9130        let buffer_hints = this
 9131            .update(&mut cx, |project, cx| {
 9132                project.inlay_hints(buffer.clone(), start..end, cx)
 9133            })?
 9134            .await
 9135            .context("inlay hints fetch")?;
 9136
 9137        this.update(&mut cx, |project, cx| {
 9138            InlayHints::response_to_proto(
 9139                buffer_hints,
 9140                project,
 9141                sender_id,
 9142                &buffer.read(cx).version(),
 9143                cx,
 9144            )
 9145        })
 9146    }
 9147
 9148    async fn handle_resolve_inlay_hint(
 9149        this: Model<Self>,
 9150        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 9151        _: Arc<Client>,
 9152        mut cx: AsyncAppContext,
 9153    ) -> Result<proto::ResolveInlayHintResponse> {
 9154        let proto_hint = envelope
 9155            .payload
 9156            .hint
 9157            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9158        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9159            .context("resolved proto inlay hint conversion")?;
 9160        let buffer = this.update(&mut cx, |this, _cx| {
 9161            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9162            this.opened_buffers
 9163                .get(&buffer_id)
 9164                .and_then(|buffer| buffer.upgrade())
 9165                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9166        })??;
 9167        let response_hint = this
 9168            .update(&mut cx, |project, cx| {
 9169                project.resolve_inlay_hint(
 9170                    hint,
 9171                    buffer,
 9172                    LanguageServerId(envelope.payload.language_server_id as usize),
 9173                    cx,
 9174                )
 9175            })?
 9176            .await
 9177            .context("inlay hints fetch")?;
 9178        Ok(proto::ResolveInlayHintResponse {
 9179            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9180        })
 9181    }
 9182
 9183    async fn try_resolve_code_action(
 9184        lang_server: &LanguageServer,
 9185        action: &mut CodeAction,
 9186    ) -> anyhow::Result<()> {
 9187        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 9188            if action.lsp_action.data.is_some()
 9189                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 9190            {
 9191                action.lsp_action = lang_server
 9192                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 9193                    .await?;
 9194            }
 9195        }
 9196
 9197        anyhow::Ok(())
 9198    }
 9199
 9200    async fn execute_code_actions_on_servers(
 9201        project: &WeakModel<Project>,
 9202        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 9203        code_actions: Vec<lsp::CodeActionKind>,
 9204        buffer: &Model<Buffer>,
 9205        push_to_history: bool,
 9206        project_transaction: &mut ProjectTransaction,
 9207        cx: &mut AsyncAppContext,
 9208    ) -> Result<(), anyhow::Error> {
 9209        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 9210            let code_actions = code_actions.clone();
 9211
 9212            let actions = project
 9213                .update(cx, move |this, cx| {
 9214                    let request = GetCodeActions {
 9215                        range: text::Anchor::MIN..text::Anchor::MAX,
 9216                        kinds: Some(code_actions),
 9217                    };
 9218                    let server = LanguageServerToQuery::Other(language_server.server_id());
 9219                    this.request_lsp(buffer.clone(), server, request, cx)
 9220                })?
 9221                .await?;
 9222
 9223            for mut action in actions {
 9224                Self::try_resolve_code_action(&language_server, &mut action)
 9225                    .await
 9226                    .context("resolving a formatting code action")?;
 9227
 9228                if let Some(edit) = action.lsp_action.edit {
 9229                    if edit.changes.is_none() && edit.document_changes.is_none() {
 9230                        continue;
 9231                    }
 9232
 9233                    let new = Self::deserialize_workspace_edit(
 9234                        project
 9235                            .upgrade()
 9236                            .ok_or_else(|| anyhow!("project dropped"))?,
 9237                        edit,
 9238                        push_to_history,
 9239                        lsp_adapter.clone(),
 9240                        language_server.clone(),
 9241                        cx,
 9242                    )
 9243                    .await?;
 9244                    project_transaction.0.extend(new.0);
 9245                }
 9246
 9247                if let Some(command) = action.lsp_action.command {
 9248                    project.update(cx, |this, _| {
 9249                        this.last_workspace_edits_by_language_server
 9250                            .remove(&language_server.server_id());
 9251                    })?;
 9252
 9253                    language_server
 9254                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 9255                            command: command.command,
 9256                            arguments: command.arguments.unwrap_or_default(),
 9257                            ..Default::default()
 9258                        })
 9259                        .await?;
 9260
 9261                    project.update(cx, |this, _| {
 9262                        project_transaction.0.extend(
 9263                            this.last_workspace_edits_by_language_server
 9264                                .remove(&language_server.server_id())
 9265                                .unwrap_or_default()
 9266                                .0,
 9267                        )
 9268                    })?;
 9269                }
 9270            }
 9271        }
 9272
 9273        Ok(())
 9274    }
 9275
 9276    async fn handle_refresh_inlay_hints(
 9277        this: Model<Self>,
 9278        _: TypedEnvelope<proto::RefreshInlayHints>,
 9279        _: Arc<Client>,
 9280        mut cx: AsyncAppContext,
 9281    ) -> Result<proto::Ack> {
 9282        this.update(&mut cx, |_, cx| {
 9283            cx.emit(Event::RefreshInlayHints);
 9284        })?;
 9285        Ok(proto::Ack {})
 9286    }
 9287
 9288    async fn handle_lsp_command<T: LspCommand>(
 9289        this: Model<Self>,
 9290        envelope: TypedEnvelope<T::ProtoRequest>,
 9291        _: Arc<Client>,
 9292        mut cx: AsyncAppContext,
 9293    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 9294    where
 9295        <T::LspRequest as lsp::request::Request>::Params: Send,
 9296        <T::LspRequest as lsp::request::Request>::Result: Send,
 9297    {
 9298        let sender_id = envelope.original_sender_id()?;
 9299        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 9300        let buffer_handle = this.update(&mut cx, |this, _cx| {
 9301            this.opened_buffers
 9302                .get(&buffer_id)
 9303                .and_then(|buffer| buffer.upgrade())
 9304                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9305        })??;
 9306        let request = T::from_proto(
 9307            envelope.payload,
 9308            this.clone(),
 9309            buffer_handle.clone(),
 9310            cx.clone(),
 9311        )
 9312        .await?;
 9313        let response = this
 9314            .update(&mut cx, |this, cx| {
 9315                this.request_lsp(
 9316                    buffer_handle.clone(),
 9317                    LanguageServerToQuery::Primary,
 9318                    request,
 9319                    cx,
 9320                )
 9321            })?
 9322            .await?;
 9323        this.update(&mut cx, |this, cx| {
 9324            Ok(T::response_to_proto(
 9325                response,
 9326                this,
 9327                sender_id,
 9328                &buffer_handle.read(cx).version(),
 9329                cx,
 9330            ))
 9331        })?
 9332    }
 9333
 9334    async fn handle_get_project_symbols(
 9335        this: Model<Self>,
 9336        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9337        _: Arc<Client>,
 9338        mut cx: AsyncAppContext,
 9339    ) -> Result<proto::GetProjectSymbolsResponse> {
 9340        let symbols = this
 9341            .update(&mut cx, |this, cx| {
 9342                this.symbols(&envelope.payload.query, cx)
 9343            })?
 9344            .await?;
 9345
 9346        Ok(proto::GetProjectSymbolsResponse {
 9347            symbols: symbols.iter().map(serialize_symbol).collect(),
 9348        })
 9349    }
 9350
 9351    async fn handle_search_project(
 9352        this: Model<Self>,
 9353        envelope: TypedEnvelope<proto::SearchProject>,
 9354        _: Arc<Client>,
 9355        mut cx: AsyncAppContext,
 9356    ) -> Result<proto::SearchProjectResponse> {
 9357        let peer_id = envelope.original_sender_id()?;
 9358        let query = SearchQuery::from_proto(envelope.payload)?;
 9359        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
 9360
 9361        cx.spawn(move |mut cx| async move {
 9362            let mut locations = Vec::new();
 9363            let mut limit_reached = false;
 9364            while let Some(result) = result.next().await {
 9365                match result {
 9366                    SearchResult::Buffer { buffer, ranges } => {
 9367                        for range in ranges {
 9368                            let start = serialize_anchor(&range.start);
 9369                            let end = serialize_anchor(&range.end);
 9370                            let buffer_id = this.update(&mut cx, |this, cx| {
 9371                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
 9372                            })?;
 9373                            locations.push(proto::Location {
 9374                                buffer_id,
 9375                                start: Some(start),
 9376                                end: Some(end),
 9377                            });
 9378                        }
 9379                    }
 9380                    SearchResult::LimitReached => limit_reached = true,
 9381                }
 9382            }
 9383            Ok(proto::SearchProjectResponse {
 9384                locations,
 9385                limit_reached,
 9386            })
 9387        })
 9388        .await
 9389    }
 9390
 9391    async fn handle_open_buffer_for_symbol(
 9392        this: Model<Self>,
 9393        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9394        _: Arc<Client>,
 9395        mut cx: AsyncAppContext,
 9396    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9397        let peer_id = envelope.original_sender_id()?;
 9398        let symbol = envelope
 9399            .payload
 9400            .symbol
 9401            .ok_or_else(|| anyhow!("invalid symbol"))?;
 9402        let symbol = Self::deserialize_symbol(symbol)?;
 9403        let symbol = this.update(&mut cx, |this, _| {
 9404            let signature = this.symbol_signature(&symbol.path);
 9405            if signature == symbol.signature {
 9406                Ok(symbol)
 9407            } else {
 9408                Err(anyhow!("invalid symbol signature"))
 9409            }
 9410        })??;
 9411        let buffer = this
 9412            .update(&mut cx, |this, cx| {
 9413                this.open_buffer_for_symbol(
 9414                    &Symbol {
 9415                        language_server_name: symbol.language_server_name,
 9416                        source_worktree_id: symbol.source_worktree_id,
 9417                        path: symbol.path,
 9418                        name: symbol.name,
 9419                        kind: symbol.kind,
 9420                        range: symbol.range,
 9421                        signature: symbol.signature,
 9422                        label: CodeLabel {
 9423                            text: Default::default(),
 9424                            runs: Default::default(),
 9425                            filter_range: Default::default(),
 9426                        },
 9427                    },
 9428                    cx,
 9429                )
 9430            })?
 9431            .await?;
 9432
 9433        this.update(&mut cx, |this, cx| {
 9434            let is_private = buffer
 9435                .read(cx)
 9436                .file()
 9437                .map(|f| f.is_private())
 9438                .unwrap_or_default();
 9439            if is_private {
 9440                Err(anyhow!(ErrorCode::UnsharedItem))
 9441            } else {
 9442                Ok(proto::OpenBufferForSymbolResponse {
 9443                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9444                })
 9445            }
 9446        })?
 9447    }
 9448
 9449    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9450        let mut hasher = Sha256::new();
 9451        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9452        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9453        hasher.update(self.nonce.to_be_bytes());
 9454        hasher.finalize().as_slice().try_into().unwrap()
 9455    }
 9456
 9457    async fn handle_open_buffer_by_id(
 9458        this: Model<Self>,
 9459        envelope: TypedEnvelope<proto::OpenBufferById>,
 9460        _: Arc<Client>,
 9461        mut cx: AsyncAppContext,
 9462    ) -> Result<proto::OpenBufferResponse> {
 9463        let peer_id = envelope.original_sender_id()?;
 9464        let buffer_id = BufferId::new(envelope.payload.id)?;
 9465        let buffer = this
 9466            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
 9467            .await?;
 9468        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9469    }
 9470
 9471    async fn handle_open_buffer_by_path(
 9472        this: Model<Self>,
 9473        envelope: TypedEnvelope<proto::OpenBufferByPath>,
 9474        _: Arc<Client>,
 9475        mut cx: AsyncAppContext,
 9476    ) -> Result<proto::OpenBufferResponse> {
 9477        let peer_id = envelope.original_sender_id()?;
 9478        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 9479        let open_buffer = this.update(&mut cx, |this, cx| {
 9480            this.open_buffer(
 9481                ProjectPath {
 9482                    worktree_id,
 9483                    path: PathBuf::from(envelope.payload.path).into(),
 9484                },
 9485                cx,
 9486            )
 9487        })?;
 9488
 9489        let buffer = open_buffer.await?;
 9490        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9491    }
 9492
 9493    async fn handle_open_new_buffer(
 9494        this: Model<Self>,
 9495        envelope: TypedEnvelope<proto::OpenNewBuffer>,
 9496        _: Arc<Client>,
 9497        mut cx: AsyncAppContext,
 9498    ) -> Result<proto::OpenBufferResponse> {
 9499        let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
 9500        let peer_id = envelope.original_sender_id()?;
 9501
 9502        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9503    }
 9504
 9505    fn respond_to_open_buffer_request(
 9506        this: Model<Self>,
 9507        buffer: Model<Buffer>,
 9508        peer_id: proto::PeerId,
 9509        cx: &mut AsyncAppContext,
 9510    ) -> Result<proto::OpenBufferResponse> {
 9511        this.update(cx, |this, cx| {
 9512            let is_private = buffer
 9513                .read(cx)
 9514                .file()
 9515                .map(|f| f.is_private())
 9516                .unwrap_or_default();
 9517            if is_private {
 9518                Err(anyhow!(ErrorCode::UnsharedItem))
 9519            } else {
 9520                Ok(proto::OpenBufferResponse {
 9521                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9522                })
 9523            }
 9524        })?
 9525    }
 9526
 9527    fn serialize_project_transaction_for_peer(
 9528        &mut self,
 9529        project_transaction: ProjectTransaction,
 9530        peer_id: proto::PeerId,
 9531        cx: &mut AppContext,
 9532    ) -> proto::ProjectTransaction {
 9533        let mut serialized_transaction = proto::ProjectTransaction {
 9534            buffer_ids: Default::default(),
 9535            transactions: Default::default(),
 9536        };
 9537        for (buffer, transaction) in project_transaction.0 {
 9538            serialized_transaction
 9539                .buffer_ids
 9540                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
 9541            serialized_transaction
 9542                .transactions
 9543                .push(language::proto::serialize_transaction(&transaction));
 9544        }
 9545        serialized_transaction
 9546    }
 9547
 9548    fn deserialize_project_transaction(
 9549        &mut self,
 9550        message: proto::ProjectTransaction,
 9551        push_to_history: bool,
 9552        cx: &mut ModelContext<Self>,
 9553    ) -> Task<Result<ProjectTransaction>> {
 9554        cx.spawn(move |this, mut cx| async move {
 9555            let mut project_transaction = ProjectTransaction::default();
 9556            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 9557            {
 9558                let buffer_id = BufferId::new(buffer_id)?;
 9559                let buffer = this
 9560                    .update(&mut cx, |this, cx| {
 9561                        this.wait_for_remote_buffer(buffer_id, cx)
 9562                    })?
 9563                    .await?;
 9564                let transaction = language::proto::deserialize_transaction(transaction)?;
 9565                project_transaction.0.insert(buffer, transaction);
 9566            }
 9567
 9568            for (buffer, transaction) in &project_transaction.0 {
 9569                buffer
 9570                    .update(&mut cx, |buffer, _| {
 9571                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 9572                    })?
 9573                    .await?;
 9574
 9575                if push_to_history {
 9576                    buffer.update(&mut cx, |buffer, _| {
 9577                        buffer.push_transaction(transaction.clone(), Instant::now());
 9578                    })?;
 9579                }
 9580            }
 9581
 9582            Ok(project_transaction)
 9583        })
 9584    }
 9585
 9586    fn create_buffer_for_peer(
 9587        &mut self,
 9588        buffer: &Model<Buffer>,
 9589        peer_id: proto::PeerId,
 9590        cx: &mut AppContext,
 9591    ) -> BufferId {
 9592        let buffer_id = buffer.read(cx).remote_id();
 9593        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
 9594            updates_tx
 9595                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
 9596                .ok();
 9597        }
 9598        buffer_id
 9599    }
 9600
 9601    fn wait_for_remote_buffer(
 9602        &mut self,
 9603        id: BufferId,
 9604        cx: &mut ModelContext<Self>,
 9605    ) -> Task<Result<Model<Buffer>>> {
 9606        let buffer = self
 9607            .opened_buffers
 9608            .get(&id)
 9609            .and_then(|buffer| buffer.upgrade());
 9610
 9611        if let Some(buffer) = buffer {
 9612            return Task::ready(Ok(buffer));
 9613        }
 9614
 9615        let (tx, rx) = oneshot::channel();
 9616        self.loading_buffers.entry(id).or_default().push(tx);
 9617
 9618        cx.background_executor().spawn(async move { rx.await? })
 9619    }
 9620
 9621    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 9622        let project_id = match self.client_state {
 9623            ProjectClientState::Remote {
 9624                sharing_has_stopped,
 9625                remote_id,
 9626                ..
 9627            } => {
 9628                if sharing_has_stopped {
 9629                    return Task::ready(Err(anyhow!(
 9630                        "can't synchronize remote buffers on a readonly project"
 9631                    )));
 9632                } else {
 9633                    remote_id
 9634                }
 9635            }
 9636            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
 9637                return Task::ready(Err(anyhow!(
 9638                    "can't synchronize remote buffers on a local project"
 9639                )))
 9640            }
 9641        };
 9642
 9643        let client = self.client.clone();
 9644        cx.spawn(move |this, mut cx| async move {
 9645            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
 9646                let buffers = this
 9647                    .opened_buffers
 9648                    .iter()
 9649                    .filter_map(|(id, buffer)| {
 9650                        let buffer = buffer.upgrade()?;
 9651                        Some(proto::BufferVersion {
 9652                            id: (*id).into(),
 9653                            version: language::proto::serialize_version(&buffer.read(cx).version),
 9654                        })
 9655                    })
 9656                    .collect();
 9657                let incomplete_buffer_ids = this
 9658                    .incomplete_remote_buffers
 9659                    .keys()
 9660                    .copied()
 9661                    .collect::<Vec<_>>();
 9662
 9663                (buffers, incomplete_buffer_ids)
 9664            })?;
 9665            let response = client
 9666                .request(proto::SynchronizeBuffers {
 9667                    project_id,
 9668                    buffers,
 9669                })
 9670                .await?;
 9671
 9672            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
 9673                response
 9674                    .buffers
 9675                    .into_iter()
 9676                    .map(|buffer| {
 9677                        let client = client.clone();
 9678                        let buffer_id = match BufferId::new(buffer.id) {
 9679                            Ok(id) => id,
 9680                            Err(e) => {
 9681                                return Task::ready(Err(e));
 9682                            }
 9683                        };
 9684                        let remote_version = language::proto::deserialize_version(&buffer.version);
 9685                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
 9686                            let operations =
 9687                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
 9688                            cx.background_executor().spawn(async move {
 9689                                let operations = operations.await;
 9690                                for chunk in split_operations(operations) {
 9691                                    client
 9692                                        .request(proto::UpdateBuffer {
 9693                                            project_id,
 9694                                            buffer_id: buffer_id.into(),
 9695                                            operations: chunk,
 9696                                        })
 9697                                        .await?;
 9698                                }
 9699                                anyhow::Ok(())
 9700                            })
 9701                        } else {
 9702                            Task::ready(Ok(()))
 9703                        }
 9704                    })
 9705                    .collect::<Vec<_>>()
 9706            })?;
 9707
 9708            // Any incomplete buffers have open requests waiting. Request that the host sends
 9709            // creates these buffers for us again to unblock any waiting futures.
 9710            for id in incomplete_buffer_ids {
 9711                cx.background_executor()
 9712                    .spawn(client.request(proto::OpenBufferById {
 9713                        project_id,
 9714                        id: id.into(),
 9715                    }))
 9716                    .detach();
 9717            }
 9718
 9719            futures::future::join_all(send_updates_for_buffers)
 9720                .await
 9721                .into_iter()
 9722                .collect()
 9723        })
 9724    }
 9725
 9726    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
 9727        self.worktrees()
 9728            .map(|worktree| {
 9729                let worktree = worktree.read(cx);
 9730                proto::WorktreeMetadata {
 9731                    id: worktree.id().to_proto(),
 9732                    root_name: worktree.root_name().into(),
 9733                    visible: worktree.is_visible(),
 9734                    abs_path: worktree.abs_path().to_string_lossy().into(),
 9735                }
 9736            })
 9737            .collect()
 9738    }
 9739
 9740    fn set_worktrees_from_proto(
 9741        &mut self,
 9742        worktrees: Vec<proto::WorktreeMetadata>,
 9743        cx: &mut ModelContext<Project>,
 9744    ) -> Result<()> {
 9745        let replica_id = self.replica_id();
 9746        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
 9747
 9748        let mut old_worktrees_by_id = self
 9749            .worktrees
 9750            .drain(..)
 9751            .filter_map(|worktree| {
 9752                let worktree = worktree.upgrade()?;
 9753                Some((worktree.read(cx).id(), worktree))
 9754            })
 9755            .collect::<HashMap<_, _>>();
 9756
 9757        for worktree in worktrees {
 9758            if let Some(old_worktree) =
 9759                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 9760            {
 9761                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
 9762            } else {
 9763                let worktree =
 9764                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
 9765                let _ = self.add_worktree(&worktree, cx);
 9766            }
 9767        }
 9768
 9769        self.metadata_changed(cx);
 9770        for id in old_worktrees_by_id.keys() {
 9771            cx.emit(Event::WorktreeRemoved(*id));
 9772        }
 9773
 9774        Ok(())
 9775    }
 9776
 9777    fn set_collaborators_from_proto(
 9778        &mut self,
 9779        messages: Vec<proto::Collaborator>,
 9780        cx: &mut ModelContext<Self>,
 9781    ) -> Result<()> {
 9782        let mut collaborators = HashMap::default();
 9783        for message in messages {
 9784            let collaborator = Collaborator::from_proto(message)?;
 9785            collaborators.insert(collaborator.peer_id, collaborator);
 9786        }
 9787        for old_peer_id in self.collaborators.keys() {
 9788            if !collaborators.contains_key(old_peer_id) {
 9789                cx.emit(Event::CollaboratorLeft(*old_peer_id));
 9790            }
 9791        }
 9792        self.collaborators = collaborators;
 9793        Ok(())
 9794    }
 9795
 9796    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
 9797        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
 9798        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
 9799        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
 9800        let path = ProjectPath {
 9801            worktree_id,
 9802            path: PathBuf::from(serialized_symbol.path).into(),
 9803        };
 9804
 9805        let start = serialized_symbol
 9806            .start
 9807            .ok_or_else(|| anyhow!("invalid start"))?;
 9808        let end = serialized_symbol
 9809            .end
 9810            .ok_or_else(|| anyhow!("invalid end"))?;
 9811        Ok(CoreSymbol {
 9812            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
 9813            source_worktree_id,
 9814            path,
 9815            name: serialized_symbol.name,
 9816            range: Unclipped(PointUtf16::new(start.row, start.column))
 9817                ..Unclipped(PointUtf16::new(end.row, end.column)),
 9818            kind,
 9819            signature: serialized_symbol
 9820                .signature
 9821                .try_into()
 9822                .map_err(|_| anyhow!("invalid signature"))?,
 9823        })
 9824    }
 9825
 9826    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
 9827        proto::Completion {
 9828            old_start: Some(serialize_anchor(&completion.old_range.start)),
 9829            old_end: Some(serialize_anchor(&completion.old_range.end)),
 9830            new_text: completion.new_text.clone(),
 9831            server_id: completion.server_id.0 as u64,
 9832            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
 9833        }
 9834    }
 9835
 9836    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
 9837        let old_start = completion
 9838            .old_start
 9839            .and_then(deserialize_anchor)
 9840            .ok_or_else(|| anyhow!("invalid old start"))?;
 9841        let old_end = completion
 9842            .old_end
 9843            .and_then(deserialize_anchor)
 9844            .ok_or_else(|| anyhow!("invalid old end"))?;
 9845        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
 9846
 9847        Ok(CoreCompletion {
 9848            old_range: old_start..old_end,
 9849            new_text: completion.new_text,
 9850            server_id: LanguageServerId(completion.server_id as usize),
 9851            lsp_completion,
 9852        })
 9853    }
 9854
 9855    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
 9856        proto::CodeAction {
 9857            server_id: action.server_id.0 as u64,
 9858            start: Some(serialize_anchor(&action.range.start)),
 9859            end: Some(serialize_anchor(&action.range.end)),
 9860            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
 9861        }
 9862    }
 9863
 9864    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
 9865        let start = action
 9866            .start
 9867            .and_then(deserialize_anchor)
 9868            .ok_or_else(|| anyhow!("invalid start"))?;
 9869        let end = action
 9870            .end
 9871            .and_then(deserialize_anchor)
 9872            .ok_or_else(|| anyhow!("invalid end"))?;
 9873        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
 9874        Ok(CodeAction {
 9875            server_id: LanguageServerId(action.server_id as usize),
 9876            range: start..end,
 9877            lsp_action,
 9878        })
 9879    }
 9880
 9881    async fn handle_buffer_saved(
 9882        this: Model<Self>,
 9883        envelope: TypedEnvelope<proto::BufferSaved>,
 9884        _: Arc<Client>,
 9885        mut cx: AsyncAppContext,
 9886    ) -> Result<()> {
 9887        let version = deserialize_version(&envelope.payload.version);
 9888        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9889        let mtime = envelope.payload.mtime.map(|time| time.into());
 9890
 9891        this.update(&mut cx, |this, cx| {
 9892            let buffer = this
 9893                .opened_buffers
 9894                .get(&buffer_id)
 9895                .and_then(|buffer| buffer.upgrade())
 9896                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
 9897            if let Some(buffer) = buffer {
 9898                buffer.update(cx, |buffer, cx| {
 9899                    buffer.did_save(version, mtime, cx);
 9900                });
 9901            }
 9902            Ok(())
 9903        })?
 9904    }
 9905
 9906    async fn handle_buffer_reloaded(
 9907        this: Model<Self>,
 9908        envelope: TypedEnvelope<proto::BufferReloaded>,
 9909        _: Arc<Client>,
 9910        mut cx: AsyncAppContext,
 9911    ) -> Result<()> {
 9912        let payload = envelope.payload;
 9913        let version = deserialize_version(&payload.version);
 9914        let line_ending = deserialize_line_ending(
 9915            proto::LineEnding::from_i32(payload.line_ending)
 9916                .ok_or_else(|| anyhow!("missing line ending"))?,
 9917        );
 9918        let mtime = payload.mtime.map(|time| time.into());
 9919        let buffer_id = BufferId::new(payload.buffer_id)?;
 9920        this.update(&mut cx, |this, cx| {
 9921            let buffer = this
 9922                .opened_buffers
 9923                .get(&buffer_id)
 9924                .and_then(|buffer| buffer.upgrade())
 9925                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
 9926            if let Some(buffer) = buffer {
 9927                buffer.update(cx, |buffer, cx| {
 9928                    buffer.did_reload(version, line_ending, mtime, cx);
 9929                });
 9930            }
 9931            Ok(())
 9932        })?
 9933    }
 9934
 9935    #[allow(clippy::type_complexity)]
 9936    fn edits_from_lsp(
 9937        &mut self,
 9938        buffer: &Model<Buffer>,
 9939        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
 9940        server_id: LanguageServerId,
 9941        version: Option<i32>,
 9942        cx: &mut ModelContext<Self>,
 9943    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
 9944        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
 9945        cx.background_executor().spawn(async move {
 9946            let snapshot = snapshot?;
 9947            let mut lsp_edits = lsp_edits
 9948                .into_iter()
 9949                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
 9950                .collect::<Vec<_>>();
 9951            lsp_edits.sort_by_key(|(range, _)| range.start);
 9952
 9953            let mut lsp_edits = lsp_edits.into_iter().peekable();
 9954            let mut edits = Vec::new();
 9955            while let Some((range, mut new_text)) = lsp_edits.next() {
 9956                // Clip invalid ranges provided by the language server.
 9957                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
 9958                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
 9959
 9960                // Combine any LSP edits that are adjacent.
 9961                //
 9962                // Also, combine LSP edits that are separated from each other by only
 9963                // a newline. This is important because for some code actions,
 9964                // Rust-analyzer rewrites the entire buffer via a series of edits that
 9965                // are separated by unchanged newline characters.
 9966                //
 9967                // In order for the diffing logic below to work properly, any edits that
 9968                // cancel each other out must be combined into one.
 9969                while let Some((next_range, next_text)) = lsp_edits.peek() {
 9970                    if next_range.start.0 > range.end {
 9971                        if next_range.start.0.row > range.end.row + 1
 9972                            || next_range.start.0.column > 0
 9973                            || snapshot.clip_point_utf16(
 9974                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
 9975                                Bias::Left,
 9976                            ) > range.end
 9977                        {
 9978                            break;
 9979                        }
 9980                        new_text.push('\n');
 9981                    }
 9982                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
 9983                    new_text.push_str(next_text);
 9984                    lsp_edits.next();
 9985                }
 9986
 9987                // For multiline edits, perform a diff of the old and new text so that
 9988                // we can identify the changes more precisely, preserving the locations
 9989                // of any anchors positioned in the unchanged regions.
 9990                if range.end.row > range.start.row {
 9991                    let mut offset = range.start.to_offset(&snapshot);
 9992                    let old_text = snapshot.text_for_range(range).collect::<String>();
 9993
 9994                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
 9995                    let mut moved_since_edit = true;
 9996                    for change in diff.iter_all_changes() {
 9997                        let tag = change.tag();
 9998                        let value = change.value();
 9999                        match tag {
10000                            ChangeTag::Equal => {
10001                                offset += value.len();
10002                                moved_since_edit = true;
10003                            }
10004                            ChangeTag::Delete => {
10005                                let start = snapshot.anchor_after(offset);
10006                                let end = snapshot.anchor_before(offset + value.len());
10007                                if moved_since_edit {
10008                                    edits.push((start..end, String::new()));
10009                                } else {
10010                                    edits.last_mut().unwrap().0.end = end;
10011                                }
10012                                offset += value.len();
10013                                moved_since_edit = false;
10014                            }
10015                            ChangeTag::Insert => {
10016                                if moved_since_edit {
10017                                    let anchor = snapshot.anchor_after(offset);
10018                                    edits.push((anchor..anchor, value.to_string()));
10019                                } else {
10020                                    edits.last_mut().unwrap().1.push_str(value);
10021                                }
10022                                moved_since_edit = false;
10023                            }
10024                        }
10025                    }
10026                } else if range.end == range.start {
10027                    let anchor = snapshot.anchor_after(range.start);
10028                    edits.push((anchor..anchor, new_text));
10029                } else {
10030                    let edit_start = snapshot.anchor_after(range.start);
10031                    let edit_end = snapshot.anchor_before(range.end);
10032                    edits.push((edit_start..edit_end, new_text));
10033                }
10034            }
10035
10036            Ok(edits)
10037        })
10038    }
10039
10040    fn buffer_snapshot_for_lsp_version(
10041        &mut self,
10042        buffer: &Model<Buffer>,
10043        server_id: LanguageServerId,
10044        version: Option<i32>,
10045        cx: &AppContext,
10046    ) -> Result<TextBufferSnapshot> {
10047        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
10048
10049        if let Some(version) = version {
10050            let buffer_id = buffer.read(cx).remote_id();
10051            let snapshots = self
10052                .buffer_snapshots
10053                .get_mut(&buffer_id)
10054                .and_then(|m| m.get_mut(&server_id))
10055                .ok_or_else(|| {
10056                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
10057                })?;
10058
10059            let found_snapshot = snapshots
10060                .binary_search_by_key(&version, |e| e.version)
10061                .map(|ix| snapshots[ix].snapshot.clone())
10062                .map_err(|_| {
10063                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
10064                })?;
10065
10066            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
10067            Ok(found_snapshot)
10068        } else {
10069            Ok((buffer.read(cx)).text_snapshot())
10070        }
10071    }
10072
10073    pub fn language_servers(
10074        &self,
10075    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
10076        self.language_server_ids
10077            .iter()
10078            .map(|((worktree_id, server_name), server_id)| {
10079                (*server_id, server_name.clone(), *worktree_id)
10080            })
10081    }
10082
10083    pub fn supplementary_language_servers(
10084        &self,
10085    ) -> impl '_
10086           + Iterator<
10087        Item = (
10088            &LanguageServerId,
10089            &(LanguageServerName, Arc<LanguageServer>),
10090        ),
10091    > {
10092        self.supplementary_language_servers.iter()
10093    }
10094
10095    pub fn language_server_adapter_for_id(
10096        &self,
10097        id: LanguageServerId,
10098    ) -> Option<Arc<CachedLspAdapter>> {
10099        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
10100            Some(adapter.clone())
10101        } else {
10102            None
10103        }
10104    }
10105
10106    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
10107        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
10108            Some(server.clone())
10109        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
10110            Some(Arc::clone(server))
10111        } else {
10112            None
10113        }
10114    }
10115
10116    pub fn language_servers_for_buffer(
10117        &self,
10118        buffer: &Buffer,
10119        cx: &AppContext,
10120    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10121        self.language_server_ids_for_buffer(buffer, cx)
10122            .into_iter()
10123            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
10124                LanguageServerState::Running {
10125                    adapter, server, ..
10126                } => Some((adapter, server)),
10127                _ => None,
10128            })
10129    }
10130
10131    fn primary_language_server_for_buffer(
10132        &self,
10133        buffer: &Buffer,
10134        cx: &AppContext,
10135    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10136        self.language_servers_for_buffer(buffer, cx)
10137            .find(|s| s.0.is_primary)
10138    }
10139
10140    pub fn language_server_for_buffer(
10141        &self,
10142        buffer: &Buffer,
10143        server_id: LanguageServerId,
10144        cx: &AppContext,
10145    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10146        self.language_servers_for_buffer(buffer, cx)
10147            .find(|(_, s)| s.server_id() == server_id)
10148    }
10149
10150    fn language_server_ids_for_buffer(
10151        &self,
10152        buffer: &Buffer,
10153        cx: &AppContext,
10154    ) -> Vec<LanguageServerId> {
10155        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
10156            let worktree_id = file.worktree_id(cx);
10157            self.languages
10158                .lsp_adapters(&language)
10159                .iter()
10160                .flat_map(|adapter| {
10161                    let key = (worktree_id, adapter.name.clone());
10162                    self.language_server_ids.get(&key).copied()
10163                })
10164                .collect()
10165        } else {
10166            Vec::new()
10167        }
10168    }
10169}
10170
10171async fn populate_labels_for_symbols(
10172    symbols: Vec<CoreSymbol>,
10173    language_registry: &Arc<LanguageRegistry>,
10174    default_language: Option<Arc<Language>>,
10175    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10176    output: &mut Vec<Symbol>,
10177) {
10178    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10179
10180    let mut unknown_path = None;
10181    for symbol in symbols {
10182        let language = language_registry
10183            .language_for_file_path(&symbol.path.path)
10184            .await
10185            .ok()
10186            .or_else(|| {
10187                unknown_path.get_or_insert(symbol.path.path.clone());
10188                default_language.clone()
10189            });
10190        symbols_by_language
10191            .entry(language)
10192            .or_default()
10193            .push(symbol);
10194    }
10195
10196    if let Some(unknown_path) = unknown_path {
10197        log::info!(
10198            "no language found for symbol path {}",
10199            unknown_path.display()
10200        );
10201    }
10202
10203    let mut label_params = Vec::new();
10204    for (language, mut symbols) in symbols_by_language {
10205        label_params.clear();
10206        label_params.extend(
10207            symbols
10208                .iter_mut()
10209                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10210        );
10211
10212        let mut labels = Vec::new();
10213        if let Some(language) = language {
10214            let lsp_adapter = lsp_adapter
10215                .clone()
10216                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
10217            if let Some(lsp_adapter) = lsp_adapter {
10218                labels = lsp_adapter
10219                    .labels_for_symbols(&label_params, &language)
10220                    .await
10221                    .log_err()
10222                    .unwrap_or_default();
10223            }
10224        }
10225
10226        for ((symbol, (name, _)), label) in symbols
10227            .into_iter()
10228            .zip(label_params.drain(..))
10229            .zip(labels.into_iter().chain(iter::repeat(None)))
10230        {
10231            output.push(Symbol {
10232                language_server_name: symbol.language_server_name,
10233                source_worktree_id: symbol.source_worktree_id,
10234                path: symbol.path,
10235                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10236                name,
10237                kind: symbol.kind,
10238                range: symbol.range,
10239                signature: symbol.signature,
10240            });
10241        }
10242    }
10243}
10244
10245async fn populate_labels_for_completions(
10246    mut new_completions: Vec<CoreCompletion>,
10247    language_registry: &Arc<LanguageRegistry>,
10248    language: Option<Arc<Language>>,
10249    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10250    completions: &mut Vec<Completion>,
10251) {
10252    let lsp_completions = new_completions
10253        .iter_mut()
10254        .map(|completion| mem::take(&mut completion.lsp_completion))
10255        .collect::<Vec<_>>();
10256
10257    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10258        lsp_adapter
10259            .labels_for_completions(&lsp_completions, language)
10260            .await
10261            .log_err()
10262            .unwrap_or_default()
10263    } else {
10264        Vec::new()
10265    };
10266
10267    for ((completion, lsp_completion), label) in new_completions
10268        .into_iter()
10269        .zip(lsp_completions)
10270        .zip(labels.into_iter().chain(iter::repeat(None)))
10271    {
10272        let documentation = if let Some(docs) = &lsp_completion.documentation {
10273            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
10274        } else {
10275            None
10276        };
10277
10278        completions.push(Completion {
10279            old_range: completion.old_range,
10280            new_text: completion.new_text,
10281            label: label.unwrap_or_else(|| {
10282                CodeLabel::plain(
10283                    lsp_completion.label.clone(),
10284                    lsp_completion.filter_text.as_deref(),
10285                )
10286            }),
10287            server_id: completion.server_id,
10288            documentation,
10289            lsp_completion,
10290        })
10291    }
10292}
10293
10294fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
10295    code_actions
10296        .iter()
10297        .flat_map(|(kind, enabled)| {
10298            if *enabled {
10299                Some(kind.clone().into())
10300            } else {
10301                None
10302            }
10303        })
10304        .collect()
10305}
10306
10307#[allow(clippy::too_many_arguments)]
10308async fn search_snapshots(
10309    snapshots: &Vec<LocalSnapshot>,
10310    worker_start_ix: usize,
10311    worker_end_ix: usize,
10312    query: &SearchQuery,
10313    results_tx: &Sender<SearchMatchCandidate>,
10314    opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
10315    include_root: bool,
10316    fs: &Arc<dyn Fs>,
10317) {
10318    let mut snapshot_start_ix = 0;
10319    let mut abs_path = PathBuf::new();
10320
10321    for snapshot in snapshots {
10322        let snapshot_end_ix = snapshot_start_ix
10323            + if query.include_ignored() {
10324                snapshot.file_count()
10325            } else {
10326                snapshot.visible_file_count()
10327            };
10328        if worker_end_ix <= snapshot_start_ix {
10329            break;
10330        } else if worker_start_ix > snapshot_end_ix {
10331            snapshot_start_ix = snapshot_end_ix;
10332            continue;
10333        } else {
10334            let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
10335            let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
10336
10337            for entry in snapshot
10338                .files(false, start_in_snapshot)
10339                .take(end_in_snapshot - start_in_snapshot)
10340            {
10341                if results_tx.is_closed() {
10342                    break;
10343                }
10344                if opened_buffers.contains_key(&entry.path) {
10345                    continue;
10346                }
10347
10348                let matched_path = if include_root {
10349                    let mut full_path = PathBuf::from(snapshot.root_name());
10350                    full_path.push(&entry.path);
10351                    query.file_matches(Some(&full_path))
10352                } else {
10353                    query.file_matches(Some(&entry.path))
10354                };
10355
10356                let matches = if matched_path {
10357                    abs_path.clear();
10358                    abs_path.push(&snapshot.abs_path());
10359                    abs_path.push(&entry.path);
10360                    if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
10361                        query.detect(file).unwrap_or(false)
10362                    } else {
10363                        false
10364                    }
10365                } else {
10366                    false
10367                };
10368
10369                if matches {
10370                    let project_path = SearchMatchCandidate::Path {
10371                        worktree_id: snapshot.id(),
10372                        path: entry.path.clone(),
10373                        is_ignored: entry.is_ignored,
10374                    };
10375                    if results_tx.send(project_path).await.is_err() {
10376                        return;
10377                    }
10378                }
10379            }
10380
10381            snapshot_start_ix = snapshot_end_ix;
10382        }
10383    }
10384}
10385
10386async fn search_ignored_entry(
10387    snapshot: &LocalSnapshot,
10388    ignored_entry: &Entry,
10389    fs: &Arc<dyn Fs>,
10390    query: &SearchQuery,
10391    counter_tx: &Sender<SearchMatchCandidate>,
10392) {
10393    let mut ignored_paths_to_process =
10394        VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
10395
10396    while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
10397        let metadata = fs
10398            .metadata(&ignored_abs_path)
10399            .await
10400            .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
10401            .log_err()
10402            .flatten();
10403
10404        if let Some(fs_metadata) = metadata {
10405            if fs_metadata.is_dir {
10406                let files = fs
10407                    .read_dir(&ignored_abs_path)
10408                    .await
10409                    .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
10410                    .log_err();
10411
10412                if let Some(mut subfiles) = files {
10413                    while let Some(subfile) = subfiles.next().await {
10414                        if let Some(subfile) = subfile.log_err() {
10415                            ignored_paths_to_process.push_back(subfile);
10416                        }
10417                    }
10418                }
10419            } else if !fs_metadata.is_symlink {
10420                if !query.file_matches(Some(&ignored_abs_path))
10421                    || snapshot.is_path_excluded(ignored_entry.path.to_path_buf())
10422                {
10423                    continue;
10424                }
10425                let matches = if let Some(file) = fs
10426                    .open_sync(&ignored_abs_path)
10427                    .await
10428                    .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
10429                    .log_err()
10430                {
10431                    query.detect(file).unwrap_or(false)
10432                } else {
10433                    false
10434                };
10435
10436                if matches {
10437                    let project_path = SearchMatchCandidate::Path {
10438                        worktree_id: snapshot.id(),
10439                        path: Arc::from(
10440                            ignored_abs_path
10441                                .strip_prefix(snapshot.abs_path())
10442                                .expect("scanning worktree-related files"),
10443                        ),
10444                        is_ignored: true,
10445                    };
10446                    if counter_tx.send(project_path).await.is_err() {
10447                        return;
10448                    }
10449                }
10450            }
10451        }
10452    }
10453}
10454
10455fn glob_literal_prefix(glob: &str) -> &str {
10456    let mut literal_end = 0;
10457    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
10458        if part.contains(&['*', '?', '{', '}']) {
10459            break;
10460        } else {
10461            if i > 0 {
10462                // Account for separator prior to this part
10463                literal_end += path::MAIN_SEPARATOR.len_utf8();
10464            }
10465            literal_end += part.len();
10466        }
10467    }
10468    &glob[..literal_end]
10469}
10470
10471impl WorktreeHandle {
10472    pub fn upgrade(&self) -> Option<Model<Worktree>> {
10473        match self {
10474            WorktreeHandle::Strong(handle) => Some(handle.clone()),
10475            WorktreeHandle::Weak(handle) => handle.upgrade(),
10476        }
10477    }
10478
10479    pub fn handle_id(&self) -> usize {
10480        match self {
10481            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
10482            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
10483        }
10484    }
10485}
10486
10487impl OpenBuffer {
10488    pub fn upgrade(&self) -> Option<Model<Buffer>> {
10489        match self {
10490            OpenBuffer::Strong(handle) => Some(handle.clone()),
10491            OpenBuffer::Weak(handle) => handle.upgrade(),
10492            OpenBuffer::Operations(_) => None,
10493        }
10494    }
10495}
10496
10497pub struct PathMatchCandidateSet {
10498    pub snapshot: Snapshot,
10499    pub include_ignored: bool,
10500    pub include_root_name: bool,
10501    pub directories_only: bool,
10502}
10503
10504impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
10505    type Candidates = PathMatchCandidateSetIter<'a>;
10506
10507    fn id(&self) -> usize {
10508        self.snapshot.id().to_usize()
10509    }
10510
10511    fn len(&self) -> usize {
10512        if self.include_ignored {
10513            self.snapshot.file_count()
10514        } else {
10515            self.snapshot.visible_file_count()
10516        }
10517    }
10518
10519    fn prefix(&self) -> Arc<str> {
10520        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
10521            self.snapshot.root_name().into()
10522        } else if self.include_root_name {
10523            format!("{}/", self.snapshot.root_name()).into()
10524        } else {
10525            "".into()
10526        }
10527    }
10528
10529    fn candidates(&'a self, start: usize) -> Self::Candidates {
10530        PathMatchCandidateSetIter {
10531            traversal: if self.directories_only {
10532                self.snapshot.directories(self.include_ignored, start)
10533            } else {
10534                self.snapshot.files(self.include_ignored, start)
10535            },
10536        }
10537    }
10538}
10539
10540pub struct PathMatchCandidateSetIter<'a> {
10541    traversal: Traversal<'a>,
10542}
10543
10544impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
10545    type Item = fuzzy::PathMatchCandidate<'a>;
10546
10547    fn next(&mut self) -> Option<Self::Item> {
10548        self.traversal.next().map(|entry| match entry.kind {
10549            EntryKind::Dir => fuzzy::PathMatchCandidate {
10550                path: &entry.path,
10551                char_bag: CharBag::from_iter(entry.path.to_string_lossy().to_lowercase().chars()),
10552            },
10553            EntryKind::File(char_bag) => fuzzy::PathMatchCandidate {
10554                path: &entry.path,
10555                char_bag,
10556            },
10557            EntryKind::UnloadedDir | EntryKind::PendingDir => unreachable!(),
10558        })
10559    }
10560}
10561
10562impl EventEmitter<Event> for Project {}
10563
10564impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
10565    fn into(self) -> SettingsLocation<'a> {
10566        SettingsLocation {
10567            worktree_id: self.worktree_id.to_usize(),
10568            path: self.path.as_ref(),
10569        }
10570    }
10571}
10572
10573impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
10574    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
10575        Self {
10576            worktree_id,
10577            path: path.as_ref().into(),
10578        }
10579    }
10580}
10581
10582struct ProjectLspAdapterDelegate {
10583    project: WeakModel<Project>,
10584    worktree: worktree::Snapshot,
10585    fs: Arc<dyn Fs>,
10586    http_client: Arc<dyn HttpClient>,
10587    language_registry: Arc<LanguageRegistry>,
10588    shell_env: Mutex<Option<HashMap<String, String>>>,
10589}
10590
10591impl ProjectLspAdapterDelegate {
10592    fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
10593        Arc::new(Self {
10594            project: cx.weak_model(),
10595            worktree: worktree.read(cx).snapshot(),
10596            fs: project.fs.clone(),
10597            http_client: project.client.http_client(),
10598            language_registry: project.languages.clone(),
10599            shell_env: Default::default(),
10600        })
10601    }
10602
10603    async fn load_shell_env(&self) {
10604        let worktree_abs_path = self.worktree.abs_path();
10605        let shell_env = load_shell_environment(&worktree_abs_path)
10606            .await
10607            .with_context(|| {
10608                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
10609            })
10610            .log_err()
10611            .unwrap_or_default();
10612        *self.shell_env.lock() = Some(shell_env);
10613    }
10614}
10615
10616#[async_trait]
10617impl LspAdapterDelegate for ProjectLspAdapterDelegate {
10618    fn show_notification(&self, message: &str, cx: &mut AppContext) {
10619        self.project
10620            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
10621            .ok();
10622    }
10623
10624    fn http_client(&self) -> Arc<dyn HttpClient> {
10625        self.http_client.clone()
10626    }
10627
10628    fn worktree_id(&self) -> u64 {
10629        self.worktree.id().to_proto()
10630    }
10631
10632    fn worktree_root_path(&self) -> &Path {
10633        self.worktree.abs_path().as_ref()
10634    }
10635
10636    async fn shell_env(&self) -> HashMap<String, String> {
10637        self.load_shell_env().await;
10638        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
10639    }
10640
10641    #[cfg(not(target_os = "windows"))]
10642    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10643        let worktree_abs_path = self.worktree.abs_path();
10644        self.load_shell_env().await;
10645        let shell_path = self
10646            .shell_env
10647            .lock()
10648            .as_ref()
10649            .and_then(|shell_env| shell_env.get("PATH").cloned());
10650        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
10651    }
10652
10653    #[cfg(target_os = "windows")]
10654    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10655        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10656        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10657        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10658        which::which(command).ok()
10659    }
10660
10661    fn update_status(
10662        &self,
10663        server_name: LanguageServerName,
10664        status: language::LanguageServerBinaryStatus,
10665    ) {
10666        self.language_registry
10667            .update_lsp_status(server_name, status);
10668    }
10669
10670    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10671        if self.worktree.entry_for_path(&path).is_none() {
10672            return Err(anyhow!("no such path {path:?}"));
10673        }
10674        let path = self.worktree.absolutize(path.as_ref())?;
10675        let content = self.fs.load(&path).await?;
10676        Ok(content)
10677    }
10678}
10679
10680fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10681    proto::Symbol {
10682        language_server_name: symbol.language_server_name.0.to_string(),
10683        source_worktree_id: symbol.source_worktree_id.to_proto(),
10684        worktree_id: symbol.path.worktree_id.to_proto(),
10685        path: symbol.path.path.to_string_lossy().to_string(),
10686        name: symbol.name.clone(),
10687        kind: unsafe { mem::transmute(symbol.kind) },
10688        start: Some(proto::PointUtf16 {
10689            row: symbol.range.start.0.row,
10690            column: symbol.range.start.0.column,
10691        }),
10692        end: Some(proto::PointUtf16 {
10693            row: symbol.range.end.0.row,
10694            column: symbol.range.end.0.column,
10695        }),
10696        signature: symbol.signature.to_vec(),
10697    }
10698}
10699
10700fn relativize_path(base: &Path, path: &Path) -> PathBuf {
10701    let mut path_components = path.components();
10702    let mut base_components = base.components();
10703    let mut components: Vec<Component> = Vec::new();
10704    loop {
10705        match (path_components.next(), base_components.next()) {
10706            (None, None) => break,
10707            (Some(a), None) => {
10708                components.push(a);
10709                components.extend(path_components.by_ref());
10710                break;
10711            }
10712            (None, _) => components.push(Component::ParentDir),
10713            (Some(a), Some(b)) if components.is_empty() && a == b => (),
10714            (Some(a), Some(Component::CurDir)) => components.push(a),
10715            (Some(a), Some(_)) => {
10716                components.push(Component::ParentDir);
10717                for _ in base_components {
10718                    components.push(Component::ParentDir);
10719                }
10720                components.push(a);
10721                components.extend(path_components.by_ref());
10722                break;
10723            }
10724        }
10725    }
10726    components.iter().map(|c| c.as_os_str()).collect()
10727}
10728
10729fn resolve_path(base: &Path, path: &Path) -> PathBuf {
10730    let mut result = base.to_path_buf();
10731    for component in path.components() {
10732        match component {
10733            Component::ParentDir => {
10734                result.pop();
10735            }
10736            Component::CurDir => (),
10737            _ => result.push(component),
10738        }
10739    }
10740    result
10741}
10742
10743impl Item for Buffer {
10744    fn try_open(
10745        project: &Model<Project>,
10746        path: &ProjectPath,
10747        cx: &mut AppContext,
10748    ) -> Option<Task<Result<Model<Self>>>> {
10749        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
10750    }
10751
10752    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
10753        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
10754    }
10755
10756    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
10757        File::from_dyn(self.file()).map(|file| ProjectPath {
10758            worktree_id: file.worktree_id(cx),
10759            path: file.path().clone(),
10760        })
10761    }
10762}
10763
10764impl Completion {
10765    /// A key that can be used to sort completions when displaying
10766    /// them to the user.
10767    pub fn sort_key(&self) -> (usize, &str) {
10768        let kind_key = match self.lsp_completion.kind {
10769            Some(lsp::CompletionItemKind::KEYWORD) => 0,
10770            Some(lsp::CompletionItemKind::VARIABLE) => 1,
10771            _ => 2,
10772        };
10773        (kind_key, &self.label.text[self.label.filter_range.clone()])
10774    }
10775
10776    /// Whether this completion is a snippet.
10777    pub fn is_snippet(&self) -> bool {
10778        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
10779    }
10780}
10781
10782async fn wait_for_loading_buffer(
10783    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
10784) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
10785    loop {
10786        if let Some(result) = receiver.borrow().as_ref() {
10787            match result {
10788                Ok(buffer) => return Ok(buffer.to_owned()),
10789                Err(e) => return Err(e.to_owned()),
10790            }
10791        }
10792        receiver.next().await;
10793    }
10794}
10795
10796fn include_text(server: &lsp::LanguageServer) -> bool {
10797    server
10798        .capabilities()
10799        .text_document_sync
10800        .as_ref()
10801        .and_then(|sync| match sync {
10802            lsp::TextDocumentSyncCapability::Kind(_) => None,
10803            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
10804        })
10805        .and_then(|save_options| match save_options {
10806            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
10807            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
10808        })
10809        .unwrap_or(false)
10810}
10811
10812async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
10813    let marker = "ZED_SHELL_START";
10814    let shell = env::var("SHELL").context(
10815        "SHELL environment variable is not assigned so we can't source login environment variables",
10816    )?;
10817
10818    // What we're doing here is to spawn a shell and then `cd` into
10819    // the project directory to get the env in there as if the user
10820    // `cd`'d into it. We do that because tools like direnv, asdf, ...
10821    // hook into `cd` and only set up the env after that.
10822    //
10823    // In certain shells we need to execute additional_command in order to
10824    // trigger the behavior of direnv, etc.
10825    //
10826    //
10827    // The `exit 0` is the result of hours of debugging, trying to find out
10828    // why running this command here, without `exit 0`, would mess
10829    // up signal process for our process so that `ctrl-c` doesn't work
10830    // anymore.
10831    //
10832    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
10833    // do that, but it does, and `exit 0` helps.
10834    let additional_command = PathBuf::from(&shell)
10835        .file_name()
10836        .and_then(|f| f.to_str())
10837        .and_then(|shell| match shell {
10838            "fish" => Some("emit fish_prompt;"),
10839            _ => None,
10840        });
10841
10842    let command = format!(
10843        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
10844        dir.display(),
10845        additional_command.unwrap_or("")
10846    );
10847
10848    let output = smol::process::Command::new(&shell)
10849        .args(["-i", "-c", &command])
10850        .output()
10851        .await
10852        .context("failed to spawn login shell to source login environment variables")?;
10853
10854    anyhow::ensure!(
10855        output.status.success(),
10856        "login shell exited with error {:?}",
10857        output.status
10858    );
10859
10860    let stdout = String::from_utf8_lossy(&output.stdout);
10861    let env_output_start = stdout.find(marker).ok_or_else(|| {
10862        anyhow!(
10863            "failed to parse output of `env` command in login shell: {}",
10864            stdout
10865        )
10866    })?;
10867
10868    let mut parsed_env = HashMap::default();
10869    let env_output = &stdout[env_output_start + marker.len()..];
10870
10871    parse_env_output(env_output, |key, value| {
10872        parsed_env.insert(key, value);
10873    });
10874
10875    Ok(parsed_env)
10876}
10877
10878fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
10879    let entries = blame
10880        .entries
10881        .into_iter()
10882        .map(|entry| proto::BlameEntry {
10883            sha: entry.sha.as_bytes().into(),
10884            start_line: entry.range.start,
10885            end_line: entry.range.end,
10886            original_line_number: entry.original_line_number,
10887            author: entry.author.clone(),
10888            author_mail: entry.author_mail.clone(),
10889            author_time: entry.author_time,
10890            author_tz: entry.author_tz.clone(),
10891            committer: entry.committer.clone(),
10892            committer_mail: entry.committer_mail.clone(),
10893            committer_time: entry.committer_time,
10894            committer_tz: entry.committer_tz.clone(),
10895            summary: entry.summary.clone(),
10896            previous: entry.previous.clone(),
10897            filename: entry.filename.clone(),
10898        })
10899        .collect::<Vec<_>>();
10900
10901    let messages = blame
10902        .messages
10903        .into_iter()
10904        .map(|(oid, message)| proto::CommitMessage {
10905            oid: oid.as_bytes().into(),
10906            message,
10907        })
10908        .collect::<Vec<_>>();
10909
10910    let permalinks = blame
10911        .permalinks
10912        .into_iter()
10913        .map(|(oid, url)| proto::CommitPermalink {
10914            oid: oid.as_bytes().into(),
10915            permalink: url.to_string(),
10916        })
10917        .collect::<Vec<_>>();
10918
10919    proto::BlameBufferResponse {
10920        entries,
10921        messages,
10922        permalinks,
10923        remote_url: blame.remote_url,
10924    }
10925}
10926
10927fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
10928    let entries = response
10929        .entries
10930        .into_iter()
10931        .filter_map(|entry| {
10932            Some(git::blame::BlameEntry {
10933                sha: git::Oid::from_bytes(&entry.sha).ok()?,
10934                range: entry.start_line..entry.end_line,
10935                original_line_number: entry.original_line_number,
10936                committer: entry.committer,
10937                committer_time: entry.committer_time,
10938                committer_tz: entry.committer_tz,
10939                committer_mail: entry.committer_mail,
10940                author: entry.author,
10941                author_mail: entry.author_mail,
10942                author_time: entry.author_time,
10943                author_tz: entry.author_tz,
10944                summary: entry.summary,
10945                previous: entry.previous,
10946                filename: entry.filename,
10947            })
10948        })
10949        .collect::<Vec<_>>();
10950
10951    let messages = response
10952        .messages
10953        .into_iter()
10954        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
10955        .collect::<HashMap<_, _>>();
10956
10957    let permalinks = response
10958        .permalinks
10959        .into_iter()
10960        .filter_map(|permalink| {
10961            Some((
10962                git::Oid::from_bytes(&permalink.oid).ok()?,
10963                Url::from_str(&permalink.permalink).ok()?,
10964            ))
10965        })
10966        .collect::<HashMap<_, _>>();
10967
10968    Blame {
10969        entries,
10970        permalinks,
10971        messages,
10972        remote_url: response.remote_url,
10973    }
10974}
10975
10976fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10977    hover
10978        .contents
10979        .retain(|hover_block| !hover_block.text.trim().is_empty());
10980    if hover.contents.is_empty() {
10981        None
10982    } else {
10983        Some(hover)
10984    }
10985}
10986
10987#[derive(Debug)]
10988pub struct NoRepositoryError {}
10989
10990impl std::fmt::Display for NoRepositoryError {
10991    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10992        write!(f, "no git repository for worktree found")
10993    }
10994}
10995
10996impl std::error::Error for NoRepositoryError {}