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