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