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