project.rs

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