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