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        this: 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 = this.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 = this.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 this = this.clone();
 3272                move |params, mut cx| {
 3273                    let this = this.clone();
 3274                    async move {
 3275                        for reg in params.registrations {
 3276                            if reg.method == "workspace/didChangeWatchedFiles" {
 3277                                if let Some(options) = reg.register_options {
 3278                                    let options = serde_json::from_value(options)?;
 3279                                    this.update(&mut cx, |this, cx| {
 3280                                        this.on_lsp_did_change_watched_files(
 3281                                            server_id, &reg.id, options, cx,
 3282                                        );
 3283                                    })?;
 3284                                }
 3285                            }
 3286                        }
 3287                        Ok(())
 3288                    }
 3289                }
 3290            })
 3291            .detach();
 3292
 3293        language_server
 3294            .on_request::<lsp::request::UnregisterCapability, _, _>({
 3295                let this = this.clone();
 3296                move |params, mut cx| {
 3297                    let this = this.clone();
 3298                    async move {
 3299                        for unreg in params.unregisterations.iter() {
 3300                            if unreg.method == "workspace/didChangeWatchedFiles" {
 3301                                this.update(&mut cx, |this, cx| {
 3302                                    this.on_lsp_unregister_did_change_watched_files(
 3303                                        server_id, &unreg.id, cx,
 3304                                    );
 3305                                })?;
 3306                            }
 3307                        }
 3308                        Ok(())
 3309                    }
 3310                }
 3311            })
 3312            .detach();
 3313
 3314        language_server
 3315            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
 3316                let adapter = adapter.clone();
 3317                let this = this.clone();
 3318                move |params, cx| {
 3319                    Self::on_lsp_workspace_edit(
 3320                        this.clone(),
 3321                        params,
 3322                        server_id,
 3323                        adapter.clone(),
 3324                        cx,
 3325                    )
 3326                }
 3327            })
 3328            .detach();
 3329
 3330        language_server
 3331            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
 3332                let this = this.clone();
 3333                move |(), mut cx| {
 3334                    let this = this.clone();
 3335                    async move {
 3336                        this.update(&mut cx, |project, cx| {
 3337                            cx.emit(Event::RefreshInlayHints);
 3338                            project.remote_id().map(|project_id| {
 3339                                project.client.send(proto::RefreshInlayHints { project_id })
 3340                            })
 3341                        })?
 3342                        .transpose()?;
 3343                        Ok(())
 3344                    }
 3345                }
 3346            })
 3347            .detach();
 3348
 3349        language_server
 3350            .on_request::<lsp::request::ShowMessageRequest, _, _>({
 3351                let this = this.clone();
 3352                let name = name.to_string();
 3353                move |params, mut cx| {
 3354                    let this = this.clone();
 3355                    let name = name.to_string();
 3356                    async move {
 3357                        let actions = params.actions.unwrap_or_default();
 3358                        let (tx, mut rx) = smol::channel::bounded(1);
 3359                        let request = LanguageServerPromptRequest {
 3360                            level: match params.typ {
 3361                                lsp::MessageType::ERROR => PromptLevel::Critical,
 3362                                lsp::MessageType::WARNING => PromptLevel::Warning,
 3363                                _ => PromptLevel::Info,
 3364                            },
 3365                            message: params.message,
 3366                            actions,
 3367                            response_channel: tx,
 3368                            lsp_name: name.clone(),
 3369                        };
 3370
 3371                        if let Ok(_) = this.update(&mut cx, |_, cx| {
 3372                            cx.emit(Event::LanguageServerPrompt(request));
 3373                        }) {
 3374                            let response = rx.next().await;
 3375
 3376                            Ok(response)
 3377                        } else {
 3378                            Ok(None)
 3379                        }
 3380                    }
 3381                }
 3382            })
 3383            .detach();
 3384
 3385        let disk_based_diagnostics_progress_token =
 3386            adapter.disk_based_diagnostics_progress_token.clone();
 3387
 3388        language_server
 3389            .on_notification::<ServerStatus, _>({
 3390                let this = this.clone();
 3391                let name = name.to_string();
 3392                move |params, mut cx| {
 3393                    let this = this.clone();
 3394                    let name = name.to_string();
 3395                    if let Some(ref message) = params.message {
 3396                        let message = message.trim();
 3397                        if !message.is_empty() {
 3398                            let formatted_message = format!(
 3399                                "Language server {name} (id {server_id}) status update: {message}"
 3400                            );
 3401                            match params.health {
 3402                                ServerHealthStatus::Ok => log::info!("{}", formatted_message),
 3403                                ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
 3404                                ServerHealthStatus::Error => {
 3405                                    log::error!("{}", formatted_message);
 3406                                    let (tx, _rx) = smol::channel::bounded(1);
 3407                                    let request = LanguageServerPromptRequest {
 3408                                        level: PromptLevel::Critical,
 3409                                        message: params.message.unwrap_or_default(),
 3410                                        actions: Vec::new(),
 3411                                        response_channel: tx,
 3412                                        lsp_name: name.clone(),
 3413                                    };
 3414                                    let _ = this
 3415                                        .update(&mut cx, |_, cx| {
 3416                                            cx.emit(Event::LanguageServerPrompt(request));
 3417                                        })
 3418                                        .ok();
 3419                                }
 3420                                ServerHealthStatus::Other(status) => {
 3421                                    log::info!(
 3422                                        "Unknown server health: {status}\n{formatted_message}"
 3423                                    )
 3424                                }
 3425                            }
 3426                        }
 3427                    }
 3428                }
 3429            })
 3430            .detach();
 3431        language_server
 3432            .on_notification::<lsp::notification::ShowMessage, _>({
 3433                let this = this.clone();
 3434                let name = name.to_string();
 3435                move |params, mut cx| {
 3436                    let this = this.clone();
 3437                    let name = name.to_string();
 3438
 3439                    let (tx, _) = smol::channel::bounded(1);
 3440                    let request = LanguageServerPromptRequest {
 3441                        level: match params.typ {
 3442                            lsp::MessageType::ERROR => PromptLevel::Critical,
 3443                            lsp::MessageType::WARNING => PromptLevel::Warning,
 3444                            _ => PromptLevel::Info,
 3445                        },
 3446                        message: params.message,
 3447                        actions: vec![],
 3448                        response_channel: tx,
 3449                        lsp_name: name.clone(),
 3450                    };
 3451
 3452                    let _ = this.update(&mut cx, |_, cx| {
 3453                        cx.emit(Event::LanguageServerPrompt(request));
 3454                    });
 3455                }
 3456            })
 3457            .detach();
 3458        language_server
 3459            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
 3460                if let Some(this) = this.upgrade() {
 3461                    this.update(&mut cx, |this, cx| {
 3462                        this.on_lsp_progress(
 3463                            params,
 3464                            server_id,
 3465                            disk_based_diagnostics_progress_token.clone(),
 3466                            cx,
 3467                        );
 3468                    })
 3469                    .ok();
 3470                }
 3471            })
 3472            .detach();
 3473
 3474        match (&mut initialization_options, override_options) {
 3475            (Some(initialization_options), Some(override_options)) => {
 3476                merge_json_value_into(override_options, initialization_options);
 3477            }
 3478            (None, override_options) => initialization_options = override_options,
 3479            _ => {}
 3480        }
 3481        let language_server = cx
 3482            .update(|cx| language_server.initialize(initialization_options, cx))?
 3483            .await?;
 3484
 3485        language_server
 3486            .notify::<lsp::notification::DidChangeConfiguration>(
 3487                lsp::DidChangeConfigurationParams {
 3488                    settings: workspace_config,
 3489                },
 3490            )
 3491            .ok();
 3492
 3493        Ok(language_server)
 3494    }
 3495
 3496    fn insert_newly_running_language_server(
 3497        &mut self,
 3498        language: Arc<Language>,
 3499        adapter: Arc<CachedLspAdapter>,
 3500        language_server: Arc<LanguageServer>,
 3501        server_id: LanguageServerId,
 3502        key: (WorktreeId, LanguageServerName),
 3503        cx: &mut ModelContext<Self>,
 3504    ) -> Result<()> {
 3505        // If the language server for this key doesn't match the server id, don't store the
 3506        // server. Which will cause it to be dropped, killing the process
 3507        if self
 3508            .language_server_ids
 3509            .get(&key)
 3510            .map(|id| id != &server_id)
 3511            .unwrap_or(false)
 3512        {
 3513            return Ok(());
 3514        }
 3515
 3516        // Update language_servers collection with Running variant of LanguageServerState
 3517        // indicating that the server is up and running and ready
 3518        self.language_servers.insert(
 3519            server_id,
 3520            LanguageServerState::Running {
 3521                adapter: adapter.clone(),
 3522                language: language.clone(),
 3523                server: language_server.clone(),
 3524                simulate_disk_based_diagnostics_completion: None,
 3525            },
 3526        );
 3527
 3528        self.language_server_statuses.insert(
 3529            server_id,
 3530            LanguageServerStatus {
 3531                name: language_server.name().to_string(),
 3532                pending_work: Default::default(),
 3533                has_pending_diagnostic_updates: false,
 3534                progress_tokens: Default::default(),
 3535            },
 3536        );
 3537
 3538        cx.emit(Event::LanguageServerAdded(server_id));
 3539
 3540        if let Some(project_id) = self.remote_id() {
 3541            self.client.send(proto::StartLanguageServer {
 3542                project_id,
 3543                server: Some(proto::LanguageServer {
 3544                    id: server_id.0 as u64,
 3545                    name: language_server.name().to_string(),
 3546                }),
 3547            })?;
 3548        }
 3549
 3550        // Tell the language server about every open buffer in the worktree that matches the language.
 3551        self.buffer_store.update(cx, |buffer_store, cx| {
 3552            for buffer_handle in buffer_store.buffers() {
 3553                let buffer = buffer_handle.read(cx);
 3554                let file = match File::from_dyn(buffer.file()) {
 3555                    Some(file) => file,
 3556                    None => continue,
 3557                };
 3558                let language = match buffer.language() {
 3559                    Some(language) => language,
 3560                    None => continue,
 3561                };
 3562
 3563                if file.worktree.read(cx).id() != key.0
 3564                    || !self
 3565                        .languages
 3566                        .lsp_adapters(&language)
 3567                        .iter()
 3568                        .any(|a| a.name == key.1)
 3569                {
 3570                    continue;
 3571                }
 3572
 3573                let file = match file.as_local() {
 3574                    Some(file) => file,
 3575                    None => continue,
 3576                };
 3577
 3578                let versions = self
 3579                    .buffer_snapshots
 3580                    .entry(buffer.remote_id())
 3581                    .or_default()
 3582                    .entry(server_id)
 3583                    .or_insert_with(|| {
 3584                        vec![LspBufferSnapshot {
 3585                            version: 0,
 3586                            snapshot: buffer.text_snapshot(),
 3587                        }]
 3588                    });
 3589
 3590                let snapshot = versions.last().unwrap();
 3591                let version = snapshot.version;
 3592                let initial_snapshot = &snapshot.snapshot;
 3593                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 3594                language_server.notify::<lsp::notification::DidOpenTextDocument>(
 3595                    lsp::DidOpenTextDocumentParams {
 3596                        text_document: lsp::TextDocumentItem::new(
 3597                            uri,
 3598                            adapter.language_id(&language),
 3599                            version,
 3600                            initial_snapshot.text(),
 3601                        ),
 3602                    },
 3603                )?;
 3604
 3605                buffer_handle.update(cx, |buffer, cx| {
 3606                    buffer.set_completion_triggers(
 3607                        language_server
 3608                            .capabilities()
 3609                            .completion_provider
 3610                            .as_ref()
 3611                            .and_then(|provider| provider.trigger_characters.clone())
 3612                            .unwrap_or_default(),
 3613                        cx,
 3614                    )
 3615                });
 3616            }
 3617            anyhow::Ok(())
 3618        })?;
 3619
 3620        cx.notify();
 3621        Ok(())
 3622    }
 3623
 3624    // Returns a list of all of the worktrees which no longer have a language server and the root path
 3625    // for the stopped server
 3626    fn stop_language_server(
 3627        &mut self,
 3628        worktree_id: WorktreeId,
 3629        adapter_name: LanguageServerName,
 3630        cx: &mut ModelContext<Self>,
 3631    ) -> Task<Vec<WorktreeId>> {
 3632        let key = (worktree_id, adapter_name);
 3633        if let Some(server_id) = self.language_server_ids.remove(&key) {
 3634            let name = key.1 .0;
 3635            log::info!("stopping language server {name}");
 3636
 3637            // Remove other entries for this language server as well
 3638            let mut orphaned_worktrees = vec![worktree_id];
 3639            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
 3640            for other_key in other_keys {
 3641                if self.language_server_ids.get(&other_key) == Some(&server_id) {
 3642                    self.language_server_ids.remove(&other_key);
 3643                    orphaned_worktrees.push(other_key.0);
 3644                }
 3645            }
 3646
 3647            self.buffer_store.update(cx, |buffer_store, cx| {
 3648                for buffer in buffer_store.buffers() {
 3649                    buffer.update(cx, |buffer, cx| {
 3650                        buffer.update_diagnostics(server_id, Default::default(), cx);
 3651                    });
 3652                }
 3653            });
 3654
 3655            let project_id = self.remote_id();
 3656            for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
 3657                summaries.retain(|path, summaries_by_server_id| {
 3658                    if summaries_by_server_id.remove(&server_id).is_some() {
 3659                        if let Some(project_id) = project_id {
 3660                            self.client
 3661                                .send(proto::UpdateDiagnosticSummary {
 3662                                    project_id,
 3663                                    worktree_id: worktree_id.to_proto(),
 3664                                    summary: Some(proto::DiagnosticSummary {
 3665                                        path: path.to_string_lossy().to_string(),
 3666                                        language_server_id: server_id.0 as u64,
 3667                                        error_count: 0,
 3668                                        warning_count: 0,
 3669                                    }),
 3670                                })
 3671                                .log_err();
 3672                        }
 3673                        !summaries_by_server_id.is_empty()
 3674                    } else {
 3675                        true
 3676                    }
 3677                });
 3678            }
 3679
 3680            for diagnostics in self.diagnostics.values_mut() {
 3681                diagnostics.retain(|_, diagnostics_by_server_id| {
 3682                    if let Ok(ix) =
 3683                        diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0)
 3684                    {
 3685                        diagnostics_by_server_id.remove(ix);
 3686                        !diagnostics_by_server_id.is_empty()
 3687                    } else {
 3688                        true
 3689                    }
 3690                });
 3691            }
 3692
 3693            self.language_server_watched_paths.remove(&server_id);
 3694            self.language_server_statuses.remove(&server_id);
 3695            cx.notify();
 3696
 3697            let server_state = self.language_servers.remove(&server_id);
 3698            cx.emit(Event::LanguageServerRemoved(server_id));
 3699            cx.spawn(move |_, cx| async move {
 3700                Self::shutdown_language_server(server_state, name, cx).await;
 3701                orphaned_worktrees
 3702            })
 3703        } else {
 3704            Task::ready(Vec::new())
 3705        }
 3706    }
 3707
 3708    async fn shutdown_language_server(
 3709        server_state: Option<LanguageServerState>,
 3710        name: Arc<str>,
 3711        cx: AsyncAppContext,
 3712    ) {
 3713        let server = match server_state {
 3714            Some(LanguageServerState::Starting(task)) => {
 3715                let mut timer = cx
 3716                    .background_executor()
 3717                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
 3718                    .fuse();
 3719
 3720                select! {
 3721                    server = task.fuse() => server,
 3722                    _ = timer => {
 3723                        log::info!(
 3724                            "timeout waiting for language server {} to finish launching before stopping",
 3725                            name
 3726                        );
 3727                        None
 3728                    },
 3729                }
 3730            }
 3731
 3732            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3733
 3734            None => None,
 3735        };
 3736
 3737        if let Some(server) = server {
 3738            if let Some(shutdown) = server.shutdown() {
 3739                shutdown.await;
 3740            }
 3741        }
 3742    }
 3743
 3744    async fn handle_restart_language_servers(
 3745        project: Model<Self>,
 3746        envelope: TypedEnvelope<proto::RestartLanguageServers>,
 3747        mut cx: AsyncAppContext,
 3748    ) -> Result<proto::Ack> {
 3749        project.update(&mut cx, |project, cx| {
 3750            let buffers: Vec<_> = envelope
 3751                .payload
 3752                .buffer_ids
 3753                .into_iter()
 3754                .flat_map(|buffer_id| {
 3755                    project.buffer_for_id(BufferId::new(buffer_id).log_err()?, cx)
 3756                })
 3757                .collect();
 3758            project.restart_language_servers_for_buffers(buffers, cx)
 3759        })?;
 3760
 3761        Ok(proto::Ack {})
 3762    }
 3763
 3764    pub fn restart_language_servers_for_buffers(
 3765        &mut self,
 3766        buffers: impl IntoIterator<Item = Model<Buffer>>,
 3767        cx: &mut ModelContext<Self>,
 3768    ) {
 3769        if self.is_remote() {
 3770            let request = self.client.request(proto::RestartLanguageServers {
 3771                project_id: self.remote_id().unwrap(),
 3772                buffer_ids: buffers
 3773                    .into_iter()
 3774                    .map(|b| b.read(cx).remote_id().to_proto())
 3775                    .collect(),
 3776            });
 3777            cx.background_executor()
 3778                .spawn(request)
 3779                .detach_and_log_err(cx);
 3780            return;
 3781        }
 3782
 3783        #[allow(clippy::mutable_key_type)]
 3784        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
 3785            .into_iter()
 3786            .filter_map(|buffer| {
 3787                let buffer = buffer.read(cx);
 3788                let file = buffer.file()?;
 3789                let worktree = File::from_dyn(Some(file))?.worktree.clone();
 3790                let language = self
 3791                    .languages
 3792                    .language_for_file(file, Some(buffer.as_rope()), cx)
 3793                    .now_or_never()?
 3794                    .ok()?;
 3795                Some((worktree, language))
 3796            })
 3797            .collect();
 3798        for (worktree, language) in language_server_lookup_info {
 3799            self.restart_language_servers(worktree, language, cx);
 3800        }
 3801    }
 3802
 3803    fn restart_language_servers(
 3804        &mut self,
 3805        worktree: Model<Worktree>,
 3806        language: Arc<Language>,
 3807        cx: &mut ModelContext<Self>,
 3808    ) {
 3809        let worktree_id = worktree.read(cx).id();
 3810
 3811        let stop_tasks = self
 3812            .languages
 3813            .clone()
 3814            .lsp_adapters(&language)
 3815            .iter()
 3816            .map(|adapter| {
 3817                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
 3818                (stop_task, adapter.name.clone())
 3819            })
 3820            .collect::<Vec<_>>();
 3821        if stop_tasks.is_empty() {
 3822            return;
 3823        }
 3824
 3825        cx.spawn(move |this, mut cx| async move {
 3826            // For each stopped language server, record all of the worktrees with which
 3827            // it was associated.
 3828            let mut affected_worktrees = Vec::new();
 3829            for (stop_task, language_server_name) in stop_tasks {
 3830                for affected_worktree_id in stop_task.await {
 3831                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
 3832                }
 3833            }
 3834
 3835            this.update(&mut cx, |this, cx| {
 3836                // Restart the language server for the given worktree.
 3837                this.start_language_servers(&worktree, language.clone(), cx);
 3838
 3839                // Lookup new server ids and set them for each of the orphaned worktrees
 3840                for (affected_worktree_id, language_server_name) in affected_worktrees {
 3841                    if let Some(new_server_id) = this
 3842                        .language_server_ids
 3843                        .get(&(worktree_id, language_server_name.clone()))
 3844                        .cloned()
 3845                    {
 3846                        this.language_server_ids
 3847                            .insert((affected_worktree_id, language_server_name), new_server_id);
 3848                    }
 3849                }
 3850            })
 3851            .ok();
 3852        })
 3853        .detach();
 3854    }
 3855
 3856    pub fn cancel_language_server_work_for_buffers(
 3857        &mut self,
 3858        buffers: impl IntoIterator<Item = Model<Buffer>>,
 3859        cx: &mut ModelContext<Self>,
 3860    ) {
 3861        let servers = buffers
 3862            .into_iter()
 3863            .flat_map(|buffer| {
 3864                self.language_server_ids_for_buffer(buffer.read(cx), cx)
 3865                    .into_iter()
 3866            })
 3867            .collect::<HashSet<_>>();
 3868
 3869        for server_id in servers {
 3870            self.cancel_language_server_work(server_id, None, cx);
 3871        }
 3872    }
 3873
 3874    pub fn cancel_language_server_work(
 3875        &mut self,
 3876        server_id: LanguageServerId,
 3877        token_to_cancel: Option<String>,
 3878        _cx: &mut ModelContext<Self>,
 3879    ) {
 3880        let status = self.language_server_statuses.get(&server_id);
 3881        let server = self.language_servers.get(&server_id);
 3882        if let Some((server, status)) = server.zip(status) {
 3883            if let LanguageServerState::Running { server, .. } = server {
 3884                for (token, progress) in &status.pending_work {
 3885                    if let Some(token_to_cancel) = token_to_cancel.as_ref() {
 3886                        if token != token_to_cancel {
 3887                            continue;
 3888                        }
 3889                    }
 3890                    if progress.is_cancellable {
 3891                        server
 3892                            .notify::<lsp::notification::WorkDoneProgressCancel>(
 3893                                WorkDoneProgressCancelParams {
 3894                                    token: lsp::NumberOrString::String(token.clone()),
 3895                                },
 3896                            )
 3897                            .ok();
 3898                    }
 3899                }
 3900            }
 3901        }
 3902    }
 3903
 3904    fn check_errored_server(
 3905        language: Arc<Language>,
 3906        adapter: Arc<CachedLspAdapter>,
 3907        server_id: LanguageServerId,
 3908        installation_test_binary: Option<LanguageServerBinary>,
 3909        cx: &mut ModelContext<Self>,
 3910    ) {
 3911        if !adapter.can_be_reinstalled() {
 3912            log::info!(
 3913                "Validation check requested for {:?} but it cannot be reinstalled",
 3914                adapter.name.0
 3915            );
 3916            return;
 3917        }
 3918
 3919        cx.spawn(move |this, mut cx| async move {
 3920            log::info!("About to spawn test binary");
 3921
 3922            // A lack of test binary counts as a failure
 3923            let process = installation_test_binary.and_then(|binary| {
 3924                smol::process::Command::new(&binary.path)
 3925                    .current_dir(&binary.path)
 3926                    .args(binary.arguments)
 3927                    .stdin(Stdio::piped())
 3928                    .stdout(Stdio::piped())
 3929                    .stderr(Stdio::inherit())
 3930                    .kill_on_drop(true)
 3931                    .spawn()
 3932                    .ok()
 3933            });
 3934
 3935            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
 3936            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
 3937
 3938            let mut errored = false;
 3939            if let Some(mut process) = process {
 3940                futures::select! {
 3941                    status = process.status().fuse() => match status {
 3942                        Ok(status) => errored = !status.success(),
 3943                        Err(_) => errored = true,
 3944                    },
 3945
 3946                    _ = timeout => {
 3947                        log::info!("test binary time-ed out, this counts as a success");
 3948                        _ = process.kill();
 3949                    }
 3950                }
 3951            } else {
 3952                log::warn!("test binary failed to launch");
 3953                errored = true;
 3954            }
 3955
 3956            if errored {
 3957                log::warn!("test binary check failed");
 3958                let task = this
 3959                    .update(&mut cx, move |this, cx| {
 3960                        this.reinstall_language_server(language, adapter, server_id, cx)
 3961                    })
 3962                    .ok()
 3963                    .flatten();
 3964
 3965                if let Some(task) = task {
 3966                    task.await;
 3967                }
 3968            }
 3969        })
 3970        .detach();
 3971    }
 3972
 3973    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
 3974        self.buffer_ordered_messages_tx
 3975            .unbounded_send(message)
 3976            .map_err(|e| anyhow!(e))
 3977    }
 3978
 3979    fn on_lsp_progress(
 3980        &mut self,
 3981        progress: lsp::ProgressParams,
 3982        language_server_id: LanguageServerId,
 3983        disk_based_diagnostics_progress_token: Option<String>,
 3984        cx: &mut ModelContext<Self>,
 3985    ) {
 3986        let token = match progress.token {
 3987            lsp::NumberOrString::String(token) => token,
 3988            lsp::NumberOrString::Number(token) => {
 3989                log::info!("skipping numeric progress token {}", token);
 3990                return;
 3991            }
 3992        };
 3993
 3994        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
 3995        let language_server_status =
 3996            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 3997                status
 3998            } else {
 3999                return;
 4000            };
 4001
 4002        if !language_server_status.progress_tokens.contains(&token) {
 4003            return;
 4004        }
 4005
 4006        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 4007            .as_ref()
 4008            .map_or(false, |disk_based_token| {
 4009                token.starts_with(disk_based_token)
 4010            });
 4011
 4012        match progress {
 4013            lsp::WorkDoneProgress::Begin(report) => {
 4014                if is_disk_based_diagnostics_progress {
 4015                    self.disk_based_diagnostics_started(language_server_id, cx);
 4016                }
 4017                self.on_lsp_work_start(
 4018                    language_server_id,
 4019                    token.clone(),
 4020                    LanguageServerProgress {
 4021                        title: Some(report.title),
 4022                        is_disk_based_diagnostics_progress,
 4023                        is_cancellable: report.cancellable.unwrap_or(false),
 4024                        message: report.message.clone(),
 4025                        percentage: report.percentage.map(|p| p as usize),
 4026                        last_update_at: cx.background_executor().now(),
 4027                    },
 4028                    cx,
 4029                );
 4030            }
 4031            lsp::WorkDoneProgress::Report(report) => {
 4032                if self.on_lsp_work_progress(
 4033                    language_server_id,
 4034                    token.clone(),
 4035                    LanguageServerProgress {
 4036                        title: None,
 4037                        is_disk_based_diagnostics_progress,
 4038                        is_cancellable: report.cancellable.unwrap_or(false),
 4039                        message: report.message.clone(),
 4040                        percentage: report.percentage.map(|p| p as usize),
 4041                        last_update_at: cx.background_executor().now(),
 4042                    },
 4043                    cx,
 4044                ) {
 4045                    self.enqueue_buffer_ordered_message(
 4046                        BufferOrderedMessage::LanguageServerUpdate {
 4047                            language_server_id,
 4048                            message: proto::update_language_server::Variant::WorkProgress(
 4049                                proto::LspWorkProgress {
 4050                                    token,
 4051                                    message: report.message,
 4052                                    percentage: report.percentage,
 4053                                },
 4054                            ),
 4055                        },
 4056                    )
 4057                    .ok();
 4058                }
 4059            }
 4060            lsp::WorkDoneProgress::End(_) => {
 4061                language_server_status.progress_tokens.remove(&token);
 4062                self.on_lsp_work_end(language_server_id, token.clone(), cx);
 4063                if is_disk_based_diagnostics_progress {
 4064                    self.disk_based_diagnostics_finished(language_server_id, cx);
 4065                }
 4066            }
 4067        }
 4068    }
 4069
 4070    fn on_lsp_work_start(
 4071        &mut self,
 4072        language_server_id: LanguageServerId,
 4073        token: String,
 4074        progress: LanguageServerProgress,
 4075        cx: &mut ModelContext<Self>,
 4076    ) {
 4077        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4078            status.pending_work.insert(token.clone(), progress.clone());
 4079            cx.notify();
 4080        }
 4081
 4082        if self.is_local() {
 4083            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4084                language_server_id,
 4085                message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
 4086                    token,
 4087                    title: progress.title,
 4088                    message: progress.message,
 4089                    percentage: progress.percentage.map(|p| p as u32),
 4090                }),
 4091            })
 4092            .ok();
 4093        }
 4094    }
 4095
 4096    fn on_lsp_work_progress(
 4097        &mut self,
 4098        language_server_id: LanguageServerId,
 4099        token: String,
 4100        progress: LanguageServerProgress,
 4101        cx: &mut ModelContext<Self>,
 4102    ) -> bool {
 4103        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4104            match status.pending_work.entry(token) {
 4105                btree_map::Entry::Vacant(entry) => {
 4106                    entry.insert(progress);
 4107                    cx.notify();
 4108                    return true;
 4109                }
 4110                btree_map::Entry::Occupied(mut entry) => {
 4111                    let entry = entry.get_mut();
 4112                    if (progress.last_update_at - entry.last_update_at)
 4113                        >= SERVER_PROGRESS_THROTTLE_TIMEOUT
 4114                    {
 4115                        entry.last_update_at = progress.last_update_at;
 4116                        if progress.message.is_some() {
 4117                            entry.message = progress.message;
 4118                        }
 4119                        if progress.percentage.is_some() {
 4120                            entry.percentage = progress.percentage;
 4121                        }
 4122                        cx.notify();
 4123                        return true;
 4124                    }
 4125                }
 4126            }
 4127        }
 4128
 4129        false
 4130    }
 4131
 4132    fn on_lsp_work_end(
 4133        &mut self,
 4134        language_server_id: LanguageServerId,
 4135        token: String,
 4136        cx: &mut ModelContext<Self>,
 4137    ) {
 4138        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4139            if let Some(work) = status.pending_work.remove(&token) {
 4140                if !work.is_disk_based_diagnostics_progress {
 4141                    cx.emit(Event::RefreshInlayHints);
 4142                }
 4143            }
 4144            cx.notify();
 4145        }
 4146
 4147        if self.is_local() {
 4148            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4149                language_server_id,
 4150                message: proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
 4151                    token,
 4152                }),
 4153            })
 4154            .ok();
 4155        }
 4156    }
 4157
 4158    fn on_lsp_did_change_watched_files(
 4159        &mut self,
 4160        language_server_id: LanguageServerId,
 4161        registration_id: &str,
 4162        params: DidChangeWatchedFilesRegistrationOptions,
 4163        cx: &mut ModelContext<Self>,
 4164    ) {
 4165        let registrations = self
 4166            .language_server_watcher_registrations
 4167            .entry(language_server_id)
 4168            .or_default();
 4169
 4170        registrations.insert(registration_id.to_string(), params.watchers);
 4171
 4172        self.rebuild_watched_paths(language_server_id, cx);
 4173    }
 4174
 4175    fn on_lsp_unregister_did_change_watched_files(
 4176        &mut self,
 4177        language_server_id: LanguageServerId,
 4178        registration_id: &str,
 4179        cx: &mut ModelContext<Self>,
 4180    ) {
 4181        let registrations = self
 4182            .language_server_watcher_registrations
 4183            .entry(language_server_id)
 4184            .or_default();
 4185
 4186        if registrations.remove(registration_id).is_some() {
 4187            log::info!(
 4188                "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
 4189                language_server_id,
 4190                registration_id
 4191            );
 4192        } else {
 4193            log::warn!(
 4194                "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
 4195                language_server_id,
 4196                registration_id
 4197            );
 4198        }
 4199
 4200        self.rebuild_watched_paths(language_server_id, cx);
 4201    }
 4202
 4203    fn rebuild_watched_paths(
 4204        &mut self,
 4205        language_server_id: LanguageServerId,
 4206        cx: &mut ModelContext<Self>,
 4207    ) {
 4208        let Some(watchers) = self
 4209            .language_server_watcher_registrations
 4210            .get(&language_server_id)
 4211        else {
 4212            return;
 4213        };
 4214
 4215        let watched_paths = self
 4216            .language_server_watched_paths
 4217            .entry(language_server_id)
 4218            .or_default();
 4219
 4220        let mut builders = HashMap::default();
 4221        for watcher in watchers.values().flatten() {
 4222            for worktree in &self.worktrees {
 4223                if let Some(worktree) = worktree.upgrade() {
 4224                    let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
 4225                        if let Some(abs_path) = tree.abs_path().to_str() {
 4226                            let relative_glob_pattern = match &watcher.glob_pattern {
 4227                                lsp::GlobPattern::String(s) => Some(
 4228                                    s.strip_prefix(abs_path)
 4229                                        .unwrap_or(s)
 4230                                        .strip_prefix(std::path::MAIN_SEPARATOR)
 4231                                        .unwrap_or(s),
 4232                                ),
 4233                                lsp::GlobPattern::Relative(rp) => {
 4234                                    let base_uri = match &rp.base_uri {
 4235                                        lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
 4236                                        lsp::OneOf::Right(base_uri) => base_uri,
 4237                                    };
 4238                                    base_uri.to_file_path().ok().and_then(|file_path| {
 4239                                        (file_path.to_str() == Some(abs_path))
 4240                                            .then_some(rp.pattern.as_str())
 4241                                    })
 4242                                }
 4243                            };
 4244                            if let Some(relative_glob_pattern) = relative_glob_pattern {
 4245                                let literal_prefix = glob_literal_prefix(relative_glob_pattern);
 4246                                tree.as_local_mut()
 4247                                    .unwrap()
 4248                                    .add_path_prefix_to_scan(Path::new(literal_prefix).into());
 4249                                if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
 4250                                    builders
 4251                                        .entry(tree.id())
 4252                                        .or_insert_with(|| GlobSetBuilder::new())
 4253                                        .add(glob);
 4254                                }
 4255                                return true;
 4256                            }
 4257                        }
 4258                        false
 4259                    });
 4260                    if glob_is_inside_worktree {
 4261                        break;
 4262                    }
 4263                }
 4264            }
 4265        }
 4266
 4267        watched_paths.clear();
 4268        for (worktree_id, builder) in builders {
 4269            if let Ok(globset) = builder.build() {
 4270                watched_paths.insert(worktree_id, globset);
 4271            }
 4272        }
 4273
 4274        cx.notify();
 4275    }
 4276
 4277    async fn on_lsp_workspace_edit(
 4278        this: WeakModel<Self>,
 4279        params: lsp::ApplyWorkspaceEditParams,
 4280        server_id: LanguageServerId,
 4281        adapter: Arc<CachedLspAdapter>,
 4282        mut cx: AsyncAppContext,
 4283    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
 4284        let this = this
 4285            .upgrade()
 4286            .ok_or_else(|| anyhow!("project project closed"))?;
 4287        let language_server = this
 4288            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
 4289            .ok_or_else(|| anyhow!("language server not found"))?;
 4290        let transaction = Self::deserialize_workspace_edit(
 4291            this.clone(),
 4292            params.edit,
 4293            true,
 4294            adapter.clone(),
 4295            language_server.clone(),
 4296            &mut cx,
 4297        )
 4298        .await
 4299        .log_err();
 4300        this.update(&mut cx, |this, _| {
 4301            if let Some(transaction) = transaction {
 4302                this.last_workspace_edits_by_language_server
 4303                    .insert(server_id, transaction);
 4304            }
 4305        })?;
 4306        Ok(lsp::ApplyWorkspaceEditResponse {
 4307            applied: true,
 4308            failed_change: None,
 4309            failure_reason: None,
 4310        })
 4311    }
 4312
 4313    pub fn language_server_statuses(
 4314        &self,
 4315    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &LanguageServerStatus)> {
 4316        self.language_server_statuses
 4317            .iter()
 4318            .map(|(key, value)| (*key, value))
 4319    }
 4320
 4321    pub fn last_formatting_failure(&self) -> Option<&str> {
 4322        self.last_formatting_failure.as_deref()
 4323    }
 4324
 4325    pub fn update_diagnostics(
 4326        &mut self,
 4327        language_server_id: LanguageServerId,
 4328        mut params: lsp::PublishDiagnosticsParams,
 4329        disk_based_sources: &[String],
 4330        cx: &mut ModelContext<Self>,
 4331    ) -> Result<()> {
 4332        let abs_path = params
 4333            .uri
 4334            .to_file_path()
 4335            .map_err(|_| anyhow!("URI is not a file"))?;
 4336        let mut diagnostics = Vec::default();
 4337        let mut primary_diagnostic_group_ids = HashMap::default();
 4338        let mut sources_by_group_id = HashMap::default();
 4339        let mut supporting_diagnostics = HashMap::default();
 4340
 4341        // Ensure that primary diagnostics are always the most severe
 4342        params.diagnostics.sort_by_key(|item| item.severity);
 4343
 4344        for diagnostic in &params.diagnostics {
 4345            let source = diagnostic.source.as_ref();
 4346            let code = diagnostic.code.as_ref().map(|code| match code {
 4347                lsp::NumberOrString::Number(code) => code.to_string(),
 4348                lsp::NumberOrString::String(code) => code.clone(),
 4349            });
 4350            let range = range_from_lsp(diagnostic.range);
 4351            let is_supporting = diagnostic
 4352                .related_information
 4353                .as_ref()
 4354                .map_or(false, |infos| {
 4355                    infos.iter().any(|info| {
 4356                        primary_diagnostic_group_ids.contains_key(&(
 4357                            source,
 4358                            code.clone(),
 4359                            range_from_lsp(info.location.range),
 4360                        ))
 4361                    })
 4362                });
 4363
 4364            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
 4365                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
 4366            });
 4367
 4368            if is_supporting {
 4369                supporting_diagnostics.insert(
 4370                    (source, code.clone(), range),
 4371                    (diagnostic.severity, is_unnecessary),
 4372                );
 4373            } else {
 4374                let group_id = post_inc(&mut self.next_diagnostic_group_id);
 4375                let is_disk_based =
 4376                    source.map_or(false, |source| disk_based_sources.contains(source));
 4377
 4378                sources_by_group_id.insert(group_id, source);
 4379                primary_diagnostic_group_ids
 4380                    .insert((source, code.clone(), range.clone()), group_id);
 4381
 4382                diagnostics.push(DiagnosticEntry {
 4383                    range,
 4384                    diagnostic: Diagnostic {
 4385                        source: diagnostic.source.clone(),
 4386                        code: code.clone(),
 4387                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
 4388                        message: diagnostic.message.trim().to_string(),
 4389                        group_id,
 4390                        is_primary: true,
 4391                        is_disk_based,
 4392                        is_unnecessary,
 4393                    },
 4394                });
 4395                if let Some(infos) = &diagnostic.related_information {
 4396                    for info in infos {
 4397                        if info.location.uri == params.uri && !info.message.is_empty() {
 4398                            let range = range_from_lsp(info.location.range);
 4399                            diagnostics.push(DiagnosticEntry {
 4400                                range,
 4401                                diagnostic: Diagnostic {
 4402                                    source: diagnostic.source.clone(),
 4403                                    code: code.clone(),
 4404                                    severity: DiagnosticSeverity::INFORMATION,
 4405                                    message: info.message.trim().to_string(),
 4406                                    group_id,
 4407                                    is_primary: false,
 4408                                    is_disk_based,
 4409                                    is_unnecessary: false,
 4410                                },
 4411                            });
 4412                        }
 4413                    }
 4414                }
 4415            }
 4416        }
 4417
 4418        for entry in &mut diagnostics {
 4419            let diagnostic = &mut entry.diagnostic;
 4420            if !diagnostic.is_primary {
 4421                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
 4422                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
 4423                    source,
 4424                    diagnostic.code.clone(),
 4425                    entry.range.clone(),
 4426                )) {
 4427                    if let Some(severity) = severity {
 4428                        diagnostic.severity = severity;
 4429                    }
 4430                    diagnostic.is_unnecessary = is_unnecessary;
 4431                }
 4432            }
 4433        }
 4434
 4435        self.update_diagnostic_entries(
 4436            language_server_id,
 4437            abs_path,
 4438            params.version,
 4439            diagnostics,
 4440            cx,
 4441        )?;
 4442        Ok(())
 4443    }
 4444
 4445    pub fn update_diagnostic_entries(
 4446        &mut self,
 4447        server_id: LanguageServerId,
 4448        abs_path: PathBuf,
 4449        version: Option<i32>,
 4450        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4451        cx: &mut ModelContext<Project>,
 4452    ) -> Result<(), anyhow::Error> {
 4453        let (worktree, relative_path) = self
 4454            .find_local_worktree(&abs_path, cx)
 4455            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
 4456
 4457        let project_path = ProjectPath {
 4458            worktree_id: worktree.read(cx).id(),
 4459            path: relative_path.into(),
 4460        };
 4461
 4462        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
 4463            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
 4464        }
 4465
 4466        let updated = worktree.update(cx, |worktree, cx| {
 4467            self.update_worktree_diagnostics(
 4468                worktree.id(),
 4469                server_id,
 4470                project_path.path.clone(),
 4471                diagnostics,
 4472                cx,
 4473            )
 4474        })?;
 4475        if updated {
 4476            cx.emit(Event::DiagnosticsUpdated {
 4477                language_server_id: server_id,
 4478                path: project_path,
 4479            });
 4480        }
 4481        Ok(())
 4482    }
 4483
 4484    pub fn update_worktree_diagnostics(
 4485        &mut self,
 4486        worktree_id: WorktreeId,
 4487        server_id: LanguageServerId,
 4488        worktree_path: Arc<Path>,
 4489        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4490        _: &mut ModelContext<Worktree>,
 4491    ) -> Result<bool> {
 4492        let summaries_for_tree = self.diagnostic_summaries.entry(worktree_id).or_default();
 4493        let diagnostics_for_tree = self.diagnostics.entry(worktree_id).or_default();
 4494        let summaries_by_server_id = summaries_for_tree.entry(worktree_path.clone()).or_default();
 4495
 4496        let old_summary = summaries_by_server_id
 4497            .remove(&server_id)
 4498            .unwrap_or_default();
 4499
 4500        let new_summary = DiagnosticSummary::new(&diagnostics);
 4501        if new_summary.is_empty() {
 4502            if let Some(diagnostics_by_server_id) = diagnostics_for_tree.get_mut(&worktree_path) {
 4503                if let Ok(ix) = diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 4504                    diagnostics_by_server_id.remove(ix);
 4505                }
 4506                if diagnostics_by_server_id.is_empty() {
 4507                    diagnostics_for_tree.remove(&worktree_path);
 4508                }
 4509            }
 4510        } else {
 4511            summaries_by_server_id.insert(server_id, new_summary);
 4512            let diagnostics_by_server_id = diagnostics_for_tree
 4513                .entry(worktree_path.clone())
 4514                .or_default();
 4515            match diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0) {
 4516                Ok(ix) => {
 4517                    diagnostics_by_server_id[ix] = (server_id, diagnostics);
 4518                }
 4519                Err(ix) => {
 4520                    diagnostics_by_server_id.insert(ix, (server_id, diagnostics));
 4521                }
 4522            }
 4523        }
 4524
 4525        if !old_summary.is_empty() || !new_summary.is_empty() {
 4526            if let Some(project_id) = self.remote_id() {
 4527                self.client
 4528                    .send(proto::UpdateDiagnosticSummary {
 4529                        project_id,
 4530                        worktree_id: worktree_id.to_proto(),
 4531                        summary: Some(proto::DiagnosticSummary {
 4532                            path: worktree_path.to_string_lossy().to_string(),
 4533                            language_server_id: server_id.0 as u64,
 4534                            error_count: new_summary.error_count as u32,
 4535                            warning_count: new_summary.warning_count as u32,
 4536                        }),
 4537                    })
 4538                    .log_err();
 4539            }
 4540        }
 4541
 4542        Ok(!old_summary.is_empty() || !new_summary.is_empty())
 4543    }
 4544
 4545    fn update_buffer_diagnostics(
 4546        &mut self,
 4547        buffer: &Model<Buffer>,
 4548        server_id: LanguageServerId,
 4549        version: Option<i32>,
 4550        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4551        cx: &mut ModelContext<Self>,
 4552    ) -> Result<()> {
 4553        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 4554            Ordering::Equal
 4555                .then_with(|| b.is_primary.cmp(&a.is_primary))
 4556                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 4557                .then_with(|| a.severity.cmp(&b.severity))
 4558                .then_with(|| a.message.cmp(&b.message))
 4559        }
 4560
 4561        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
 4562
 4563        diagnostics.sort_unstable_by(|a, b| {
 4564            Ordering::Equal
 4565                .then_with(|| a.range.start.cmp(&b.range.start))
 4566                .then_with(|| b.range.end.cmp(&a.range.end))
 4567                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 4568        });
 4569
 4570        let mut sanitized_diagnostics = Vec::new();
 4571        let edits_since_save = Patch::new(
 4572            snapshot
 4573                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
 4574                .collect(),
 4575        );
 4576        for entry in diagnostics {
 4577            let start;
 4578            let end;
 4579            if entry.diagnostic.is_disk_based {
 4580                // Some diagnostics are based on files on disk instead of buffers'
 4581                // current contents. Adjust these diagnostics' ranges to reflect
 4582                // any unsaved edits.
 4583                start = edits_since_save.old_to_new(entry.range.start);
 4584                end = edits_since_save.old_to_new(entry.range.end);
 4585            } else {
 4586                start = entry.range.start;
 4587                end = entry.range.end;
 4588            }
 4589
 4590            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
 4591                ..snapshot.clip_point_utf16(end, Bias::Right);
 4592
 4593            // Expand empty ranges by one codepoint
 4594            if range.start == range.end {
 4595                // This will be go to the next boundary when being clipped
 4596                range.end.column += 1;
 4597                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
 4598                if range.start == range.end && range.end.column > 0 {
 4599                    range.start.column -= 1;
 4600                    range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
 4601                }
 4602            }
 4603
 4604            sanitized_diagnostics.push(DiagnosticEntry {
 4605                range,
 4606                diagnostic: entry.diagnostic,
 4607            });
 4608        }
 4609        drop(edits_since_save);
 4610
 4611        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
 4612        buffer.update(cx, |buffer, cx| {
 4613            buffer.update_diagnostics(server_id, set, cx)
 4614        });
 4615        Ok(())
 4616    }
 4617
 4618    pub fn reload_buffers(
 4619        &self,
 4620        buffers: HashSet<Model<Buffer>>,
 4621        push_to_history: bool,
 4622        cx: &mut ModelContext<Self>,
 4623    ) -> Task<Result<ProjectTransaction>> {
 4624        let mut local_buffers = Vec::new();
 4625        let mut remote_buffers = None;
 4626        for buffer_handle in buffers {
 4627            let buffer = buffer_handle.read(cx);
 4628            if buffer.is_dirty() {
 4629                if let Some(file) = File::from_dyn(buffer.file()) {
 4630                    if file.is_local() {
 4631                        local_buffers.push(buffer_handle);
 4632                    } else {
 4633                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
 4634                    }
 4635                }
 4636            }
 4637        }
 4638
 4639        let remote_buffers = self.remote_id().zip(remote_buffers);
 4640        let client = self.client.clone();
 4641
 4642        cx.spawn(move |this, mut cx| async move {
 4643            let mut project_transaction = ProjectTransaction::default();
 4644
 4645            if let Some((project_id, remote_buffers)) = remote_buffers {
 4646                let response = client
 4647                    .request(proto::ReloadBuffers {
 4648                        project_id,
 4649                        buffer_ids: remote_buffers
 4650                            .iter()
 4651                            .filter_map(|buffer| {
 4652                                buffer
 4653                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
 4654                                    .ok()
 4655                            })
 4656                            .collect(),
 4657                    })
 4658                    .await?
 4659                    .transaction
 4660                    .ok_or_else(|| anyhow!("missing transaction"))?;
 4661                Self::deserialize_project_transaction(this, response, push_to_history, cx.clone())
 4662                    .await?;
 4663            }
 4664
 4665            for buffer in local_buffers {
 4666                let transaction = buffer
 4667                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
 4668                    .await?;
 4669                buffer.update(&mut cx, |buffer, cx| {
 4670                    if let Some(transaction) = transaction {
 4671                        if !push_to_history {
 4672                            buffer.forget_transaction(transaction.id);
 4673                        }
 4674                        project_transaction.0.insert(cx.handle(), transaction);
 4675                    }
 4676                })?;
 4677            }
 4678
 4679            Ok(project_transaction)
 4680        })
 4681    }
 4682
 4683    pub fn format(
 4684        &mut self,
 4685        buffers: HashSet<Model<Buffer>>,
 4686        push_to_history: bool,
 4687        trigger: FormatTrigger,
 4688        cx: &mut ModelContext<Project>,
 4689    ) -> Task<anyhow::Result<ProjectTransaction>> {
 4690        if self.is_local() {
 4691            let buffers_with_paths = buffers
 4692                .into_iter()
 4693                .map(|buffer_handle| {
 4694                    let buffer = buffer_handle.read(cx);
 4695                    let buffer_abs_path = File::from_dyn(buffer.file())
 4696                        .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
 4697                    (buffer_handle, buffer_abs_path)
 4698                })
 4699                .collect::<Vec<_>>();
 4700
 4701            cx.spawn(move |project, mut cx| async move {
 4702                let result = Self::format_locally(
 4703                    project.clone(),
 4704                    buffers_with_paths,
 4705                    push_to_history,
 4706                    trigger,
 4707                    cx.clone(),
 4708                )
 4709                .await;
 4710
 4711                project.update(&mut cx, |project, _| match &result {
 4712                    Ok(_) => project.last_formatting_failure = None,
 4713                    Err(error) => {
 4714                        project.last_formatting_failure.replace(error.to_string());
 4715                    }
 4716                })?;
 4717
 4718                result
 4719            })
 4720        } else {
 4721            let remote_id = self.remote_id();
 4722            let client = self.client.clone();
 4723            cx.spawn(move |this, mut cx| async move {
 4724                if let Some(project_id) = remote_id {
 4725                    let response = client
 4726                        .request(proto::FormatBuffers {
 4727                            project_id,
 4728                            trigger: trigger as i32,
 4729                            buffer_ids: buffers
 4730                                .iter()
 4731                                .map(|buffer| {
 4732                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
 4733                                })
 4734                                .collect::<Result<_>>()?,
 4735                        })
 4736                        .await?
 4737                        .transaction
 4738                        .ok_or_else(|| anyhow!("missing transaction"))?;
 4739                    Self::deserialize_project_transaction(this, response, push_to_history, cx).await
 4740                } else {
 4741                    Ok(ProjectTransaction::default())
 4742                }
 4743            })
 4744        }
 4745    }
 4746
 4747    async fn format_locally(
 4748        project: WeakModel<Project>,
 4749        mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
 4750        push_to_history: bool,
 4751        trigger: FormatTrigger,
 4752        mut cx: AsyncAppContext,
 4753    ) -> anyhow::Result<ProjectTransaction> {
 4754        // Do not allow multiple concurrent formatting requests for the
 4755        // same buffer.
 4756        project.update(&mut cx, |this, cx| {
 4757            buffers_with_paths.retain(|(buffer, _)| {
 4758                this.buffers_being_formatted
 4759                    .insert(buffer.read(cx).remote_id())
 4760            });
 4761        })?;
 4762
 4763        let _cleanup = defer({
 4764            let this = project.clone();
 4765            let mut cx = cx.clone();
 4766            let buffers = &buffers_with_paths;
 4767            move || {
 4768                this.update(&mut cx, |this, cx| {
 4769                    for (buffer, _) in buffers {
 4770                        this.buffers_being_formatted
 4771                            .remove(&buffer.read(cx).remote_id());
 4772                    }
 4773                })
 4774                .ok();
 4775            }
 4776        });
 4777
 4778        let mut project_transaction = ProjectTransaction::default();
 4779        for (buffer, buffer_abs_path) in &buffers_with_paths {
 4780            let (primary_adapter_and_server, adapters_and_servers) =
 4781                project.update(&mut cx, |project, cx| {
 4782                    let buffer = buffer.read(cx);
 4783
 4784                    let adapters_and_servers = project
 4785                        .language_servers_for_buffer(buffer, cx)
 4786                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
 4787                        .collect::<Vec<_>>();
 4788
 4789                    let primary_adapter = project
 4790                        .primary_language_server_for_buffer(buffer, cx)
 4791                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
 4792
 4793                    (primary_adapter, adapters_and_servers)
 4794                })?;
 4795
 4796            let settings = buffer.update(&mut cx, |buffer, cx| {
 4797                language_settings(buffer.language(), buffer.file(), cx).clone()
 4798            })?;
 4799
 4800            let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
 4801            let ensure_final_newline = settings.ensure_final_newline_on_save;
 4802            let tab_size = settings.tab_size;
 4803
 4804            // First, format buffer's whitespace according to the settings.
 4805            let trailing_whitespace_diff = if remove_trailing_whitespace {
 4806                Some(
 4807                    buffer
 4808                        .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
 4809                        .await,
 4810                )
 4811            } else {
 4812                None
 4813            };
 4814            let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
 4815                buffer.finalize_last_transaction();
 4816                buffer.start_transaction();
 4817                if let Some(diff) = trailing_whitespace_diff {
 4818                    buffer.apply_diff(diff, cx);
 4819                }
 4820                if ensure_final_newline {
 4821                    buffer.ensure_final_newline(cx);
 4822                }
 4823                buffer.end_transaction(cx)
 4824            })?;
 4825
 4826            // Apply the `code_actions_on_format` before we run the formatter.
 4827            let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
 4828            #[allow(clippy::nonminimal_bool)]
 4829            if !code_actions.is_empty()
 4830                && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
 4831            {
 4832                Self::execute_code_actions_on_servers(
 4833                    &project,
 4834                    &adapters_and_servers,
 4835                    code_actions,
 4836                    buffer,
 4837                    push_to_history,
 4838                    &mut project_transaction,
 4839                    &mut cx,
 4840                )
 4841                .await?;
 4842            }
 4843
 4844            // Apply language-specific formatting using either the primary language server
 4845            // or external command.
 4846            // Except for code actions, which are applied with all connected language servers.
 4847            let primary_language_server =
 4848                primary_adapter_and_server.map(|(_adapter, server)| server.clone());
 4849            let server_and_buffer = primary_language_server
 4850                .as_ref()
 4851                .zip(buffer_abs_path.as_ref());
 4852
 4853            let mut format_operation = None;
 4854            let prettier_settings = buffer.read_with(&mut cx, |buffer, cx| {
 4855                language_settings(buffer.language(), buffer.file(), cx)
 4856                    .prettier
 4857                    .clone()
 4858            })?;
 4859            match (&settings.formatter, &settings.format_on_save) {
 4860                (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
 4861
 4862                (Formatter::CodeActions(code_actions), FormatOnSave::On | FormatOnSave::Off)
 4863                | (_, FormatOnSave::CodeActions(code_actions)) => {
 4864                    let code_actions = deserialize_code_actions(code_actions);
 4865                    if !code_actions.is_empty() {
 4866                        Self::execute_code_actions_on_servers(
 4867                            &project,
 4868                            &adapters_and_servers,
 4869                            code_actions,
 4870                            buffer,
 4871                            push_to_history,
 4872                            &mut project_transaction,
 4873                            &mut cx,
 4874                        )
 4875                        .await?;
 4876                    }
 4877                }
 4878                (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
 4879                | (_, FormatOnSave::LanguageServer) => {
 4880                    if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4881                        format_operation = Some(FormatOperation::Lsp(
 4882                            Self::format_via_lsp(
 4883                                &project,
 4884                                buffer,
 4885                                buffer_abs_path,
 4886                                language_server,
 4887                                tab_size,
 4888                                &mut cx,
 4889                            )
 4890                            .await
 4891                            .context("failed to format via language server")?,
 4892                        ));
 4893                    }
 4894                }
 4895
 4896                (
 4897                    Formatter::External { command, arguments },
 4898                    FormatOnSave::On | FormatOnSave::Off,
 4899                )
 4900                | (_, FormatOnSave::External { command, arguments }) => {
 4901                    let buffer_abs_path = buffer_abs_path.as_ref().map(|path| path.as_path());
 4902                    format_operation = Self::format_via_external_command(
 4903                        buffer,
 4904                        buffer_abs_path,
 4905                        command,
 4906                        arguments,
 4907                        &mut cx,
 4908                    )
 4909                    .await
 4910                    .context(format!(
 4911                        "failed to format via external command {:?}",
 4912                        command
 4913                    ))?
 4914                    .map(FormatOperation::External);
 4915                }
 4916                (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
 4917                    let prettier = if prettier_settings.allowed {
 4918                        prettier_support::format_with_prettier(&project, buffer, &mut cx)
 4919                            .await
 4920                            .transpose()
 4921                            .ok()
 4922                            .flatten()
 4923                    } else {
 4924                        None
 4925                    };
 4926
 4927                    if let Some(operation) = prettier {
 4928                        format_operation = Some(operation);
 4929                    } else if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4930                        format_operation = Some(FormatOperation::Lsp(
 4931                            Self::format_via_lsp(
 4932                                &project,
 4933                                buffer,
 4934                                buffer_abs_path,
 4935                                language_server,
 4936                                tab_size,
 4937                                &mut cx,
 4938                            )
 4939                            .await
 4940                            .context("failed to format via language server")?,
 4941                        ));
 4942                    }
 4943                }
 4944                (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
 4945                    if prettier_settings.allowed {
 4946                        if let Some(operation) =
 4947                            prettier_support::format_with_prettier(&project, buffer, &mut cx).await
 4948                        {
 4949                            format_operation = Some(operation?);
 4950                        }
 4951                    }
 4952                }
 4953            };
 4954
 4955            buffer.update(&mut cx, |b, cx| {
 4956                // If the buffer had its whitespace formatted and was edited while the language-specific
 4957                // formatting was being computed, avoid applying the language-specific formatting, because
 4958                // it can't be grouped with the whitespace formatting in the undo history.
 4959                if let Some(transaction_id) = whitespace_transaction_id {
 4960                    if b.peek_undo_stack()
 4961                        .map_or(true, |e| e.transaction_id() != transaction_id)
 4962                    {
 4963                        format_operation.take();
 4964                    }
 4965                }
 4966
 4967                // Apply any language-specific formatting, and group the two formatting operations
 4968                // in the buffer's undo history.
 4969                if let Some(operation) = format_operation {
 4970                    match operation {
 4971                        FormatOperation::Lsp(edits) => {
 4972                            b.edit(edits, None, cx);
 4973                        }
 4974                        FormatOperation::External(diff) => {
 4975                            b.apply_diff(diff, cx);
 4976                        }
 4977                        FormatOperation::Prettier(diff) => {
 4978                            b.apply_diff(diff, cx);
 4979                        }
 4980                    }
 4981
 4982                    if let Some(transaction_id) = whitespace_transaction_id {
 4983                        b.group_until_transaction(transaction_id);
 4984                    } else if let Some(transaction) = project_transaction.0.get(buffer) {
 4985                        b.group_until_transaction(transaction.id)
 4986                    }
 4987                }
 4988
 4989                if let Some(transaction) = b.finalize_last_transaction().cloned() {
 4990                    if !push_to_history {
 4991                        b.forget_transaction(transaction.id);
 4992                    }
 4993                    project_transaction.0.insert(buffer.clone(), transaction);
 4994                }
 4995            })?;
 4996        }
 4997
 4998        Ok(project_transaction)
 4999    }
 5000
 5001    async fn format_via_lsp(
 5002        this: &WeakModel<Self>,
 5003        buffer: &Model<Buffer>,
 5004        abs_path: &Path,
 5005        language_server: &Arc<LanguageServer>,
 5006        tab_size: NonZeroU32,
 5007        cx: &mut AsyncAppContext,
 5008    ) -> Result<Vec<(Range<Anchor>, String)>> {
 5009        let uri = lsp::Url::from_file_path(abs_path)
 5010            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
 5011        let text_document = lsp::TextDocumentIdentifier::new(uri);
 5012        let capabilities = &language_server.capabilities();
 5013
 5014        let formatting_provider = capabilities.document_formatting_provider.as_ref();
 5015        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
 5016
 5017        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 5018            language_server
 5019                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
 5020                    text_document,
 5021                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 5022                    work_done_progress_params: Default::default(),
 5023                })
 5024                .await?
 5025        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 5026            let buffer_start = lsp::Position::new(0, 0);
 5027            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
 5028
 5029            language_server
 5030                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
 5031                    text_document,
 5032                    range: lsp::Range::new(buffer_start, buffer_end),
 5033                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 5034                    work_done_progress_params: Default::default(),
 5035                })
 5036                .await?
 5037        } else {
 5038            None
 5039        };
 5040
 5041        if let Some(lsp_edits) = lsp_edits {
 5042            this.update(cx, |this, cx| {
 5043                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
 5044            })?
 5045            .await
 5046        } else {
 5047            Ok(Vec::new())
 5048        }
 5049    }
 5050
 5051    async fn format_via_external_command(
 5052        buffer: &Model<Buffer>,
 5053        buffer_abs_path: Option<&Path>,
 5054        command: &str,
 5055        arguments: &[String],
 5056        cx: &mut AsyncAppContext,
 5057    ) -> Result<Option<Diff>> {
 5058        let working_dir_path = buffer.update(cx, |buffer, cx| {
 5059            let file = File::from_dyn(buffer.file())?;
 5060            let worktree = file.worktree.read(cx);
 5061            let mut worktree_path = worktree.abs_path().to_path_buf();
 5062            if worktree.root_entry()?.is_file() {
 5063                worktree_path.pop();
 5064            }
 5065            Some(worktree_path)
 5066        })?;
 5067
 5068        let mut child = smol::process::Command::new(command);
 5069
 5070        if let Some(working_dir_path) = working_dir_path {
 5071            child.current_dir(working_dir_path);
 5072        }
 5073
 5074        let mut child = child
 5075            .args(arguments.iter().map(|arg| {
 5076                if let Some(buffer_abs_path) = buffer_abs_path {
 5077                    arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
 5078                } else {
 5079                    arg.replace("{buffer_path}", "Untitled")
 5080                }
 5081            }))
 5082            .stdin(smol::process::Stdio::piped())
 5083            .stdout(smol::process::Stdio::piped())
 5084            .stderr(smol::process::Stdio::piped())
 5085            .spawn()?;
 5086
 5087        let stdin = child
 5088            .stdin
 5089            .as_mut()
 5090            .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
 5091        let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
 5092        for chunk in text.chunks() {
 5093            stdin.write_all(chunk.as_bytes()).await?;
 5094        }
 5095        stdin.flush().await?;
 5096
 5097        let output = child.output().await?;
 5098        if !output.status.success() {
 5099            return Err(anyhow!(
 5100                "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
 5101                output.status.code(),
 5102                String::from_utf8_lossy(&output.stdout),
 5103                String::from_utf8_lossy(&output.stderr),
 5104            ));
 5105        }
 5106
 5107        let stdout = String::from_utf8(output.stdout)?;
 5108        Ok(Some(
 5109            buffer
 5110                .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
 5111                .await,
 5112        ))
 5113    }
 5114
 5115    #[inline(never)]
 5116    fn definition_impl(
 5117        &self,
 5118        buffer: &Model<Buffer>,
 5119        position: PointUtf16,
 5120        cx: &mut ModelContext<Self>,
 5121    ) -> Task<Result<Vec<LocationLink>>> {
 5122        self.request_lsp(
 5123            buffer.clone(),
 5124            LanguageServerToQuery::Primary,
 5125            GetDefinition { position },
 5126            cx,
 5127        )
 5128    }
 5129    pub fn definition<T: ToPointUtf16>(
 5130        &self,
 5131        buffer: &Model<Buffer>,
 5132        position: T,
 5133        cx: &mut ModelContext<Self>,
 5134    ) -> Task<Result<Vec<LocationLink>>> {
 5135        let position = position.to_point_utf16(buffer.read(cx));
 5136        self.definition_impl(buffer, position, cx)
 5137    }
 5138
 5139    fn type_definition_impl(
 5140        &self,
 5141        buffer: &Model<Buffer>,
 5142        position: PointUtf16,
 5143        cx: &mut ModelContext<Self>,
 5144    ) -> Task<Result<Vec<LocationLink>>> {
 5145        self.request_lsp(
 5146            buffer.clone(),
 5147            LanguageServerToQuery::Primary,
 5148            GetTypeDefinition { position },
 5149            cx,
 5150        )
 5151    }
 5152
 5153    pub fn type_definition<T: ToPointUtf16>(
 5154        &self,
 5155        buffer: &Model<Buffer>,
 5156        position: T,
 5157        cx: &mut ModelContext<Self>,
 5158    ) -> Task<Result<Vec<LocationLink>>> {
 5159        let position = position.to_point_utf16(buffer.read(cx));
 5160        self.type_definition_impl(buffer, position, cx)
 5161    }
 5162
 5163    fn implementation_impl(
 5164        &self,
 5165        buffer: &Model<Buffer>,
 5166        position: PointUtf16,
 5167        cx: &mut ModelContext<Self>,
 5168    ) -> Task<Result<Vec<LocationLink>>> {
 5169        self.request_lsp(
 5170            buffer.clone(),
 5171            LanguageServerToQuery::Primary,
 5172            GetImplementation { position },
 5173            cx,
 5174        )
 5175    }
 5176
 5177    pub fn implementation<T: ToPointUtf16>(
 5178        &self,
 5179        buffer: &Model<Buffer>,
 5180        position: T,
 5181        cx: &mut ModelContext<Self>,
 5182    ) -> Task<Result<Vec<LocationLink>>> {
 5183        let position = position.to_point_utf16(buffer.read(cx));
 5184        self.implementation_impl(buffer, position, cx)
 5185    }
 5186
 5187    fn references_impl(
 5188        &self,
 5189        buffer: &Model<Buffer>,
 5190        position: PointUtf16,
 5191        cx: &mut ModelContext<Self>,
 5192    ) -> Task<Result<Vec<Location>>> {
 5193        self.request_lsp(
 5194            buffer.clone(),
 5195            LanguageServerToQuery::Primary,
 5196            GetReferences { position },
 5197            cx,
 5198        )
 5199    }
 5200    pub fn references<T: ToPointUtf16>(
 5201        &self,
 5202        buffer: &Model<Buffer>,
 5203        position: T,
 5204        cx: &mut ModelContext<Self>,
 5205    ) -> Task<Result<Vec<Location>>> {
 5206        let position = position.to_point_utf16(buffer.read(cx));
 5207        self.references_impl(buffer, position, cx)
 5208    }
 5209
 5210    fn document_highlights_impl(
 5211        &self,
 5212        buffer: &Model<Buffer>,
 5213        position: PointUtf16,
 5214        cx: &mut ModelContext<Self>,
 5215    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5216        self.request_lsp(
 5217            buffer.clone(),
 5218            LanguageServerToQuery::Primary,
 5219            GetDocumentHighlights { position },
 5220            cx,
 5221        )
 5222    }
 5223
 5224    pub fn document_highlights<T: ToPointUtf16>(
 5225        &self,
 5226        buffer: &Model<Buffer>,
 5227        position: T,
 5228        cx: &mut ModelContext<Self>,
 5229    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5230        let position = position.to_point_utf16(buffer.read(cx));
 5231        self.document_highlights_impl(buffer, position, cx)
 5232    }
 5233
 5234    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
 5235        let language_registry = self.languages.clone();
 5236
 5237        if self.is_local() {
 5238            let mut requests = Vec::new();
 5239            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
 5240                let Some(worktree_handle) = self.worktree_for_id(*worktree_id, cx) else {
 5241                    continue;
 5242                };
 5243                let worktree = worktree_handle.read(cx);
 5244                if !worktree.is_visible() {
 5245                    continue;
 5246                }
 5247                let worktree_abs_path = worktree.abs_path().clone();
 5248
 5249                let (adapter, language, server) = match self.language_servers.get(server_id) {
 5250                    Some(LanguageServerState::Running {
 5251                        adapter,
 5252                        language,
 5253                        server,
 5254                        ..
 5255                    }) => (adapter.clone(), language.clone(), server),
 5256
 5257                    _ => continue,
 5258                };
 5259
 5260                requests.push(
 5261                    server
 5262                        .request::<lsp::request::WorkspaceSymbolRequest>(
 5263                            lsp::WorkspaceSymbolParams {
 5264                                query: query.to_string(),
 5265                                ..Default::default()
 5266                            },
 5267                        )
 5268                        .log_err()
 5269                        .map(move |response| {
 5270                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
 5271                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 5272                                    flat_responses.into_iter().map(|lsp_symbol| {
 5273                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 5274                                    }).collect::<Vec<_>>()
 5275                                }
 5276                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 5277                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
 5278                                        let location = match lsp_symbol.location {
 5279                                            OneOf::Left(location) => location,
 5280                                            OneOf::Right(_) => {
 5281                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 5282                                                return None
 5283                                            }
 5284                                        };
 5285                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
 5286                                    }).collect::<Vec<_>>()
 5287                                }
 5288                            }).unwrap_or_default();
 5289
 5290                            (
 5291                                adapter,
 5292                                language,
 5293                                worktree_handle.downgrade(),
 5294                                worktree_abs_path,
 5295                                lsp_symbols,
 5296                            )
 5297                        }),
 5298                );
 5299            }
 5300
 5301            cx.spawn(move |this, mut cx| async move {
 5302                let responses = futures::future::join_all(requests).await;
 5303                let this = match this.upgrade() {
 5304                    Some(this) => this,
 5305                    None => return Ok(Vec::new()),
 5306                };
 5307
 5308                let mut symbols = Vec::new();
 5309                for (adapter, adapter_language, source_worktree, worktree_abs_path, lsp_symbols) in
 5310                    responses
 5311                {
 5312                    let core_symbols = this.update(&mut cx, |this, cx| {
 5313                        lsp_symbols
 5314                            .into_iter()
 5315                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 5316                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 5317                                let source_worktree = source_worktree.upgrade()?;
 5318                                let source_worktree_id = source_worktree.read(cx).id();
 5319
 5320                                let path;
 5321                                let worktree;
 5322                                if let Some((tree, rel_path)) =
 5323                                    this.find_local_worktree(&abs_path, cx)
 5324                                {
 5325                                    worktree = tree;
 5326                                    path = rel_path;
 5327                                } else {
 5328                                    worktree = source_worktree.clone();
 5329                                    path = relativize_path(&worktree_abs_path, &abs_path);
 5330                                }
 5331
 5332                                let worktree_id = worktree.read(cx).id();
 5333                                let project_path = ProjectPath {
 5334                                    worktree_id,
 5335                                    path: path.into(),
 5336                                };
 5337                                let signature = this.symbol_signature(&project_path);
 5338                                Some(CoreSymbol {
 5339                                    language_server_name: adapter.name.clone(),
 5340                                    source_worktree_id,
 5341                                    path: project_path,
 5342                                    kind: symbol_kind,
 5343                                    name: symbol_name,
 5344                                    range: range_from_lsp(symbol_location.range),
 5345                                    signature,
 5346                                })
 5347                            })
 5348                            .collect()
 5349                    })?;
 5350
 5351                    populate_labels_for_symbols(
 5352                        core_symbols,
 5353                        &language_registry,
 5354                        Some(adapter_language),
 5355                        Some(adapter),
 5356                        &mut symbols,
 5357                    )
 5358                    .await;
 5359                }
 5360
 5361                Ok(symbols)
 5362            })
 5363        } else if let Some(project_id) = self.remote_id() {
 5364            let request = self.client.request(proto::GetProjectSymbols {
 5365                project_id,
 5366                query: query.to_string(),
 5367            });
 5368            cx.foreground_executor().spawn(async move {
 5369                let response = request.await?;
 5370                let mut symbols = Vec::new();
 5371                let core_symbols = response
 5372                    .symbols
 5373                    .into_iter()
 5374                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 5375                    .collect::<Vec<_>>();
 5376                populate_labels_for_symbols(
 5377                    core_symbols,
 5378                    &language_registry,
 5379                    None,
 5380                    None,
 5381                    &mut symbols,
 5382                )
 5383                .await;
 5384                Ok(symbols)
 5385            })
 5386        } else {
 5387            Task::ready(Ok(Default::default()))
 5388        }
 5389    }
 5390
 5391    pub fn open_buffer_for_symbol(
 5392        &mut self,
 5393        symbol: &Symbol,
 5394        cx: &mut ModelContext<Self>,
 5395    ) -> Task<Result<Model<Buffer>>> {
 5396        if self.is_local() {
 5397            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
 5398                symbol.source_worktree_id,
 5399                symbol.language_server_name.clone(),
 5400            )) {
 5401                *id
 5402            } else {
 5403                return Task::ready(Err(anyhow!(
 5404                    "language server for worktree and language not found"
 5405                )));
 5406            };
 5407
 5408            let worktree_abs_path = if let Some(worktree_abs_path) = self
 5409                .worktree_for_id(symbol.path.worktree_id, cx)
 5410                .map(|worktree| worktree.read(cx).abs_path())
 5411            {
 5412                worktree_abs_path
 5413            } else {
 5414                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 5415            };
 5416
 5417            let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
 5418            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 5419                uri
 5420            } else {
 5421                return Task::ready(Err(anyhow!("invalid symbol path")));
 5422            };
 5423
 5424            self.open_local_buffer_via_lsp(
 5425                symbol_uri,
 5426                language_server_id,
 5427                symbol.language_server_name.clone(),
 5428                cx,
 5429            )
 5430        } else if let Some(project_id) = self.remote_id() {
 5431            let request = self.client.request(proto::OpenBufferForSymbol {
 5432                project_id,
 5433                symbol: Some(serialize_symbol(symbol)),
 5434            });
 5435            cx.spawn(move |this, mut cx| async move {
 5436                let response = request.await?;
 5437                let buffer_id = BufferId::new(response.buffer_id)?;
 5438                this.update(&mut cx, |this, cx| {
 5439                    this.wait_for_remote_buffer(buffer_id, cx)
 5440                })?
 5441                .await
 5442            })
 5443        } else {
 5444            Task::ready(Err(anyhow!("project does not have a remote id")))
 5445        }
 5446    }
 5447
 5448    pub fn signature_help<T: ToPointUtf16>(
 5449        &self,
 5450        buffer: &Model<Buffer>,
 5451        position: T,
 5452        cx: &mut ModelContext<Self>,
 5453    ) -> Task<Vec<SignatureHelp>> {
 5454        let position = position.to_point_utf16(buffer.read(cx));
 5455        if self.is_local() {
 5456            let all_actions_task = self.request_multiple_lsp_locally(
 5457                buffer,
 5458                Some(position),
 5459                |server_capabilities| server_capabilities.signature_help_provider.is_some(),
 5460                GetSignatureHelp { position },
 5461                cx,
 5462            );
 5463            cx.spawn(|_, _| async move {
 5464                all_actions_task
 5465                    .await
 5466                    .into_iter()
 5467                    .flatten()
 5468                    .filter(|help| !help.markdown.is_empty())
 5469                    .collect::<Vec<_>>()
 5470            })
 5471        } else if let Some(project_id) = self.remote_id() {
 5472            let request_task = self.client().request(proto::MultiLspQuery {
 5473                buffer_id: buffer.read(cx).remote_id().into(),
 5474                version: serialize_version(&buffer.read(cx).version()),
 5475                project_id,
 5476                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5477                    proto::AllLanguageServers {},
 5478                )),
 5479                request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
 5480                    GetSignatureHelp { position }.to_proto(project_id, buffer.read(cx)),
 5481                )),
 5482            });
 5483            let buffer = buffer.clone();
 5484            cx.spawn(|weak_project, cx| async move {
 5485                let Some(project) = weak_project.upgrade() else {
 5486                    return Vec::new();
 5487                };
 5488                join_all(
 5489                    request_task
 5490                        .await
 5491                        .log_err()
 5492                        .map(|response| response.responses)
 5493                        .unwrap_or_default()
 5494                        .into_iter()
 5495                        .filter_map(|lsp_response| match lsp_response.response? {
 5496                            proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
 5497                                Some(response)
 5498                            }
 5499                            unexpected => {
 5500                                debug_panic!("Unexpected response: {unexpected:?}");
 5501                                None
 5502                            }
 5503                        })
 5504                        .map(|signature_response| {
 5505                            let response = GetSignatureHelp { position }.response_from_proto(
 5506                                signature_response,
 5507                                project.clone(),
 5508                                buffer.clone(),
 5509                                cx.clone(),
 5510                            );
 5511                            async move { response.await.log_err().flatten() }
 5512                        }),
 5513                )
 5514                .await
 5515                .into_iter()
 5516                .flatten()
 5517                .collect()
 5518            })
 5519        } else {
 5520            Task::ready(Vec::new())
 5521        }
 5522    }
 5523
 5524    fn hover_impl(
 5525        &self,
 5526        buffer: &Model<Buffer>,
 5527        position: PointUtf16,
 5528        cx: &mut ModelContext<Self>,
 5529    ) -> Task<Vec<Hover>> {
 5530        if self.is_local() {
 5531            let all_actions_task = self.request_multiple_lsp_locally(
 5532                &buffer,
 5533                Some(position),
 5534                |server_capabilities| match server_capabilities.hover_provider {
 5535                    Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 5536                    Some(lsp::HoverProviderCapability::Options(_)) => true,
 5537                    None => false,
 5538                },
 5539                GetHover { position },
 5540                cx,
 5541            );
 5542            cx.spawn(|_, _| async move {
 5543                all_actions_task
 5544                    .await
 5545                    .into_iter()
 5546                    .filter_map(|hover| remove_empty_hover_blocks(hover?))
 5547                    .collect::<Vec<Hover>>()
 5548            })
 5549        } else if let Some(project_id) = self.remote_id() {
 5550            let request_task = self.client().request(proto::MultiLspQuery {
 5551                buffer_id: buffer.read(cx).remote_id().into(),
 5552                version: serialize_version(&buffer.read(cx).version()),
 5553                project_id,
 5554                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5555                    proto::AllLanguageServers {},
 5556                )),
 5557                request: Some(proto::multi_lsp_query::Request::GetHover(
 5558                    GetHover { position }.to_proto(project_id, buffer.read(cx)),
 5559                )),
 5560            });
 5561            let buffer = buffer.clone();
 5562            cx.spawn(|weak_project, cx| async move {
 5563                let Some(project) = weak_project.upgrade() else {
 5564                    return Vec::new();
 5565                };
 5566                join_all(
 5567                    request_task
 5568                        .await
 5569                        .log_err()
 5570                        .map(|response| response.responses)
 5571                        .unwrap_or_default()
 5572                        .into_iter()
 5573                        .filter_map(|lsp_response| match lsp_response.response? {
 5574                            proto::lsp_response::Response::GetHoverResponse(response) => {
 5575                                Some(response)
 5576                            }
 5577                            unexpected => {
 5578                                debug_panic!("Unexpected response: {unexpected:?}");
 5579                                None
 5580                            }
 5581                        })
 5582                        .map(|hover_response| {
 5583                            let response = GetHover { position }.response_from_proto(
 5584                                hover_response,
 5585                                project.clone(),
 5586                                buffer.clone(),
 5587                                cx.clone(),
 5588                            );
 5589                            async move {
 5590                                response
 5591                                    .await
 5592                                    .log_err()
 5593                                    .flatten()
 5594                                    .and_then(remove_empty_hover_blocks)
 5595                            }
 5596                        }),
 5597                )
 5598                .await
 5599                .into_iter()
 5600                .flatten()
 5601                .collect()
 5602            })
 5603        } else {
 5604            log::error!("cannot show hovers: project does not have a remote id");
 5605            Task::ready(Vec::new())
 5606        }
 5607    }
 5608
 5609    pub fn hover<T: ToPointUtf16>(
 5610        &self,
 5611        buffer: &Model<Buffer>,
 5612        position: T,
 5613        cx: &mut ModelContext<Self>,
 5614    ) -> Task<Vec<Hover>> {
 5615        let position = position.to_point_utf16(buffer.read(cx));
 5616        self.hover_impl(buffer, position, cx)
 5617    }
 5618
 5619    fn linked_edit_impl(
 5620        &self,
 5621        buffer: &Model<Buffer>,
 5622        position: Anchor,
 5623        cx: &mut ModelContext<Self>,
 5624    ) -> Task<Result<Vec<Range<Anchor>>>> {
 5625        let snapshot = buffer.read(cx).snapshot();
 5626        let scope = snapshot.language_scope_at(position);
 5627        let Some(server_id) = self
 5628            .language_servers_for_buffer(buffer.read(cx), cx)
 5629            .filter(|(_, server)| {
 5630                server
 5631                    .capabilities()
 5632                    .linked_editing_range_provider
 5633                    .is_some()
 5634            })
 5635            .filter(|(adapter, _)| {
 5636                scope
 5637                    .as_ref()
 5638                    .map(|scope| scope.language_allowed(&adapter.name))
 5639                    .unwrap_or(true)
 5640            })
 5641            .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
 5642            .next()
 5643            .or_else(|| self.is_remote().then_some(LanguageServerToQuery::Primary))
 5644            .filter(|_| {
 5645                maybe!({
 5646                    let language_name = buffer.read(cx).language_at(position)?.name();
 5647                    Some(
 5648                        AllLanguageSettings::get_global(cx)
 5649                            .language(Some(&language_name))
 5650                            .linked_edits,
 5651                    )
 5652                }) == Some(true)
 5653            })
 5654        else {
 5655            return Task::ready(Ok(vec![]));
 5656        };
 5657
 5658        self.request_lsp(
 5659            buffer.clone(),
 5660            server_id,
 5661            LinkedEditingRange { position },
 5662            cx,
 5663        )
 5664    }
 5665
 5666    pub fn linked_edit(
 5667        &self,
 5668        buffer: &Model<Buffer>,
 5669        position: Anchor,
 5670        cx: &mut ModelContext<Self>,
 5671    ) -> Task<Result<Vec<Range<Anchor>>>> {
 5672        self.linked_edit_impl(buffer, position, cx)
 5673    }
 5674
 5675    #[inline(never)]
 5676    fn completions_impl(
 5677        &self,
 5678        buffer: &Model<Buffer>,
 5679        position: PointUtf16,
 5680        context: CompletionContext,
 5681        cx: &mut ModelContext<Self>,
 5682    ) -> Task<Result<Vec<Completion>>> {
 5683        let language_registry = self.languages.clone();
 5684
 5685        if self.is_local() {
 5686            let snapshot = buffer.read(cx).snapshot();
 5687            let offset = position.to_offset(&snapshot);
 5688            let scope = snapshot.language_scope_at(offset);
 5689            let language = snapshot.language().cloned();
 5690
 5691            let server_ids: Vec<_> = self
 5692                .language_servers_for_buffer(buffer.read(cx), cx)
 5693                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 5694                .filter(|(adapter, _)| {
 5695                    scope
 5696                        .as_ref()
 5697                        .map(|scope| scope.language_allowed(&adapter.name))
 5698                        .unwrap_or(true)
 5699                })
 5700                .map(|(_, server)| server.server_id())
 5701                .collect();
 5702
 5703            let buffer = buffer.clone();
 5704            cx.spawn(move |this, mut cx| async move {
 5705                let mut tasks = Vec::with_capacity(server_ids.len());
 5706                this.update(&mut cx, |this, cx| {
 5707                    for server_id in server_ids {
 5708                        let lsp_adapter = this.language_server_adapter_for_id(server_id);
 5709                        tasks.push((
 5710                            lsp_adapter,
 5711                            this.request_lsp(
 5712                                buffer.clone(),
 5713                                LanguageServerToQuery::Other(server_id),
 5714                                GetCompletions {
 5715                                    position,
 5716                                    context: context.clone(),
 5717                                },
 5718                                cx,
 5719                            ),
 5720                        ));
 5721                    }
 5722                })?;
 5723
 5724                let mut completions = Vec::new();
 5725                for (lsp_adapter, task) in tasks {
 5726                    if let Ok(new_completions) = task.await {
 5727                        populate_labels_for_completions(
 5728                            new_completions,
 5729                            &language_registry,
 5730                            language.clone(),
 5731                            lsp_adapter,
 5732                            &mut completions,
 5733                        )
 5734                        .await;
 5735                    }
 5736                }
 5737
 5738                Ok(completions)
 5739            })
 5740        } else if let Some(project_id) = self.remote_id() {
 5741            let task = self.send_lsp_proto_request(
 5742                buffer.clone(),
 5743                project_id,
 5744                GetCompletions { position, context },
 5745                cx,
 5746            );
 5747            let language = buffer.read(cx).language().cloned();
 5748
 5749            // In the future, we should provide project guests with the names of LSP adapters,
 5750            // so that they can use the correct LSP adapter when computing labels. For now,
 5751            // guests just use the first LSP adapter associated with the buffer's language.
 5752            let lsp_adapter = language
 5753                .as_ref()
 5754                .and_then(|language| language_registry.lsp_adapters(language).first().cloned());
 5755
 5756            cx.foreground_executor().spawn(async move {
 5757                let completions = task.await?;
 5758                let mut result = Vec::new();
 5759                populate_labels_for_completions(
 5760                    completions,
 5761                    &language_registry,
 5762                    language,
 5763                    lsp_adapter,
 5764                    &mut result,
 5765                )
 5766                .await;
 5767                Ok(result)
 5768            })
 5769        } else {
 5770            Task::ready(Ok(Default::default()))
 5771        }
 5772    }
 5773
 5774    pub fn completions<T: ToOffset + ToPointUtf16>(
 5775        &self,
 5776        buffer: &Model<Buffer>,
 5777        position: T,
 5778        context: CompletionContext,
 5779        cx: &mut ModelContext<Self>,
 5780    ) -> Task<Result<Vec<Completion>>> {
 5781        let position = position.to_point_utf16(buffer.read(cx));
 5782        self.completions_impl(buffer, position, context, cx)
 5783    }
 5784
 5785    pub fn resolve_completions(
 5786        &self,
 5787        buffer: Model<Buffer>,
 5788        completion_indices: Vec<usize>,
 5789        completions: Arc<RwLock<Box<[Completion]>>>,
 5790        cx: &mut ModelContext<Self>,
 5791    ) -> Task<Result<bool>> {
 5792        let client = self.client();
 5793        let language_registry = self.languages().clone();
 5794
 5795        let is_remote = self.is_remote();
 5796        let project_id = self.remote_id();
 5797
 5798        let buffer_id = buffer.read(cx).remote_id();
 5799        let buffer_snapshot = buffer.read(cx).snapshot();
 5800
 5801        cx.spawn(move |this, mut cx| async move {
 5802            let mut did_resolve = false;
 5803            if is_remote {
 5804                let project_id =
 5805                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
 5806
 5807                for completion_index in completion_indices {
 5808                    let (server_id, completion) = {
 5809                        let completions_guard = completions.read();
 5810                        let completion = &completions_guard[completion_index];
 5811                        if completion.documentation.is_some() {
 5812                            continue;
 5813                        }
 5814
 5815                        did_resolve = true;
 5816                        let server_id = completion.server_id;
 5817                        let completion = completion.lsp_completion.clone();
 5818
 5819                        (server_id, completion)
 5820                    };
 5821
 5822                    Self::resolve_completion_remote(
 5823                        project_id,
 5824                        server_id,
 5825                        buffer_id,
 5826                        completions.clone(),
 5827                        completion_index,
 5828                        completion,
 5829                        client.clone(),
 5830                        language_registry.clone(),
 5831                    )
 5832                    .await;
 5833                }
 5834            } else {
 5835                for completion_index in completion_indices {
 5836                    let (server_id, completion) = {
 5837                        let completions_guard = completions.read();
 5838                        let completion = &completions_guard[completion_index];
 5839                        if completion.documentation.is_some() {
 5840                            continue;
 5841                        }
 5842
 5843                        let server_id = completion.server_id;
 5844                        let completion = completion.lsp_completion.clone();
 5845
 5846                        (server_id, completion)
 5847                    };
 5848
 5849                    let server = this
 5850                        .read_with(&mut cx, |project, _| {
 5851                            project.language_server_for_id(server_id)
 5852                        })
 5853                        .ok()
 5854                        .flatten();
 5855                    let Some(server) = server else {
 5856                        continue;
 5857                    };
 5858
 5859                    did_resolve = true;
 5860                    Self::resolve_completion_local(
 5861                        server,
 5862                        &buffer_snapshot,
 5863                        completions.clone(),
 5864                        completion_index,
 5865                        completion,
 5866                        language_registry.clone(),
 5867                    )
 5868                    .await;
 5869                }
 5870            }
 5871
 5872            Ok(did_resolve)
 5873        })
 5874    }
 5875
 5876    async fn resolve_completion_local(
 5877        server: Arc<lsp::LanguageServer>,
 5878        snapshot: &BufferSnapshot,
 5879        completions: Arc<RwLock<Box<[Completion]>>>,
 5880        completion_index: usize,
 5881        completion: lsp::CompletionItem,
 5882        language_registry: Arc<LanguageRegistry>,
 5883    ) {
 5884        let can_resolve = server
 5885            .capabilities()
 5886            .completion_provider
 5887            .as_ref()
 5888            .and_then(|options| options.resolve_provider)
 5889            .unwrap_or(false);
 5890        if !can_resolve {
 5891            return;
 5892        }
 5893
 5894        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 5895        let Some(completion_item) = request.await.log_err() else {
 5896            return;
 5897        };
 5898
 5899        if let Some(lsp_documentation) = completion_item.documentation.as_ref() {
 5900            let documentation = language::prepare_completion_documentation(
 5901                lsp_documentation,
 5902                &language_registry,
 5903                None, // TODO: Try to reasonably work out which language the completion is for
 5904            )
 5905            .await;
 5906
 5907            let mut completions = completions.write();
 5908            let completion = &mut completions[completion_index];
 5909            completion.documentation = Some(documentation);
 5910        } else {
 5911            let mut completions = completions.write();
 5912            let completion = &mut completions[completion_index];
 5913            completion.documentation = Some(Documentation::Undocumented);
 5914        }
 5915
 5916        if let Some(text_edit) = completion_item.text_edit.as_ref() {
 5917            // Technically we don't have to parse the whole `text_edit`, since the only
 5918            // language server we currently use that does update `text_edit` in `completionItem/resolve`
 5919            // is `typescript-language-server` and they only update `text_edit.new_text`.
 5920            // But we should not rely on that.
 5921            let edit = parse_completion_text_edit(text_edit, snapshot);
 5922
 5923            if let Some((old_range, mut new_text)) = edit {
 5924                LineEnding::normalize(&mut new_text);
 5925
 5926                let mut completions = completions.write();
 5927                let completion = &mut completions[completion_index];
 5928
 5929                completion.new_text = new_text;
 5930                completion.old_range = old_range;
 5931            }
 5932        }
 5933        if completion_item.insert_text_format == Some(InsertTextFormat::SNIPPET) {
 5934            // vtsls might change the type of completion after resolution.
 5935            let mut completions = completions.write();
 5936            let completion = &mut completions[completion_index];
 5937            if completion_item.insert_text_format != completion.lsp_completion.insert_text_format {
 5938                completion.lsp_completion.insert_text_format = completion_item.insert_text_format;
 5939            }
 5940        }
 5941    }
 5942
 5943    #[allow(clippy::too_many_arguments)]
 5944    async fn resolve_completion_remote(
 5945        project_id: u64,
 5946        server_id: LanguageServerId,
 5947        buffer_id: BufferId,
 5948        completions: Arc<RwLock<Box<[Completion]>>>,
 5949        completion_index: usize,
 5950        completion: lsp::CompletionItem,
 5951        client: Arc<Client>,
 5952        language_registry: Arc<LanguageRegistry>,
 5953    ) {
 5954        let request = proto::ResolveCompletionDocumentation {
 5955            project_id,
 5956            language_server_id: server_id.0 as u64,
 5957            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 5958            buffer_id: buffer_id.into(),
 5959        };
 5960
 5961        let Some(response) = client
 5962            .request(request)
 5963            .await
 5964            .context("completion documentation resolve proto request")
 5965            .log_err()
 5966        else {
 5967            return;
 5968        };
 5969
 5970        let documentation = if response.documentation.is_empty() {
 5971            Documentation::Undocumented
 5972        } else if response.documentation_is_markdown {
 5973            Documentation::MultiLineMarkdown(
 5974                markdown::parse_markdown(&response.documentation, &language_registry, None).await,
 5975            )
 5976        } else if response.documentation.lines().count() <= 1 {
 5977            Documentation::SingleLine(response.documentation)
 5978        } else {
 5979            Documentation::MultiLinePlainText(response.documentation)
 5980        };
 5981
 5982        let mut completions = completions.write();
 5983        let completion = &mut completions[completion_index];
 5984        completion.documentation = Some(documentation);
 5985
 5986        let old_range = response
 5987            .old_start
 5988            .and_then(deserialize_anchor)
 5989            .zip(response.old_end.and_then(deserialize_anchor));
 5990        if let Some((old_start, old_end)) = old_range {
 5991            if !response.new_text.is_empty() {
 5992                completion.new_text = response.new_text;
 5993                completion.old_range = old_start..old_end;
 5994            }
 5995        }
 5996    }
 5997
 5998    pub fn apply_additional_edits_for_completion(
 5999        &self,
 6000        buffer_handle: Model<Buffer>,
 6001        completion: Completion,
 6002        push_to_history: bool,
 6003        cx: &mut ModelContext<Self>,
 6004    ) -> Task<Result<Option<Transaction>>> {
 6005        let buffer = buffer_handle.read(cx);
 6006        let buffer_id = buffer.remote_id();
 6007
 6008        if self.is_local() {
 6009            let server_id = completion.server_id;
 6010            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
 6011                Some((_, server)) => server.clone(),
 6012                _ => return Task::ready(Ok(Default::default())),
 6013            };
 6014
 6015            cx.spawn(move |this, mut cx| async move {
 6016                let can_resolve = lang_server
 6017                    .capabilities()
 6018                    .completion_provider
 6019                    .as_ref()
 6020                    .and_then(|options| options.resolve_provider)
 6021                    .unwrap_or(false);
 6022                let additional_text_edits = if can_resolve {
 6023                    lang_server
 6024                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
 6025                        .await?
 6026                        .additional_text_edits
 6027                } else {
 6028                    completion.lsp_completion.additional_text_edits
 6029                };
 6030                if let Some(edits) = additional_text_edits {
 6031                    let edits = this
 6032                        .update(&mut cx, |this, cx| {
 6033                            this.edits_from_lsp(
 6034                                &buffer_handle,
 6035                                edits,
 6036                                lang_server.server_id(),
 6037                                None,
 6038                                cx,
 6039                            )
 6040                        })?
 6041                        .await?;
 6042
 6043                    buffer_handle.update(&mut cx, |buffer, cx| {
 6044                        buffer.finalize_last_transaction();
 6045                        buffer.start_transaction();
 6046
 6047                        for (range, text) in edits {
 6048                            let primary = &completion.old_range;
 6049                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 6050                                && primary.end.cmp(&range.start, buffer).is_ge();
 6051                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 6052                                && range.end.cmp(&primary.end, buffer).is_ge();
 6053
 6054                            //Skip additional edits which overlap with the primary completion edit
 6055                            //https://github.com/zed-industries/zed/pull/1871
 6056                            if !start_within && !end_within {
 6057                                buffer.edit([(range, text)], None, cx);
 6058                            }
 6059                        }
 6060
 6061                        let transaction = if buffer.end_transaction(cx).is_some() {
 6062                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6063                            if !push_to_history {
 6064                                buffer.forget_transaction(transaction.id);
 6065                            }
 6066                            Some(transaction)
 6067                        } else {
 6068                            None
 6069                        };
 6070                        Ok(transaction)
 6071                    })?
 6072                } else {
 6073                    Ok(None)
 6074                }
 6075            })
 6076        } else if let Some(project_id) = self.remote_id() {
 6077            let client = self.client.clone();
 6078            cx.spawn(move |_, mut cx| async move {
 6079                let response = client
 6080                    .request(proto::ApplyCompletionAdditionalEdits {
 6081                        project_id,
 6082                        buffer_id: buffer_id.into(),
 6083                        completion: Some(Self::serialize_completion(&CoreCompletion {
 6084                            old_range: completion.old_range,
 6085                            new_text: completion.new_text,
 6086                            server_id: completion.server_id,
 6087                            lsp_completion: completion.lsp_completion,
 6088                        })),
 6089                    })
 6090                    .await?;
 6091
 6092                if let Some(transaction) = response.transaction {
 6093                    let transaction = language::proto::deserialize_transaction(transaction)?;
 6094                    buffer_handle
 6095                        .update(&mut cx, |buffer, _| {
 6096                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 6097                        })?
 6098                        .await?;
 6099                    if push_to_history {
 6100                        buffer_handle.update(&mut cx, |buffer, _| {
 6101                            buffer.push_transaction(transaction.clone(), Instant::now());
 6102                        })?;
 6103                    }
 6104                    Ok(Some(transaction))
 6105                } else {
 6106                    Ok(None)
 6107                }
 6108            })
 6109        } else {
 6110            Task::ready(Err(anyhow!("project does not have a remote id")))
 6111        }
 6112    }
 6113
 6114    fn code_actions_impl(
 6115        &mut self,
 6116        buffer_handle: &Model<Buffer>,
 6117        range: Range<Anchor>,
 6118        cx: &mut ModelContext<Self>,
 6119    ) -> Task<Vec<CodeAction>> {
 6120        if self.is_local() {
 6121            let all_actions_task = self.request_multiple_lsp_locally(
 6122                &buffer_handle,
 6123                Some(range.start),
 6124                GetCodeActions::supports_code_actions,
 6125                GetCodeActions {
 6126                    range: range.clone(),
 6127                    kinds: None,
 6128                },
 6129                cx,
 6130            );
 6131            cx.spawn(|_, _| async move { all_actions_task.await.into_iter().flatten().collect() })
 6132        } else if let Some(project_id) = self.remote_id() {
 6133            let request_task = self.client().request(proto::MultiLspQuery {
 6134                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6135                version: serialize_version(&buffer_handle.read(cx).version()),
 6136                project_id,
 6137                strategy: Some(proto::multi_lsp_query::Strategy::All(
 6138                    proto::AllLanguageServers {},
 6139                )),
 6140                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 6141                    GetCodeActions {
 6142                        range: range.clone(),
 6143                        kinds: None,
 6144                    }
 6145                    .to_proto(project_id, buffer_handle.read(cx)),
 6146                )),
 6147            });
 6148            let buffer = buffer_handle.clone();
 6149            cx.spawn(|weak_project, cx| async move {
 6150                let Some(project) = weak_project.upgrade() else {
 6151                    return Vec::new();
 6152                };
 6153                join_all(
 6154                    request_task
 6155                        .await
 6156                        .log_err()
 6157                        .map(|response| response.responses)
 6158                        .unwrap_or_default()
 6159                        .into_iter()
 6160                        .filter_map(|lsp_response| match lsp_response.response? {
 6161                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 6162                                Some(response)
 6163                            }
 6164                            unexpected => {
 6165                                debug_panic!("Unexpected response: {unexpected:?}");
 6166                                None
 6167                            }
 6168                        })
 6169                        .map(|code_actions_response| {
 6170                            let response = GetCodeActions {
 6171                                range: range.clone(),
 6172                                kinds: None,
 6173                            }
 6174                            .response_from_proto(
 6175                                code_actions_response,
 6176                                project.clone(),
 6177                                buffer.clone(),
 6178                                cx.clone(),
 6179                            );
 6180                            async move { response.await.log_err().unwrap_or_default() }
 6181                        }),
 6182                )
 6183                .await
 6184                .into_iter()
 6185                .flatten()
 6186                .collect()
 6187            })
 6188        } else {
 6189            log::error!("cannot fetch actions: project does not have a remote id");
 6190            Task::ready(Vec::new())
 6191        }
 6192    }
 6193
 6194    pub fn code_actions<T: Clone + ToOffset>(
 6195        &mut self,
 6196        buffer_handle: &Model<Buffer>,
 6197        range: Range<T>,
 6198        cx: &mut ModelContext<Self>,
 6199    ) -> Task<Vec<CodeAction>> {
 6200        let buffer = buffer_handle.read(cx);
 6201        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 6202        self.code_actions_impl(buffer_handle, range, cx)
 6203    }
 6204
 6205    pub fn apply_code_action(
 6206        &self,
 6207        buffer_handle: Model<Buffer>,
 6208        mut action: CodeAction,
 6209        push_to_history: bool,
 6210        cx: &mut ModelContext<Self>,
 6211    ) -> Task<Result<ProjectTransaction>> {
 6212        if self.is_local() {
 6213            let buffer = buffer_handle.read(cx);
 6214            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
 6215                self.language_server_for_buffer(buffer, action.server_id, cx)
 6216            {
 6217                (adapter.clone(), server.clone())
 6218            } else {
 6219                return Task::ready(Ok(Default::default()));
 6220            };
 6221            cx.spawn(move |this, mut cx| async move {
 6222                Self::try_resolve_code_action(&lang_server, &mut action)
 6223                    .await
 6224                    .context("resolving a code action")?;
 6225                if let Some(edit) = action.lsp_action.edit {
 6226                    if edit.changes.is_some() || edit.document_changes.is_some() {
 6227                        return Self::deserialize_workspace_edit(
 6228                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
 6229                            edit,
 6230                            push_to_history,
 6231                            lsp_adapter.clone(),
 6232                            lang_server.clone(),
 6233                            &mut cx,
 6234                        )
 6235                        .await;
 6236                    }
 6237                }
 6238
 6239                if let Some(command) = action.lsp_action.command {
 6240                    this.update(&mut cx, |this, _| {
 6241                        this.last_workspace_edits_by_language_server
 6242                            .remove(&lang_server.server_id());
 6243                    })?;
 6244
 6245                    let result = lang_server
 6246                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 6247                            command: command.command,
 6248                            arguments: command.arguments.unwrap_or_default(),
 6249                            ..Default::default()
 6250                        })
 6251                        .await;
 6252
 6253                    if let Err(err) = result {
 6254                        // TODO: LSP ERROR
 6255                        return Err(err);
 6256                    }
 6257
 6258                    return this.update(&mut cx, |this, _| {
 6259                        this.last_workspace_edits_by_language_server
 6260                            .remove(&lang_server.server_id())
 6261                            .unwrap_or_default()
 6262                    });
 6263                }
 6264
 6265                Ok(ProjectTransaction::default())
 6266            })
 6267        } else if let Some(project_id) = self.remote_id() {
 6268            let client = self.client.clone();
 6269            let request = proto::ApplyCodeAction {
 6270                project_id,
 6271                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6272                action: Some(Self::serialize_code_action(&action)),
 6273            };
 6274            cx.spawn(move |this, cx| async move {
 6275                let response = client
 6276                    .request(request)
 6277                    .await?
 6278                    .transaction
 6279                    .ok_or_else(|| anyhow!("missing transaction"))?;
 6280                Self::deserialize_project_transaction(this, response, push_to_history, cx).await
 6281            })
 6282        } else {
 6283            Task::ready(Err(anyhow!("project does not have a remote id")))
 6284        }
 6285    }
 6286
 6287    fn apply_on_type_formatting(
 6288        &self,
 6289        buffer: Model<Buffer>,
 6290        position: Anchor,
 6291        trigger: String,
 6292        cx: &mut ModelContext<Self>,
 6293    ) -> Task<Result<Option<Transaction>>> {
 6294        if self.is_local() {
 6295            cx.spawn(move |this, mut cx| async move {
 6296                // Do not allow multiple concurrent formatting requests for the
 6297                // same buffer.
 6298                this.update(&mut cx, |this, cx| {
 6299                    this.buffers_being_formatted
 6300                        .insert(buffer.read(cx).remote_id())
 6301                })?;
 6302
 6303                let _cleanup = defer({
 6304                    let this = this.clone();
 6305                    let mut cx = cx.clone();
 6306                    let closure_buffer = buffer.clone();
 6307                    move || {
 6308                        this.update(&mut cx, |this, cx| {
 6309                            this.buffers_being_formatted
 6310                                .remove(&closure_buffer.read(cx).remote_id());
 6311                        })
 6312                        .ok();
 6313                    }
 6314                });
 6315
 6316                buffer
 6317                    .update(&mut cx, |buffer, _| {
 6318                        buffer.wait_for_edits(Some(position.timestamp))
 6319                    })?
 6320                    .await?;
 6321                this.update(&mut cx, |this, cx| {
 6322                    let position = position.to_point_utf16(buffer.read(cx));
 6323                    this.on_type_format(buffer, position, trigger, false, cx)
 6324                })?
 6325                .await
 6326            })
 6327        } else if let Some(project_id) = self.remote_id() {
 6328            let client = self.client.clone();
 6329            let request = proto::OnTypeFormatting {
 6330                project_id,
 6331                buffer_id: buffer.read(cx).remote_id().into(),
 6332                position: Some(serialize_anchor(&position)),
 6333                trigger,
 6334                version: serialize_version(&buffer.read(cx).version()),
 6335            };
 6336            cx.spawn(move |_, _| async move {
 6337                client
 6338                    .request(request)
 6339                    .await?
 6340                    .transaction
 6341                    .map(language::proto::deserialize_transaction)
 6342                    .transpose()
 6343            })
 6344        } else {
 6345            Task::ready(Err(anyhow!("project does not have a remote id")))
 6346        }
 6347    }
 6348
 6349    async fn deserialize_edits(
 6350        this: Model<Self>,
 6351        buffer_to_edit: Model<Buffer>,
 6352        edits: Vec<lsp::TextEdit>,
 6353        push_to_history: bool,
 6354        _: Arc<CachedLspAdapter>,
 6355        language_server: Arc<LanguageServer>,
 6356        cx: &mut AsyncAppContext,
 6357    ) -> Result<Option<Transaction>> {
 6358        let edits = this
 6359            .update(cx, |this, cx| {
 6360                this.edits_from_lsp(
 6361                    &buffer_to_edit,
 6362                    edits,
 6363                    language_server.server_id(),
 6364                    None,
 6365                    cx,
 6366                )
 6367            })?
 6368            .await?;
 6369
 6370        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6371            buffer.finalize_last_transaction();
 6372            buffer.start_transaction();
 6373            for (range, text) in edits {
 6374                buffer.edit([(range, text)], None, cx);
 6375            }
 6376
 6377            if buffer.end_transaction(cx).is_some() {
 6378                let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6379                if !push_to_history {
 6380                    buffer.forget_transaction(transaction.id);
 6381                }
 6382                Some(transaction)
 6383            } else {
 6384                None
 6385            }
 6386        })?;
 6387
 6388        Ok(transaction)
 6389    }
 6390
 6391    async fn deserialize_workspace_edit(
 6392        this: Model<Self>,
 6393        edit: lsp::WorkspaceEdit,
 6394        push_to_history: bool,
 6395        lsp_adapter: Arc<CachedLspAdapter>,
 6396        language_server: Arc<LanguageServer>,
 6397        cx: &mut AsyncAppContext,
 6398    ) -> Result<ProjectTransaction> {
 6399        let fs = this.update(cx, |this, _| this.fs.clone())?;
 6400        let mut operations = Vec::new();
 6401        if let Some(document_changes) = edit.document_changes {
 6402            match document_changes {
 6403                lsp::DocumentChanges::Edits(edits) => {
 6404                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
 6405                }
 6406                lsp::DocumentChanges::Operations(ops) => operations = ops,
 6407            }
 6408        } else if let Some(changes) = edit.changes {
 6409            operations.extend(changes.into_iter().map(|(uri, edits)| {
 6410                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
 6411                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
 6412                        uri,
 6413                        version: None,
 6414                    },
 6415                    edits: edits.into_iter().map(Edit::Plain).collect(),
 6416                })
 6417            }));
 6418        }
 6419
 6420        let mut project_transaction = ProjectTransaction::default();
 6421        for operation in operations {
 6422            match operation {
 6423                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
 6424                    let abs_path = op
 6425                        .uri
 6426                        .to_file_path()
 6427                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6428
 6429                    if let Some(parent_path) = abs_path.parent() {
 6430                        fs.create_dir(parent_path).await?;
 6431                    }
 6432                    if abs_path.ends_with("/") {
 6433                        fs.create_dir(&abs_path).await?;
 6434                    } else {
 6435                        fs.create_file(
 6436                            &abs_path,
 6437                            op.options
 6438                                .map(|options| fs::CreateOptions {
 6439                                    overwrite: options.overwrite.unwrap_or(false),
 6440                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6441                                })
 6442                                .unwrap_or_default(),
 6443                        )
 6444                        .await?;
 6445                    }
 6446                }
 6447
 6448                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
 6449                    let source_abs_path = op
 6450                        .old_uri
 6451                        .to_file_path()
 6452                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6453                    let target_abs_path = op
 6454                        .new_uri
 6455                        .to_file_path()
 6456                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6457                    fs.rename(
 6458                        &source_abs_path,
 6459                        &target_abs_path,
 6460                        op.options
 6461                            .map(|options| fs::RenameOptions {
 6462                                overwrite: options.overwrite.unwrap_or(false),
 6463                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6464                            })
 6465                            .unwrap_or_default(),
 6466                    )
 6467                    .await?;
 6468                }
 6469
 6470                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
 6471                    let abs_path = op
 6472                        .uri
 6473                        .to_file_path()
 6474                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6475                    let options = op
 6476                        .options
 6477                        .map(|options| fs::RemoveOptions {
 6478                            recursive: options.recursive.unwrap_or(false),
 6479                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
 6480                        })
 6481                        .unwrap_or_default();
 6482                    if abs_path.ends_with("/") {
 6483                        fs.remove_dir(&abs_path, options).await?;
 6484                    } else {
 6485                        fs.remove_file(&abs_path, options).await?;
 6486                    }
 6487                }
 6488
 6489                lsp::DocumentChangeOperation::Edit(op) => {
 6490                    let buffer_to_edit = this
 6491                        .update(cx, |this, cx| {
 6492                            this.open_local_buffer_via_lsp(
 6493                                op.text_document.uri.clone(),
 6494                                language_server.server_id(),
 6495                                lsp_adapter.name.clone(),
 6496                                cx,
 6497                            )
 6498                        })?
 6499                        .await?;
 6500
 6501                    let edits = this
 6502                        .update(cx, |this, cx| {
 6503                            let path = buffer_to_edit.read(cx).project_path(cx);
 6504                            let active_entry = this.active_entry;
 6505                            let is_active_entry = path.clone().map_or(false, |project_path| {
 6506                                this.entry_for_path(&project_path, cx)
 6507                                    .map_or(false, |entry| Some(entry.id) == active_entry)
 6508                            });
 6509
 6510                            let (mut edits, mut snippet_edits) = (vec![], vec![]);
 6511                            for edit in op.edits {
 6512                                match edit {
 6513                                    Edit::Plain(edit) => edits.push(edit),
 6514                                    Edit::Annotated(edit) => edits.push(edit.text_edit),
 6515                                    Edit::Snippet(edit) => {
 6516                                        let Ok(snippet) = Snippet::parse(&edit.snippet.value)
 6517                                        else {
 6518                                            continue;
 6519                                        };
 6520
 6521                                        if is_active_entry {
 6522                                            snippet_edits.push((edit.range, snippet));
 6523                                        } else {
 6524                                            // Since this buffer is not focused, apply a normal edit.
 6525                                            edits.push(TextEdit {
 6526                                                range: edit.range,
 6527                                                new_text: snippet.text,
 6528                                            });
 6529                                        }
 6530                                    }
 6531                                }
 6532                            }
 6533                            if !snippet_edits.is_empty() {
 6534                                if let Some(buffer_version) = op.text_document.version {
 6535                                    let buffer_id = buffer_to_edit.read(cx).remote_id();
 6536                                    // Check if the edit that triggered that edit has been made by this participant.
 6537                                    let should_apply_edit = this
 6538                                        .buffer_snapshots
 6539                                        .get(&buffer_id)
 6540                                        .and_then(|server_to_snapshots| {
 6541                                            let all_snapshots = server_to_snapshots
 6542                                                .get(&language_server.server_id())?;
 6543                                            all_snapshots
 6544                                                .binary_search_by_key(&buffer_version, |snapshot| {
 6545                                                    snapshot.version
 6546                                                })
 6547                                                .ok()
 6548                                                .and_then(|index| all_snapshots.get(index))
 6549                                        })
 6550                                        .map_or(false, |lsp_snapshot| {
 6551                                            let version = lsp_snapshot.snapshot.version();
 6552                                            let most_recent_edit = version
 6553                                                .iter()
 6554                                                .max_by_key(|timestamp| timestamp.value);
 6555                                            most_recent_edit.map_or(false, |edit| {
 6556                                                edit.replica_id == this.replica_id()
 6557                                            })
 6558                                        });
 6559                                    if should_apply_edit {
 6560                                        cx.emit(Event::SnippetEdit(buffer_id, snippet_edits));
 6561                                    }
 6562                                }
 6563                            }
 6564
 6565                            this.edits_from_lsp(
 6566                                &buffer_to_edit,
 6567                                edits,
 6568                                language_server.server_id(),
 6569                                op.text_document.version,
 6570                                cx,
 6571                            )
 6572                        })?
 6573                        .await?;
 6574
 6575                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6576                        buffer.finalize_last_transaction();
 6577                        buffer.start_transaction();
 6578                        for (range, text) in edits {
 6579                            buffer.edit([(range, text)], None, cx);
 6580                        }
 6581                        let transaction = if buffer.end_transaction(cx).is_some() {
 6582                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6583                            if !push_to_history {
 6584                                buffer.forget_transaction(transaction.id);
 6585                            }
 6586                            Some(transaction)
 6587                        } else {
 6588                            None
 6589                        };
 6590
 6591                        transaction
 6592                    })?;
 6593                    if let Some(transaction) = transaction {
 6594                        project_transaction.0.insert(buffer_to_edit, transaction);
 6595                    }
 6596                }
 6597            }
 6598        }
 6599
 6600        Ok(project_transaction)
 6601    }
 6602
 6603    fn prepare_rename_impl(
 6604        &mut self,
 6605        buffer: Model<Buffer>,
 6606        position: PointUtf16,
 6607        cx: &mut ModelContext<Self>,
 6608    ) -> Task<Result<Option<Range<Anchor>>>> {
 6609        self.request_lsp(
 6610            buffer,
 6611            LanguageServerToQuery::Primary,
 6612            PrepareRename { position },
 6613            cx,
 6614        )
 6615    }
 6616    pub fn prepare_rename<T: ToPointUtf16>(
 6617        &mut self,
 6618        buffer: Model<Buffer>,
 6619        position: T,
 6620        cx: &mut ModelContext<Self>,
 6621    ) -> Task<Result<Option<Range<Anchor>>>> {
 6622        let position = position.to_point_utf16(buffer.read(cx));
 6623        self.prepare_rename_impl(buffer, position, cx)
 6624    }
 6625
 6626    fn perform_rename_impl(
 6627        &mut self,
 6628        buffer: Model<Buffer>,
 6629        position: PointUtf16,
 6630        new_name: String,
 6631        push_to_history: bool,
 6632        cx: &mut ModelContext<Self>,
 6633    ) -> Task<Result<ProjectTransaction>> {
 6634        let position = position.to_point_utf16(buffer.read(cx));
 6635        self.request_lsp(
 6636            buffer,
 6637            LanguageServerToQuery::Primary,
 6638            PerformRename {
 6639                position,
 6640                new_name,
 6641                push_to_history,
 6642            },
 6643            cx,
 6644        )
 6645    }
 6646    pub fn perform_rename<T: ToPointUtf16>(
 6647        &mut self,
 6648        buffer: Model<Buffer>,
 6649        position: T,
 6650        new_name: String,
 6651        push_to_history: bool,
 6652        cx: &mut ModelContext<Self>,
 6653    ) -> Task<Result<ProjectTransaction>> {
 6654        let position = position.to_point_utf16(buffer.read(cx));
 6655        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
 6656    }
 6657
 6658    pub fn on_type_format_impl(
 6659        &mut self,
 6660        buffer: Model<Buffer>,
 6661        position: PointUtf16,
 6662        trigger: String,
 6663        push_to_history: bool,
 6664        cx: &mut ModelContext<Self>,
 6665    ) -> Task<Result<Option<Transaction>>> {
 6666        let tab_size = buffer.update(cx, |buffer, cx| {
 6667            language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
 6668        });
 6669        self.request_lsp(
 6670            buffer.clone(),
 6671            LanguageServerToQuery::Primary,
 6672            OnTypeFormatting {
 6673                position,
 6674                trigger,
 6675                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
 6676                push_to_history,
 6677            },
 6678            cx,
 6679        )
 6680    }
 6681
 6682    pub fn on_type_format<T: ToPointUtf16>(
 6683        &mut self,
 6684        buffer: Model<Buffer>,
 6685        position: T,
 6686        trigger: String,
 6687        push_to_history: bool,
 6688        cx: &mut ModelContext<Self>,
 6689    ) -> Task<Result<Option<Transaction>>> {
 6690        let position = position.to_point_utf16(buffer.read(cx));
 6691        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 6692    }
 6693
 6694    pub fn inlay_hints<T: ToOffset>(
 6695        &mut self,
 6696        buffer_handle: Model<Buffer>,
 6697        range: Range<T>,
 6698        cx: &mut ModelContext<Self>,
 6699    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6700        let buffer = buffer_handle.read(cx);
 6701        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 6702        self.inlay_hints_impl(buffer_handle, range, cx)
 6703    }
 6704    fn inlay_hints_impl(
 6705        &mut self,
 6706        buffer_handle: Model<Buffer>,
 6707        range: Range<Anchor>,
 6708        cx: &mut ModelContext<Self>,
 6709    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6710        let buffer = buffer_handle.read(cx);
 6711        let range_start = range.start;
 6712        let range_end = range.end;
 6713        let buffer_id = buffer.remote_id().into();
 6714        let lsp_request = InlayHints { range };
 6715
 6716        if self.is_local() {
 6717            let lsp_request_task = self.request_lsp(
 6718                buffer_handle.clone(),
 6719                LanguageServerToQuery::Primary,
 6720                lsp_request,
 6721                cx,
 6722            );
 6723            cx.spawn(move |_, mut cx| async move {
 6724                buffer_handle
 6725                    .update(&mut cx, |buffer, _| {
 6726                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 6727                    })?
 6728                    .await
 6729                    .context("waiting for inlay hint request range edits")?;
 6730                lsp_request_task.await.context("inlay hints LSP request")
 6731            })
 6732        } else if let Some(project_id) = self.remote_id() {
 6733            let client = self.client.clone();
 6734            let request = proto::InlayHints {
 6735                project_id,
 6736                buffer_id,
 6737                start: Some(serialize_anchor(&range_start)),
 6738                end: Some(serialize_anchor(&range_end)),
 6739                version: serialize_version(&buffer_handle.read(cx).version()),
 6740            };
 6741            cx.spawn(move |project, cx| async move {
 6742                let response = client
 6743                    .request(request)
 6744                    .await
 6745                    .context("inlay hints proto request")?;
 6746                LspCommand::response_from_proto(
 6747                    lsp_request,
 6748                    response,
 6749                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
 6750                    buffer_handle.clone(),
 6751                    cx.clone(),
 6752                )
 6753                .await
 6754                .context("inlay hints proto response conversion")
 6755            })
 6756        } else {
 6757            Task::ready(Err(anyhow!("project does not have a remote id")))
 6758        }
 6759    }
 6760
 6761    pub fn resolve_inlay_hint(
 6762        &self,
 6763        hint: InlayHint,
 6764        buffer_handle: Model<Buffer>,
 6765        server_id: LanguageServerId,
 6766        cx: &mut ModelContext<Self>,
 6767    ) -> Task<anyhow::Result<InlayHint>> {
 6768        if self.is_local() {
 6769            let buffer = buffer_handle.read(cx);
 6770            let (_, lang_server) = if let Some((adapter, server)) =
 6771                self.language_server_for_buffer(buffer, server_id, cx)
 6772            {
 6773                (adapter.clone(), server.clone())
 6774            } else {
 6775                return Task::ready(Ok(hint));
 6776            };
 6777            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
 6778                return Task::ready(Ok(hint));
 6779            }
 6780
 6781            let buffer_snapshot = buffer.snapshot();
 6782            cx.spawn(move |_, mut cx| async move {
 6783                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
 6784                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
 6785                );
 6786                let resolved_hint = resolve_task
 6787                    .await
 6788                    .context("inlay hint resolve LSP request")?;
 6789                let resolved_hint = InlayHints::lsp_to_project_hint(
 6790                    resolved_hint,
 6791                    &buffer_handle,
 6792                    server_id,
 6793                    ResolveState::Resolved,
 6794                    false,
 6795                    &mut cx,
 6796                )
 6797                .await?;
 6798                Ok(resolved_hint)
 6799            })
 6800        } else if let Some(project_id) = self.remote_id() {
 6801            let client = self.client.clone();
 6802            let request = proto::ResolveInlayHint {
 6803                project_id,
 6804                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6805                language_server_id: server_id.0 as u64,
 6806                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
 6807            };
 6808            cx.spawn(move |_, _| async move {
 6809                let response = client
 6810                    .request(request)
 6811                    .await
 6812                    .context("inlay hints proto request")?;
 6813                match response.hint {
 6814                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
 6815                        .context("inlay hints proto resolve response conversion"),
 6816                    None => Ok(hint),
 6817                }
 6818            })
 6819        } else {
 6820            Task::ready(Err(anyhow!("project does not have a remote id")))
 6821        }
 6822    }
 6823
 6824    #[allow(clippy::type_complexity)]
 6825    pub fn search(
 6826        &self,
 6827        query: SearchQuery,
 6828        cx: &mut ModelContext<Self>,
 6829    ) -> Receiver<SearchResult> {
 6830        if self.is_local() {
 6831            self.search_local(query, cx)
 6832        } else if let Some(project_id) = self.remote_id() {
 6833            let (tx, rx) = smol::channel::unbounded();
 6834            let request = self.client.request(query.to_proto(project_id));
 6835            cx.spawn(move |this, mut cx| async move {
 6836                let response = request.await?;
 6837                let mut result = HashMap::default();
 6838                for location in response.locations {
 6839                    let buffer_id = BufferId::new(location.buffer_id)?;
 6840                    let target_buffer = this
 6841                        .update(&mut cx, |this, cx| {
 6842                            this.wait_for_remote_buffer(buffer_id, cx)
 6843                        })?
 6844                        .await?;
 6845                    let start = location
 6846                        .start
 6847                        .and_then(deserialize_anchor)
 6848                        .ok_or_else(|| anyhow!("missing target start"))?;
 6849                    let end = location
 6850                        .end
 6851                        .and_then(deserialize_anchor)
 6852                        .ok_or_else(|| anyhow!("missing target end"))?;
 6853                    result
 6854                        .entry(target_buffer)
 6855                        .or_insert(Vec::new())
 6856                        .push(start..end)
 6857                }
 6858                for (buffer, ranges) in result {
 6859                    let _ = tx.send(SearchResult::Buffer { buffer, ranges }).await;
 6860                }
 6861
 6862                if response.limit_reached {
 6863                    let _ = tx.send(SearchResult::LimitReached).await;
 6864                }
 6865
 6866                Result::<(), anyhow::Error>::Ok(())
 6867            })
 6868            .detach_and_log_err(cx);
 6869            rx
 6870        } else {
 6871            unimplemented!();
 6872        }
 6873    }
 6874
 6875    pub fn search_local(
 6876        &self,
 6877        query: SearchQuery,
 6878        cx: &mut ModelContext<Self>,
 6879    ) -> Receiver<SearchResult> {
 6880        // Local search is split into several phases.
 6881        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
 6882        // and the second phase that finds positions of all the matches found in the candidate files.
 6883        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
 6884        //
 6885        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
 6886        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
 6887        //
 6888        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
 6889        //    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
 6890        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
 6891        // 2. At this point, we have a list of all potentially matching buffers/files.
 6892        //    We sort that list by buffer path - this list is retained for later use.
 6893        //    We ensure that all buffers are now opened and available in project.
 6894        // 3. We run a scan over all the candidate buffers on multiple background threads.
 6895        //    We cannot assume that there will even be a match - while at least one match
 6896        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
 6897        //    There is also an auxiliary background thread responsible for result gathering.
 6898        //    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),
 6899        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
 6900        //    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
 6901        //    entry - which might already be available thanks to out-of-order processing.
 6902        //
 6903        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
 6904        // 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.
 6905        // 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
 6906        // in face of constantly updating list of sorted matches.
 6907        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
 6908        let snapshots = self
 6909            .visible_worktrees(cx)
 6910            .filter_map(|tree| {
 6911                let tree = tree.read(cx);
 6912                Some((tree.snapshot(), tree.as_local()?.settings()))
 6913            })
 6914            .collect::<Vec<_>>();
 6915        let include_root = snapshots.len() > 1;
 6916
 6917        let background = cx.background_executor().clone();
 6918        let path_count: usize = snapshots
 6919            .iter()
 6920            .map(|(snapshot, _)| {
 6921                if query.include_ignored() {
 6922                    snapshot.file_count()
 6923                } else {
 6924                    snapshot.visible_file_count()
 6925                }
 6926            })
 6927            .sum();
 6928        if path_count == 0 {
 6929            let (_, rx) = smol::channel::bounded(1024);
 6930            return rx;
 6931        }
 6932        let workers = background.num_cpus().min(path_count);
 6933        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
 6934        let mut unnamed_files = vec![];
 6935        let opened_buffers = self.buffer_store.update(cx, |buffer_store, cx| {
 6936            buffer_store
 6937                .buffers()
 6938                .filter_map(|buffer| {
 6939                    let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
 6940                        let is_ignored = buffer
 6941                            .project_path(cx)
 6942                            .and_then(|path| self.entry_for_path(&path, cx))
 6943                            .map_or(false, |entry| entry.is_ignored);
 6944                        (is_ignored, buffer.snapshot())
 6945                    });
 6946                    if is_ignored && !query.include_ignored() {
 6947                        return None;
 6948                    } else if let Some(file) = snapshot.file() {
 6949                        let matched_path = if include_root {
 6950                            query.file_matches(Some(&file.full_path(cx)))
 6951                        } else {
 6952                            query.file_matches(Some(file.path()))
 6953                        };
 6954
 6955                        if matched_path {
 6956                            Some((file.path().clone(), (buffer, snapshot)))
 6957                        } else {
 6958                            None
 6959                        }
 6960                    } else {
 6961                        unnamed_files.push(buffer);
 6962                        None
 6963                    }
 6964                })
 6965                .collect()
 6966        });
 6967        cx.background_executor()
 6968            .spawn(Self::background_search(
 6969                unnamed_files,
 6970                opened_buffers,
 6971                cx.background_executor().clone(),
 6972                self.fs.clone(),
 6973                workers,
 6974                query.clone(),
 6975                include_root,
 6976                path_count,
 6977                snapshots,
 6978                matching_paths_tx,
 6979            ))
 6980            .detach();
 6981
 6982        let (result_tx, result_rx) = smol::channel::bounded(1024);
 6983
 6984        cx.spawn(|this, mut cx| async move {
 6985            const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 6986            const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 6987
 6988            let mut matching_paths = matching_paths_rx
 6989                .take(MAX_SEARCH_RESULT_FILES + 1)
 6990                .collect::<Vec<_>>()
 6991                .await;
 6992            let mut limit_reached = if matching_paths.len() > MAX_SEARCH_RESULT_FILES {
 6993                matching_paths.pop();
 6994                true
 6995            } else {
 6996                false
 6997            };
 6998            cx.update(|cx| {
 6999                sort_search_matches(&mut matching_paths, cx);
 7000            })?;
 7001
 7002            let mut range_count = 0;
 7003            let query = Arc::new(query);
 7004
 7005            // Now that we know what paths match the query, we will load at most
 7006            // 64 buffers at a time to avoid overwhelming the main thread. For each
 7007            // opened buffer, we will spawn a background task that retrieves all the
 7008            // ranges in the buffer matched by the query.
 7009            'outer: for matching_paths_chunk in matching_paths.chunks(64) {
 7010                let mut chunk_results = Vec::new();
 7011                for matching_path in matching_paths_chunk {
 7012                    let query = query.clone();
 7013                    let buffer = match matching_path {
 7014                        SearchMatchCandidate::OpenBuffer { buffer, .. } => {
 7015                            Task::ready(Ok(buffer.clone()))
 7016                        }
 7017                        SearchMatchCandidate::Path {
 7018                            worktree_id, path, ..
 7019                        } => this.update(&mut cx, |this, cx| {
 7020                            this.open_buffer((*worktree_id, path.clone()), cx)
 7021                        })?,
 7022                    };
 7023
 7024                    chunk_results.push(cx.spawn(|cx| async move {
 7025                        let buffer = buffer.await?;
 7026                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
 7027                        let ranges = cx
 7028                            .background_executor()
 7029                            .spawn(async move {
 7030                                query
 7031                                    .search(&snapshot, None)
 7032                                    .await
 7033                                    .iter()
 7034                                    .map(|range| {
 7035                                        snapshot.anchor_before(range.start)
 7036                                            ..snapshot.anchor_after(range.end)
 7037                                    })
 7038                                    .collect::<Vec<_>>()
 7039                            })
 7040                            .await;
 7041                        anyhow::Ok((buffer, ranges))
 7042                    }));
 7043                }
 7044
 7045                let chunk_results = futures::future::join_all(chunk_results).await;
 7046                for result in chunk_results {
 7047                    if let Some((buffer, ranges)) = result.log_err() {
 7048                        range_count += ranges.len();
 7049                        result_tx
 7050                            .send(SearchResult::Buffer { buffer, ranges })
 7051                            .await?;
 7052                        if range_count > MAX_SEARCH_RESULT_RANGES {
 7053                            limit_reached = true;
 7054                            break 'outer;
 7055                        }
 7056                    }
 7057                }
 7058            }
 7059
 7060            if limit_reached {
 7061                result_tx.send(SearchResult::LimitReached).await?;
 7062            }
 7063
 7064            anyhow::Ok(())
 7065        })
 7066        .detach();
 7067
 7068        result_rx
 7069    }
 7070
 7071    /// Pick paths that might potentially contain a match of a given search query.
 7072    #[allow(clippy::too_many_arguments)]
 7073    async fn background_search(
 7074        unnamed_buffers: Vec<Model<Buffer>>,
 7075        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
 7076        executor: BackgroundExecutor,
 7077        fs: Arc<dyn Fs>,
 7078        workers: usize,
 7079        query: SearchQuery,
 7080        include_root: bool,
 7081        path_count: usize,
 7082        snapshots: Vec<(Snapshot, WorktreeSettings)>,
 7083        matching_paths_tx: Sender<SearchMatchCandidate>,
 7084    ) {
 7085        let fs = &fs;
 7086        let query = &query;
 7087        let matching_paths_tx = &matching_paths_tx;
 7088        let snapshots = &snapshots;
 7089        for buffer in unnamed_buffers {
 7090            matching_paths_tx
 7091                .send(SearchMatchCandidate::OpenBuffer {
 7092                    buffer: buffer.clone(),
 7093                    path: None,
 7094                })
 7095                .await
 7096                .log_err();
 7097        }
 7098        for (path, (buffer, _)) in opened_buffers.iter() {
 7099            matching_paths_tx
 7100                .send(SearchMatchCandidate::OpenBuffer {
 7101                    buffer: buffer.clone(),
 7102                    path: Some(path.clone()),
 7103                })
 7104                .await
 7105                .log_err();
 7106        }
 7107
 7108        let paths_per_worker = (path_count + workers - 1) / workers;
 7109
 7110        executor
 7111            .scoped(|scope| {
 7112                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
 7113
 7114                for worker_ix in 0..workers {
 7115                    let worker_start_ix = worker_ix * paths_per_worker;
 7116                    let worker_end_ix = worker_start_ix + paths_per_worker;
 7117                    let opened_buffers = opened_buffers.clone();
 7118                    let limiter = Arc::clone(&max_concurrent_workers);
 7119                    scope.spawn({
 7120                        async move {
 7121                            let _guard = limiter.acquire().await;
 7122                            search_snapshots(
 7123                                snapshots,
 7124                                worker_start_ix,
 7125                                worker_end_ix,
 7126                                query,
 7127                                matching_paths_tx,
 7128                                &opened_buffers,
 7129                                include_root,
 7130                                fs,
 7131                            )
 7132                            .await;
 7133                        }
 7134                    });
 7135                }
 7136
 7137                if query.include_ignored() {
 7138                    for (snapshot, settings) in snapshots {
 7139                        for ignored_entry in snapshot.entries(true, 0).filter(|e| e.is_ignored) {
 7140                            let limiter = Arc::clone(&max_concurrent_workers);
 7141                            scope.spawn(async move {
 7142                                let _guard = limiter.acquire().await;
 7143                                search_ignored_entry(
 7144                                    snapshot,
 7145                                    settings,
 7146                                    ignored_entry,
 7147                                    fs,
 7148                                    query,
 7149                                    matching_paths_tx,
 7150                                )
 7151                                .await;
 7152                            });
 7153                        }
 7154                    }
 7155                }
 7156            })
 7157            .await;
 7158    }
 7159
 7160    pub fn request_lsp<R: LspCommand>(
 7161        &self,
 7162        buffer_handle: Model<Buffer>,
 7163        server: LanguageServerToQuery,
 7164        request: R,
 7165        cx: &mut ModelContext<Self>,
 7166    ) -> Task<Result<R::Response>>
 7167    where
 7168        <R::LspRequest as lsp::request::Request>::Result: Send,
 7169        <R::LspRequest as lsp::request::Request>::Params: Send,
 7170    {
 7171        let buffer = buffer_handle.read(cx);
 7172        if self.is_local() {
 7173            let language_server = match server {
 7174                LanguageServerToQuery::Primary => {
 7175                    match self.primary_language_server_for_buffer(buffer, cx) {
 7176                        Some((_, server)) => Some(Arc::clone(server)),
 7177                        None => return Task::ready(Ok(Default::default())),
 7178                    }
 7179                }
 7180                LanguageServerToQuery::Other(id) => self
 7181                    .language_server_for_buffer(buffer, id, cx)
 7182                    .map(|(_, server)| Arc::clone(server)),
 7183            };
 7184            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 7185            if let (Some(file), Some(language_server)) = (file, language_server) {
 7186                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
 7187                let status = request.status();
 7188                return cx.spawn(move |this, cx| async move {
 7189                    if !request.check_capabilities(language_server.capabilities()) {
 7190                        return Ok(Default::default());
 7191                    }
 7192
 7193                    let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
 7194
 7195                    let id = lsp_request.id();
 7196                    let _cleanup = if status.is_some() {
 7197                        cx.update(|cx| {
 7198                            this.update(cx, |this, cx| {
 7199                                this.on_lsp_work_start(
 7200                                    language_server.server_id(),
 7201                                    id.to_string(),
 7202                                    LanguageServerProgress {
 7203                                        is_disk_based_diagnostics_progress: false,
 7204                                        is_cancellable: false,
 7205                                        title: None,
 7206                                        message: status.clone(),
 7207                                        percentage: None,
 7208                                        last_update_at: cx.background_executor().now(),
 7209                                    },
 7210                                    cx,
 7211                                );
 7212                            })
 7213                        })
 7214                        .log_err();
 7215
 7216                        Some(defer(|| {
 7217                            cx.update(|cx| {
 7218                                this.update(cx, |this, cx| {
 7219                                    this.on_lsp_work_end(
 7220                                        language_server.server_id(),
 7221                                        id.to_string(),
 7222                                        cx,
 7223                                    );
 7224                                })
 7225                            })
 7226                            .log_err();
 7227                        }))
 7228                    } else {
 7229                        None
 7230                    };
 7231
 7232                    let result = lsp_request.await;
 7233
 7234                    let response = result.map_err(|err| {
 7235                        log::warn!(
 7236                            "Generic lsp request to {} failed: {}",
 7237                            language_server.name(),
 7238                            err
 7239                        );
 7240                        err
 7241                    })?;
 7242
 7243                    request
 7244                        .response_from_lsp(
 7245                            response,
 7246                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 7247                            buffer_handle,
 7248                            language_server.server_id(),
 7249                            cx.clone(),
 7250                        )
 7251                        .await
 7252                });
 7253            }
 7254        } else if let Some(project_id) = self.remote_id() {
 7255            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
 7256        }
 7257
 7258        Task::ready(Ok(Default::default()))
 7259    }
 7260
 7261    fn request_multiple_lsp_locally<P, R>(
 7262        &self,
 7263        buffer: &Model<Buffer>,
 7264        position: Option<P>,
 7265        server_capabilities_check: fn(&ServerCapabilities) -> bool,
 7266        request: R,
 7267        cx: &mut ModelContext<'_, Self>,
 7268    ) -> Task<Vec<R::Response>>
 7269    where
 7270        P: ToOffset,
 7271        R: LspCommand + Clone,
 7272        <R::LspRequest as lsp::request::Request>::Result: Send,
 7273        <R::LspRequest as lsp::request::Request>::Params: Send,
 7274    {
 7275        if !self.is_local() {
 7276            debug_panic!("Should not request multiple lsp commands in non-local project");
 7277            return Task::ready(Vec::new());
 7278        }
 7279        let snapshot = buffer.read(cx).snapshot();
 7280        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 7281        let mut response_results = self
 7282            .language_servers_for_buffer(buffer.read(cx), cx)
 7283            .filter(|(_, server)| server_capabilities_check(server.capabilities()))
 7284            .filter(|(adapter, _)| {
 7285                scope
 7286                    .as_ref()
 7287                    .map(|scope| scope.language_allowed(&adapter.name))
 7288                    .unwrap_or(true)
 7289            })
 7290            .map(|(_, server)| server.server_id())
 7291            .map(|server_id| {
 7292                self.request_lsp(
 7293                    buffer.clone(),
 7294                    LanguageServerToQuery::Other(server_id),
 7295                    request.clone(),
 7296                    cx,
 7297                )
 7298            })
 7299            .collect::<FuturesUnordered<_>>();
 7300
 7301        return cx.spawn(|_, _| async move {
 7302            let mut responses = Vec::with_capacity(response_results.len());
 7303            while let Some(response_result) = response_results.next().await {
 7304                if let Some(response) = response_result.log_err() {
 7305                    responses.push(response);
 7306                }
 7307            }
 7308            responses
 7309        });
 7310    }
 7311
 7312    fn send_lsp_proto_request<R: LspCommand>(
 7313        &self,
 7314        buffer: Model<Buffer>,
 7315        project_id: u64,
 7316        request: R,
 7317        cx: &mut ModelContext<'_, Project>,
 7318    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
 7319        let rpc = self.client.clone();
 7320        let message = request.to_proto(project_id, buffer.read(cx));
 7321        cx.spawn(move |this, mut cx| async move {
 7322            // Ensure the project is still alive by the time the task
 7323            // is scheduled.
 7324            this.upgrade().context("project dropped")?;
 7325            let response = rpc.request(message).await?;
 7326            let this = this.upgrade().context("project dropped")?;
 7327            if this.update(&mut cx, |this, _| this.is_disconnected())? {
 7328                Err(anyhow!("disconnected before completing request"))
 7329            } else {
 7330                request
 7331                    .response_from_proto(response, this, buffer, cx)
 7332                    .await
 7333            }
 7334        })
 7335    }
 7336
 7337    /// Move a worktree to a new position in the worktree order.
 7338    ///
 7339    /// The worktree will moved to the opposite side of the destination worktree.
 7340    ///
 7341    /// # Example
 7342    ///
 7343    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
 7344    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
 7345    ///
 7346    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
 7347    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
 7348    ///
 7349    /// # Errors
 7350    ///
 7351    /// An error will be returned if the worktree or destination worktree are not found.
 7352    pub fn move_worktree(
 7353        &mut self,
 7354        source: WorktreeId,
 7355        destination: WorktreeId,
 7356        cx: &mut ModelContext<'_, Self>,
 7357    ) -> Result<()> {
 7358        if source == destination {
 7359            return Ok(());
 7360        }
 7361
 7362        let mut source_index = None;
 7363        let mut destination_index = None;
 7364        for (i, worktree) in self.worktrees.iter().enumerate() {
 7365            if let Some(worktree) = worktree.upgrade() {
 7366                let worktree_id = worktree.read(cx).id();
 7367                if worktree_id == source {
 7368                    source_index = Some(i);
 7369                    if destination_index.is_some() {
 7370                        break;
 7371                    }
 7372                } else if worktree_id == destination {
 7373                    destination_index = Some(i);
 7374                    if source_index.is_some() {
 7375                        break;
 7376                    }
 7377                }
 7378            }
 7379        }
 7380
 7381        let source_index =
 7382            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
 7383        let destination_index =
 7384            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
 7385
 7386        if source_index == destination_index {
 7387            return Ok(());
 7388        }
 7389
 7390        let worktree_to_move = self.worktrees.remove(source_index);
 7391        self.worktrees.insert(destination_index, worktree_to_move);
 7392        self.worktrees_reordered = true;
 7393        cx.emit(Event::WorktreeOrderChanged);
 7394        cx.notify();
 7395        Ok(())
 7396    }
 7397
 7398    pub fn find_or_create_local_worktree(
 7399        &mut self,
 7400        abs_path: impl AsRef<Path>,
 7401        visible: bool,
 7402        cx: &mut ModelContext<Self>,
 7403    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
 7404        let abs_path = abs_path.as_ref();
 7405        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
 7406            Task::ready(Ok((tree, relative_path)))
 7407        } else {
 7408            let worktree = self.create_local_worktree(abs_path, visible, cx);
 7409            cx.background_executor()
 7410                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
 7411        }
 7412    }
 7413
 7414    pub fn find_local_worktree(
 7415        &self,
 7416        abs_path: &Path,
 7417        cx: &AppContext,
 7418    ) -> Option<(Model<Worktree>, PathBuf)> {
 7419        for tree in &self.worktrees {
 7420            if let Some(tree) = tree.upgrade() {
 7421                if let Some(relative_path) = tree
 7422                    .read(cx)
 7423                    .as_local()
 7424                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 7425                {
 7426                    return Some((tree.clone(), relative_path.into()));
 7427                }
 7428            }
 7429        }
 7430        None
 7431    }
 7432
 7433    pub fn is_shared(&self) -> bool {
 7434        match &self.client_state {
 7435            ProjectClientState::Shared { .. } => true,
 7436            ProjectClientState::Local => false,
 7437            ProjectClientState::Remote { in_room, .. } => *in_room,
 7438        }
 7439    }
 7440
 7441    fn create_local_worktree(
 7442        &mut self,
 7443        abs_path: impl AsRef<Path>,
 7444        visible: bool,
 7445        cx: &mut ModelContext<Self>,
 7446    ) -> Task<Result<Model<Worktree>>> {
 7447        let fs = self.fs.clone();
 7448        let next_entry_id = self.next_entry_id.clone();
 7449        let path: Arc<Path> = abs_path.as_ref().into();
 7450        let task = self
 7451            .loading_local_worktrees
 7452            .entry(path.clone())
 7453            .or_insert_with(|| {
 7454                cx.spawn(move |project, mut cx| {
 7455                    async move {
 7456                        let worktree =
 7457                            Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx)
 7458                                .await;
 7459
 7460                        project.update(&mut cx, |project, _| {
 7461                            project.loading_local_worktrees.remove(&path);
 7462                        })?;
 7463
 7464                        let worktree = worktree?;
 7465                        project
 7466                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
 7467
 7468                        if visible {
 7469                            cx.update(|cx| {
 7470                                cx.add_recent_document(&path);
 7471                            })
 7472                            .log_err();
 7473                        }
 7474
 7475                        Ok(worktree)
 7476                    }
 7477                    .map_err(Arc::new)
 7478                })
 7479                .shared()
 7480            })
 7481            .clone();
 7482        cx.background_executor().spawn(async move {
 7483            match task.await {
 7484                Ok(worktree) => Ok(worktree),
 7485                Err(err) => Err(anyhow!("{}", err)),
 7486            }
 7487        })
 7488    }
 7489
 7490    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
 7491        self.diagnostics.remove(&id_to_remove);
 7492        self.diagnostic_summaries.remove(&id_to_remove);
 7493
 7494        let mut servers_to_remove = HashMap::default();
 7495        let mut servers_to_preserve = HashSet::default();
 7496        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
 7497            if worktree_id == &id_to_remove {
 7498                servers_to_remove.insert(server_id, server_name.clone());
 7499            } else {
 7500                servers_to_preserve.insert(server_id);
 7501            }
 7502        }
 7503        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
 7504        for (server_id_to_remove, server_name) in servers_to_remove {
 7505            self.language_server_ids
 7506                .remove(&(id_to_remove, server_name));
 7507            self.language_server_statuses.remove(&server_id_to_remove);
 7508            self.language_server_watched_paths
 7509                .remove(&server_id_to_remove);
 7510            self.last_workspace_edits_by_language_server
 7511                .remove(&server_id_to_remove);
 7512            self.language_servers.remove(&server_id_to_remove);
 7513            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
 7514        }
 7515
 7516        let mut prettier_instances_to_clean = FuturesUnordered::new();
 7517        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
 7518            for path in prettier_paths.iter().flatten() {
 7519                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
 7520                    prettier_instances_to_clean.push(async move {
 7521                        prettier_instance
 7522                            .server()
 7523                            .await
 7524                            .map(|server| server.server_id())
 7525                    });
 7526                }
 7527            }
 7528        }
 7529        cx.spawn(|project, mut cx| async move {
 7530            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
 7531                if let Some(prettier_server_id) = prettier_server_id {
 7532                    project
 7533                        .update(&mut cx, |project, cx| {
 7534                            project
 7535                                .supplementary_language_servers
 7536                                .remove(&prettier_server_id);
 7537                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
 7538                        })
 7539                        .ok();
 7540                }
 7541            }
 7542        })
 7543        .detach();
 7544
 7545        self.task_inventory().update(cx, |inventory, _| {
 7546            inventory.remove_worktree_sources(id_to_remove);
 7547        });
 7548
 7549        self.worktrees.retain(|worktree| {
 7550            if let Some(worktree) = worktree.upgrade() {
 7551                let id = worktree.read(cx).id();
 7552                if id == id_to_remove {
 7553                    cx.emit(Event::WorktreeRemoved(id));
 7554                    false
 7555                } else {
 7556                    true
 7557                }
 7558            } else {
 7559                false
 7560            }
 7561        });
 7562
 7563        self.metadata_changed(cx);
 7564    }
 7565
 7566    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
 7567        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
 7568        cx.subscribe(worktree, |this, worktree, event, cx| {
 7569            let is_local = worktree.read(cx).is_local();
 7570            match event {
 7571                worktree::Event::UpdatedEntries(changes) => {
 7572                    if is_local {
 7573                        this.update_local_worktree_buffers(&worktree, changes, cx);
 7574                        this.update_local_worktree_language_servers(&worktree, changes, cx);
 7575                        this.update_local_worktree_settings(&worktree, changes, cx);
 7576                        this.update_prettier_settings(&worktree, changes, cx);
 7577                    }
 7578
 7579                    cx.emit(Event::WorktreeUpdatedEntries(
 7580                        worktree.read(cx).id(),
 7581                        changes.clone(),
 7582                    ));
 7583
 7584                    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
 7585                    this.client()
 7586                        .telemetry()
 7587                        .report_discovered_project_events(worktree_id, changes);
 7588                }
 7589                worktree::Event::UpdatedGitRepositories(updated_repos) => {
 7590                    if is_local {
 7591                        this.update_local_worktree_buffers_git_repos(
 7592                            worktree.clone(),
 7593                            updated_repos,
 7594                            cx,
 7595                        )
 7596                    }
 7597                    cx.emit(Event::WorktreeUpdatedGitRepositories);
 7598                }
 7599            }
 7600        })
 7601        .detach();
 7602
 7603        let push_strong_handle = {
 7604            let worktree = worktree.read(cx);
 7605            self.is_shared() || worktree.is_visible() || worktree.is_remote()
 7606        };
 7607        let handle = if push_strong_handle {
 7608            WorktreeHandle::Strong(worktree.clone())
 7609        } else {
 7610            WorktreeHandle::Weak(worktree.downgrade())
 7611        };
 7612        if self.worktrees_reordered {
 7613            self.worktrees.push(handle);
 7614        } else {
 7615            let i = match self
 7616                .worktrees
 7617                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
 7618                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
 7619                }) {
 7620                Ok(i) | Err(i) => i,
 7621            };
 7622            self.worktrees.insert(i, handle);
 7623        }
 7624
 7625        let handle_id = worktree.entity_id();
 7626        cx.observe_release(worktree, move |this, worktree, cx| {
 7627            let _ = this.remove_worktree(worktree.id(), cx);
 7628            cx.update_global::<SettingsStore, _>(|store, cx| {
 7629                store
 7630                    .clear_local_settings(handle_id.as_u64() as usize, cx)
 7631                    .log_err()
 7632            });
 7633        })
 7634        .detach();
 7635
 7636        cx.emit(Event::WorktreeAdded);
 7637        self.metadata_changed(cx);
 7638    }
 7639
 7640    fn update_local_worktree_buffers(
 7641        &mut self,
 7642        worktree_handle: &Model<Worktree>,
 7643        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7644        cx: &mut ModelContext<Self>,
 7645    ) {
 7646        let snapshot = worktree_handle.read(cx).snapshot();
 7647        self.buffer_store.clone().update(cx, |buffer_store, cx| {
 7648            for (path, entry_id, _) in changes {
 7649                if let Some((buffer, _, new_file)) = buffer_store.file_changed(
 7650                    path.clone(),
 7651                    *entry_id,
 7652                    worktree_handle,
 7653                    &snapshot,
 7654                    cx,
 7655                ) {
 7656                    if let Some(project_id) = self.remote_id() {
 7657                        self.client
 7658                            .send(proto::UpdateBufferFile {
 7659                                project_id,
 7660                                buffer_id: buffer.read(cx).remote_id().into(),
 7661                                file: Some(new_file.to_proto()),
 7662                            })
 7663                            .log_err();
 7664                    }
 7665                }
 7666            }
 7667        });
 7668    }
 7669
 7670    fn update_local_worktree_language_servers(
 7671        &mut self,
 7672        worktree_handle: &Model<Worktree>,
 7673        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7674        cx: &mut ModelContext<Self>,
 7675    ) {
 7676        if changes.is_empty() {
 7677            return;
 7678        }
 7679
 7680        let worktree_id = worktree_handle.read(cx).id();
 7681        let mut language_server_ids = self
 7682            .language_server_ids
 7683            .iter()
 7684            .filter_map(|((server_worktree_id, _), server_id)| {
 7685                (*server_worktree_id == worktree_id).then_some(*server_id)
 7686            })
 7687            .collect::<Vec<_>>();
 7688        language_server_ids.sort();
 7689        language_server_ids.dedup();
 7690
 7691        let abs_path = worktree_handle.read(cx).abs_path();
 7692        for server_id in &language_server_ids {
 7693            if let Some(LanguageServerState::Running { server, .. }) =
 7694                self.language_servers.get(server_id)
 7695            {
 7696                if let Some(watched_paths) = self
 7697                    .language_server_watched_paths
 7698                    .get(&server_id)
 7699                    .and_then(|paths| paths.get(&worktree_id))
 7700                {
 7701                    let params = lsp::DidChangeWatchedFilesParams {
 7702                        changes: changes
 7703                            .iter()
 7704                            .filter_map(|(path, _, change)| {
 7705                                if !watched_paths.is_match(&path) {
 7706                                    return None;
 7707                                }
 7708                                let typ = match change {
 7709                                    PathChange::Loaded => return None,
 7710                                    PathChange::Added => lsp::FileChangeType::CREATED,
 7711                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 7712                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 7713                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 7714                                };
 7715                                Some(lsp::FileEvent {
 7716                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
 7717                                    typ,
 7718                                })
 7719                            })
 7720                            .collect(),
 7721                    };
 7722                    if !params.changes.is_empty() {
 7723                        server
 7724                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
 7725                            .log_err();
 7726                    }
 7727                }
 7728            }
 7729        }
 7730    }
 7731
 7732    fn update_local_worktree_buffers_git_repos(
 7733        &mut self,
 7734        worktree_handle: Model<Worktree>,
 7735        changed_repos: &UpdatedGitRepositoriesSet,
 7736        cx: &mut ModelContext<Self>,
 7737    ) {
 7738        debug_assert!(worktree_handle.read(cx).is_local());
 7739
 7740        // Identify the loading buffers whose containing repository that has changed.
 7741        let future_buffers = self
 7742            .buffer_store
 7743            .read(cx)
 7744            .loading_buffers()
 7745            .filter_map(|(project_path, receiver)| {
 7746                if project_path.worktree_id != worktree_handle.read(cx).id() {
 7747                    return None;
 7748                }
 7749                let path = &project_path.path;
 7750                changed_repos
 7751                    .iter()
 7752                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7753                let path = path.clone();
 7754                let abs_path = worktree_handle.read(cx).absolutize(&path).ok()?;
 7755                Some(async move {
 7756                    BufferStore::wait_for_loading_buffer(receiver)
 7757                        .await
 7758                        .ok()
 7759                        .map(|buffer| (buffer, path, abs_path))
 7760                })
 7761            })
 7762            .collect::<FuturesUnordered<_>>();
 7763
 7764        // Identify the current buffers whose containing repository has changed.
 7765        let current_buffers = self
 7766            .buffer_store
 7767            .read(cx)
 7768            .buffers()
 7769            .filter_map(|buffer| {
 7770                let file = File::from_dyn(buffer.read(cx).file())?;
 7771                if file.worktree != worktree_handle {
 7772                    return None;
 7773                }
 7774                let path = file.path();
 7775                changed_repos
 7776                    .iter()
 7777                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7778                Some((buffer, path.clone(), file.abs_path(cx)))
 7779            })
 7780            .collect::<Vec<_>>();
 7781
 7782        if future_buffers.len() + current_buffers.len() == 0 {
 7783            return;
 7784        }
 7785
 7786        let remote_id = self.remote_id();
 7787        let client = self.client.clone();
 7788        let fs = self.fs.clone();
 7789        cx.spawn(move |_, mut cx| async move {
 7790            // Wait for all of the buffers to load.
 7791            let future_buffers = future_buffers.collect::<Vec<_>>().await;
 7792
 7793            // Reload the diff base for every buffer whose containing git repository has changed.
 7794            let snapshot =
 7795                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
 7796            let diff_bases_by_buffer = cx
 7797                .background_executor()
 7798                .spawn(async move {
 7799                    let mut diff_base_tasks = future_buffers
 7800                        .into_iter()
 7801                        .flatten()
 7802                        .chain(current_buffers)
 7803                        .filter_map(|(buffer, path, abs_path)| {
 7804                            let (repo_entry, local_repo_entry) = snapshot.repo_for_path(&path)?;
 7805                            Some((buffer, path, abs_path, repo_entry, local_repo_entry))
 7806                        })
 7807                        .map(|(buffer, path, abs_path, repo, local_repo_entry)| {
 7808                            let fs = fs.clone();
 7809                            let snapshot = snapshot.clone();
 7810                            async move {
 7811                                let abs_path_metadata = fs
 7812                                    .metadata(&abs_path)
 7813                                    .await
 7814                                    .with_context(|| {
 7815                                        format!("loading file and FS metadata for {path:?}")
 7816                                    })
 7817                                    .log_err()
 7818                                    .flatten()?;
 7819                                let base_text = if abs_path_metadata.is_dir
 7820                                    || abs_path_metadata.is_symlink
 7821                                {
 7822                                    None
 7823                                } else {
 7824                                    let relative_path = repo.relativize(&snapshot, &path).ok()?;
 7825                                    local_repo_entry.repo().load_index_text(&relative_path)
 7826                                };
 7827                                Some((buffer, base_text))
 7828                            }
 7829                        })
 7830                        .collect::<FuturesUnordered<_>>();
 7831
 7832                    let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
 7833                    while let Some(diff_base) = diff_base_tasks.next().await {
 7834                        if let Some(diff_base) = diff_base {
 7835                            diff_bases.push(diff_base);
 7836                        }
 7837                    }
 7838                    diff_bases
 7839                })
 7840                .await;
 7841
 7842            // Assign the new diff bases on all of the buffers.
 7843            for (buffer, diff_base) in diff_bases_by_buffer {
 7844                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
 7845                    buffer.set_diff_base(diff_base.clone(), cx);
 7846                    buffer.remote_id().into()
 7847                })?;
 7848                if let Some(project_id) = remote_id {
 7849                    client
 7850                        .send(proto::UpdateDiffBase {
 7851                            project_id,
 7852                            buffer_id,
 7853                            diff_base,
 7854                        })
 7855                        .log_err();
 7856                }
 7857            }
 7858
 7859            anyhow::Ok(())
 7860        })
 7861        .detach();
 7862    }
 7863
 7864    fn update_local_worktree_settings(
 7865        &mut self,
 7866        worktree: &Model<Worktree>,
 7867        changes: &UpdatedEntriesSet,
 7868        cx: &mut ModelContext<Self>,
 7869    ) {
 7870        if worktree.read(cx).is_remote() {
 7871            return;
 7872        }
 7873        let project_id = self.remote_id();
 7874        let worktree_id = worktree.entity_id();
 7875        let remote_worktree_id = worktree.read(cx).id();
 7876
 7877        let mut settings_contents = Vec::new();
 7878        for (path, _, change) in changes.iter() {
 7879            let removed = change == &PathChange::Removed;
 7880            let abs_path = match worktree.read(cx).absolutize(path) {
 7881                Ok(abs_path) => abs_path,
 7882                Err(e) => {
 7883                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 7884                    continue;
 7885                }
 7886            };
 7887
 7888            if path.ends_with(local_settings_file_relative_path()) {
 7889                let settings_dir = Arc::from(
 7890                    path.ancestors()
 7891                        .nth(local_settings_file_relative_path().components().count())
 7892                        .unwrap(),
 7893                );
 7894                let fs = self.fs.clone();
 7895                settings_contents.push(async move {
 7896                    (
 7897                        settings_dir,
 7898                        if removed {
 7899                            None
 7900                        } else {
 7901                            Some(async move { fs.load(&abs_path).await }.await)
 7902                        },
 7903                    )
 7904                });
 7905            } else if path.ends_with(local_tasks_file_relative_path()) {
 7906                self.task_inventory().update(cx, |task_inventory, cx| {
 7907                    if removed {
 7908                        task_inventory.remove_local_static_source(&abs_path);
 7909                    } else {
 7910                        let fs = self.fs.clone();
 7911                        let task_abs_path = abs_path.clone();
 7912                        let tasks_file_rx =
 7913                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7914                        task_inventory.add_source(
 7915                            TaskSourceKind::Worktree {
 7916                                id: remote_worktree_id,
 7917                                abs_path,
 7918                                id_base: "local_tasks_for_worktree".into(),
 7919                            },
 7920                            |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
 7921                            cx,
 7922                        );
 7923                    }
 7924                })
 7925            } else if path.ends_with(local_vscode_tasks_file_relative_path()) {
 7926                self.task_inventory().update(cx, |task_inventory, cx| {
 7927                    if removed {
 7928                        task_inventory.remove_local_static_source(&abs_path);
 7929                    } else {
 7930                        let fs = self.fs.clone();
 7931                        let task_abs_path = abs_path.clone();
 7932                        let tasks_file_rx =
 7933                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7934                        task_inventory.add_source(
 7935                            TaskSourceKind::Worktree {
 7936                                id: remote_worktree_id,
 7937                                abs_path,
 7938                                id_base: "local_vscode_tasks_for_worktree".into(),
 7939                            },
 7940                            |tx, cx| {
 7941                                StaticSource::new(TrackedFile::new_convertible::<
 7942                                    task::VsCodeTaskFile,
 7943                                >(
 7944                                    tasks_file_rx, tx, cx
 7945                                ))
 7946                            },
 7947                            cx,
 7948                        );
 7949                    }
 7950                })
 7951            }
 7952        }
 7953
 7954        if settings_contents.is_empty() {
 7955            return;
 7956        }
 7957
 7958        let client = self.client.clone();
 7959        cx.spawn(move |_, cx| async move {
 7960            let settings_contents: Vec<(Arc<Path>, _)> =
 7961                futures::future::join_all(settings_contents).await;
 7962            cx.update(|cx| {
 7963                cx.update_global::<SettingsStore, _>(|store, cx| {
 7964                    for (directory, file_content) in settings_contents {
 7965                        let file_content = file_content.and_then(|content| content.log_err());
 7966                        store
 7967                            .set_local_settings(
 7968                                worktree_id.as_u64() as usize,
 7969                                directory.clone(),
 7970                                file_content.as_deref(),
 7971                                cx,
 7972                            )
 7973                            .log_err();
 7974                        if let Some(remote_id) = project_id {
 7975                            client
 7976                                .send(proto::UpdateWorktreeSettings {
 7977                                    project_id: remote_id,
 7978                                    worktree_id: remote_worktree_id.to_proto(),
 7979                                    path: directory.to_string_lossy().into_owned(),
 7980                                    content: file_content,
 7981                                })
 7982                                .log_err();
 7983                        }
 7984                    }
 7985                });
 7986            })
 7987            .ok();
 7988        })
 7989        .detach();
 7990    }
 7991
 7992    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 7993        let new_active_entry = entry.and_then(|project_path| {
 7994            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 7995            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 7996            Some(entry.id)
 7997        });
 7998        if new_active_entry != self.active_entry {
 7999            self.active_entry = new_active_entry;
 8000            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 8001        }
 8002    }
 8003
 8004    pub fn language_servers_running_disk_based_diagnostics(
 8005        &self,
 8006    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 8007        self.language_server_statuses
 8008            .iter()
 8009            .filter_map(|(id, status)| {
 8010                if status.has_pending_diagnostic_updates {
 8011                    Some(*id)
 8012                } else {
 8013                    None
 8014                }
 8015            })
 8016    }
 8017
 8018    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 8019        let mut summary = DiagnosticSummary::default();
 8020        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 8021            summary.error_count += path_summary.error_count;
 8022            summary.warning_count += path_summary.warning_count;
 8023        }
 8024        summary
 8025    }
 8026
 8027    pub fn diagnostic_summaries<'a>(
 8028        &'a self,
 8029        include_ignored: bool,
 8030        cx: &'a AppContext,
 8031    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 8032        self.visible_worktrees(cx)
 8033            .filter_map(|worktree| {
 8034                let worktree = worktree.read(cx);
 8035                Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
 8036            })
 8037            .flat_map(move |(worktree, summaries)| {
 8038                let worktree_id = worktree.id();
 8039                summaries
 8040                    .iter()
 8041                    .filter(move |(path, _)| {
 8042                        include_ignored
 8043                            || worktree
 8044                                .entry_for_path(path.as_ref())
 8045                                .map_or(false, |entry| !entry.is_ignored)
 8046                    })
 8047                    .flat_map(move |(path, summaries)| {
 8048                        summaries.iter().map(move |(server_id, summary)| {
 8049                            (
 8050                                ProjectPath {
 8051                                    worktree_id,
 8052                                    path: path.clone(),
 8053                                },
 8054                                *server_id,
 8055                                *summary,
 8056                            )
 8057                        })
 8058                    })
 8059            })
 8060    }
 8061
 8062    pub fn disk_based_diagnostics_started(
 8063        &mut self,
 8064        language_server_id: LanguageServerId,
 8065        cx: &mut ModelContext<Self>,
 8066    ) {
 8067        if let Some(language_server_status) =
 8068            self.language_server_statuses.get_mut(&language_server_id)
 8069        {
 8070            language_server_status.has_pending_diagnostic_updates = true;
 8071        }
 8072
 8073        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 8074        if self.is_local() {
 8075            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8076                language_server_id,
 8077                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 8078                    Default::default(),
 8079                ),
 8080            })
 8081            .ok();
 8082        }
 8083    }
 8084
 8085    pub fn disk_based_diagnostics_finished(
 8086        &mut self,
 8087        language_server_id: LanguageServerId,
 8088        cx: &mut ModelContext<Self>,
 8089    ) {
 8090        if let Some(language_server_status) =
 8091            self.language_server_statuses.get_mut(&language_server_id)
 8092        {
 8093            language_server_status.has_pending_diagnostic_updates = false;
 8094        }
 8095
 8096        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 8097
 8098        if self.is_local() {
 8099            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8100                language_server_id,
 8101                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 8102                    Default::default(),
 8103                ),
 8104            })
 8105            .ok();
 8106        }
 8107    }
 8108
 8109    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 8110        self.active_entry
 8111    }
 8112
 8113    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 8114        self.worktree_for_id(path.worktree_id, cx)?
 8115            .read(cx)
 8116            .entry_for_path(&path.path)
 8117            .cloned()
 8118    }
 8119
 8120    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 8121        let worktree = self.worktree_for_entry(entry_id, cx)?;
 8122        let worktree = worktree.read(cx);
 8123        let worktree_id = worktree.id();
 8124        let path = worktree.entry_for_id(entry_id)?.path.clone();
 8125        Some(ProjectPath { worktree_id, path })
 8126    }
 8127
 8128    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 8129        let workspace_root = self
 8130            .worktree_for_id(project_path.worktree_id, cx)?
 8131            .read(cx)
 8132            .abs_path();
 8133        let project_path = project_path.path.as_ref();
 8134
 8135        Some(if project_path == Path::new("") {
 8136            workspace_root.to_path_buf()
 8137        } else {
 8138            workspace_root.join(project_path)
 8139        })
 8140    }
 8141
 8142    pub fn project_path_for_absolute_path(
 8143        &self,
 8144        abs_path: &Path,
 8145        cx: &AppContext,
 8146    ) -> Option<ProjectPath> {
 8147        self.find_local_worktree(abs_path, cx)
 8148            .map(|(worktree, relative_path)| ProjectPath {
 8149                worktree_id: worktree.read(cx).id(),
 8150                path: relative_path.into(),
 8151            })
 8152    }
 8153
 8154    pub fn get_workspace_root(
 8155        &self,
 8156        project_path: &ProjectPath,
 8157        cx: &AppContext,
 8158    ) -> Option<PathBuf> {
 8159        Some(
 8160            self.worktree_for_id(project_path.worktree_id, cx)?
 8161                .read(cx)
 8162                .abs_path()
 8163                .to_path_buf(),
 8164        )
 8165    }
 8166
 8167    pub fn get_repo(
 8168        &self,
 8169        project_path: &ProjectPath,
 8170        cx: &AppContext,
 8171    ) -> Option<Arc<dyn GitRepository>> {
 8172        self.worktree_for_id(project_path.worktree_id, cx)?
 8173            .read(cx)
 8174            .as_local()?
 8175            .local_git_repo(&project_path.path)
 8176    }
 8177
 8178    pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
 8179        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
 8180        let root_entry = worktree.root_git_entry()?;
 8181        worktree.get_local_repo(&root_entry)?.repo().clone().into()
 8182    }
 8183
 8184    pub fn blame_buffer(
 8185        &self,
 8186        buffer: &Model<Buffer>,
 8187        version: Option<clock::Global>,
 8188        cx: &AppContext,
 8189    ) -> Task<Result<Blame>> {
 8190        if self.is_local() {
 8191            let blame_params = maybe!({
 8192                let buffer = buffer.read(cx);
 8193                let buffer_project_path = buffer
 8194                    .project_path(cx)
 8195                    .context("failed to get buffer project path")?;
 8196
 8197                let worktree = self
 8198                    .worktree_for_id(buffer_project_path.worktree_id, cx)
 8199                    .context("failed to get worktree")?
 8200                    .read(cx)
 8201                    .as_local()
 8202                    .context("worktree was not local")?
 8203                    .snapshot();
 8204
 8205                let (repo_entry, local_repo_entry) =
 8206                    match worktree.repo_for_path(&buffer_project_path.path) {
 8207                        Some(repo_for_path) => repo_for_path,
 8208                        None => anyhow::bail!(NoRepositoryError {}),
 8209                    };
 8210
 8211                let relative_path = repo_entry
 8212                    .relativize(&worktree, &buffer_project_path.path)
 8213                    .context("failed to relativize buffer path")?;
 8214
 8215                let repo = local_repo_entry.repo().clone();
 8216
 8217                let content = match version {
 8218                    Some(version) => buffer.rope_for_version(&version).clone(),
 8219                    None => buffer.as_rope().clone(),
 8220                };
 8221
 8222                anyhow::Ok((repo, relative_path, content))
 8223            });
 8224
 8225            cx.background_executor().spawn(async move {
 8226                let (repo, relative_path, content) = blame_params?;
 8227                repo.blame(&relative_path, content)
 8228                    .with_context(|| format!("Failed to blame {:?}", relative_path.0))
 8229            })
 8230        } else {
 8231            let project_id = self.remote_id();
 8232            let buffer_id = buffer.read(cx).remote_id();
 8233            let client = self.client.clone();
 8234            let version = buffer.read(cx).version();
 8235
 8236            cx.spawn(|_| async move {
 8237                let project_id = project_id.context("unable to get project id for buffer")?;
 8238                let response = client
 8239                    .request(proto::BlameBuffer {
 8240                        project_id,
 8241                        buffer_id: buffer_id.into(),
 8242                        version: serialize_version(&version),
 8243                    })
 8244                    .await?;
 8245
 8246                Ok(deserialize_blame_buffer_response(response))
 8247            })
 8248        }
 8249    }
 8250
 8251    // RPC message handlers
 8252
 8253    async fn handle_blame_buffer(
 8254        this: Model<Self>,
 8255        envelope: TypedEnvelope<proto::BlameBuffer>,
 8256        mut cx: AsyncAppContext,
 8257    ) -> Result<proto::BlameBufferResponse> {
 8258        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8259        let version = deserialize_version(&envelope.payload.version);
 8260
 8261        let buffer = this.update(&mut cx, |this, cx| {
 8262            this.buffer_store.read(cx).get_existing(buffer_id)
 8263        })??;
 8264
 8265        buffer
 8266            .update(&mut cx, |buffer, _| {
 8267                buffer.wait_for_version(version.clone())
 8268            })?
 8269            .await?;
 8270
 8271        let blame = this
 8272            .update(&mut cx, |this, cx| {
 8273                this.blame_buffer(&buffer, Some(version), cx)
 8274            })?
 8275            .await?;
 8276
 8277        Ok(serialize_blame_buffer_response(blame))
 8278    }
 8279
 8280    async fn handle_multi_lsp_query(
 8281        project: Model<Self>,
 8282        envelope: TypedEnvelope<proto::MultiLspQuery>,
 8283        mut cx: AsyncAppContext,
 8284    ) -> Result<proto::MultiLspQueryResponse> {
 8285        let sender_id = envelope.original_sender_id()?;
 8286        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8287        let version = deserialize_version(&envelope.payload.version);
 8288        let buffer = project.update(&mut cx, |project, cx| {
 8289            project.buffer_store.read(cx).get_existing(buffer_id)
 8290        })??;
 8291        buffer
 8292            .update(&mut cx, |buffer, _| {
 8293                buffer.wait_for_version(version.clone())
 8294            })?
 8295            .await?;
 8296        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 8297        match envelope
 8298            .payload
 8299            .strategy
 8300            .context("invalid request without the strategy")?
 8301        {
 8302            proto::multi_lsp_query::Strategy::All(_) => {
 8303                // currently, there's only one multiple language servers query strategy,
 8304                // so just ensure it's specified correctly
 8305            }
 8306        }
 8307        match envelope.payload.request {
 8308            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 8309                let get_hover =
 8310                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 8311                        .await?;
 8312                let all_hovers = project
 8313                    .update(&mut cx, |project, cx| {
 8314                        project.request_multiple_lsp_locally(
 8315                            &buffer,
 8316                            Some(get_hover.position),
 8317                            |server_capabilities| match server_capabilities.hover_provider {
 8318                                Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 8319                                Some(lsp::HoverProviderCapability::Options(_)) => true,
 8320                                None => false,
 8321                            },
 8322                            get_hover,
 8323                            cx,
 8324                        )
 8325                    })?
 8326                    .await
 8327                    .into_iter()
 8328                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 8329                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8330                    responses: all_hovers
 8331                        .map(|hover| proto::LspResponse {
 8332                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 8333                                GetHover::response_to_proto(
 8334                                    Some(hover),
 8335                                    project,
 8336                                    sender_id,
 8337                                    &buffer_version,
 8338                                    cx,
 8339                                ),
 8340                            )),
 8341                        })
 8342                        .collect(),
 8343                })
 8344            }
 8345            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 8346                let get_code_actions = GetCodeActions::from_proto(
 8347                    get_code_actions,
 8348                    project.clone(),
 8349                    buffer.clone(),
 8350                    cx.clone(),
 8351                )
 8352                .await?;
 8353
 8354                let all_actions = project
 8355                    .update(&mut cx, |project, cx| {
 8356                        project.request_multiple_lsp_locally(
 8357                            &buffer,
 8358                            Some(get_code_actions.range.start),
 8359                            GetCodeActions::supports_code_actions,
 8360                            get_code_actions,
 8361                            cx,
 8362                        )
 8363                    })?
 8364                    .await
 8365                    .into_iter();
 8366
 8367                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8368                    responses: all_actions
 8369                        .map(|code_actions| proto::LspResponse {
 8370                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8371                                GetCodeActions::response_to_proto(
 8372                                    code_actions,
 8373                                    project,
 8374                                    sender_id,
 8375                                    &buffer_version,
 8376                                    cx,
 8377                                ),
 8378                            )),
 8379                        })
 8380                        .collect(),
 8381                })
 8382            }
 8383            Some(proto::multi_lsp_query::Request::GetSignatureHelp(get_signature_help)) => {
 8384                let get_signature_help = GetSignatureHelp::from_proto(
 8385                    get_signature_help,
 8386                    project.clone(),
 8387                    buffer.clone(),
 8388                    cx.clone(),
 8389                )
 8390                .await?;
 8391
 8392                let all_signatures = project
 8393                    .update(&mut cx, |project, cx| {
 8394                        project.request_multiple_lsp_locally(
 8395                            &buffer,
 8396                            Some(get_signature_help.position),
 8397                            |server_capabilities| {
 8398                                server_capabilities.signature_help_provider.is_some()
 8399                            },
 8400                            get_signature_help,
 8401                            cx,
 8402                        )
 8403                    })?
 8404                    .await
 8405                    .into_iter();
 8406
 8407                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8408                    responses: all_signatures
 8409                        .map(|signature_help| proto::LspResponse {
 8410                            response: Some(
 8411                                proto::lsp_response::Response::GetSignatureHelpResponse(
 8412                                    GetSignatureHelp::response_to_proto(
 8413                                        signature_help,
 8414                                        project,
 8415                                        sender_id,
 8416                                        &buffer_version,
 8417                                        cx,
 8418                                    ),
 8419                                ),
 8420                            ),
 8421                        })
 8422                        .collect(),
 8423                })
 8424            }
 8425            None => anyhow::bail!("empty multi lsp query request"),
 8426        }
 8427    }
 8428
 8429    async fn handle_unshare_project(
 8430        this: Model<Self>,
 8431        _: TypedEnvelope<proto::UnshareProject>,
 8432        mut cx: AsyncAppContext,
 8433    ) -> Result<()> {
 8434        this.update(&mut cx, |this, cx| {
 8435            if this.is_local() {
 8436                this.unshare(cx)?;
 8437            } else {
 8438                this.disconnected_from_host(cx);
 8439            }
 8440            Ok(())
 8441        })?
 8442    }
 8443
 8444    async fn handle_add_collaborator(
 8445        this: Model<Self>,
 8446        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 8447        mut cx: AsyncAppContext,
 8448    ) -> Result<()> {
 8449        let collaborator = envelope
 8450            .payload
 8451            .collaborator
 8452            .take()
 8453            .ok_or_else(|| anyhow!("empty collaborator"))?;
 8454
 8455        let collaborator = Collaborator::from_proto(collaborator)?;
 8456        this.update(&mut cx, |this, cx| {
 8457            this.shared_buffers.remove(&collaborator.peer_id);
 8458            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 8459            this.collaborators
 8460                .insert(collaborator.peer_id, collaborator);
 8461            cx.notify();
 8462        })?;
 8463
 8464        Ok(())
 8465    }
 8466
 8467    async fn handle_update_project_collaborator(
 8468        this: Model<Self>,
 8469        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 8470        mut cx: AsyncAppContext,
 8471    ) -> Result<()> {
 8472        let old_peer_id = envelope
 8473            .payload
 8474            .old_peer_id
 8475            .ok_or_else(|| anyhow!("missing old peer id"))?;
 8476        let new_peer_id = envelope
 8477            .payload
 8478            .new_peer_id
 8479            .ok_or_else(|| anyhow!("missing new peer id"))?;
 8480        this.update(&mut cx, |this, cx| {
 8481            let collaborator = this
 8482                .collaborators
 8483                .remove(&old_peer_id)
 8484                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 8485            let is_host = collaborator.replica_id == 0;
 8486            this.collaborators.insert(new_peer_id, collaborator);
 8487
 8488            let buffers = this.shared_buffers.remove(&old_peer_id);
 8489            log::info!(
 8490                "peer {} became {}. moving buffers {:?}",
 8491                old_peer_id,
 8492                new_peer_id,
 8493                &buffers
 8494            );
 8495            if let Some(buffers) = buffers {
 8496                this.shared_buffers.insert(new_peer_id, buffers);
 8497            }
 8498
 8499            if is_host {
 8500                this.buffer_store
 8501                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
 8502                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 8503                    .unwrap();
 8504                cx.emit(Event::HostReshared);
 8505            }
 8506
 8507            cx.emit(Event::CollaboratorUpdated {
 8508                old_peer_id,
 8509                new_peer_id,
 8510            });
 8511            cx.notify();
 8512            Ok(())
 8513        })?
 8514    }
 8515
 8516    async fn handle_remove_collaborator(
 8517        this: Model<Self>,
 8518        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 8519        mut cx: AsyncAppContext,
 8520    ) -> Result<()> {
 8521        this.update(&mut cx, |this, cx| {
 8522            let peer_id = envelope
 8523                .payload
 8524                .peer_id
 8525                .ok_or_else(|| anyhow!("invalid peer id"))?;
 8526            let replica_id = this
 8527                .collaborators
 8528                .remove(&peer_id)
 8529                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 8530                .replica_id;
 8531            this.buffer_store.update(cx, |buffer_store, cx| {
 8532                for buffer in buffer_store.buffers() {
 8533                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 8534                }
 8535            });
 8536            this.shared_buffers.remove(&peer_id);
 8537
 8538            cx.emit(Event::CollaboratorLeft(peer_id));
 8539            cx.notify();
 8540            Ok(())
 8541        })?
 8542    }
 8543
 8544    async fn handle_update_project(
 8545        this: Model<Self>,
 8546        envelope: TypedEnvelope<proto::UpdateProject>,
 8547        mut cx: AsyncAppContext,
 8548    ) -> Result<()> {
 8549        this.update(&mut cx, |this, cx| {
 8550            // Don't handle messages that were sent before the response to us joining the project
 8551            if envelope.message_id > this.join_project_response_message_id {
 8552                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 8553            }
 8554            Ok(())
 8555        })?
 8556    }
 8557
 8558    async fn handle_update_worktree(
 8559        this: Model<Self>,
 8560        envelope: TypedEnvelope<proto::UpdateWorktree>,
 8561        mut cx: AsyncAppContext,
 8562    ) -> Result<()> {
 8563        this.update(&mut cx, |this, cx| {
 8564            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8565            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8566                worktree.update(cx, |worktree, _| {
 8567                    let worktree = worktree.as_remote_mut().unwrap();
 8568                    worktree.update_from_remote(envelope.payload);
 8569                });
 8570            }
 8571            Ok(())
 8572        })?
 8573    }
 8574
 8575    async fn handle_update_worktree_settings(
 8576        this: Model<Self>,
 8577        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 8578        mut cx: AsyncAppContext,
 8579    ) -> Result<()> {
 8580        this.update(&mut cx, |this, cx| {
 8581            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8582            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8583                cx.update_global::<SettingsStore, _>(|store, cx| {
 8584                    store
 8585                        .set_local_settings(
 8586                            worktree.entity_id().as_u64() as usize,
 8587                            PathBuf::from(&envelope.payload.path).into(),
 8588                            envelope.payload.content.as_deref(),
 8589                            cx,
 8590                        )
 8591                        .log_err();
 8592                });
 8593            }
 8594            Ok(())
 8595        })?
 8596    }
 8597
 8598    async fn handle_create_project_entry(
 8599        this: Model<Self>,
 8600        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 8601        mut cx: AsyncAppContext,
 8602    ) -> Result<proto::ProjectEntryResponse> {
 8603        let worktree = this.update(&mut cx, |this, cx| {
 8604            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8605            this.worktree_for_id(worktree_id, cx)
 8606                .ok_or_else(|| anyhow!("worktree not found"))
 8607        })??;
 8608        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
 8609    }
 8610
 8611    async fn handle_rename_project_entry(
 8612        this: Model<Self>,
 8613        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8614        mut cx: AsyncAppContext,
 8615    ) -> Result<proto::ProjectEntryResponse> {
 8616        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8617        let worktree = this.update(&mut cx, |this, cx| {
 8618            this.worktree_for_entry(entry_id, cx)
 8619                .ok_or_else(|| anyhow!("worktree not found"))
 8620        })??;
 8621        Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
 8622    }
 8623
 8624    async fn handle_copy_project_entry(
 8625        this: Model<Self>,
 8626        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 8627        mut cx: AsyncAppContext,
 8628    ) -> Result<proto::ProjectEntryResponse> {
 8629        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8630        let worktree = this.update(&mut cx, |this, cx| {
 8631            this.worktree_for_entry(entry_id, cx)
 8632                .ok_or_else(|| anyhow!("worktree not found"))
 8633        })??;
 8634        Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
 8635    }
 8636
 8637    async fn handle_delete_project_entry(
 8638        this: Model<Self>,
 8639        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 8640        mut cx: AsyncAppContext,
 8641    ) -> Result<proto::ProjectEntryResponse> {
 8642        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8643        let worktree = this.update(&mut cx, |this, cx| {
 8644            this.worktree_for_entry(entry_id, cx)
 8645                .ok_or_else(|| anyhow!("worktree not found"))
 8646        })??;
 8647        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
 8648        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
 8649    }
 8650
 8651    async fn handle_expand_project_entry(
 8652        this: Model<Self>,
 8653        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
 8654        mut cx: AsyncAppContext,
 8655    ) -> Result<proto::ExpandProjectEntryResponse> {
 8656        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8657        let worktree = this
 8658            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
 8659            .ok_or_else(|| anyhow!("invalid request"))?;
 8660        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
 8661    }
 8662
 8663    async fn handle_update_diagnostic_summary(
 8664        this: Model<Self>,
 8665        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8666        mut cx: AsyncAppContext,
 8667    ) -> Result<()> {
 8668        this.update(&mut cx, |this, cx| {
 8669            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8670            if let Some(message) = envelope.payload.summary {
 8671                let project_path = ProjectPath {
 8672                    worktree_id,
 8673                    path: Path::new(&message.path).into(),
 8674                };
 8675                let path = project_path.path.clone();
 8676                let server_id = LanguageServerId(message.language_server_id as usize);
 8677                let summary = DiagnosticSummary {
 8678                    error_count: message.error_count as usize,
 8679                    warning_count: message.warning_count as usize,
 8680                };
 8681
 8682                if summary.is_empty() {
 8683                    if let Some(worktree_summaries) =
 8684                        this.diagnostic_summaries.get_mut(&worktree_id)
 8685                    {
 8686                        if let Some(summaries) = worktree_summaries.get_mut(&path) {
 8687                            summaries.remove(&server_id);
 8688                            if summaries.is_empty() {
 8689                                worktree_summaries.remove(&path);
 8690                            }
 8691                        }
 8692                    }
 8693                } else {
 8694                    this.diagnostic_summaries
 8695                        .entry(worktree_id)
 8696                        .or_default()
 8697                        .entry(path)
 8698                        .or_default()
 8699                        .insert(server_id, summary);
 8700                }
 8701                cx.emit(Event::DiagnosticsUpdated {
 8702                    language_server_id: LanguageServerId(message.language_server_id as usize),
 8703                    path: project_path,
 8704                });
 8705            }
 8706            Ok(())
 8707        })?
 8708    }
 8709
 8710    async fn handle_start_language_server(
 8711        this: Model<Self>,
 8712        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8713        mut cx: AsyncAppContext,
 8714    ) -> Result<()> {
 8715        let server = envelope
 8716            .payload
 8717            .server
 8718            .ok_or_else(|| anyhow!("invalid server"))?;
 8719        this.update(&mut cx, |this, cx| {
 8720            this.language_server_statuses.insert(
 8721                LanguageServerId(server.id as usize),
 8722                LanguageServerStatus {
 8723                    name: server.name,
 8724                    pending_work: Default::default(),
 8725                    has_pending_diagnostic_updates: false,
 8726                    progress_tokens: Default::default(),
 8727                },
 8728            );
 8729            cx.notify();
 8730        })?;
 8731        Ok(())
 8732    }
 8733
 8734    async fn handle_update_language_server(
 8735        this: Model<Self>,
 8736        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8737        mut cx: AsyncAppContext,
 8738    ) -> Result<()> {
 8739        this.update(&mut cx, |this, cx| {
 8740            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8741
 8742            match envelope
 8743                .payload
 8744                .variant
 8745                .ok_or_else(|| anyhow!("invalid variant"))?
 8746            {
 8747                proto::update_language_server::Variant::WorkStart(payload) => {
 8748                    this.on_lsp_work_start(
 8749                        language_server_id,
 8750                        payload.token,
 8751                        LanguageServerProgress {
 8752                            title: payload.title,
 8753                            is_disk_based_diagnostics_progress: false,
 8754                            is_cancellable: false,
 8755                            message: payload.message,
 8756                            percentage: payload.percentage.map(|p| p as usize),
 8757                            last_update_at: cx.background_executor().now(),
 8758                        },
 8759                        cx,
 8760                    );
 8761                }
 8762
 8763                proto::update_language_server::Variant::WorkProgress(payload) => {
 8764                    this.on_lsp_work_progress(
 8765                        language_server_id,
 8766                        payload.token,
 8767                        LanguageServerProgress {
 8768                            title: None,
 8769                            is_disk_based_diagnostics_progress: false,
 8770                            is_cancellable: false,
 8771                            message: payload.message,
 8772                            percentage: payload.percentage.map(|p| p as usize),
 8773                            last_update_at: cx.background_executor().now(),
 8774                        },
 8775                        cx,
 8776                    );
 8777                }
 8778
 8779                proto::update_language_server::Variant::WorkEnd(payload) => {
 8780                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 8781                }
 8782
 8783                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8784                    this.disk_based_diagnostics_started(language_server_id, cx);
 8785                }
 8786
 8787                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8788                    this.disk_based_diagnostics_finished(language_server_id, cx)
 8789                }
 8790            }
 8791
 8792            Ok(())
 8793        })?
 8794    }
 8795
 8796    async fn handle_update_buffer(
 8797        this: Model<Self>,
 8798        envelope: TypedEnvelope<proto::UpdateBuffer>,
 8799        mut cx: AsyncAppContext,
 8800    ) -> Result<proto::Ack> {
 8801        this.update(&mut cx, |this, cx| {
 8802            this.buffer_store.update(cx, |buffer_store, cx| {
 8803                buffer_store.handle_update_buffer(envelope, this.is_remote(), cx)
 8804            })
 8805        })?
 8806    }
 8807
 8808    async fn handle_create_buffer_for_peer(
 8809        this: Model<Self>,
 8810        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 8811        mut cx: AsyncAppContext,
 8812    ) -> Result<()> {
 8813        this.update(&mut cx, |this, cx| {
 8814            this.buffer_store.update(cx, |buffer_store, cx| {
 8815                buffer_store.handle_create_buffer_for_peer(
 8816                    envelope,
 8817                    this.worktrees(),
 8818                    this.replica_id(),
 8819                    this.capability(),
 8820                    cx,
 8821                )
 8822            })
 8823        })?
 8824    }
 8825
 8826    async fn handle_update_diff_base(
 8827        this: Model<Self>,
 8828        envelope: TypedEnvelope<proto::UpdateDiffBase>,
 8829        mut cx: AsyncAppContext,
 8830    ) -> Result<()> {
 8831        this.update(&mut cx, |this, cx| {
 8832            let buffer_id = envelope.payload.buffer_id;
 8833            let buffer_id = BufferId::new(buffer_id)?;
 8834            if let Some(buffer) = this
 8835                .buffer_store
 8836                .read(cx)
 8837                .get_possibly_incomplete(buffer_id)
 8838            {
 8839                buffer.update(cx, |buffer, cx| {
 8840                    buffer.set_diff_base(envelope.payload.diff_base, cx)
 8841                });
 8842            }
 8843            Ok(())
 8844        })?
 8845    }
 8846
 8847    async fn handle_update_buffer_file(
 8848        this: Model<Self>,
 8849        envelope: TypedEnvelope<proto::UpdateBufferFile>,
 8850        mut cx: AsyncAppContext,
 8851    ) -> Result<()> {
 8852        let buffer_id = envelope.payload.buffer_id;
 8853        let buffer_id = BufferId::new(buffer_id)?;
 8854
 8855        this.update(&mut cx, |this, cx| {
 8856            let payload = envelope.payload.clone();
 8857            if let Some(buffer) = this
 8858                .buffer_store
 8859                .read(cx)
 8860                .get_possibly_incomplete(buffer_id)
 8861            {
 8862                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
 8863                let worktree = this
 8864                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
 8865                    .ok_or_else(|| anyhow!("no such worktree"))?;
 8866                let file = File::from_proto(file, worktree, cx)?;
 8867                buffer.update(cx, |buffer, cx| {
 8868                    buffer.file_updated(Arc::new(file), cx);
 8869                });
 8870                this.detect_language_for_buffer(&buffer, cx);
 8871            }
 8872            Ok(())
 8873        })?
 8874    }
 8875
 8876    async fn handle_save_buffer(
 8877        this: Model<Self>,
 8878        envelope: TypedEnvelope<proto::SaveBuffer>,
 8879        mut cx: AsyncAppContext,
 8880    ) -> Result<proto::BufferSaved> {
 8881        let (buffer_store, worktree, project_id) = this.update(&mut cx, |this, cx| {
 8882            let buffer_store = this.buffer_store.clone();
 8883            let project_id = this.remote_id().context("not connected")?;
 8884            let worktree = if let Some(path) = &envelope.payload.new_path {
 8885                Some(
 8886                    this.worktree_for_id(WorktreeId::from_proto(path.worktree_id), cx)
 8887                        .context("worktree does not exist")?,
 8888                )
 8889            } else {
 8890                None
 8891            };
 8892            anyhow::Ok((buffer_store, worktree, project_id))
 8893        })??;
 8894        BufferStore::handle_save_buffer(buffer_store, project_id, worktree, envelope, cx).await
 8895    }
 8896
 8897    async fn handle_reload_buffers(
 8898        this: Model<Self>,
 8899        envelope: TypedEnvelope<proto::ReloadBuffers>,
 8900        mut cx: AsyncAppContext,
 8901    ) -> Result<proto::ReloadBuffersResponse> {
 8902        let sender_id = envelope.original_sender_id()?;
 8903        let reload = this.update(&mut cx, |this, cx| {
 8904            let mut buffers = HashSet::default();
 8905            for buffer_id in &envelope.payload.buffer_ids {
 8906                let buffer_id = BufferId::new(*buffer_id)?;
 8907                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
 8908            }
 8909            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 8910        })??;
 8911
 8912        let project_transaction = reload.await?;
 8913        let project_transaction = this.update(&mut cx, |this, cx| {
 8914            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8915        })?;
 8916        Ok(proto::ReloadBuffersResponse {
 8917            transaction: Some(project_transaction),
 8918        })
 8919    }
 8920
 8921    async fn handle_synchronize_buffers(
 8922        this: Model<Self>,
 8923        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 8924        mut cx: AsyncAppContext,
 8925    ) -> Result<proto::SynchronizeBuffersResponse> {
 8926        let project_id = envelope.payload.project_id;
 8927        let mut response = proto::SynchronizeBuffersResponse {
 8928            buffers: Default::default(),
 8929        };
 8930
 8931        this.update(&mut cx, |this, cx| {
 8932            let Some(guest_id) = envelope.original_sender_id else {
 8933                error!("missing original_sender_id on SynchronizeBuffers request");
 8934                bail!("missing original_sender_id on SynchronizeBuffers request");
 8935            };
 8936
 8937            this.shared_buffers.entry(guest_id).or_default().clear();
 8938            for buffer in envelope.payload.buffers {
 8939                let buffer_id = BufferId::new(buffer.id)?;
 8940                let remote_version = language::proto::deserialize_version(&buffer.version);
 8941                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
 8942                    this.shared_buffers
 8943                        .entry(guest_id)
 8944                        .or_default()
 8945                        .insert(buffer_id);
 8946
 8947                    let buffer = buffer.read(cx);
 8948                    response.buffers.push(proto::BufferVersion {
 8949                        id: buffer_id.into(),
 8950                        version: language::proto::serialize_version(&buffer.version),
 8951                    });
 8952
 8953                    let operations = buffer.serialize_ops(Some(remote_version), cx);
 8954                    let client = this.client.clone();
 8955                    if let Some(file) = buffer.file() {
 8956                        client
 8957                            .send(proto::UpdateBufferFile {
 8958                                project_id,
 8959                                buffer_id: buffer_id.into(),
 8960                                file: Some(file.to_proto()),
 8961                            })
 8962                            .log_err();
 8963                    }
 8964
 8965                    client
 8966                        .send(proto::UpdateDiffBase {
 8967                            project_id,
 8968                            buffer_id: buffer_id.into(),
 8969                            diff_base: buffer.diff_base().map(ToString::to_string),
 8970                        })
 8971                        .log_err();
 8972
 8973                    client
 8974                        .send(proto::BufferReloaded {
 8975                            project_id,
 8976                            buffer_id: buffer_id.into(),
 8977                            version: language::proto::serialize_version(buffer.saved_version()),
 8978                            mtime: buffer.saved_mtime().map(|time| time.into()),
 8979                            line_ending: language::proto::serialize_line_ending(
 8980                                buffer.line_ending(),
 8981                            ) as i32,
 8982                        })
 8983                        .log_err();
 8984
 8985                    cx.background_executor()
 8986                        .spawn(
 8987                            async move {
 8988                                let operations = operations.await;
 8989                                for chunk in split_operations(operations) {
 8990                                    client
 8991                                        .request(proto::UpdateBuffer {
 8992                                            project_id,
 8993                                            buffer_id: buffer_id.into(),
 8994                                            operations: chunk,
 8995                                        })
 8996                                        .await?;
 8997                                }
 8998                                anyhow::Ok(())
 8999                            }
 9000                            .log_err(),
 9001                        )
 9002                        .detach();
 9003                }
 9004            }
 9005            Ok(())
 9006        })??;
 9007
 9008        Ok(response)
 9009    }
 9010
 9011    async fn handle_format_buffers(
 9012        this: Model<Self>,
 9013        envelope: TypedEnvelope<proto::FormatBuffers>,
 9014        mut cx: AsyncAppContext,
 9015    ) -> Result<proto::FormatBuffersResponse> {
 9016        let sender_id = envelope.original_sender_id()?;
 9017        let format = this.update(&mut cx, |this, cx| {
 9018            let mut buffers = HashSet::default();
 9019            for buffer_id in &envelope.payload.buffer_ids {
 9020                let buffer_id = BufferId::new(*buffer_id)?;
 9021                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
 9022            }
 9023            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 9024            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 9025        })??;
 9026
 9027        let project_transaction = format.await?;
 9028        let project_transaction = this.update(&mut cx, |this, cx| {
 9029            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9030        })?;
 9031        Ok(proto::FormatBuffersResponse {
 9032            transaction: Some(project_transaction),
 9033        })
 9034    }
 9035
 9036    async fn handle_apply_additional_edits_for_completion(
 9037        this: Model<Self>,
 9038        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 9039        mut cx: AsyncAppContext,
 9040    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 9041        let (buffer, completion) = this.update(&mut cx, |this, cx| {
 9042            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9043            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9044            let completion = Self::deserialize_completion(
 9045                envelope
 9046                    .payload
 9047                    .completion
 9048                    .ok_or_else(|| anyhow!("invalid completion"))?,
 9049            )?;
 9050            anyhow::Ok((buffer, completion))
 9051        })??;
 9052
 9053        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 9054            this.apply_additional_edits_for_completion(
 9055                buffer,
 9056                Completion {
 9057                    old_range: completion.old_range,
 9058                    new_text: completion.new_text,
 9059                    lsp_completion: completion.lsp_completion,
 9060                    server_id: completion.server_id,
 9061                    documentation: None,
 9062                    label: CodeLabel {
 9063                        text: Default::default(),
 9064                        runs: Default::default(),
 9065                        filter_range: Default::default(),
 9066                    },
 9067                    confirm: None,
 9068                    show_new_completions_on_confirm: false,
 9069                },
 9070                false,
 9071                cx,
 9072            )
 9073        })?;
 9074
 9075        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 9076            transaction: apply_additional_edits
 9077                .await?
 9078                .as_ref()
 9079                .map(language::proto::serialize_transaction),
 9080        })
 9081    }
 9082
 9083    async fn handle_resolve_completion_documentation(
 9084        this: Model<Self>,
 9085        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 9086        mut cx: AsyncAppContext,
 9087    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 9088        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 9089
 9090        let completion = this
 9091            .read_with(&mut cx, |this, _| {
 9092                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 9093                let Some(server) = this.language_server_for_id(id) else {
 9094                    return Err(anyhow!("No language server {id}"));
 9095                };
 9096
 9097                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 9098            })??
 9099            .await?;
 9100
 9101        let mut documentation_is_markdown = false;
 9102        let documentation = match completion.documentation {
 9103            Some(lsp::Documentation::String(text)) => text,
 9104
 9105            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 9106                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 9107                value
 9108            }
 9109
 9110            _ => String::new(),
 9111        };
 9112
 9113        // If we have a new buffer_id, that means we're talking to a new client
 9114        // and want to check for new text_edits in the completion too.
 9115        let mut old_start = None;
 9116        let mut old_end = None;
 9117        let mut new_text = String::default();
 9118        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 9119            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 9120                let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9121                anyhow::Ok(buffer.read(cx).snapshot())
 9122            })??;
 9123
 9124            if let Some(text_edit) = completion.text_edit.as_ref() {
 9125                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 9126
 9127                if let Some((old_range, mut text_edit_new_text)) = edit {
 9128                    LineEnding::normalize(&mut text_edit_new_text);
 9129
 9130                    new_text = text_edit_new_text;
 9131                    old_start = Some(serialize_anchor(&old_range.start));
 9132                    old_end = Some(serialize_anchor(&old_range.end));
 9133                }
 9134            }
 9135        }
 9136
 9137        Ok(proto::ResolveCompletionDocumentationResponse {
 9138            documentation,
 9139            documentation_is_markdown,
 9140            old_start,
 9141            old_end,
 9142            new_text,
 9143        })
 9144    }
 9145
 9146    async fn handle_apply_code_action(
 9147        this: Model<Self>,
 9148        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 9149        mut cx: AsyncAppContext,
 9150    ) -> Result<proto::ApplyCodeActionResponse> {
 9151        let sender_id = envelope.original_sender_id()?;
 9152        let action = Self::deserialize_code_action(
 9153            envelope
 9154                .payload
 9155                .action
 9156                .ok_or_else(|| anyhow!("invalid action"))?,
 9157        )?;
 9158        let apply_code_action = this.update(&mut cx, |this, cx| {
 9159            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9160            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9161            anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
 9162        })??;
 9163
 9164        let project_transaction = apply_code_action.await?;
 9165        let project_transaction = this.update(&mut cx, |this, cx| {
 9166            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9167        })?;
 9168        Ok(proto::ApplyCodeActionResponse {
 9169            transaction: Some(project_transaction),
 9170        })
 9171    }
 9172
 9173    async fn handle_on_type_formatting(
 9174        this: Model<Self>,
 9175        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 9176        mut cx: AsyncAppContext,
 9177    ) -> Result<proto::OnTypeFormattingResponse> {
 9178        let on_type_formatting = this.update(&mut cx, |this, cx| {
 9179            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9180            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9181            let position = envelope
 9182                .payload
 9183                .position
 9184                .and_then(deserialize_anchor)
 9185                .ok_or_else(|| anyhow!("invalid position"))?;
 9186            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 9187                buffer,
 9188                position,
 9189                envelope.payload.trigger.clone(),
 9190                cx,
 9191            ))
 9192        })??;
 9193
 9194        let transaction = on_type_formatting
 9195            .await?
 9196            .as_ref()
 9197            .map(language::proto::serialize_transaction);
 9198        Ok(proto::OnTypeFormattingResponse { transaction })
 9199    }
 9200
 9201    async fn handle_inlay_hints(
 9202        this: Model<Self>,
 9203        envelope: TypedEnvelope<proto::InlayHints>,
 9204        mut cx: AsyncAppContext,
 9205    ) -> Result<proto::InlayHintsResponse> {
 9206        let sender_id = envelope.original_sender_id()?;
 9207        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9208        let buffer = this.update(&mut cx, |this, cx| {
 9209            this.buffer_store.read(cx).get_existing(buffer_id)
 9210        })??;
 9211        buffer
 9212            .update(&mut cx, |buffer, _| {
 9213                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9214            })?
 9215            .await
 9216            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 9217
 9218        let start = envelope
 9219            .payload
 9220            .start
 9221            .and_then(deserialize_anchor)
 9222            .context("missing range start")?;
 9223        let end = envelope
 9224            .payload
 9225            .end
 9226            .and_then(deserialize_anchor)
 9227            .context("missing range end")?;
 9228        let buffer_hints = this
 9229            .update(&mut cx, |project, cx| {
 9230                project.inlay_hints(buffer.clone(), start..end, cx)
 9231            })?
 9232            .await
 9233            .context("inlay hints fetch")?;
 9234
 9235        this.update(&mut cx, |project, cx| {
 9236            InlayHints::response_to_proto(
 9237                buffer_hints,
 9238                project,
 9239                sender_id,
 9240                &buffer.read(cx).version(),
 9241                cx,
 9242            )
 9243        })
 9244    }
 9245
 9246    async fn handle_resolve_inlay_hint(
 9247        this: Model<Self>,
 9248        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 9249        mut cx: AsyncAppContext,
 9250    ) -> Result<proto::ResolveInlayHintResponse> {
 9251        let proto_hint = envelope
 9252            .payload
 9253            .hint
 9254            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9255        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9256            .context("resolved proto inlay hint conversion")?;
 9257        let buffer = this.update(&mut cx, |this, cx| {
 9258            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9259            this.buffer_store.read(cx).get_existing(buffer_id)
 9260        })??;
 9261        let response_hint = this
 9262            .update(&mut cx, |project, cx| {
 9263                project.resolve_inlay_hint(
 9264                    hint,
 9265                    buffer,
 9266                    LanguageServerId(envelope.payload.language_server_id as usize),
 9267                    cx,
 9268                )
 9269            })?
 9270            .await
 9271            .context("inlay hints fetch")?;
 9272        Ok(proto::ResolveInlayHintResponse {
 9273            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9274        })
 9275    }
 9276
 9277    async fn handle_task_context_for_location(
 9278        project: Model<Self>,
 9279        envelope: TypedEnvelope<proto::TaskContextForLocation>,
 9280        mut cx: AsyncAppContext,
 9281    ) -> Result<proto::TaskContext> {
 9282        let location = envelope
 9283            .payload
 9284            .location
 9285            .context("no location given for task context handling")?;
 9286        let location = cx
 9287            .update(|cx| deserialize_location(&project, location, cx))?
 9288            .await?;
 9289        let context_task = project.update(&mut cx, |project, cx| {
 9290            let captured_variables = {
 9291                let mut variables = TaskVariables::default();
 9292                for range in location
 9293                    .buffer
 9294                    .read(cx)
 9295                    .snapshot()
 9296                    .runnable_ranges(location.range.clone())
 9297                {
 9298                    for (capture_name, value) in range.extra_captures {
 9299                        variables.insert(VariableName::Custom(capture_name.into()), value);
 9300                    }
 9301                }
 9302                variables
 9303            };
 9304            project.task_context_for_location(captured_variables, location, cx)
 9305        })?;
 9306        let task_context = context_task.await.unwrap_or_default();
 9307        Ok(proto::TaskContext {
 9308            cwd: task_context
 9309                .cwd
 9310                .map(|cwd| cwd.to_string_lossy().to_string()),
 9311            task_variables: task_context
 9312                .task_variables
 9313                .into_iter()
 9314                .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
 9315                .collect(),
 9316        })
 9317    }
 9318
 9319    async fn handle_task_templates(
 9320        project: Model<Self>,
 9321        envelope: TypedEnvelope<proto::TaskTemplates>,
 9322        mut cx: AsyncAppContext,
 9323    ) -> Result<proto::TaskTemplatesResponse> {
 9324        let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
 9325        let location = match envelope.payload.location {
 9326            Some(location) => Some(
 9327                cx.update(|cx| deserialize_location(&project, location, cx))?
 9328                    .await
 9329                    .context("task templates request location deserializing")?,
 9330            ),
 9331            None => None,
 9332        };
 9333
 9334        let templates = project
 9335            .update(&mut cx, |project, cx| {
 9336                project.task_templates(worktree, location, cx)
 9337            })?
 9338            .await
 9339            .context("receiving task templates")?
 9340            .into_iter()
 9341            .map(|(kind, template)| {
 9342                let kind = Some(match kind {
 9343                    TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
 9344                        proto::task_source_kind::UserInput {},
 9345                    ),
 9346                    TaskSourceKind::Worktree {
 9347                        id,
 9348                        abs_path,
 9349                        id_base,
 9350                    } => {
 9351                        proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
 9352                            id: id.to_proto(),
 9353                            abs_path: abs_path.to_string_lossy().to_string(),
 9354                            id_base: id_base.to_string(),
 9355                        })
 9356                    }
 9357                    TaskSourceKind::AbsPath { id_base, abs_path } => {
 9358                        proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
 9359                            abs_path: abs_path.to_string_lossy().to_string(),
 9360                            id_base: id_base.to_string(),
 9361                        })
 9362                    }
 9363                    TaskSourceKind::Language { name } => {
 9364                        proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
 9365                            name: name.to_string(),
 9366                        })
 9367                    }
 9368                });
 9369                let kind = Some(proto::TaskSourceKind { kind });
 9370                let template = Some(proto::TaskTemplate {
 9371                    label: template.label,
 9372                    command: template.command,
 9373                    args: template.args,
 9374                    env: template.env.into_iter().collect(),
 9375                    cwd: template.cwd,
 9376                    use_new_terminal: template.use_new_terminal,
 9377                    allow_concurrent_runs: template.allow_concurrent_runs,
 9378                    reveal: match template.reveal {
 9379                        RevealStrategy::Always => proto::RevealStrategy::Always as i32,
 9380                        RevealStrategy::Never => proto::RevealStrategy::Never as i32,
 9381                    },
 9382                    tags: template.tags,
 9383                });
 9384                proto::TemplatePair { kind, template }
 9385            })
 9386            .collect();
 9387
 9388        Ok(proto::TaskTemplatesResponse { templates })
 9389    }
 9390
 9391    async fn try_resolve_code_action(
 9392        lang_server: &LanguageServer,
 9393        action: &mut CodeAction,
 9394    ) -> anyhow::Result<()> {
 9395        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 9396            if action.lsp_action.data.is_some()
 9397                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 9398            {
 9399                action.lsp_action = lang_server
 9400                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 9401                    .await?;
 9402            }
 9403        }
 9404
 9405        anyhow::Ok(())
 9406    }
 9407
 9408    async fn execute_code_actions_on_servers(
 9409        project: &WeakModel<Project>,
 9410        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 9411        code_actions: Vec<lsp::CodeActionKind>,
 9412        buffer: &Model<Buffer>,
 9413        push_to_history: bool,
 9414        project_transaction: &mut ProjectTransaction,
 9415        cx: &mut AsyncAppContext,
 9416    ) -> Result<(), anyhow::Error> {
 9417        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 9418            let code_actions = code_actions.clone();
 9419
 9420            let actions = project
 9421                .update(cx, move |this, cx| {
 9422                    let request = GetCodeActions {
 9423                        range: text::Anchor::MIN..text::Anchor::MAX,
 9424                        kinds: Some(code_actions),
 9425                    };
 9426                    let server = LanguageServerToQuery::Other(language_server.server_id());
 9427                    this.request_lsp(buffer.clone(), server, request, cx)
 9428                })?
 9429                .await?;
 9430
 9431            for mut action in actions {
 9432                Self::try_resolve_code_action(&language_server, &mut action)
 9433                    .await
 9434                    .context("resolving a formatting code action")?;
 9435
 9436                if let Some(edit) = action.lsp_action.edit {
 9437                    if edit.changes.is_none() && edit.document_changes.is_none() {
 9438                        continue;
 9439                    }
 9440
 9441                    let new = Self::deserialize_workspace_edit(
 9442                        project
 9443                            .upgrade()
 9444                            .ok_or_else(|| anyhow!("project dropped"))?,
 9445                        edit,
 9446                        push_to_history,
 9447                        lsp_adapter.clone(),
 9448                        language_server.clone(),
 9449                        cx,
 9450                    )
 9451                    .await?;
 9452                    project_transaction.0.extend(new.0);
 9453                }
 9454
 9455                if let Some(command) = action.lsp_action.command {
 9456                    project.update(cx, |this, _| {
 9457                        this.last_workspace_edits_by_language_server
 9458                            .remove(&language_server.server_id());
 9459                    })?;
 9460
 9461                    language_server
 9462                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 9463                            command: command.command,
 9464                            arguments: command.arguments.unwrap_or_default(),
 9465                            ..Default::default()
 9466                        })
 9467                        .await?;
 9468
 9469                    project.update(cx, |this, _| {
 9470                        project_transaction.0.extend(
 9471                            this.last_workspace_edits_by_language_server
 9472                                .remove(&language_server.server_id())
 9473                                .unwrap_or_default()
 9474                                .0,
 9475                        )
 9476                    })?;
 9477                }
 9478            }
 9479        }
 9480
 9481        Ok(())
 9482    }
 9483
 9484    async fn handle_refresh_inlay_hints(
 9485        this: Model<Self>,
 9486        _: TypedEnvelope<proto::RefreshInlayHints>,
 9487        mut cx: AsyncAppContext,
 9488    ) -> Result<proto::Ack> {
 9489        this.update(&mut cx, |_, cx| {
 9490            cx.emit(Event::RefreshInlayHints);
 9491        })?;
 9492        Ok(proto::Ack {})
 9493    }
 9494
 9495    async fn handle_lsp_command<T: LspCommand>(
 9496        this: Model<Self>,
 9497        envelope: TypedEnvelope<T::ProtoRequest>,
 9498        mut cx: AsyncAppContext,
 9499    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 9500    where
 9501        <T::LspRequest as lsp::request::Request>::Params: Send,
 9502        <T::LspRequest as lsp::request::Request>::Result: Send,
 9503    {
 9504        let sender_id = envelope.original_sender_id()?;
 9505        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 9506        let buffer_handle = this.update(&mut cx, |this, cx| {
 9507            this.buffer_store.read(cx).get_existing(buffer_id)
 9508        })??;
 9509        let request = T::from_proto(
 9510            envelope.payload,
 9511            this.clone(),
 9512            buffer_handle.clone(),
 9513            cx.clone(),
 9514        )
 9515        .await?;
 9516        let response = this
 9517            .update(&mut cx, |this, cx| {
 9518                this.request_lsp(
 9519                    buffer_handle.clone(),
 9520                    LanguageServerToQuery::Primary,
 9521                    request,
 9522                    cx,
 9523                )
 9524            })?
 9525            .await?;
 9526        this.update(&mut cx, |this, cx| {
 9527            Ok(T::response_to_proto(
 9528                response,
 9529                this,
 9530                sender_id,
 9531                &buffer_handle.read(cx).version(),
 9532                cx,
 9533            ))
 9534        })?
 9535    }
 9536
 9537    async fn handle_get_project_symbols(
 9538        this: Model<Self>,
 9539        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9540        mut cx: AsyncAppContext,
 9541    ) -> Result<proto::GetProjectSymbolsResponse> {
 9542        let symbols = this
 9543            .update(&mut cx, |this, cx| {
 9544                this.symbols(&envelope.payload.query, cx)
 9545            })?
 9546            .await?;
 9547
 9548        Ok(proto::GetProjectSymbolsResponse {
 9549            symbols: symbols.iter().map(serialize_symbol).collect(),
 9550        })
 9551    }
 9552
 9553    async fn handle_search_project(
 9554        this: Model<Self>,
 9555        envelope: TypedEnvelope<proto::SearchProject>,
 9556        mut cx: AsyncAppContext,
 9557    ) -> Result<proto::SearchProjectResponse> {
 9558        let peer_id = envelope.original_sender_id()?;
 9559        let query = SearchQuery::from_proto(envelope.payload)?;
 9560        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
 9561
 9562        cx.spawn(move |mut cx| async move {
 9563            let mut locations = Vec::new();
 9564            let mut limit_reached = false;
 9565            while let Some(result) = result.next().await {
 9566                match result {
 9567                    SearchResult::Buffer { buffer, ranges } => {
 9568                        for range in ranges {
 9569                            let start = serialize_anchor(&range.start);
 9570                            let end = serialize_anchor(&range.end);
 9571                            let buffer_id = this.update(&mut cx, |this, cx| {
 9572                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
 9573                            })?;
 9574                            locations.push(proto::Location {
 9575                                buffer_id,
 9576                                start: Some(start),
 9577                                end: Some(end),
 9578                            });
 9579                        }
 9580                    }
 9581                    SearchResult::LimitReached => limit_reached = true,
 9582                }
 9583            }
 9584            Ok(proto::SearchProjectResponse {
 9585                locations,
 9586                limit_reached,
 9587            })
 9588        })
 9589        .await
 9590    }
 9591
 9592    async fn handle_open_buffer_for_symbol(
 9593        this: Model<Self>,
 9594        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9595        mut cx: AsyncAppContext,
 9596    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9597        let peer_id = envelope.original_sender_id()?;
 9598        let symbol = envelope
 9599            .payload
 9600            .symbol
 9601            .ok_or_else(|| anyhow!("invalid symbol"))?;
 9602        let symbol = Self::deserialize_symbol(symbol)?;
 9603        let symbol = this.update(&mut cx, |this, _| {
 9604            let signature = this.symbol_signature(&symbol.path);
 9605            if signature == symbol.signature {
 9606                Ok(symbol)
 9607            } else {
 9608                Err(anyhow!("invalid symbol signature"))
 9609            }
 9610        })??;
 9611        let buffer = this
 9612            .update(&mut cx, |this, cx| {
 9613                this.open_buffer_for_symbol(
 9614                    &Symbol {
 9615                        language_server_name: symbol.language_server_name,
 9616                        source_worktree_id: symbol.source_worktree_id,
 9617                        path: symbol.path,
 9618                        name: symbol.name,
 9619                        kind: symbol.kind,
 9620                        range: symbol.range,
 9621                        signature: symbol.signature,
 9622                        label: CodeLabel {
 9623                            text: Default::default(),
 9624                            runs: Default::default(),
 9625                            filter_range: Default::default(),
 9626                        },
 9627                    },
 9628                    cx,
 9629                )
 9630            })?
 9631            .await?;
 9632
 9633        this.update(&mut cx, |this, cx| {
 9634            let is_private = buffer
 9635                .read(cx)
 9636                .file()
 9637                .map(|f| f.is_private())
 9638                .unwrap_or_default();
 9639            if is_private {
 9640                Err(anyhow!(ErrorCode::UnsharedItem))
 9641            } else {
 9642                Ok(proto::OpenBufferForSymbolResponse {
 9643                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9644                })
 9645            }
 9646        })?
 9647    }
 9648
 9649    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9650        let mut hasher = Sha256::new();
 9651        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9652        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9653        hasher.update(self.nonce.to_be_bytes());
 9654        hasher.finalize().as_slice().try_into().unwrap()
 9655    }
 9656
 9657    async fn handle_open_buffer_by_id(
 9658        this: Model<Self>,
 9659        envelope: TypedEnvelope<proto::OpenBufferById>,
 9660        mut cx: AsyncAppContext,
 9661    ) -> Result<proto::OpenBufferResponse> {
 9662        let peer_id = envelope.original_sender_id()?;
 9663        let buffer_id = BufferId::new(envelope.payload.id)?;
 9664        let buffer = this
 9665            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
 9666            .await?;
 9667        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9668    }
 9669
 9670    async fn handle_open_buffer_by_path(
 9671        this: Model<Self>,
 9672        envelope: TypedEnvelope<proto::OpenBufferByPath>,
 9673        mut cx: AsyncAppContext,
 9674    ) -> Result<proto::OpenBufferResponse> {
 9675        let peer_id = envelope.original_sender_id()?;
 9676        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 9677        let open_buffer = this.update(&mut cx, |this, cx| {
 9678            this.open_buffer(
 9679                ProjectPath {
 9680                    worktree_id,
 9681                    path: PathBuf::from(envelope.payload.path).into(),
 9682                },
 9683                cx,
 9684            )
 9685        })?;
 9686
 9687        let buffer = open_buffer.await?;
 9688        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9689    }
 9690
 9691    async fn handle_open_new_buffer(
 9692        this: Model<Self>,
 9693        envelope: TypedEnvelope<proto::OpenNewBuffer>,
 9694        mut cx: AsyncAppContext,
 9695    ) -> Result<proto::OpenBufferResponse> {
 9696        let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
 9697        let peer_id = envelope.original_sender_id()?;
 9698
 9699        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9700    }
 9701
 9702    fn respond_to_open_buffer_request(
 9703        this: Model<Self>,
 9704        buffer: Model<Buffer>,
 9705        peer_id: proto::PeerId,
 9706        cx: &mut AsyncAppContext,
 9707    ) -> Result<proto::OpenBufferResponse> {
 9708        this.update(cx, |this, cx| {
 9709            let is_private = buffer
 9710                .read(cx)
 9711                .file()
 9712                .map(|f| f.is_private())
 9713                .unwrap_or_default();
 9714            if is_private {
 9715                Err(anyhow!(ErrorCode::UnsharedItem))
 9716            } else {
 9717                Ok(proto::OpenBufferResponse {
 9718                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9719                })
 9720            }
 9721        })?
 9722    }
 9723
 9724    fn serialize_project_transaction_for_peer(
 9725        &mut self,
 9726        project_transaction: ProjectTransaction,
 9727        peer_id: proto::PeerId,
 9728        cx: &mut AppContext,
 9729    ) -> proto::ProjectTransaction {
 9730        let mut serialized_transaction = proto::ProjectTransaction {
 9731            buffer_ids: Default::default(),
 9732            transactions: Default::default(),
 9733        };
 9734        for (buffer, transaction) in project_transaction.0 {
 9735            serialized_transaction
 9736                .buffer_ids
 9737                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
 9738            serialized_transaction
 9739                .transactions
 9740                .push(language::proto::serialize_transaction(&transaction));
 9741        }
 9742        serialized_transaction
 9743    }
 9744
 9745    async fn deserialize_project_transaction(
 9746        this: WeakModel<Self>,
 9747        message: proto::ProjectTransaction,
 9748        push_to_history: bool,
 9749        mut cx: AsyncAppContext,
 9750    ) -> Result<ProjectTransaction> {
 9751        let mut project_transaction = ProjectTransaction::default();
 9752        for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions) {
 9753            let buffer_id = BufferId::new(buffer_id)?;
 9754            let buffer = this
 9755                .update(&mut cx, |this, cx| {
 9756                    this.wait_for_remote_buffer(buffer_id, cx)
 9757                })?
 9758                .await?;
 9759            let transaction = language::proto::deserialize_transaction(transaction)?;
 9760            project_transaction.0.insert(buffer, transaction);
 9761        }
 9762
 9763        for (buffer, transaction) in &project_transaction.0 {
 9764            buffer
 9765                .update(&mut cx, |buffer, _| {
 9766                    buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 9767                })?
 9768                .await?;
 9769
 9770            if push_to_history {
 9771                buffer.update(&mut cx, |buffer, _| {
 9772                    buffer.push_transaction(transaction.clone(), Instant::now());
 9773                })?;
 9774            }
 9775        }
 9776
 9777        Ok(project_transaction)
 9778    }
 9779
 9780    fn create_buffer_for_peer(
 9781        &mut self,
 9782        buffer: &Model<Buffer>,
 9783        peer_id: proto::PeerId,
 9784        cx: &mut AppContext,
 9785    ) -> BufferId {
 9786        let buffer_id = buffer.read(cx).remote_id();
 9787        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
 9788            updates_tx
 9789                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
 9790                .ok();
 9791        }
 9792        buffer_id
 9793    }
 9794
 9795    fn wait_for_remote_buffer(
 9796        &mut self,
 9797        id: BufferId,
 9798        cx: &mut ModelContext<Self>,
 9799    ) -> Task<Result<Model<Buffer>>> {
 9800        self.buffer_store.update(cx, |buffer_store, cx| {
 9801            buffer_store.wait_for_remote_buffer(id, cx)
 9802        })
 9803    }
 9804
 9805    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 9806        let project_id = match self.client_state {
 9807            ProjectClientState::Remote {
 9808                sharing_has_stopped,
 9809                remote_id,
 9810                ..
 9811            } => {
 9812                if sharing_has_stopped {
 9813                    return Task::ready(Err(anyhow!(
 9814                        "can't synchronize remote buffers on a readonly project"
 9815                    )));
 9816                } else {
 9817                    remote_id
 9818                }
 9819            }
 9820            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
 9821                return Task::ready(Err(anyhow!(
 9822                    "can't synchronize remote buffers on a local project"
 9823                )))
 9824            }
 9825        };
 9826
 9827        let client = self.client.clone();
 9828        cx.spawn(move |this, mut cx| async move {
 9829            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
 9830                this.buffer_store.read(cx).buffer_version_info(cx)
 9831            })?;
 9832            let response = client
 9833                .request(proto::SynchronizeBuffers {
 9834                    project_id,
 9835                    buffers,
 9836                })
 9837                .await?;
 9838
 9839            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
 9840                response
 9841                    .buffers
 9842                    .into_iter()
 9843                    .map(|buffer| {
 9844                        let client = client.clone();
 9845                        let buffer_id = match BufferId::new(buffer.id) {
 9846                            Ok(id) => id,
 9847                            Err(e) => {
 9848                                return Task::ready(Err(e));
 9849                            }
 9850                        };
 9851                        let remote_version = language::proto::deserialize_version(&buffer.version);
 9852                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
 9853                            let operations =
 9854                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
 9855                            cx.background_executor().spawn(async move {
 9856                                let operations = operations.await;
 9857                                for chunk in split_operations(operations) {
 9858                                    client
 9859                                        .request(proto::UpdateBuffer {
 9860                                            project_id,
 9861                                            buffer_id: buffer_id.into(),
 9862                                            operations: chunk,
 9863                                        })
 9864                                        .await?;
 9865                                }
 9866                                anyhow::Ok(())
 9867                            })
 9868                        } else {
 9869                            Task::ready(Ok(()))
 9870                        }
 9871                    })
 9872                    .collect::<Vec<_>>()
 9873            })?;
 9874
 9875            // Any incomplete buffers have open requests waiting. Request that the host sends
 9876            // creates these buffers for us again to unblock any waiting futures.
 9877            for id in incomplete_buffer_ids {
 9878                cx.background_executor()
 9879                    .spawn(client.request(proto::OpenBufferById {
 9880                        project_id,
 9881                        id: id.into(),
 9882                    }))
 9883                    .detach();
 9884            }
 9885
 9886            futures::future::join_all(send_updates_for_buffers)
 9887                .await
 9888                .into_iter()
 9889                .collect()
 9890        })
 9891    }
 9892
 9893    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
 9894        self.worktrees()
 9895            .map(|worktree| {
 9896                let worktree = worktree.read(cx);
 9897                proto::WorktreeMetadata {
 9898                    id: worktree.id().to_proto(),
 9899                    root_name: worktree.root_name().into(),
 9900                    visible: worktree.is_visible(),
 9901                    abs_path: worktree.abs_path().to_string_lossy().into(),
 9902                }
 9903            })
 9904            .collect()
 9905    }
 9906
 9907    fn set_worktrees_from_proto(
 9908        &mut self,
 9909        worktrees: Vec<proto::WorktreeMetadata>,
 9910        cx: &mut ModelContext<Project>,
 9911    ) -> Result<()> {
 9912        let replica_id = self.replica_id();
 9913        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
 9914
 9915        let mut old_worktrees_by_id = self
 9916            .worktrees
 9917            .drain(..)
 9918            .filter_map(|worktree| {
 9919                let worktree = worktree.upgrade()?;
 9920                Some((worktree.read(cx).id(), worktree))
 9921            })
 9922            .collect::<HashMap<_, _>>();
 9923
 9924        for worktree in worktrees {
 9925            if let Some(old_worktree) =
 9926                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 9927            {
 9928                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
 9929            } else {
 9930                self.add_worktree(
 9931                    &Worktree::remote(
 9932                        remote_id,
 9933                        replica_id,
 9934                        worktree,
 9935                        self.client.clone().into(),
 9936                        cx,
 9937                    ),
 9938                    cx,
 9939                );
 9940            }
 9941        }
 9942
 9943        self.metadata_changed(cx);
 9944        for id in old_worktrees_by_id.keys() {
 9945            cx.emit(Event::WorktreeRemoved(*id));
 9946        }
 9947
 9948        Ok(())
 9949    }
 9950
 9951    fn set_collaborators_from_proto(
 9952        &mut self,
 9953        messages: Vec<proto::Collaborator>,
 9954        cx: &mut ModelContext<Self>,
 9955    ) -> Result<()> {
 9956        let mut collaborators = HashMap::default();
 9957        for message in messages {
 9958            let collaborator = Collaborator::from_proto(message)?;
 9959            collaborators.insert(collaborator.peer_id, collaborator);
 9960        }
 9961        for old_peer_id in self.collaborators.keys() {
 9962            if !collaborators.contains_key(old_peer_id) {
 9963                cx.emit(Event::CollaboratorLeft(*old_peer_id));
 9964            }
 9965        }
 9966        self.collaborators = collaborators;
 9967        Ok(())
 9968    }
 9969
 9970    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
 9971        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
 9972        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
 9973        let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
 9974        let path = ProjectPath {
 9975            worktree_id,
 9976            path: PathBuf::from(serialized_symbol.path).into(),
 9977        };
 9978
 9979        let start = serialized_symbol
 9980            .start
 9981            .ok_or_else(|| anyhow!("invalid start"))?;
 9982        let end = serialized_symbol
 9983            .end
 9984            .ok_or_else(|| anyhow!("invalid end"))?;
 9985        Ok(CoreSymbol {
 9986            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
 9987            source_worktree_id,
 9988            path,
 9989            name: serialized_symbol.name,
 9990            range: Unclipped(PointUtf16::new(start.row, start.column))
 9991                ..Unclipped(PointUtf16::new(end.row, end.column)),
 9992            kind,
 9993            signature: serialized_symbol
 9994                .signature
 9995                .try_into()
 9996                .map_err(|_| anyhow!("invalid signature"))?,
 9997        })
 9998    }
 9999
