project.rs

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