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