project.rs

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