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