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