10000    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
10001        proto::Completion {
10002            old_start: Some(serialize_anchor(&completion.old_range.start)),
10003            old_end: Some(serialize_anchor(&completion.old_range.end)),
10004            new_text: completion.new_text.clone(),
10005            server_id: completion.server_id.0 as u64,
10006            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
10007        }
10008    }
10009
10010    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
10011        let old_start = completion
10012            .old_start
10013            .and_then(deserialize_anchor)
10014            .ok_or_else(|| anyhow!("invalid old start"))?;
10015        let old_end = completion
10016            .old_end
10017            .and_then(deserialize_anchor)
10018            .ok_or_else(|| anyhow!("invalid old end"))?;
10019        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
10020
10021        Ok(CoreCompletion {
10022            old_range: old_start..old_end,
10023            new_text: completion.new_text,
10024            server_id: LanguageServerId(completion.server_id as usize),
10025            lsp_completion,
10026        })
10027    }
10028
10029    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
10030        proto::CodeAction {
10031            server_id: action.server_id.0 as u64,
10032            start: Some(serialize_anchor(&action.range.start)),
10033            end: Some(serialize_anchor(&action.range.end)),
10034            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
10035        }
10036    }
10037
10038    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
10039        let start = action
10040            .start
10041            .and_then(deserialize_anchor)
10042            .ok_or_else(|| anyhow!("invalid start"))?;
10043        let end = action
10044            .end
10045            .and_then(deserialize_anchor)
10046            .ok_or_else(|| anyhow!("invalid end"))?;
10047        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
10048        Ok(CodeAction {
10049            server_id: LanguageServerId(action.server_id as usize),
10050            range: start..end,
10051            lsp_action,
10052        })
10053    }
10054
10055    async fn handle_buffer_saved(
10056        this: Model<Self>,
10057        envelope: TypedEnvelope<proto::BufferSaved>,
10058        mut cx: AsyncAppContext,
10059    ) -> Result<()> {
10060        let version = deserialize_version(&envelope.payload.version);
10061        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
10062        let mtime = envelope.payload.mtime.map(|time| time.into());
10063
10064        this.update(&mut cx, |this, cx| {
10065            let buffer = this
10066                .buffer_store
10067                .read(cx)
10068                .get_possibly_incomplete(buffer_id);
10069            if let Some(buffer) = buffer {
10070                buffer.update(cx, |buffer, cx| {
10071                    buffer.did_save(version, mtime, cx);
10072                });
10073            }
10074            Ok(())
10075        })?
10076    }
10077
10078    async fn handle_buffer_reloaded(
10079        this: Model<Self>,
10080        envelope: TypedEnvelope<proto::BufferReloaded>,
10081        mut cx: AsyncAppContext,
10082    ) -> Result<()> {
10083        let payload = envelope.payload;
10084        let version = deserialize_version(&payload.version);
10085        let line_ending = deserialize_line_ending(
10086            proto::LineEnding::from_i32(payload.line_ending)
10087                .ok_or_else(|| anyhow!("missing line ending"))?,
10088        );
10089        let mtime = payload.mtime.map(|time| time.into());
10090        let buffer_id = BufferId::new(payload.buffer_id)?;
10091        this.update(&mut cx, |this, cx| {
10092            if let Some(buffer) = this
10093                .buffer_store
10094                .read(cx)
10095                .get_possibly_incomplete(buffer_id)
10096            {
10097                buffer.update(cx, |buffer, cx| {
10098                    buffer.did_reload(version, line_ending, mtime, cx);
10099                });
10100            }
10101            Ok(())
10102        })?
10103    }
10104
10105    #[allow(clippy::type_complexity)]
10106    fn edits_from_lsp(
10107        &mut self,
10108        buffer: &Model<Buffer>,
10109        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
10110        server_id: LanguageServerId,
10111        version: Option<i32>,
10112        cx: &mut ModelContext<Self>,
10113    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
10114        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
10115        cx.background_executor().spawn(async move {
10116            let snapshot = snapshot?;
10117            let mut lsp_edits = lsp_edits
10118                .into_iter()
10119                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
10120                .collect::<Vec<_>>();
10121            lsp_edits.sort_by_key(|(range, _)| range.start);
10122
10123            let mut lsp_edits = lsp_edits.into_iter().peekable();
10124            let mut edits = Vec::new();
10125            while let Some((range, mut new_text)) = lsp_edits.next() {
10126                // Clip invalid ranges provided by the language server.
10127                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
10128                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
10129
10130                // Combine any LSP edits that are adjacent.
10131                //
10132                // Also, combine LSP edits that are separated from each other by only
10133                // a newline. This is important because for some code actions,
10134                // Rust-analyzer rewrites the entire buffer via a series of edits that
10135                // are separated by unchanged newline characters.
10136                //
10137                // In order for the diffing logic below to work properly, any edits that
10138                // cancel each other out must be combined into one.
10139                while let Some((next_range, next_text)) = lsp_edits.peek() {
10140                    if next_range.start.0 > range.end {
10141                        if next_range.start.0.row > range.end.row + 1
10142                            || next_range.start.0.column > 0
10143                            || snapshot.clip_point_utf16(
10144                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
10145                                Bias::Left,
10146                            ) > range.end
10147                        {
10148                            break;
10149                        }
10150                        new_text.push('\n');
10151                    }
10152                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
10153                    new_text.push_str(next_text);
10154                    lsp_edits.next();
10155                }
10156
10157                // For multiline edits, perform a diff of the old and new text so that
10158                // we can identify the changes more precisely, preserving the locations
10159                // of any anchors positioned in the unchanged regions.
10160                if range.end.row > range.start.row {
10161                    let mut offset = range.start.to_offset(&snapshot);
10162                    let old_text = snapshot.text_for_range(range).collect::<String>();
10163
10164                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
10165                    let mut moved_since_edit = true;
10166                    for change in diff.iter_all_changes() {
10167                        let tag = change.tag();
10168                        let value = change.value();
10169                        match tag {
10170                            ChangeTag::Equal => {
10171                                offset += value.len();
10172                                moved_since_edit = true;
10173                            }
10174                            ChangeTag::Delete => {
10175                                let start = snapshot.anchor_after(offset);
10176                                let end = snapshot.anchor_before(offset + value.len());
10177                                if moved_since_edit {
10178                                    edits.push((start..end, String::new()));
10179                                } else {
10180                                    edits.last_mut().unwrap().0.end = end;
10181                                }
10182                                offset += value.len();
10183                                moved_since_edit = false;
10184                            }
10185                            ChangeTag::Insert => {
10186                                if moved_since_edit {
10187                                    let anchor = snapshot.anchor_after(offset);
10188                                    edits.push((anchor..anchor, value.to_string()));
10189                                } else {
10190                                    edits.last_mut().unwrap().1.push_str(value);
10191                                }
10192                                moved_since_edit = false;
10193                            }
10194                        }
10195                    }
10196                } else if range.end == range.start {
10197                    let anchor = snapshot.anchor_after(range.start);
10198                    edits.push((anchor..anchor, new_text));
10199                } else {
10200                    let edit_start = snapshot.anchor_after(range.start);
10201                    let edit_end = snapshot.anchor_before(range.end);
10202                    edits.push((edit_start..edit_end, new_text));
10203                }
10204            }
10205
10206            Ok(edits)
10207        })
10208    }
10209
10210    fn buffer_snapshot_for_lsp_version(
10211        &mut self,
10212        buffer: &Model<Buffer>,
10213        server_id: LanguageServerId,
10214        version: Option<i32>,
10215        cx: &AppContext,
10216    ) -> Result<TextBufferSnapshot> {
10217        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
10218
10219        if let Some(version) = version {
10220            let buffer_id = buffer.read(cx).remote_id();
10221            let snapshots = self
10222                .buffer_snapshots
10223                .get_mut(&buffer_id)
10224                .and_then(|m| m.get_mut(&server_id))
10225                .ok_or_else(|| {
10226                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
10227                })?;
10228
10229            let found_snapshot = snapshots
10230                .binary_search_by_key(&version, |e| e.version)
10231                .map(|ix| snapshots[ix].snapshot.clone())
10232                .map_err(|_| {
10233                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
10234                })?;
10235
10236            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
10237            Ok(found_snapshot)
10238        } else {
10239            Ok((buffer.read(cx)).text_snapshot())
10240        }
10241    }
10242
10243    pub fn language_servers(
10244        &self,
10245    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
10246        self.language_server_ids
10247            .iter()
10248            .map(|((worktree_id, server_name), server_id)| {
10249                (*server_id, server_name.clone(), *worktree_id)
10250            })
10251    }
10252
10253    pub fn supplementary_language_servers(
10254        &self,
10255    ) -> impl '_
10256           + Iterator<
10257        Item = (
10258            &LanguageServerId,
10259            &(LanguageServerName, Arc<LanguageServer>),
10260        ),
10261    > {
10262        self.supplementary_language_servers.iter()
10263    }
10264
10265    pub fn language_server_adapter_for_id(
10266        &self,
10267        id: LanguageServerId,
10268    ) -> Option<Arc<CachedLspAdapter>> {
10269        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
10270            Some(adapter.clone())
10271        } else {
10272            None
10273        }
10274    }
10275
10276    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
10277        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
10278            Some(server.clone())
10279        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
10280            Some(Arc::clone(server))
10281        } else {
10282            None
10283        }
10284    }
10285
10286    pub fn language_servers_for_buffer(
10287        &self,
10288        buffer: &Buffer,
10289        cx: &AppContext,
10290    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10291        self.language_server_ids_for_buffer(buffer, cx)
10292            .into_iter()
10293            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
10294                LanguageServerState::Running {
10295                    adapter, server, ..
10296                } => Some((adapter, server)),
10297                _ => None,
10298            })
10299    }
10300
10301    fn primary_language_server_for_buffer(
10302        &self,
10303        buffer: &Buffer,
10304        cx: &AppContext,
10305    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10306        self.language_servers_for_buffer(buffer, cx)
10307            .find(|s| s.0.is_primary)
10308    }
10309
10310    pub fn language_server_for_buffer(
10311        &self,
10312        buffer: &Buffer,
10313        server_id: LanguageServerId,
10314        cx: &AppContext,
10315    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10316        self.language_servers_for_buffer(buffer, cx)
10317            .find(|(_, s)| s.server_id() == server_id)
10318    }
10319
10320    fn language_server_ids_for_buffer(
10321        &self,
10322        buffer: &Buffer,
10323        cx: &AppContext,
10324    ) -> Vec<LanguageServerId> {
10325        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
10326            let worktree_id = file.worktree_id(cx);
10327            self.languages
10328                .lsp_adapters(&language)
10329                .iter()
10330                .flat_map(|adapter| {
10331                    let key = (worktree_id, adapter.name.clone());
10332                    self.language_server_ids.get(&key).copied()
10333                })
10334                .collect()
10335        } else {
10336            Vec::new()
10337        }
10338    }
10339
10340    pub fn task_context_for_location(
10341        &self,
10342        captured_variables: TaskVariables,
10343        location: Location,
10344        cx: &mut ModelContext<'_, Project>,
10345    ) -> Task<Option<TaskContext>> {
10346        if self.is_local() {
10347            let cwd = self.task_cwd(cx).log_err().flatten();
10348
10349            cx.spawn(|project, cx| async move {
10350                let mut task_variables = cx
10351                    .update(|cx| {
10352                        combine_task_variables(
10353                            captured_variables,
10354                            location,
10355                            BasicContextProvider::new(project.upgrade()?),
10356                            cx,
10357                        )
10358                        .log_err()
10359                    })
10360                    .ok()
10361                    .flatten()?;
10362                // Remove all custom entries starting with _, as they're not intended for use by the end user.
10363                task_variables.sweep();
10364                Some(TaskContext {
10365                    cwd,
10366                    task_variables,
10367                })
10368            })
10369        } else if let Some(project_id) = self
10370            .remote_id()
10371            .filter(|_| self.ssh_connection_string(cx).is_some())
10372        {
10373            let task_context = self.client().request(proto::TaskContextForLocation {
10374                project_id,
10375                location: Some(proto::Location {
10376                    buffer_id: location.buffer.read(cx).remote_id().into(),
10377                    start: Some(serialize_anchor(&location.range.start)),
10378                    end: Some(serialize_anchor(&location.range.end)),
10379                }),
10380            });
10381            cx.background_executor().spawn(async move {
10382                let task_context = task_context.await.log_err()?;
10383                Some(TaskContext {
10384                    cwd: task_context.cwd.map(PathBuf::from),
10385                    task_variables: task_context
10386                        .task_variables
10387                        .into_iter()
10388                        .filter_map(
10389                            |(variable_name, variable_value)| match variable_name.parse() {
10390                                Ok(variable_name) => Some((variable_name, variable_value)),
10391                                Err(()) => {
10392                                    log::error!("Unknown variable name: {variable_name}");
10393                                    None
10394                                }
10395                            },
10396                        )
10397                        .collect(),
10398                })
10399            })
10400        } else {
10401            Task::ready(None)
10402        }
10403    }
10404
10405    pub fn task_templates(
10406        &self,
10407        worktree: Option<WorktreeId>,
10408        location: Option<Location>,
10409        cx: &mut ModelContext<Self>,
10410    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10411        if self.is_local() {
10412            let (file, language) = location
10413                .map(|location| {
10414                    let buffer = location.buffer.read(cx);
10415                    (
10416                        buffer.file().cloned(),
10417                        buffer.language_at(location.range.start),
10418                    )
10419                })
10420                .unwrap_or_default();
10421            Task::ready(Ok(self
10422                .task_inventory()
10423                .read(cx)
10424                .list_tasks(file, language, worktree, cx)))
10425        } else if let Some(project_id) = self
10426            .remote_id()
10427            .filter(|_| self.ssh_connection_string(cx).is_some())
10428        {
10429            let remote_templates =
10430                self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
10431            cx.background_executor().spawn(remote_templates)
10432        } else {
10433            Task::ready(Ok(Vec::new()))
10434        }
10435    }
10436
10437    pub fn query_remote_task_templates(
10438        &self,
10439        project_id: u64,
10440        worktree: Option<WorktreeId>,
10441        location: Option<&Location>,
10442        cx: &AppContext,
10443    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10444        let client = self.client();
10445        let location = location.map(|location| serialize_location(location, cx));
10446        cx.spawn(|_| async move {
10447            let response = client
10448                .request(proto::TaskTemplates {
10449                    project_id,
10450                    worktree_id: worktree.map(|id| id.to_proto()),
10451                    location,
10452                })
10453                .await?;
10454
10455            Ok(response
10456                .templates
10457                .into_iter()
10458                .filter_map(|template_pair| {
10459                    let task_source_kind = match template_pair.kind?.kind? {
10460                        proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
10461                        proto::task_source_kind::Kind::Worktree(worktree) => {
10462                            TaskSourceKind::Worktree {
10463                                id: WorktreeId::from_proto(worktree.id),
10464                                abs_path: PathBuf::from(worktree.abs_path),
10465                                id_base: Cow::Owned(worktree.id_base),
10466                            }
10467                        }
10468                        proto::task_source_kind::Kind::AbsPath(abs_path) => {
10469                            TaskSourceKind::AbsPath {
10470                                id_base: Cow::Owned(abs_path.id_base),
10471                                abs_path: PathBuf::from(abs_path.abs_path),
10472                            }
10473                        }
10474                        proto::task_source_kind::Kind::Language(language) => {
10475                            TaskSourceKind::Language {
10476                                name: language.name.into(),
10477                            }
10478                        }
10479                    };
10480
10481                    let proto_template = template_pair.template?;
10482                    let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
10483                        .unwrap_or(proto::RevealStrategy::Always)
10484                    {
10485                        proto::RevealStrategy::Always => RevealStrategy::Always,
10486                        proto::RevealStrategy::Never => RevealStrategy::Never,
10487                    };
10488                    let task_template = TaskTemplate {
10489                        label: proto_template.label,
10490                        command: proto_template.command,
10491                        args: proto_template.args,
10492                        env: proto_template.env.into_iter().collect(),
10493                        cwd: proto_template.cwd,
10494                        use_new_terminal: proto_template.use_new_terminal,
10495                        allow_concurrent_runs: proto_template.allow_concurrent_runs,
10496                        reveal,
10497                        tags: proto_template.tags,
10498                    };
10499                    Some((task_source_kind, task_template))
10500                })
10501                .collect())
10502        })
10503    }
10504
10505    fn task_cwd(&self, cx: &AppContext) -> anyhow::Result<Option<PathBuf>> {
10506        let available_worktrees = self
10507            .worktrees()
10508            .filter(|worktree| {
10509                let worktree = worktree.read(cx);
10510                worktree.is_visible()
10511                    && worktree.is_local()
10512                    && worktree.root_entry().map_or(false, |e| e.is_dir())
10513            })
10514            .collect::<Vec<_>>();
10515        let cwd = match available_worktrees.len() {
10516            0 => None,
10517            1 => Some(available_worktrees[0].read(cx).abs_path()),
10518            _ => {
10519                let cwd_for_active_entry = self.active_entry().and_then(|entry_id| {
10520                    available_worktrees.into_iter().find_map(|worktree| {
10521                        let worktree = worktree.read(cx);
10522                        if worktree.contains_entry(entry_id) {
10523                            Some(worktree.abs_path())
10524                        } else {
10525                            None
10526                        }
10527                    })
10528                });
10529                anyhow::ensure!(
10530                    cwd_for_active_entry.is_some(),
10531                    "Cannot determine task cwd for multiple worktrees"
10532                );
10533                cwd_for_active_entry
10534            }
10535        };
10536        Ok(cwd.map(|path| path.to_path_buf()))
10537    }
10538}
10539
10540fn combine_task_variables(
10541    mut captured_variables: TaskVariables,
10542    location: Location,
10543    baseline: BasicContextProvider,
10544    cx: &mut AppContext,
10545) -> anyhow::Result<TaskVariables> {
10546    let language_context_provider = location
10547        .buffer
10548        .read(cx)
10549        .language()
10550        .and_then(|language| language.context_provider());
10551    let baseline = baseline
10552        .build_context(&captured_variables, &location, cx)
10553        .context("building basic default context")?;
10554    captured_variables.extend(baseline);
10555    if let Some(provider) = language_context_provider {
10556        captured_variables.extend(
10557            provider
10558                .build_context(&captured_variables, &location, cx)
10559                .context("building provider context")?,
10560        );
10561    }
10562    Ok(captured_variables)
10563}
10564
10565async fn populate_labels_for_symbols(
10566    symbols: Vec<CoreSymbol>,
10567    language_registry: &Arc<LanguageRegistry>,
10568    default_language: Option<Arc<Language>>,
10569    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10570    output: &mut Vec<Symbol>,
10571) {
10572    #[allow(clippy::mutable_key_type)]
10573    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10574
10575    let mut unknown_path = None;
10576    for symbol in symbols {
10577        let language = language_registry
10578            .language_for_file_path(&symbol.path.path)
10579            .await
10580            .ok()
10581            .or_else(|| {
10582                unknown_path.get_or_insert(symbol.path.path.clone());
10583                default_language.clone()
10584            });
10585        symbols_by_language
10586            .entry(language)
10587            .or_default()
10588            .push(symbol);
10589    }
10590
10591    if let Some(unknown_path) = unknown_path {
10592        log::info!(
10593            "no language found for symbol path {}",
10594            unknown_path.display()
10595        );
10596    }
10597
10598    let mut label_params = Vec::new();
10599    for (language, mut symbols) in symbols_by_language {
10600        label_params.clear();
10601        label_params.extend(
10602            symbols
10603                .iter_mut()
10604                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10605        );
10606
10607        let mut labels = Vec::new();
10608        if let Some(language) = language {
10609            let lsp_adapter = lsp_adapter
10610                .clone()
10611                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
10612            if let Some(lsp_adapter) = lsp_adapter {
10613                labels = lsp_adapter
10614                    .labels_for_symbols(&label_params, &language)
10615                    .await
10616                    .log_err()
10617                    .unwrap_or_default();
10618            }
10619        }
10620
10621        for ((symbol, (name, _)), label) in symbols
10622            .into_iter()
10623            .zip(label_params.drain(..))
10624            .zip(labels.into_iter().chain(iter::repeat(None)))
10625        {
10626            output.push(Symbol {
10627                language_server_name: symbol.language_server_name,
10628                source_worktree_id: symbol.source_worktree_id,
10629                path: symbol.path,
10630                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10631                name,
10632                kind: symbol.kind,
10633                range: symbol.range,
10634                signature: symbol.signature,
10635            });
10636        }
10637    }
10638}
10639
10640async fn populate_labels_for_completions(
10641    mut new_completions: Vec<CoreCompletion>,
10642    language_registry: &Arc<LanguageRegistry>,
10643    language: Option<Arc<Language>>,
10644    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10645    completions: &mut Vec<Completion>,
10646) {
10647    let lsp_completions = new_completions
10648        .iter_mut()
10649        .map(|completion| mem::take(&mut completion.lsp_completion))
10650        .collect::<Vec<_>>();
10651
10652    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10653        lsp_adapter
10654            .labels_for_completions(&lsp_completions, language)
10655            .await
10656            .log_err()
10657            .unwrap_or_default()
10658    } else {
10659        Vec::new()
10660    };
10661
10662    for ((completion, lsp_completion), label) in new_completions
10663        .into_iter()
10664        .zip(lsp_completions)
10665        .zip(labels.into_iter().chain(iter::repeat(None)))
10666    {
10667        let documentation = if let Some(docs) = &lsp_completion.documentation {
10668            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
10669        } else {
10670            None
10671        };
10672
10673        completions.push(Completion {
10674            old_range: completion.old_range,
10675            new_text: completion.new_text,
10676            label: label.unwrap_or_else(|| {
10677                CodeLabel::plain(
10678                    lsp_completion.label.clone(),
10679                    lsp_completion.filter_text.as_deref(),
10680                )
10681            }),
10682            server_id: completion.server_id,
10683            documentation,
10684            lsp_completion,
10685            confirm: None,
10686            show_new_completions_on_confirm: false,
10687        })
10688    }
10689}
10690
10691fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
10692    code_actions
10693        .iter()
10694        .flat_map(|(kind, enabled)| {
10695            if *enabled {
10696                Some(kind.clone().into())
10697            } else {
10698                None
10699            }
10700        })
10701        .collect()
10702}
10703
10704#[allow(clippy::too_many_arguments)]
10705async fn search_snapshots(
10706    snapshots: &Vec<(Snapshot, WorktreeSettings)>,
10707    worker_start_ix: usize,
10708    worker_end_ix: usize,
10709    query: &SearchQuery,
10710    results_tx: &Sender<SearchMatchCandidate>,
10711    opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
10712    include_root: bool,
10713    fs: &Arc<dyn Fs>,
10714) {
10715    let mut snapshot_start_ix = 0;
10716    let mut abs_path = PathBuf::new();
10717
10718    for (snapshot, _) in snapshots {
10719        let snapshot_end_ix = snapshot_start_ix
10720            + if query.include_ignored() {
10721                snapshot.file_count()
10722            } else {
10723                snapshot.visible_file_count()
10724            };
10725        if worker_end_ix <= snapshot_start_ix {
10726            break;
10727        } else if worker_start_ix > snapshot_end_ix {
10728            snapshot_start_ix = snapshot_end_ix;
10729            continue;
10730        } else {
10731            let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
10732            let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
10733
10734            for entry in snapshot
10735                .files(false, start_in_snapshot)
10736                .take(end_in_snapshot - start_in_snapshot)
10737            {
10738                if results_tx.is_closed() {
10739                    break;
10740                }
10741                if opened_buffers.contains_key(&entry.path) {
10742                    continue;
10743                }
10744
10745                let matched_path = if include_root {
10746                    let mut full_path = PathBuf::from(snapshot.root_name());
10747                    full_path.push(&entry.path);
10748                    query.file_matches(Some(&full_path))
10749                } else {
10750                    query.file_matches(Some(&entry.path))
10751                };
10752
10753                let matches = if matched_path {
10754                    abs_path.clear();
10755                    abs_path.push(&snapshot.abs_path());
10756                    abs_path.push(&entry.path);
10757                    if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
10758                        query.detect(file).unwrap_or(false)
10759                    } else {
10760                        false
10761                    }
10762                } else {
10763                    false
10764                };
10765
10766                if matches {
10767                    let project_path = SearchMatchCandidate::Path {
10768                        worktree_id: snapshot.id(),
10769                        path: entry.path.clone(),
10770                        is_ignored: entry.is_ignored,
10771                        is_file: entry.is_file(),
10772                    };
10773                    if results_tx.send(project_path).await.is_err() {
10774                        return;
10775                    }
10776                }
10777            }
10778
10779            snapshot_start_ix = snapshot_end_ix;
10780        }
10781    }
10782}
10783
10784async fn search_ignored_entry(
10785    snapshot: &Snapshot,
10786    settings: &WorktreeSettings,
10787    ignored_entry: &Entry,
10788    fs: &Arc<dyn Fs>,
10789    query: &SearchQuery,
10790    counter_tx: &Sender<SearchMatchCandidate>,
10791) {
10792    let mut ignored_paths_to_process =
10793        VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
10794
10795    while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
10796        let metadata = fs
10797            .metadata(&ignored_abs_path)
10798            .await
10799            .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
10800            .log_err()
10801            .flatten();
10802
10803        if let Some(fs_metadata) = metadata {
10804            if fs_metadata.is_dir {
10805                let files = fs
10806                    .read_dir(&ignored_abs_path)
10807                    .await
10808                    .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
10809                    .log_err();
10810
10811                if let Some(mut subfiles) = files {
10812                    while let Some(subfile) = subfiles.next().await {
10813                        if let Some(subfile) = subfile.log_err() {
10814                            ignored_paths_to_process.push_back(subfile);
10815                        }
10816                    }
10817                }
10818            } else if !fs_metadata.is_symlink {
10819                if !query.file_matches(Some(&ignored_abs_path))
10820                    || settings.is_path_excluded(&ignored_entry.path)
10821                {
10822                    continue;
10823                }
10824                let matches = if let Some(file) = fs
10825                    .open_sync(&ignored_abs_path)
10826                    .await
10827                    .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
10828                    .log_err()
10829                {
10830                    query.detect(file).unwrap_or(false)
10831                } else {
10832                    false
10833                };
10834
10835                if matches {
10836                    let project_path = SearchMatchCandidate::Path {
10837                        worktree_id: snapshot.id(),
10838                        path: Arc::from(
10839                            ignored_abs_path
10840                                .strip_prefix(snapshot.abs_path())
10841                                .expect("scanning worktree-related files"),
10842                        ),
10843                        is_ignored: true,
10844                        is_file: ignored_entry.is_file(),
10845                    };
10846                    if counter_tx.send(project_path).await.is_err() {
10847                        return;
10848                    }
10849                }
10850            }
10851        }
10852    }
10853}
10854
10855fn glob_literal_prefix(glob: &str) -> &str {
10856    let mut literal_end = 0;
10857    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
10858        if part.contains(&['*', '?', '{', '}']) {
10859            break;
10860        } else {
10861            if i > 0 {
10862                // Account for separator prior to this part
10863                literal_end += path::MAIN_SEPARATOR.len_utf8();
10864            }
10865            literal_end += part.len();
10866        }
10867    }
10868    &glob[..literal_end]
10869}
10870
10871impl WorktreeHandle {
10872    pub fn upgrade(&self) -> Option<Model<Worktree>> {
10873        match self {
10874            WorktreeHandle::Strong(handle) => Some(handle.clone()),
10875            WorktreeHandle::Weak(handle) => handle.upgrade(),
10876        }
10877    }
10878
10879    pub fn handle_id(&self) -> usize {
10880        match self {
10881            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
10882            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
10883        }
10884    }
10885}
10886
10887pub struct PathMatchCandidateSet {
10888    pub snapshot: Snapshot,
10889    pub include_ignored: bool,
10890    pub include_root_name: bool,
10891    pub candidates: Candidates,
10892}
10893
10894pub enum Candidates {
10895    /// Only consider directories.
10896    Directories,
10897    /// Only consider files.
10898    Files,
10899    /// Consider directories and files.
10900    Entries,
10901}
10902
10903impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
10904    type Candidates = PathMatchCandidateSetIter<'a>;
10905
10906    fn id(&self) -> usize {
10907        self.snapshot.id().to_usize()
10908    }
10909
10910    fn len(&self) -> usize {
10911        if self.include_ignored {
10912            self.snapshot.file_count()
10913        } else {
10914            self.snapshot.visible_file_count()
10915        }
10916    }
10917
10918    fn prefix(&self) -> Arc<str> {
10919        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
10920            self.snapshot.root_name().into()
10921        } else if self.include_root_name {
10922            format!("{}/", self.snapshot.root_name()).into()
10923        } else {
10924            "".into()
10925        }
10926    }
10927
10928    fn candidates(&'a self, start: usize) -> Self::Candidates {
10929        PathMatchCandidateSetIter {
10930            traversal: match self.candidates {
10931                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
10932                Candidates::Files => self.snapshot.files(self.include_ignored, start),
10933                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
10934            },
10935        }
10936    }
10937}
10938
10939pub struct PathMatchCandidateSetIter<'a> {
10940    traversal: Traversal<'a>,
10941}
10942
10943impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
10944    type Item = fuzzy::PathMatchCandidate<'a>;
10945
10946    fn next(&mut self) -> Option<Self::Item> {
10947        self.traversal.next().map(|entry| match entry.kind {
10948            EntryKind::Dir => fuzzy::PathMatchCandidate {
10949                path: &entry.path,
10950                char_bag: CharBag::from_iter(entry.path.to_string_lossy().to_lowercase().chars()),
10951            },
10952            EntryKind::File(char_bag) => fuzzy::PathMatchCandidate {
10953                path: &entry.path,
10954                char_bag,
10955            },
10956            EntryKind::UnloadedDir | EntryKind::PendingDir => unreachable!(),
10957        })
10958    }
10959}
10960
10961impl EventEmitter<Event> for Project {}
10962
10963impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
10964    fn into(self) -> SettingsLocation<'a> {
10965        SettingsLocation {
10966            worktree_id: self.worktree_id.to_usize(),
10967            path: self.path.as_ref(),
10968        }
10969    }
10970}
10971
10972impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
10973    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
10974        Self {
10975            worktree_id,
10976            path: path.as_ref().into(),
10977        }
10978    }
10979}
10980
10981pub struct ProjectLspAdapterDelegate {
10982    project: WeakModel<Project>,
10983    worktree: worktree::Snapshot,
10984    fs: Arc<dyn Fs>,
10985    http_client: Arc<dyn HttpClient>,
10986    language_registry: Arc<LanguageRegistry>,
10987    shell_env: Mutex<Option<HashMap<String, String>>>,
10988    load_direnv: DirenvSettings,
10989}
10990
10991impl ProjectLspAdapterDelegate {
10992    pub fn new(
10993        project: &Project,
10994        worktree: &Model<Worktree>,
10995        cx: &ModelContext<Project>,
10996    ) -> Arc<Self> {
10997        let load_direnv = ProjectSettings::get_global(cx).load_direnv.clone();
10998        Arc::new(Self {
10999            project: cx.weak_model(),
11000            worktree: worktree.read(cx).snapshot(),
11001            fs: project.fs.clone(),
11002            http_client: project.client.http_client(),
11003            language_registry: project.languages.clone(),
11004            shell_env: Default::default(),
11005            load_direnv,
11006        })
11007    }
11008
11009    async fn load_shell_env(&self) {
11010        let worktree_abs_path = self.worktree.abs_path();
11011        let shell_env = load_shell_environment(&worktree_abs_path, &self.load_direnv)
11012            .await
11013            .with_context(|| {
11014                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
11015            })
11016            .log_err()
11017            .unwrap_or_default();
11018        *self.shell_env.lock() = Some(shell_env);
11019    }
11020}
11021
11022#[async_trait]
11023impl LspAdapterDelegate for ProjectLspAdapterDelegate {
11024    fn show_notification(&self, message: &str, cx: &mut AppContext) {
11025        self.project
11026            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
11027            .ok();
11028    }
11029
11030    fn http_client(&self) -> Arc<dyn HttpClient> {
11031        self.http_client.clone()
11032    }
11033
11034    fn worktree_id(&self) -> u64 {
11035        self.worktree.id().to_proto()
11036    }
11037
11038    fn worktree_root_path(&self) -> &Path {
11039        self.worktree.abs_path().as_ref()
11040    }
11041
11042    async fn shell_env(&self) -> HashMap<String, String> {
11043        self.load_shell_env().await;
11044        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
11045    }
11046
11047    #[cfg(not(target_os = "windows"))]
11048    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11049        let worktree_abs_path = self.worktree.abs_path();
11050        self.load_shell_env().await;
11051        let shell_path = self
11052            .shell_env
11053            .lock()
11054            .as_ref()
11055            .and_then(|shell_env| shell_env.get("PATH").cloned());
11056        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
11057    }
11058
11059    #[cfg(target_os = "windows")]
11060    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11061        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
11062        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
11063        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
11064        which::which(command).ok()
11065    }
11066
11067    fn update_status(
11068        &self,
11069        server_name: LanguageServerName,
11070        status: language::LanguageServerBinaryStatus,
11071    ) {
11072        self.language_registry
11073            .update_lsp_status(server_name, status);
11074    }
11075
11076    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
11077        if self.worktree.entry_for_path(&path).is_none() {
11078            return Err(anyhow!("no such path {path:?}"));
11079        }
11080        let path = self.worktree.absolutize(path.as_ref())?;
11081        let content = self.fs.load(&path).await?;
11082        Ok(content)
11083    }
11084}
11085
11086fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
11087    proto::Symbol {
11088        language_server_name: symbol.language_server_name.0.to_string(),
11089        source_worktree_id: symbol.source_worktree_id.to_proto(),
11090        worktree_id: symbol.path.worktree_id.to_proto(),
11091        path: symbol.path.path.to_string_lossy().to_string(),
11092        name: symbol.name.clone(),
11093        kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
11094        start: Some(proto::PointUtf16 {
11095            row: symbol.range.start.0.row,
11096            column: symbol.range.start.0.column,
11097        }),
11098        end: Some(proto::PointUtf16 {
11099            row: symbol.range.end.0.row,
11100            column: symbol.range.end.0.column,
11101        }),
11102        signature: symbol.signature.to_vec(),
11103    }
11104}
11105
11106fn relativize_path(base: &Path, path: &Path) -> PathBuf {
11107    let mut path_components = path.components();
11108    let mut base_components = base.components();
11109    let mut components: Vec<Component> = Vec::new();
11110    loop {
11111        match (path_components.next(), base_components.next()) {
11112            (None, None) => break,
11113            (Some(a), None) => {
11114                components.push(a);
11115                components.extend(path_components.by_ref());
11116                break;
11117            }
11118            (None, _) => components.push(Component::ParentDir),
11119            (Some(a), Some(b)) if components.is_empty() && a == b => (),
11120            (Some(a), Some(Component::CurDir)) => components.push(a),
11121            (Some(a), Some(_)) => {
11122                components.push(Component::ParentDir);
11123                for _ in base_components {
11124                    components.push(Component::ParentDir);
11125                }
11126                components.push(a);
11127                components.extend(path_components.by_ref());
11128                break;
11129            }
11130        }
11131    }
11132    components.iter().map(|c| c.as_os_str()).collect()
11133}
11134
11135fn resolve_path(base: &Path, path: &Path) -> PathBuf {
11136    let mut result = base.to_path_buf();
11137    for component in path.components() {
11138        match component {
11139            Component::ParentDir => {
11140                result.pop();
11141            }
11142            Component::CurDir => (),
11143            _ => result.push(component),
11144        }
11145    }
11146    result
11147}
11148
11149impl Item for Buffer {
11150    fn try_open(
11151        project: &Model<Project>,
11152        path: &ProjectPath,
11153        cx: &mut AppContext,
11154    ) -> Option<Task<Result<Model<Self>>>> {
11155        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
11156    }
11157
11158    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
11159        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
11160    }
11161
11162    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
11163        File::from_dyn(self.file()).map(|file| ProjectPath {
11164            worktree_id: file.worktree_id(cx),
11165            path: file.path().clone(),
11166        })
11167    }
11168}
11169
11170impl Completion {
11171    /// A key that can be used to sort completions when displaying
11172    /// them to the user.
11173    pub fn sort_key(&self) -> (usize, &str) {
11174        let kind_key = match self.lsp_completion.kind {
11175            Some(lsp::CompletionItemKind::KEYWORD) => 0,
11176            Some(lsp::CompletionItemKind::VARIABLE) => 1,
11177            _ => 2,
11178        };
11179        (kind_key, &self.label.text[self.label.filter_range.clone()])
11180    }
11181
11182    /// Whether this completion is a snippet.
11183    pub fn is_snippet(&self) -> bool {
11184        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
11185    }
11186}
11187
11188fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
11189    match server.capabilities().text_document_sync.as_ref()? {
11190        lsp::TextDocumentSyncCapability::Kind(kind) => match kind {
11191            &lsp::TextDocumentSyncKind::NONE => None,
11192            &lsp::TextDocumentSyncKind::FULL => Some(true),
11193            &lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
11194            _ => None,
11195        },
11196        lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
11197            lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
11198                if *supported {
11199                    Some(true)
11200                } else {
11201                    None
11202                }
11203            }
11204            lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
11205                Some(save_options.include_text.unwrap_or(false))
11206            }
11207        },
11208    }
11209}
11210
11211async fn load_direnv_environment(dir: &Path) -> Result<Option<HashMap<String, String>>> {
11212    let Ok(direnv_path) = which::which("direnv") else {
11213        return Ok(None);
11214    };
11215
11216    let direnv_output = smol::process::Command::new(direnv_path)
11217        .args(["export", "json"])
11218        .current_dir(dir)
11219        .output()
11220        .await
11221        .context("failed to spawn direnv to get local environment variables")?;
11222
11223    anyhow::ensure!(
11224        direnv_output.status.success(),
11225        "direnv exited with error {:?}",
11226        direnv_output.status
11227    );
11228
11229    let output = String::from_utf8_lossy(&direnv_output.stdout);
11230    if output.is_empty() {
11231        return Ok(None);
11232    }
11233
11234    Ok(Some(
11235        serde_json::from_str(&output).context("failed to parse direnv output")?,
11236    ))
11237}
11238
11239async fn load_shell_environment(
11240    dir: &Path,
11241    load_direnv: &DirenvSettings,
11242) -> Result<HashMap<String, String>> {
11243    let direnv_environment = match load_direnv {
11244        DirenvSettings::ShellHook => None,
11245        DirenvSettings::Direct => load_direnv_environment(dir).await?,
11246    }
11247    .unwrap_or(HashMap::default());
11248
11249    let marker = "ZED_SHELL_START";
11250    let shell = env::var("SHELL").context(
11251        "SHELL environment variable is not assigned so we can't source login environment variables",
11252    )?;
11253
11254    // What we're doing here is to spawn a shell and then `cd` into
11255    // the project directory to get the env in there as if the user
11256    // `cd`'d into it. We do that because tools like direnv, asdf, ...
11257    // hook into `cd` and only set up the env after that.
11258    //
11259    // If the user selects `Direct` for direnv, it would set an environment
11260    // variable that later uses to know that it should not run the hook.
11261    // We would include in `.envs` call so it is okay to run the hook
11262    // even if direnv direct mode is enabled.
11263    //
11264    // In certain shells we need to execute additional_command in order to
11265    // trigger the behavior of direnv, etc.
11266    //
11267    //
11268    // The `exit 0` is the result of hours of debugging, trying to find out
11269    // why running this command here, without `exit 0`, would mess
11270    // up signal process for our process so that `ctrl-c` doesn't work
11271    // anymore.
11272    //
11273    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
11274    // do that, but it does, and `exit 0` helps.
11275    let additional_command = PathBuf::from(&shell)
11276        .file_name()
11277        .and_then(|f| f.to_str())
11278        .and_then(|shell| match shell {
11279            "fish" => Some("emit fish_prompt;"),
11280            _ => None,
11281        });
11282
11283    let command = format!(
11284        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
11285        dir.display(),
11286        additional_command.unwrap_or("")
11287    );
11288
11289    let output = smol::process::Command::new(&shell)
11290        .args(["-i", "-c", &command])
11291        .envs(direnv_environment)
11292        .output()
11293        .await
11294        .context("failed to spawn login shell to source login environment variables")?;
11295
11296    anyhow::ensure!(
11297        output.status.success(),
11298        "login shell exited with error {:?}",
11299        output.status
11300    );
11301
11302    let stdout = String::from_utf8_lossy(&output.stdout);
11303    let env_output_start = stdout.find(marker).ok_or_else(|| {
11304        anyhow!(
11305            "failed to parse output of `env` command in login shell: {}",
11306            stdout
11307        )
11308    })?;
11309
11310    let mut parsed_env = HashMap::default();
11311    let env_output = &stdout[env_output_start + marker.len()..];
11312
11313    parse_env_output(env_output, |key, value| {
11314        parsed_env.insert(key, value);
11315    });
11316
11317    Ok(parsed_env)
11318}
11319
11320fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
11321    let entries = blame
11322        .entries
11323        .into_iter()
11324        .map(|entry| proto::BlameEntry {
11325            sha: entry.sha.as_bytes().into(),
11326            start_line: entry.range.start,
11327            end_line: entry.range.end,
11328            original_line_number: entry.original_line_number,
11329            author: entry.author.clone(),
11330            author_mail: entry.author_mail.clone(),
11331            author_time: entry.author_time,
11332            author_tz: entry.author_tz.clone(),
11333            committer: entry.committer.clone(),
11334            committer_mail: entry.committer_mail.clone(),
11335            committer_time: entry.committer_time,
11336            committer_tz: entry.committer_tz.clone(),
11337            summary: entry.summary.clone(),
11338            previous: entry.previous.clone(),
11339            filename: entry.filename.clone(),
11340        })
11341        .collect::<Vec<_>>();
11342
11343    let messages = blame
11344        .messages
11345        .into_iter()
11346        .map(|(oid, message)| proto::CommitMessage {
11347            oid: oid.as_bytes().into(),
11348            message,
11349        })
11350        .collect::<Vec<_>>();
11351
11352    let permalinks = blame
11353        .permalinks
11354        .into_iter()
11355        .map(|(oid, url)| proto::CommitPermalink {
11356            oid: oid.as_bytes().into(),
11357            permalink: url.to_string(),
11358        })
11359        .collect::<Vec<_>>();
11360
11361    proto::BlameBufferResponse {
11362        entries,
11363        messages,
11364        permalinks,
11365        remote_url: blame.remote_url,
11366    }
11367}
11368
11369fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
11370    let entries = response
11371        .entries
11372        .into_iter()
11373        .filter_map(|entry| {
11374            Some(git::blame::BlameEntry {
11375                sha: git::Oid::from_bytes(&entry.sha).ok()?,
11376                range: entry.start_line..entry.end_line,
11377                original_line_number: entry.original_line_number,
11378                committer: entry.committer,
11379                committer_time: entry.committer_time,
11380                committer_tz: entry.committer_tz,
11381                committer_mail: entry.committer_mail,
11382                author: entry.author,
11383                author_mail: entry.author_mail,
11384                author_time: entry.author_time,
11385                author_tz: entry.author_tz,
11386                summary: entry.summary,
11387                previous: entry.previous,
11388                filename: entry.filename,
11389            })
11390        })
11391        .collect::<Vec<_>>();
11392
11393    let messages = response
11394        .messages
11395        .into_iter()
11396        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
11397        .collect::<HashMap<_, _>>();
11398
11399    let permalinks = response
11400        .permalinks
11401        .into_iter()
11402        .filter_map(|permalink| {
11403            Some((
11404                git::Oid::from_bytes(&permalink.oid).ok()?,
11405                Url::from_str(&permalink.permalink).ok()?,
11406            ))
11407        })
11408        .collect::<HashMap<_, _>>();
11409
11410    Blame {
11411        entries,
11412        permalinks,
11413        messages,
11414        remote_url: response.remote_url,
11415    }
11416}
11417
11418fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
11419    hover
11420        .contents
11421        .retain(|hover_block| !hover_block.text.trim().is_empty());
11422    if hover.contents.is_empty() {
11423        None
11424    } else {
11425        Some(hover)
11426    }
11427}
11428
11429#[derive(Debug)]
11430pub struct NoRepositoryError {}
11431
11432impl std::fmt::Display for NoRepositoryError {
11433    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11434        write!(f, "no git repository for worktree found")
11435    }
11436}
11437
11438impl std::error::Error for NoRepositoryError {}
11439
11440fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
11441    proto::Location {
11442        buffer_id: location.buffer.read(cx).remote_id().into(),
11443        start: Some(serialize_anchor(&location.range.start)),
11444        end: Some(serialize_anchor(&location.range.end)),
11445    }
11446}
11447
11448fn deserialize_location(
11449    project: &Model<Project>,
11450    location: proto::Location,
11451    cx: &mut AppContext,
11452) -> Task<Result<Location>> {
11453    let buffer_id = match BufferId::new(location.buffer_id) {
11454        Ok(id) => id,
11455        Err(e) => return Task::ready(Err(e)),
11456    };
11457    let buffer_task = project.update(cx, |project, cx| {
11458        project.wait_for_remote_buffer(buffer_id, cx)
11459    });
11460    cx.spawn(|_| async move {
11461        let buffer = buffer_task.await?;
11462        let start = location
11463            .start
11464            .and_then(deserialize_anchor)
11465            .context("missing task context location start")?;
11466        let end = location
11467            .end
11468            .and_then(deserialize_anchor)
11469            .context("missing task context location end")?;
11470        Ok(Location {
11471            buffer,
11472            range: start..end,
11473        })
11474    })
11475}
11476
11477#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
11478pub struct DiagnosticSummary {
11479    pub error_count: usize,
11480    pub warning_count: usize,
11481}
11482
11483impl DiagnosticSummary {
11484    pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
11485        let mut this = Self {
11486            error_count: 0,
11487            warning_count: 0,
11488        };
11489
11490        for entry in diagnostics {
11491            if entry.diagnostic.is_primary {
11492                match entry.diagnostic.severity {
11493                    DiagnosticSeverity::ERROR => this.error_count += 1,
11494                    DiagnosticSeverity::WARNING => this.warning_count += 1,
11495                    _ => {}
11496                }
11497            }
11498        }
11499
11500        this
11501    }
11502
11503    pub fn is_empty(&self) -> bool {
11504        self.error_count == 0 && self.warning_count == 0
11505    }
11506
11507    pub fn to_proto(
11508        &self,
11509        language_server_id: LanguageServerId,
11510        path: &Path,
11511    ) -> proto::DiagnosticSummary {
11512        proto::DiagnosticSummary {
11513            path: path.to_string_lossy().to_string(),
11514            language_server_id: language_server_id.0 as u64,
11515            error_count: self.error_count as u32,
11516            warning_count: self.warning_count as u32,
11517        }
11518    }
11519}
11520
11521pub fn sort_worktree_entries(entries: &mut Vec<Entry>) {
11522    entries.sort_by(|entry_a, entry_b| {
11523        compare_paths(
11524            (&entry_a.path, entry_a.is_file()),
11525            (&entry_b.path, entry_b.is_file()),
11526        )
11527    });
11528}
11529
11530fn sort_search_matches(search_matches: &mut Vec<SearchMatchCandidate>, cx: &AppContext) {
11531    search_matches.sort_by(|entry_a, entry_b| match (entry_a, entry_b) {
11532        (
11533            SearchMatchCandidate::OpenBuffer {
11534                buffer: buffer_a,
11535                path: None,
11536            },
11537            SearchMatchCandidate::OpenBuffer {
11538                buffer: buffer_b,
11539                path: None,
11540            },
11541        ) => buffer_a
11542            .read(cx)
11543            .remote_id()
11544            .cmp(&buffer_b.read(cx).remote_id()),
11545        (
11546            SearchMatchCandidate::OpenBuffer { path: None, .. },
11547            SearchMatchCandidate::Path { .. }
11548            | SearchMatchCandidate::OpenBuffer { path: Some(_), .. },
11549        ) => Ordering::Less,
11550        (
11551            SearchMatchCandidate::OpenBuffer { path: Some(_), .. }
11552            | SearchMatchCandidate::Path { .. },
11553            SearchMatchCandidate::OpenBuffer { path: None, .. },
11554        ) => Ordering::Greater,
11555        (
11556            SearchMatchCandidate::OpenBuffer {
11557                path: Some(path_a), ..
11558            },
11559            SearchMatchCandidate::Path {
11560                is_file: is_file_b,
11561                path: path_b,
11562                ..
11563            },
11564        ) => compare_paths((path_a.as_ref(), true), (path_b.as_ref(), *is_file_b)),
11565        (
11566            SearchMatchCandidate::Path {
11567                is_file: is_file_a,
11568                path: path_a,
11569                ..
11570            },
11571            SearchMatchCandidate::OpenBuffer {
11572                path: Some(path_b), ..
11573            },
11574        ) => compare_paths((path_a.as_ref(), *is_file_a), (path_b.as_ref(), true)),
11575        (
11576            SearchMatchCandidate::OpenBuffer {
11577                path: Some(path_a), ..
11578            },
11579            SearchMatchCandidate::OpenBuffer {
11580                path: Some(path_b), ..
11581            },
11582        ) => compare_paths((path_a.as_ref(), true), (path_b.as_ref(), true)),
11583        (
11584            SearchMatchCandidate::Path {
11585                worktree_id: worktree_id_a,
11586                is_file: is_file_a,
11587                path: path_a,
11588                ..
11589            },
11590            SearchMatchCandidate::Path {
11591                worktree_id: worktree_id_b,
11592                is_file: is_file_b,
11593                path: path_b,
11594                ..
11595            },
11596        ) => worktree_id_a.cmp(&worktree_id_b).then_with(|| {
11597            compare_paths((path_a.as_ref(), *is_file_a), (path_b.as_ref(), *is_file_b))
11598        }),
11599    });
11600}
11601
11602fn compare_paths(
11603    (path_a, a_is_file): (&Path, bool),
11604    (path_b, b_is_file): (&Path, bool),
11605) -> cmp::Ordering {
11606    let mut components_a = path_a.components().peekable();
11607    let mut components_b = path_b.components().peekable();
11608    loop {
11609        match (components_a.next(), components_b.next()) {
11610            (Some(component_a), Some(component_b)) => {
11611                let a_is_file = components_a.peek().is_none() && a_is_file;
11612                let b_is_file = components_b.peek().is_none() && b_is_file;
11613                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
11614                    let maybe_numeric_ordering = maybe!({
11615                        let num_and_remainder_a = Path::new(component_a.as_os_str())
11616                            .file_stem()
11617                            .and_then(|s| s.to_str())
11618                            .and_then(NumericPrefixWithSuffix::from_numeric_prefixed_str)?;
11619                        let num_and_remainder_b = Path::new(component_b.as_os_str())
11620                            .file_stem()
11621                            .and_then(|s| s.to_str())
11622                            .and_then(NumericPrefixWithSuffix::from_numeric_prefixed_str)?;
11623
11624                        num_and_remainder_a.partial_cmp(&num_and_remainder_b)
11625                    });
11626
11627                    maybe_numeric_ordering.unwrap_or_else(|| {
11628                        let name_a = UniCase::new(component_a.as_os_str().to_string_lossy());
11629                        let name_b = UniCase::new(component_b.as_os_str().to_string_lossy());
11630
11631                        name_a.cmp(&name_b)
11632                    })
11633                });
11634                if !ordering.is_eq() {
11635                    return ordering;
11636                }
11637            }
11638            (Some(_), None) => break cmp::Ordering::Greater,
11639            (None, Some(_)) => break cmp::Ordering::Less,
11640            (None, None) => break cmp::Ordering::Equal,
11641        }
11642    }
11643}