project.rs

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