project.rs

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