project.rs

    1pub mod connection_manager;
    2pub mod debounced_delay;
    3pub mod lsp_command;
    4pub mod lsp_ext_command;
    5mod prettier_support;
    6pub mod project_settings;
    7pub mod search;
    8mod task_inventory;
    9pub mod terminals;
   10
   11#[cfg(test)]
   12mod project_tests;
   13pub mod search_history;
   14
   15use anyhow::{anyhow, bail, Context as _, Result};
   16use async_trait::async_trait;
   17use client::{
   18    proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
   19    TypedEnvelope, UserStore,
   20};
   21use clock::ReplicaId;
   22use collections::{btree_map, hash_map, BTreeMap, HashMap, HashSet, VecDeque};
   23use debounced_delay::DebouncedDelay;
   24use futures::{
   25    channel::{
   26        mpsc::{self, UnboundedReceiver},
   27        oneshot,
   28    },
   29    future::{join_all, try_join_all, Shared},
   30    prelude::future::BoxFuture,
   31    select,
   32    stream::FuturesUnordered,
   33    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
   34};
   35use fuzzy::CharBag;
   36use git::{blame::Blame, repository::GitRepository};
   37use globset::{Glob, GlobSet, GlobSetBuilder};
   38use gpui::{
   39    AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, BorrowAppContext, Context, Entity,
   40    EventEmitter, Model, ModelContext, PromptLevel, SharedString, Task, WeakModel, WindowContext,
   41};
   42use http::{HttpClient, Url};
   43use itertools::Itertools;
   44use language::{
   45    language_settings::{
   46        language_settings, AllLanguageSettings, FormatOnSave, Formatter, InlayHintKind,
   47    },
   48    markdown, point_to_lsp, prepare_completion_documentation,
   49    proto::{
   50        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
   51        serialize_line_ending, serialize_version, split_operations,
   52    },
   53    range_from_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability, CodeLabel,
   54    ContextProvider, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Documentation,
   55    Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName, LocalFile,
   56    LspAdapterDelegate, Operation, Patch, PendingLanguageServer, PointUtf16, TextBufferSnapshot,
   57    ToOffset, ToPointUtf16, Transaction, Unclipped,
   58};
   59use log::error;
   60use lsp::{
   61    CompletionContext, DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
   62    DocumentHighlightKind, Edit, FileSystemWatcher, InsertTextFormat, LanguageServer,
   63    LanguageServerBinary, LanguageServerId, LspRequestFuture, MessageActionItem, OneOf,
   64    ServerCapabilities, ServerHealthStatus, ServerStatus, TextEdit, Uri,
   65    WorkDoneProgressCancelParams,
   66};
   67use lsp_command::*;
   68use node_runtime::NodeRuntime;
   69use parking_lot::{Mutex, RwLock};
   70use paths::{
   71    LOCAL_SETTINGS_RELATIVE_PATH, LOCAL_TASKS_RELATIVE_PATH, LOCAL_VSCODE_TASKS_RELATIVE_PATH,
   72};
   73use postage::watch;
   74use prettier_support::{DefaultPrettier, PrettierInstance};
   75use project_settings::{LspSettings, ProjectSettings};
   76use rand::prelude::*;
   77use rpc::{ErrorCode, ErrorExt as _};
   78use search::SearchQuery;
   79use search_history::SearchHistory;
   80use serde::Serialize;
   81use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
   82use sha2::{Digest, Sha256};
   83use similar::{ChangeTag, TextDiff};
   84use smol::channel::{Receiver, Sender};
   85use smol::lock::Semaphore;
   86use snippet::Snippet;
   87use std::{
   88    borrow::Cow,
   89    cmp::{self, Ordering},
   90    convert::TryInto,
   91    env,
   92    ffi::OsStr,
   93    hash::Hash,
   94    io, iter, mem,
   95    num::NonZeroU32,
   96    ops::Range,
   97    path::{self, Component, Path, PathBuf},
   98    process::Stdio,
   99    str::{self, FromStr},
  100    sync::{
  101        atomic::{AtomicUsize, Ordering::SeqCst},
  102        Arc,
  103    },
  104    time::{Duration, Instant},
  105};
  106use task::{
  107    static_source::{StaticSource, TrackedFile},
  108    RevealStrategy, TaskContext, TaskTemplate, TaskVariables, VariableName,
  109};
  110use terminals::Terminals;
  111use text::{Anchor, BufferId, LineEnding};
  112use unicase::UniCase;
  113use util::{
  114    debug_panic, defer, maybe, merge_json_value_into, parse_env_output, post_inc,
  115    NumericPrefixWithSuffix, ResultExt, TryFutureExt as _,
  116};
  117use worktree::{CreatedEntry, RemoteWorktreeClient, Snapshot, Traversal};
  118
  119pub use fs::*;
  120pub use language::Location;
  121#[cfg(any(test, feature = "test-support"))]
  122pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  123pub use task_inventory::{
  124    BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
  125};
  126pub use worktree::{
  127    Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, RepositoryEntry,
  128    UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
  129    FS_WATCH_LATENCY,
  130};
  131
  132const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  133const SERVER_REINSTALL_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  134const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
  135pub const SERVER_PROGRESS_THROTTLE_TIMEOUT: Duration = Duration::from_millis(100);
  136
  137const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
  138
  139pub trait Item {
  140    fn try_open(
  141        project: &Model<Project>,
  142        path: &ProjectPath,
  143        cx: &mut AppContext,
  144    ) -> Option<Task<Result<Model<Self>>>>
  145    where
  146        Self: Sized;
  147    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  148    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
  149}
  150
  151#[derive(Clone)]
  152pub enum OpenedBufferEvent {
  153    Disconnected,
  154    Ok(BufferId),
  155    Err(BufferId, Arc<anyhow::Error>),
  156}
  157
  158/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
  159/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
  160/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
  161///
  162/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
  163pub struct Project {
  164    worktrees: Vec<WorktreeHandle>,
  165    worktrees_reordered: bool,
  166    active_entry: Option<ProjectEntryId>,
  167    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
  168    languages: Arc<LanguageRegistry>,
  169    supplementary_language_servers:
  170        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
  171    language_servers: HashMap<LanguageServerId, LanguageServerState>,
  172    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
  173    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
  174    last_formatting_failure: Option<String>,
  175    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
  176    language_server_watched_paths: HashMap<LanguageServerId, HashMap<WorktreeId, GlobSet>>,
  177    language_server_watcher_registrations:
  178        HashMap<LanguageServerId, HashMap<String, Vec<FileSystemWatcher>>>,
  179    client: Arc<client::Client>,
  180    next_entry_id: Arc<AtomicUsize>,
  181    join_project_response_message_id: u32,
  182    next_diagnostic_group_id: usize,
  183    diagnostic_summaries:
  184        HashMap<WorktreeId, HashMap<Arc<Path>, HashMap<LanguageServerId, DiagnosticSummary>>>,
  185    diagnostics: HashMap<
  186        WorktreeId,
  187        HashMap<
  188            Arc<Path>,
  189            Vec<(
  190                LanguageServerId,
  191                Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
  192            )>,
  193        >,
  194    >,
  195    user_store: Model<UserStore>,
  196    fs: Arc<dyn Fs>,
  197    client_state: ProjectClientState,
  198    collaborators: HashMap<proto::PeerId, Collaborator>,
  199    client_subscriptions: Vec<client::Subscription>,
  200    _subscriptions: Vec<gpui::Subscription>,
  201    loading_buffers: HashMap<BufferId, Vec<oneshot::Sender<Result<Model<Buffer>, anyhow::Error>>>>,
  202    incomplete_remote_buffers: HashMap<BufferId, Model<Buffer>>,
  203    shared_buffers: HashMap<proto::PeerId, HashSet<BufferId>>,
  204    #[allow(clippy::type_complexity)]
  205    loading_buffers_by_path: HashMap<
  206        ProjectPath,
  207        postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
  208    >,
  209    #[allow(clippy::type_complexity)]
  210    loading_local_worktrees:
  211        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
  212    opened_buffers: HashMap<BufferId, OpenBuffer>,
  213    local_buffer_ids_by_path: HashMap<ProjectPath, BufferId>,
  214    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  215    buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
  216    buffers_being_formatted: HashSet<BufferId>,
  217    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
  218    git_diff_debouncer: DebouncedDelay,
  219    nonce: u128,
  220    _maintain_buffer_languages: Task<()>,
  221    _maintain_workspace_config: Task<Result<()>>,
  222    terminals: Terminals,
  223    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
  224    node: Option<Arc<dyn NodeRuntime>>,
  225    default_prettier: DefaultPrettier,
  226    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
  227    prettier_instances: HashMap<PathBuf, PrettierInstance>,
  228    tasks: Model<Inventory>,
  229    hosted_project_id: Option<ProjectId>,
  230    dev_server_project_id: Option<client::DevServerProjectId>,
  231    search_history: SearchHistory,
  232}
  233
  234pub enum LanguageServerToQuery {
  235    Primary,
  236    Other(LanguageServerId),
  237}
  238
  239struct LspBufferSnapshot {
  240    version: i32,
  241    snapshot: TextBufferSnapshot,
  242}
  243
  244/// Message ordered with respect to buffer operations
  245#[derive(Debug)]
  246enum BufferOrderedMessage {
  247    Operation {
  248        buffer_id: BufferId,
  249        operation: proto::Operation,
  250    },
  251    LanguageServerUpdate {
  252        language_server_id: LanguageServerId,
  253        message: proto::update_language_server::Variant,
  254    },
  255    Resync,
  256}
  257
  258#[derive(Debug)]
  259enum LocalProjectUpdate {
  260    WorktreesChanged,
  261    CreateBufferForPeer {
  262        peer_id: proto::PeerId,
  263        buffer_id: BufferId,
  264    },
  265}
  266
  267enum OpenBuffer {
  268    Strong(Model<Buffer>),
  269    Weak(WeakModel<Buffer>),
  270    Operations(Vec<Operation>),
  271}
  272
  273#[derive(Clone)]
  274enum WorktreeHandle {
  275    Strong(Model<Worktree>),
  276    Weak(WeakModel<Worktree>),
  277}
  278
  279#[derive(Debug)]
  280enum ProjectClientState {
  281    Local,
  282    Shared {
  283        remote_id: u64,
  284        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
  285        _send_updates: Task<Result<()>>,
  286    },
  287    Remote {
  288        sharing_has_stopped: bool,
  289        capability: Capability,
  290        remote_id: u64,
  291        replica_id: ReplicaId,
  292        in_room: bool,
  293    },
  294}
  295
  296/// A prompt requested by LSP server.
  297#[derive(Clone, Debug)]
  298pub struct LanguageServerPromptRequest {
  299    pub level: PromptLevel,
  300    pub message: String,
  301    pub actions: Vec<MessageActionItem>,
  302    pub lsp_name: String,
  303    response_channel: Sender<MessageActionItem>,
  304}
  305
  306impl LanguageServerPromptRequest {
  307    pub async fn respond(self, index: usize) -> Option<()> {
  308        if let Some(response) = self.actions.into_iter().nth(index) {
  309            self.response_channel.send(response).await.ok()
  310        } else {
  311            None
  312        }
  313    }
  314}
  315impl PartialEq for LanguageServerPromptRequest {
  316    fn eq(&self, other: &Self) -> bool {
  317        self.message == other.message && self.actions == other.actions
  318    }
  319}
  320
  321#[derive(Clone, Debug, PartialEq)]
  322pub enum Event {
  323    LanguageServerAdded(LanguageServerId),
  324    LanguageServerRemoved(LanguageServerId),
  325    LanguageServerLog(LanguageServerId, String),
  326    Notification(String),
  327    LanguageServerPrompt(LanguageServerPromptRequest),
  328    LanguageNotFound(Model<Buffer>),
  329    ActiveEntryChanged(Option<ProjectEntryId>),
  330    ActivateProjectPanel,
  331    WorktreeAdded,
  332    WorktreeOrderChanged,
  333    WorktreeRemoved(WorktreeId),
  334    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
  335    WorktreeUpdatedGitRepositories,
  336    DiskBasedDiagnosticsStarted {
  337        language_server_id: LanguageServerId,
  338    },
  339    DiskBasedDiagnosticsFinished {
  340        language_server_id: LanguageServerId,
  341    },
  342    DiagnosticsUpdated {
  343        path: ProjectPath,
  344        language_server_id: LanguageServerId,
  345    },
  346    RemoteIdChanged(Option<u64>),
  347    DisconnectedFromHost,
  348    Closed,
  349    DeletedEntry(ProjectEntryId),
  350    CollaboratorUpdated {
  351        old_peer_id: proto::PeerId,
  352        new_peer_id: proto::PeerId,
  353    },
  354    CollaboratorJoined(proto::PeerId),
  355    CollaboratorLeft(proto::PeerId),
  356    RefreshInlayHints,
  357    RevealInProjectPanel(ProjectEntryId),
  358    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
  359}
  360
  361pub enum LanguageServerState {
  362    Starting(Task<Option<Arc<LanguageServer>>>),
  363
  364    Running {
  365        language: Arc<Language>,
  366        adapter: Arc<CachedLspAdapter>,
  367        server: Arc<LanguageServer>,
  368        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
  369    },
  370}
  371
  372#[derive(Clone, Debug, Serialize)]
  373pub struct LanguageServerStatus {
  374    pub name: String,
  375    pub pending_work: BTreeMap<String, LanguageServerProgress>,
  376    pub has_pending_diagnostic_updates: bool,
  377    progress_tokens: HashSet<String>,
  378}
  379
  380#[derive(Clone, Debug, Serialize)]
  381pub struct LanguageServerProgress {
  382    pub is_disk_based_diagnostics_progress: bool,
  383    pub is_cancellable: bool,
  384    pub title: Option<String>,
  385    pub message: Option<String>,
  386    pub percentage: Option<usize>,
  387    #[serde(skip_serializing)]
  388    pub last_update_at: Instant,
  389}
  390
  391#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
  392pub struct ProjectPath {
  393    pub worktree_id: WorktreeId,
  394    pub path: Arc<Path>,
  395}
  396
  397impl ProjectPath {
  398    pub fn from_proto(p: proto::ProjectPath) -> Self {
  399        Self {
  400            worktree_id: WorktreeId::from_proto(p.worktree_id),
  401            path: Arc::from(PathBuf::from(p.path)),
  402        }
  403    }
  404
  405    pub fn to_proto(&self) -> proto::ProjectPath {
  406        proto::ProjectPath {
  407            worktree_id: self.worktree_id.to_proto(),
  408            path: self.path.to_string_lossy().to_string(),
  409        }
  410    }
  411}
  412
  413#[derive(Debug, Clone, PartialEq, Eq)]
  414pub struct InlayHint {
  415    pub position: language::Anchor,
  416    pub label: InlayHintLabel,
  417    pub kind: Option<InlayHintKind>,
  418    pub padding_left: bool,
  419    pub padding_right: bool,
  420    pub tooltip: Option<InlayHintTooltip>,
  421    pub resolve_state: ResolveState,
  422}
  423
  424/// A completion provided by a language server
  425#[derive(Clone)]
  426pub struct Completion {
  427    /// The range of the buffer that will be replaced.
  428    pub old_range: Range<Anchor>,
  429    /// The new text that will be inserted.
  430    pub new_text: String,
  431    /// A label for this completion that is shown in the menu.
  432    pub label: CodeLabel,
  433    /// The id of the language server that produced this completion.
  434    pub server_id: LanguageServerId,
  435    /// The documentation for this completion.
  436    pub documentation: Option<Documentation>,
  437    /// The raw completion provided by the language server.
  438    pub lsp_completion: lsp::CompletionItem,
  439    /// An optional callback to invoke when this completion is confirmed.
  440    pub confirm: Option<Arc<dyn Send + Sync + Fn(&mut WindowContext)>>,
  441    /// If true, the editor will show a new completion menu after this completion is confirmed.
  442    pub show_new_completions_on_confirm: bool,
  443}
  444
  445impl std::fmt::Debug for Completion {
  446    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  447        f.debug_struct("Completion")
  448            .field("old_range", &self.old_range)
  449            .field("new_text", &self.new_text)
  450            .field("label", &self.label)
  451            .field("server_id", &self.server_id)
  452            .field("documentation", &self.documentation)
  453            .field("lsp_completion", &self.lsp_completion)
  454            .finish()
  455    }
  456}
  457
  458/// A completion provided by a language server
  459#[derive(Clone, Debug)]
  460struct CoreCompletion {
  461    old_range: Range<Anchor>,
  462    new_text: String,
  463    server_id: LanguageServerId,
  464    lsp_completion: lsp::CompletionItem,
  465}
  466
  467/// A code action provided by a language server.
  468#[derive(Clone, Debug)]
  469pub struct CodeAction {
  470    /// The id of the language server that produced this code action.
  471    pub server_id: LanguageServerId,
  472    /// The range of the buffer where this code action is applicable.
  473    pub range: Range<Anchor>,
  474    /// The raw code action provided by the language server.
  475    pub lsp_action: lsp::CodeAction,
  476}
  477
  478#[derive(Debug, Clone, PartialEq, Eq)]
  479pub enum ResolveState {
  480    Resolved,
  481    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
  482    Resolving,
  483}
  484
  485impl InlayHint {
  486    pub fn text(&self) -> String {
  487        match &self.label {
  488            InlayHintLabel::String(s) => s.to_owned(),
  489            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
  490        }
  491    }
  492}
  493
  494#[derive(Debug, Clone, PartialEq, Eq)]
  495pub enum InlayHintLabel {
  496    String(String),
  497    LabelParts(Vec<InlayHintLabelPart>),
  498}
  499
  500#[derive(Debug, Clone, PartialEq, Eq)]
  501pub struct InlayHintLabelPart {
  502    pub value: String,
  503    pub tooltip: Option<InlayHintLabelPartTooltip>,
  504    pub location: Option<(LanguageServerId, lsp::Location)>,
  505}
  506
  507#[derive(Debug, Clone, PartialEq, Eq)]
  508pub enum InlayHintTooltip {
  509    String(String),
  510    MarkupContent(MarkupContent),
  511}
  512
  513#[derive(Debug, Clone, PartialEq, Eq)]
  514pub enum InlayHintLabelPartTooltip {
  515    String(String),
  516    MarkupContent(MarkupContent),
  517}
  518
  519#[derive(Debug, Clone, PartialEq, Eq)]
  520pub struct MarkupContent {
  521    pub kind: HoverBlockKind,
  522    pub value: String,
  523}
  524
  525#[derive(Debug, Clone)]
  526pub struct LocationLink {
  527    pub origin: Option<Location>,
  528    pub target: Location,
  529}
  530
  531#[derive(Debug)]
  532pub struct DocumentHighlight {
  533    pub range: Range<language::Anchor>,
  534    pub kind: DocumentHighlightKind,
  535}
  536
  537#[derive(Clone, Debug)]
  538pub struct Symbol {
  539    pub language_server_name: LanguageServerName,
  540    pub source_worktree_id: WorktreeId,
  541    pub path: ProjectPath,
  542    pub label: CodeLabel,
  543    pub name: String,
  544    pub kind: lsp::SymbolKind,
  545    pub range: Range<Unclipped<PointUtf16>>,
  546    pub signature: [u8; 32],
  547}
  548
  549#[derive(Clone, Debug)]
  550struct CoreSymbol {
  551    pub language_server_name: LanguageServerName,
  552    pub source_worktree_id: WorktreeId,
  553    pub path: ProjectPath,
  554    pub name: String,
  555    pub kind: lsp::SymbolKind,
  556    pub range: Range<Unclipped<PointUtf16>>,
  557    pub signature: [u8; 32],
  558}
  559
  560#[derive(Clone, Debug, PartialEq)]
  561pub struct HoverBlock {
  562    pub text: String,
  563    pub kind: HoverBlockKind,
  564}
  565
  566#[derive(Clone, Debug, PartialEq, Eq)]
  567pub enum HoverBlockKind {
  568    PlainText,
  569    Markdown,
  570    Code { language: String },
  571}
  572
  573#[derive(Debug, Clone)]
  574pub struct Hover {
  575    pub contents: Vec<HoverBlock>,
  576    pub range: Option<Range<language::Anchor>>,
  577    pub language: Option<Arc<Language>>,
  578}
  579
  580impl Hover {
  581    pub fn is_empty(&self) -> bool {
  582        self.contents.iter().all(|block| block.text.is_empty())
  583    }
  584}
  585
  586#[derive(Default)]
  587pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
  588
  589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  590pub enum FormatTrigger {
  591    Save,
  592    Manual,
  593}
  594
  595// Currently, formatting operations are represented differently depending on
  596// whether they come from a language server or an external command.
  597#[derive(Debug)]
  598enum FormatOperation {
  599    Lsp(Vec<(Range<Anchor>, String)>),
  600    External(Diff),
  601    Prettier(Diff),
  602}
  603
  604impl FormatTrigger {
  605    fn from_proto(value: i32) -> FormatTrigger {
  606        match value {
  607            0 => FormatTrigger::Save,
  608            1 => FormatTrigger::Manual,
  609            _ => FormatTrigger::Save,
  610        }
  611    }
  612}
  613
  614#[derive(Clone, Debug, PartialEq)]
  615enum SearchMatchCandidate {
  616    OpenBuffer {
  617        buffer: Model<Buffer>,
  618        // This might be an unnamed file without representation on filesystem
  619        path: Option<Arc<Path>>,
  620    },
  621    Path {
  622        worktree_id: WorktreeId,
  623        is_ignored: bool,
  624        is_file: bool,
  625        path: Arc<Path>,
  626    },
  627}
  628
  629pub enum SearchResult {
  630    Buffer {
  631        buffer: Model<Buffer>,
  632        ranges: Vec<Range<Anchor>>,
  633    },
  634    LimitReached,
  635}
  636
  637#[cfg(any(test, feature = "test-support"))]
  638pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
  639    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
  640    trigger_character: None,
  641};
  642
  643impl Project {
  644    pub fn init_settings(cx: &mut AppContext) {
  645        WorktreeSettings::register(cx);
  646        ProjectSettings::register(cx);
  647    }
  648
  649    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
  650        connection_manager::init(client.clone(), cx);
  651        Self::init_settings(cx);
  652
  653        client.add_model_message_handler(Self::handle_add_collaborator);
  654        client.add_model_message_handler(Self::handle_update_project_collaborator);
  655        client.add_model_message_handler(Self::handle_remove_collaborator);
  656        client.add_model_message_handler(Self::handle_buffer_reloaded);
  657        client.add_model_message_handler(Self::handle_buffer_saved);
  658        client.add_model_message_handler(Self::handle_start_language_server);
  659        client.add_model_message_handler(Self::handle_update_language_server);
  660        client.add_model_message_handler(Self::handle_update_project);
  661        client.add_model_message_handler(Self::handle_unshare_project);
  662        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
  663        client.add_model_message_handler(Self::handle_update_buffer_file);
  664        client.add_model_request_handler(Self::handle_update_buffer);
  665        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
  666        client.add_model_message_handler(Self::handle_update_worktree);
  667        client.add_model_message_handler(Self::handle_update_worktree_settings);
  668        client.add_model_request_handler(Self::handle_create_project_entry);
  669        client.add_model_request_handler(Self::handle_rename_project_entry);
  670        client.add_model_request_handler(Self::handle_copy_project_entry);
  671        client.add_model_request_handler(Self::handle_delete_project_entry);
  672        client.add_model_request_handler(Self::handle_expand_project_entry);
  673        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
  674        client.add_model_request_handler(Self::handle_resolve_completion_documentation);
  675        client.add_model_request_handler(Self::handle_apply_code_action);
  676        client.add_model_request_handler(Self::handle_on_type_formatting);
  677        client.add_model_request_handler(Self::handle_inlay_hints);
  678        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
  679        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
  680        client.add_model_request_handler(Self::handle_reload_buffers);
  681        client.add_model_request_handler(Self::handle_synchronize_buffers);
  682        client.add_model_request_handler(Self::handle_format_buffers);
  683        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
  684        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
  685        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
  686        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
  687        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
  688        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
  689        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
  690        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
  691        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
  692        client.add_model_request_handler(Self::handle_search_project);
  693        client.add_model_request_handler(Self::handle_get_project_symbols);
  694        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
  695        client.add_model_request_handler(Self::handle_open_buffer_by_id);
  696        client.add_model_request_handler(Self::handle_open_buffer_by_path);
  697        client.add_model_request_handler(Self::handle_open_new_buffer);
  698        client.add_model_request_handler(Self::handle_save_buffer);
  699        client.add_model_message_handler(Self::handle_update_diff_base);
  700        client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
  701        client.add_model_request_handler(Self::handle_blame_buffer);
  702        client.add_model_request_handler(Self::handle_multi_lsp_query);
  703        client.add_model_request_handler(Self::handle_restart_language_servers);
  704        client.add_model_request_handler(Self::handle_task_context_for_location);
  705        client.add_model_request_handler(Self::handle_task_templates);
  706        client.add_model_request_handler(Self::handle_lsp_command::<LinkedEditingRange>);
  707    }
  708
  709    pub fn local(
  710        client: Arc<Client>,
  711        node: Arc<dyn NodeRuntime>,
  712        user_store: Model<UserStore>,
  713        languages: Arc<LanguageRegistry>,
  714        fs: Arc<dyn Fs>,
  715        cx: &mut AppContext,
  716    ) -> Model<Self> {
  717        cx.new_model(|cx: &mut ModelContext<Self>| {
  718            let (tx, rx) = mpsc::unbounded();
  719            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  720                .detach();
  721            let tasks = Inventory::new(cx);
  722
  723            Self {
  724                worktrees: Vec::new(),
  725                worktrees_reordered: false,
  726                buffer_ordered_messages_tx: tx,
  727                collaborators: Default::default(),
  728                opened_buffers: Default::default(),
  729                shared_buffers: Default::default(),
  730                loading_buffers_by_path: Default::default(),
  731                loading_local_worktrees: Default::default(),
  732                local_buffer_ids_by_path: Default::default(),
  733                local_buffer_ids_by_entry_id: Default::default(),
  734                buffer_snapshots: Default::default(),
  735                join_project_response_message_id: 0,
  736                client_state: ProjectClientState::Local,
  737                loading_buffers: HashMap::default(),
  738                incomplete_remote_buffers: HashMap::default(),
  739                client_subscriptions: Vec::new(),
  740                _subscriptions: vec![
  741                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
  742                    cx.on_release(Self::release),
  743                    cx.on_app_quit(Self::shutdown_language_servers),
  744                ],
  745                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  746                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  747                active_entry: None,
  748                languages,
  749                client,
  750                user_store,
  751                fs,
  752                next_entry_id: Default::default(),
  753                next_diagnostic_group_id: Default::default(),
  754                diagnostics: Default::default(),
  755                diagnostic_summaries: Default::default(),
  756                supplementary_language_servers: HashMap::default(),
  757                language_servers: Default::default(),
  758                language_server_ids: HashMap::default(),
  759                language_server_statuses: Default::default(),
  760                last_formatting_failure: None,
  761                last_workspace_edits_by_language_server: Default::default(),
  762                language_server_watched_paths: HashMap::default(),
  763                language_server_watcher_registrations: HashMap::default(),
  764                buffers_being_formatted: Default::default(),
  765                buffers_needing_diff: Default::default(),
  766                git_diff_debouncer: DebouncedDelay::new(),
  767                nonce: StdRng::from_entropy().gen(),
  768                terminals: Terminals {
  769                    local_handles: Vec::new(),
  770                },
  771                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  772                node: Some(node),
  773                default_prettier: DefaultPrettier::default(),
  774                prettiers_per_worktree: HashMap::default(),
  775                prettier_instances: HashMap::default(),
  776                tasks,
  777                hosted_project_id: None,
  778                dev_server_project_id: None,
  779                search_history: Self::new_search_history(),
  780            }
  781        })
  782    }
  783
  784    pub async fn remote(
  785        remote_id: u64,
  786        client: Arc<Client>,
  787        user_store: Model<UserStore>,
  788        languages: Arc<LanguageRegistry>,
  789        fs: Arc<dyn Fs>,
  790        cx: AsyncAppContext,
  791    ) -> Result<Model<Self>> {
  792        let project =
  793            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
  794        cx.update(|cx| {
  795            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
  796                manager.maintain_project_connection(&project, cx)
  797            })
  798        })?;
  799        Ok(project)
  800    }
  801
  802    pub async fn in_room(
  803        remote_id: u64,
  804        client: Arc<Client>,
  805        user_store: Model<UserStore>,
  806        languages: Arc<LanguageRegistry>,
  807        fs: Arc<dyn Fs>,
  808        cx: AsyncAppContext,
  809    ) -> Result<Model<Self>> {
  810        client.authenticate_and_connect(true, &cx).await?;
  811
  812        let subscription = client.subscribe_to_entity(remote_id)?;
  813        let response = client
  814            .request_envelope(proto::JoinProject {
  815                project_id: remote_id,
  816            })
  817            .await?;
  818        Self::from_join_project_response(
  819            response,
  820            subscription,
  821            client,
  822            user_store,
  823            languages,
  824            fs,
  825            cx,
  826        )
  827        .await
  828    }
  829
  830    async fn from_join_project_response(
  831        response: TypedEnvelope<proto::JoinProjectResponse>,
  832        subscription: PendingEntitySubscription<Project>,
  833        client: Arc<Client>,
  834        user_store: Model<UserStore>,
  835        languages: Arc<LanguageRegistry>,
  836        fs: Arc<dyn Fs>,
  837        mut cx: AsyncAppContext,
  838    ) -> Result<Model<Self>> {
  839        let remote_id = response.payload.project_id;
  840        let role = response.payload.role();
  841        let this = cx.new_model(|cx| {
  842            let replica_id = response.payload.replica_id as ReplicaId;
  843            let tasks = Inventory::new(cx);
  844            // BIG CAUTION NOTE: The order in which we initialize fields here matters and it should match what's done in Self::local.
  845            // Otherwise, you might run into issues where worktree id on remote is different than what's on local host.
  846            // That's because Worktree's identifier is entity id, which should probably be changed.
  847            let mut worktrees = Vec::new();
  848            for worktree in response.payload.worktrees {
  849                let worktree = Worktree::remote(
  850                    remote_id,
  851                    replica_id,
  852                    worktree,
  853                    Box::new(CollabRemoteWorktreeClient(client.clone())),
  854                    cx,
  855                );
  856                worktrees.push(worktree);
  857            }
  858
  859            let (tx, rx) = mpsc::unbounded();
  860            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  861                .detach();
  862            let mut this = Self {
  863                worktrees: Vec::new(),
  864                worktrees_reordered: false,
  865                buffer_ordered_messages_tx: tx,
  866                loading_buffers_by_path: Default::default(),
  867                loading_buffers: Default::default(),
  868                shared_buffers: Default::default(),
  869                incomplete_remote_buffers: Default::default(),
  870                loading_local_worktrees: Default::default(),
  871                local_buffer_ids_by_path: Default::default(),
  872                local_buffer_ids_by_entry_id: Default::default(),
  873                active_entry: None,
  874                collaborators: Default::default(),
  875                join_project_response_message_id: response.message_id,
  876                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  877                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  878                languages,
  879                user_store: user_store.clone(),
  880                fs,
  881                next_entry_id: Default::default(),
  882                next_diagnostic_group_id: Default::default(),
  883                diagnostic_summaries: Default::default(),
  884                diagnostics: Default::default(),
  885                client_subscriptions: Default::default(),
  886                _subscriptions: vec![
  887                    cx.on_release(Self::release),
  888                    cx.on_app_quit(Self::shutdown_language_servers),
  889                ],
  890                client: client.clone(),
  891                client_state: ProjectClientState::Remote {
  892                    sharing_has_stopped: false,
  893                    capability: Capability::ReadWrite,
  894                    remote_id,
  895                    replica_id,
  896                    in_room: response.payload.dev_server_project_id.is_none(),
  897                },
  898                supplementary_language_servers: HashMap::default(),
  899                language_servers: Default::default(),
  900                language_server_ids: HashMap::default(),
  901                language_server_statuses: response
  902                    .payload
  903                    .language_servers
  904                    .into_iter()
  905                    .map(|server| {
  906                        (
  907                            LanguageServerId(server.id as usize),
  908                            LanguageServerStatus {
  909                                name: server.name,
  910                                pending_work: Default::default(),
  911                                has_pending_diagnostic_updates: false,
  912                                progress_tokens: Default::default(),
  913                            },
  914                        )
  915                    })
  916                    .collect(),
  917                last_formatting_failure: None,
  918                last_workspace_edits_by_language_server: Default::default(),
  919                language_server_watched_paths: HashMap::default(),
  920                language_server_watcher_registrations: HashMap::default(),
  921                opened_buffers: Default::default(),
  922                buffers_being_formatted: Default::default(),
  923                buffers_needing_diff: Default::default(),
  924                git_diff_debouncer: DebouncedDelay::new(),
  925                buffer_snapshots: Default::default(),
  926                nonce: StdRng::from_entropy().gen(),
  927                terminals: Terminals {
  928                    local_handles: Vec::new(),
  929                },
  930                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  931                node: None,
  932                default_prettier: DefaultPrettier::default(),
  933                prettiers_per_worktree: HashMap::default(),
  934                prettier_instances: HashMap::default(),
  935                tasks,
  936                hosted_project_id: None,
  937                dev_server_project_id: response
  938                    .payload
  939                    .dev_server_project_id
  940                    .map(|dev_server_project_id| DevServerProjectId(dev_server_project_id)),
  941                search_history: Self::new_search_history(),
  942            };
  943            this.set_role(role, cx);
  944            for worktree in worktrees {
  945                let _ = this.add_worktree(&worktree, cx);
  946            }
  947            this
  948        })?;
  949        let subscription = subscription.set_model(&this, &mut cx);
  950
  951        let user_ids = response
  952            .payload
  953            .collaborators
  954            .iter()
  955            .map(|peer| peer.user_id)
  956            .collect();
  957        user_store
  958            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
  959            .await?;
  960
  961        this.update(&mut cx, |this, cx| {
  962            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
  963            this.client_subscriptions.push(subscription);
  964            anyhow::Ok(())
  965        })??;
  966
  967        Ok(this)
  968    }
  969
  970    pub async fn hosted(
  971        remote_id: ProjectId,
  972        user_store: Model<UserStore>,
  973        client: Arc<Client>,
  974        languages: Arc<LanguageRegistry>,
  975        fs: Arc<dyn Fs>,
  976        cx: AsyncAppContext,
  977    ) -> Result<Model<Self>> {
  978        client.authenticate_and_connect(true, &cx).await?;
  979
  980        let subscription = client.subscribe_to_entity(remote_id.0)?;
  981        let response = client
  982            .request_envelope(proto::JoinHostedProject {
  983                project_id: remote_id.0,
  984            })
  985            .await?;
  986        Self::from_join_project_response(
  987            response,
  988            subscription,
  989            client,
  990            user_store,
  991            languages,
  992            fs,
  993            cx,
  994        )
  995        .await
  996    }
  997
  998    fn new_search_history() -> SearchHistory {
  999        SearchHistory::new(
 1000            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
 1001            search_history::QueryInsertionBehavior::AlwaysInsert,
 1002        )
 1003    }
 1004
 1005    fn release(&mut self, cx: &mut AppContext) {
 1006        match &self.client_state {
 1007            ProjectClientState::Local => {}
 1008            ProjectClientState::Shared { .. } => {
 1009                let _ = self.unshare_internal(cx);
 1010            }
 1011            ProjectClientState::Remote { remote_id, .. } => {
 1012                let _ = self.client.send(proto::LeaveProject {
 1013                    project_id: *remote_id,
 1014                });
 1015                self.disconnected_from_host_internal(cx);
 1016            }
 1017        }
 1018    }
 1019
 1020    fn shutdown_language_servers(
 1021        &mut self,
 1022        _cx: &mut ModelContext<Self>,
 1023    ) -> impl Future<Output = ()> {
 1024        let shutdown_futures = self
 1025            .language_servers
 1026            .drain()
 1027            .map(|(_, server_state)| async {
 1028                use LanguageServerState::*;
 1029                match server_state {
 1030                    Running { server, .. } => server.shutdown()?.await,
 1031                    Starting(task) => task.await?.shutdown()?.await,
 1032                }
 1033            })
 1034            .collect::<Vec<_>>();
 1035
 1036        async move {
 1037            futures::future::join_all(shutdown_futures).await;
 1038        }
 1039    }
 1040
 1041    #[cfg(any(test, feature = "test-support"))]
 1042    pub async fn example(
 1043        root_paths: impl IntoIterator<Item = &Path>,
 1044        cx: &mut AsyncAppContext,
 1045    ) -> Model<Project> {
 1046        use clock::FakeSystemClock;
 1047
 1048        let fs = Arc::new(RealFs::default());
 1049        let languages = LanguageRegistry::test(cx.background_executor().clone());
 1050        let clock = Arc::new(FakeSystemClock::default());
 1051        let http_client = http::FakeHttpClient::with_404_response();
 1052        let client = cx
 1053            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
 1054            .unwrap();
 1055        let user_store = cx
 1056            .new_model(|cx| UserStore::new(client.clone(), cx))
 1057            .unwrap();
 1058        let project = cx
 1059            .update(|cx| {
 1060                Project::local(
 1061                    client,
 1062                    node_runtime::FakeNodeRuntime::new(),
 1063                    user_store,
 1064                    Arc::new(languages),
 1065                    fs,
 1066                    cx,
 1067                )
 1068            })
 1069            .unwrap();
 1070        for path in root_paths {
 1071            let (tree, _) = project
 1072                .update(cx, |project, cx| {
 1073                    project.find_or_create_local_worktree(path, true, cx)
 1074                })
 1075                .unwrap()
 1076                .await
 1077                .unwrap();
 1078            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 1079                .unwrap()
 1080                .await;
 1081        }
 1082        project
 1083    }
 1084
 1085    #[cfg(any(test, feature = "test-support"))]
 1086    pub async fn test(
 1087        fs: Arc<dyn Fs>,
 1088        root_paths: impl IntoIterator<Item = &Path>,
 1089        cx: &mut gpui::TestAppContext,
 1090    ) -> Model<Project> {
 1091        use clock::FakeSystemClock;
 1092
 1093        let languages = LanguageRegistry::test(cx.executor());
 1094        let clock = Arc::new(FakeSystemClock::default());
 1095        let http_client = http::FakeHttpClient::with_404_response();
 1096        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
 1097        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
 1098        let project = cx.update(|cx| {
 1099            Project::local(
 1100                client,
 1101                node_runtime::FakeNodeRuntime::new(),
 1102                user_store,
 1103                Arc::new(languages),
 1104                fs,
 1105                cx,
 1106            )
 1107        });
 1108        for path in root_paths {
 1109            let (tree, _) = project
 1110                .update(cx, |project, cx| {
 1111                    project.find_or_create_local_worktree(path, true, cx)
 1112                })
 1113                .await
 1114                .unwrap();
 1115            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 1116                .await;
 1117        }
 1118        project
 1119    }
 1120
 1121    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 1122        let mut language_servers_to_start = Vec::new();
 1123        let mut language_formatters_to_check = Vec::new();
 1124        for buffer in self.opened_buffers.values() {
 1125            if let Some(buffer) = buffer.upgrade() {
 1126                let buffer = buffer.read(cx);
 1127                let buffer_file = File::from_dyn(buffer.file());
 1128                let buffer_language = buffer.language();
 1129                let settings = language_settings(buffer_language, buffer.file(), cx);
 1130                if let Some(language) = buffer_language {
 1131                    if settings.enable_language_server {
 1132                        if let Some(file) = buffer_file {
 1133                            language_servers_to_start
 1134                                .push((file.worktree.clone(), Arc::clone(language)));
 1135                        }
 1136                    }
 1137                    language_formatters_to_check
 1138                        .push((buffer_file.map(|f| f.worktree_id(cx)), settings.clone()));
 1139                }
 1140            }
 1141        }
 1142
 1143        let mut language_servers_to_stop = Vec::new();
 1144        let mut language_servers_to_restart = Vec::new();
 1145        let languages = self.languages.to_vec();
 1146
 1147        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
 1148        let current_lsp_settings = &self.current_lsp_settings;
 1149        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 1150            let language = languages.iter().find_map(|l| {
 1151                let adapter = self
 1152                    .languages
 1153                    .lsp_adapters(l)
 1154                    .iter()
 1155                    .find(|adapter| &adapter.name == started_lsp_name)?
 1156                    .clone();
 1157                Some((l, adapter))
 1158            });
 1159            if let Some((language, adapter)) = language {
 1160                let worktree = self.worktree_for_id(*worktree_id, cx);
 1161                let file = worktree.as_ref().and_then(|tree| {
 1162                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 1163                });
 1164                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 1165                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 1166                } else if let Some(worktree) = worktree {
 1167                    let server_name = &adapter.name.0;
 1168                    match (
 1169                        current_lsp_settings.get(server_name),
 1170                        new_lsp_settings.get(server_name),
 1171                    ) {
 1172                        (None, None) => {}
 1173                        (Some(_), None) | (None, Some(_)) => {
 1174                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 1175                        }
 1176                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 1177                            if current_lsp_settings != new_lsp_settings {
 1178                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 1179                            }
 1180                        }
 1181                    }
 1182                }
 1183            }
 1184        }
 1185        self.current_lsp_settings = new_lsp_settings;
 1186
 1187        // Stop all newly-disabled language servers.
 1188        for (worktree_id, adapter_name) in language_servers_to_stop {
 1189            self.stop_language_server(worktree_id, adapter_name, cx)
 1190                .detach();
 1191        }
 1192
 1193        let mut prettier_plugins_by_worktree = HashMap::default();
 1194        for (worktree, language_settings) in language_formatters_to_check {
 1195            if let Some(plugins) =
 1196                prettier_support::prettier_plugins_for_language(&language_settings)
 1197            {
 1198                prettier_plugins_by_worktree
 1199                    .entry(worktree)
 1200                    .or_insert_with(|| HashSet::default())
 1201                    .extend(plugins.iter().cloned());
 1202            }
 1203        }
 1204        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
 1205            self.install_default_prettier(
 1206                worktree,
 1207                prettier_plugins.into_iter().map(Arc::from),
 1208                cx,
 1209            );
 1210        }
 1211
 1212        // Start all the newly-enabled language servers.
 1213        for (worktree, language) in language_servers_to_start {
 1214            self.start_language_servers(&worktree, language, cx);
 1215        }
 1216
 1217        // Restart all language servers with changed initialization options.
 1218        for (worktree, language) in language_servers_to_restart {
 1219            self.restart_language_servers(worktree, language, cx);
 1220        }
 1221
 1222        cx.notify();
 1223    }
 1224
 1225    pub fn buffer_for_id(&self, remote_id: BufferId) -> Option<Model<Buffer>> {
 1226        self.opened_buffers
 1227            .get(&remote_id)
 1228            .and_then(|buffer| buffer.upgrade())
 1229    }
 1230
 1231    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 1232        &self.languages
 1233    }
 1234
 1235    pub fn client(&self) -> Arc<Client> {
 1236        self.client.clone()
 1237    }
 1238
 1239    pub fn user_store(&self) -> Model<UserStore> {
 1240        self.user_store.clone()
 1241    }
 1242
 1243    pub fn node_runtime(&self) -> Option<&Arc<dyn NodeRuntime>> {
 1244        self.node.as_ref()
 1245    }
 1246
 1247    pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
 1248        self.opened_buffers
 1249            .values()
 1250            .filter_map(|b| b.upgrade())
 1251            .collect()
 1252    }
 1253
 1254    #[cfg(any(test, feature = "test-support"))]
 1255    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 1256        let path = path.into();
 1257        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 1258            self.opened_buffers.iter().any(|(_, buffer)| {
 1259                if let Some(buffer) = buffer.upgrade() {
 1260                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 1261                        if file.worktree == worktree && file.path() == &path.path {
 1262                            return true;
 1263                        }
 1264                    }
 1265                }
 1266                false
 1267            })
 1268        } else {
 1269            false
 1270        }
 1271    }
 1272
 1273    pub fn fs(&self) -> &Arc<dyn Fs> {
 1274        &self.fs
 1275    }
 1276
 1277    pub fn remote_id(&self) -> Option<u64> {
 1278        match self.client_state {
 1279            ProjectClientState::Local => None,
 1280            ProjectClientState::Shared { remote_id, .. }
 1281            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
 1282        }
 1283    }
 1284
 1285    pub fn hosted_project_id(&self) -> Option<ProjectId> {
 1286        self.hosted_project_id
 1287    }
 1288
 1289    pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
 1290        self.dev_server_project_id
 1291    }
 1292
 1293    pub fn supports_remote_terminal(&self, cx: &AppContext) -> bool {
 1294        let Some(id) = self.dev_server_project_id else {
 1295            return false;
 1296        };
 1297        let Some(server) = dev_server_projects::Store::global(cx)
 1298            .read(cx)
 1299            .dev_server_for_project(id)
 1300        else {
 1301            return false;
 1302        };
 1303        server.ssh_connection_string.is_some()
 1304    }
 1305
 1306    pub fn ssh_connection_string(&self, cx: &ModelContext<Self>) -> Option<SharedString> {
 1307        if self.is_local() {
 1308            return None;
 1309        }
 1310
 1311        let dev_server_id = self.dev_server_project_id()?;
 1312        dev_server_projects::Store::global(cx)
 1313            .read(cx)
 1314            .dev_server_for_project(dev_server_id)?
 1315            .ssh_connection_string
 1316            .clone()
 1317    }
 1318
 1319    pub fn replica_id(&self) -> ReplicaId {
 1320        match self.client_state {
 1321            ProjectClientState::Remote { replica_id, .. } => replica_id,
 1322            _ => 0,
 1323        }
 1324    }
 1325
 1326    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
 1327        if let ProjectClientState::Shared { updates_tx, .. } = &mut self.client_state {
 1328            updates_tx
 1329                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
 1330                .ok();
 1331        }
 1332        cx.notify();
 1333    }
 1334
 1335    pub fn task_inventory(&self) -> &Model<Inventory> {
 1336        &self.tasks
 1337    }
 1338
 1339    pub fn search_history(&self) -> &SearchHistory {
 1340        &self.search_history
 1341    }
 1342
 1343    pub fn search_history_mut(&mut self) -> &mut SearchHistory {
 1344        &mut self.search_history
 1345    }
 1346
 1347    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 1348        &self.collaborators
 1349    }
 1350
 1351    pub fn host(&self) -> Option<&Collaborator> {
 1352        self.collaborators.values().find(|c| c.replica_id == 0)
 1353    }
 1354
 1355    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
 1356        self.worktrees_reordered = worktrees_reordered;
 1357    }
 1358
 1359    /// Collect all worktrees, including ones that don't appear in the project panel
 1360    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
 1361        self.worktrees
 1362            .iter()
 1363            .filter_map(move |worktree| worktree.upgrade())
 1364    }
 1365
 1366    /// Collect all user-visible worktrees, the ones that appear in the project panel.
 1367    pub fn visible_worktrees<'a>(
 1368        &'a self,
 1369        cx: &'a AppContext,
 1370    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
 1371        self.worktrees()
 1372            .filter(|worktree| worktree.read(cx).is_visible())
 1373    }
 1374
 1375    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 1376        self.visible_worktrees(cx)
 1377            .map(|tree| tree.read(cx).root_name())
 1378    }
 1379
 1380    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
 1381        self.worktrees()
 1382            .find(|worktree| worktree.read(cx).id() == id)
 1383    }
 1384
 1385    pub fn worktree_for_entry(
 1386        &self,
 1387        entry_id: ProjectEntryId,
 1388        cx: &AppContext,
 1389    ) -> Option<Model<Worktree>> {
 1390        self.worktrees()
 1391            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 1392    }
 1393
 1394    pub fn worktree_id_for_entry(
 1395        &self,
 1396        entry_id: ProjectEntryId,
 1397        cx: &AppContext,
 1398    ) -> Option<WorktreeId> {
 1399        self.worktree_for_entry(entry_id, cx)
 1400            .map(|worktree| worktree.read(cx).id())
 1401    }
 1402
 1403    /// Checks if the entry is the root of a worktree.
 1404    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
 1405        self.worktree_for_entry(entry_id, cx)
 1406            .map(|worktree| {
 1407                worktree
 1408                    .read(cx)
 1409                    .root_entry()
 1410                    .is_some_and(|e| e.id == entry_id)
 1411            })
 1412            .unwrap_or(false)
 1413    }
 1414
 1415    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
 1416        paths
 1417            .iter()
 1418            .map(|path| self.visibility_for_path(path, cx))
 1419            .max()
 1420            .flatten()
 1421    }
 1422
 1423    pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
 1424        self.worktrees()
 1425            .filter_map(|worktree| {
 1426                let worktree = worktree.read(cx);
 1427                worktree
 1428                    .as_local()?
 1429                    .contains_abs_path(path)
 1430                    .then(|| worktree.is_visible())
 1431            })
 1432            .max()
 1433    }
 1434
 1435    pub fn create_entry(
 1436        &mut self,
 1437        project_path: impl Into<ProjectPath>,
 1438        is_directory: bool,
 1439        cx: &mut ModelContext<Self>,
 1440    ) -> Task<Result<CreatedEntry>> {
 1441        let project_path = project_path.into();
 1442        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
 1443            return Task::ready(Err(anyhow!(format!(
 1444                "No worktree for path {project_path:?}"
 1445            ))));
 1446        };
 1447        worktree.update(cx, |worktree, cx| {
 1448            worktree.create_entry(project_path.path, is_directory, cx)
 1449        })
 1450    }
 1451
 1452    pub fn copy_entry(
 1453        &mut self,
 1454        entry_id: ProjectEntryId,
 1455        new_path: impl Into<Arc<Path>>,
 1456        cx: &mut ModelContext<Self>,
 1457    ) -> Task<Result<Option<Entry>>> {
 1458        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1459            return Task::ready(Ok(None));
 1460        };
 1461        worktree.update(cx, |worktree, cx| {
 1462            worktree.copy_entry(entry_id, new_path, cx)
 1463        })
 1464    }
 1465
 1466    pub fn rename_entry(
 1467        &mut self,
 1468        entry_id: ProjectEntryId,
 1469        new_path: impl Into<Arc<Path>>,
 1470        cx: &mut ModelContext<Self>,
 1471    ) -> Task<Result<CreatedEntry>> {
 1472        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1473            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
 1474        };
 1475        worktree.update(cx, |worktree, cx| {
 1476            worktree.rename_entry(entry_id, new_path, cx)
 1477        })
 1478    }
 1479
 1480    pub fn delete_entry(
 1481        &mut self,
 1482        entry_id: ProjectEntryId,
 1483        trash: bool,
 1484        cx: &mut ModelContext<Self>,
 1485    ) -> Option<Task<Result<()>>> {
 1486        let worktree = self.worktree_for_entry(entry_id, cx)?;
 1487        cx.emit(Event::DeletedEntry(entry_id));
 1488        worktree.update(cx, |worktree, cx| {
 1489            worktree.delete_entry(entry_id, trash, cx)
 1490        })
 1491    }
 1492
 1493    pub fn expand_entry(
 1494        &mut self,
 1495        worktree_id: WorktreeId,
 1496        entry_id: ProjectEntryId,
 1497        cx: &mut ModelContext<Self>,
 1498    ) -> Option<Task<Result<()>>> {
 1499        let worktree = self.worktree_for_id(worktree_id, cx)?;
 1500        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
 1501    }
 1502
 1503    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
 1504        if !matches!(self.client_state, ProjectClientState::Local) {
 1505            if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
 1506                if *in_room || self.dev_server_project_id.is_none() {
 1507                    return Err(anyhow!("project was already shared"));
 1508                } else {
 1509                    *in_room = true;
 1510                    return Ok(());
 1511                }
 1512            } else {
 1513                return Err(anyhow!("project was already shared"));
 1514            }
 1515        }
 1516        self.client_subscriptions.push(
 1517            self.client
 1518                .subscribe_to_entity(project_id)?
 1519                .set_model(&cx.handle(), &mut cx.to_async()),
 1520        );
 1521
 1522        for open_buffer in self.opened_buffers.values_mut() {
 1523            match open_buffer {
 1524                OpenBuffer::Strong(_) => {}
 1525                OpenBuffer::Weak(buffer) => {
 1526                    if let Some(buffer) = buffer.upgrade() {
 1527                        *open_buffer = OpenBuffer::Strong(buffer);
 1528                    }
 1529                }
 1530                OpenBuffer::Operations(_) => unreachable!(),
 1531            }
 1532        }
 1533
 1534        for worktree_handle in self.worktrees.iter_mut() {
 1535            match worktree_handle {
 1536                WorktreeHandle::Strong(_) => {}
 1537                WorktreeHandle::Weak(worktree) => {
 1538                    if let Some(worktree) = worktree.upgrade() {
 1539                        *worktree_handle = WorktreeHandle::Strong(worktree);
 1540                    }
 1541                }
 1542            }
 1543        }
 1544
 1545        for (server_id, status) in &self.language_server_statuses {
 1546            self.client
 1547                .send(proto::StartLanguageServer {
 1548                    project_id,
 1549                    server: Some(proto::LanguageServer {
 1550                        id: server_id.0 as u64,
 1551                        name: status.name.clone(),
 1552                    }),
 1553                })
 1554                .log_err();
 1555        }
 1556
 1557        let store = cx.global::<SettingsStore>();
 1558        for worktree in self.worktrees() {
 1559            let worktree_id = worktree.read(cx).id().to_proto();
 1560            for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
 1561                self.client
 1562                    .send(proto::UpdateWorktreeSettings {
 1563                        project_id,
 1564                        worktree_id,
 1565                        path: path.to_string_lossy().into(),
 1566                        content: Some(content),
 1567                    })
 1568                    .log_err();
 1569            }
 1570        }
 1571
 1572        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 1573        let client = self.client.clone();
 1574        self.client_state = ProjectClientState::Shared {
 1575            remote_id: project_id,
 1576            updates_tx,
 1577            _send_updates: cx.spawn(move |this, mut cx| async move {
 1578                while let Some(update) = updates_rx.next().await {
 1579                    match update {
 1580                        LocalProjectUpdate::WorktreesChanged => {
 1581                            let worktrees = this.update(&mut cx, |this, _cx| {
 1582                                this.worktrees().collect::<Vec<_>>()
 1583                            })?;
 1584
 1585                            let update_project = this
 1586                                .update(&mut cx, |this, cx| {
 1587                                    this.client.request(proto::UpdateProject {
 1588                                        project_id,
 1589                                        worktrees: this.worktree_metadata_protos(cx),
 1590                                    })
 1591                                })?
 1592                                .await;
 1593                            if update_project.log_err().is_none() {
 1594                                continue;
 1595                            }
 1596
 1597                            this.update(&mut cx, |this, cx| {
 1598                                for worktree in worktrees {
 1599                                    worktree.update(cx, |worktree, cx| {
 1600                                        if let Some(summaries) =
 1601                                            this.diagnostic_summaries.get(&worktree.id())
 1602                                        {
 1603                                            for (path, summaries) in summaries {
 1604                                                for (&server_id, summary) in summaries {
 1605                                                    this.client.send(
 1606                                                        proto::UpdateDiagnosticSummary {
 1607                                                            project_id,
 1608                                                            worktree_id: cx.entity_id().as_u64(),
 1609                                                            summary: Some(
 1610                                                                summary.to_proto(server_id, path),
 1611                                                            ),
 1612                                                        },
 1613                                                    )?;
 1614                                                }
 1615                                            }
 1616                                        }
 1617
 1618                                        worktree.observe_updates(project_id, cx, {
 1619                                            let client = client.clone();
 1620                                            move |update| {
 1621                                                client.request(update).map(|result| result.is_ok())
 1622                                            }
 1623                                        });
 1624
 1625                                        anyhow::Ok(())
 1626                                    })?;
 1627                                }
 1628                                anyhow::Ok(())
 1629                            })??;
 1630                        }
 1631                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
 1632                            let buffer = this.update(&mut cx, |this, _| {
 1633                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
 1634                                let shared_buffers =
 1635                                    this.shared_buffers.entry(peer_id).or_default();
 1636                                if shared_buffers.insert(buffer_id) {
 1637                                    if let OpenBuffer::Strong(buffer) = buffer {
 1638                                        Some(buffer.clone())
 1639                                    } else {
 1640                                        None
 1641                                    }
 1642                                } else {
 1643                                    None
 1644                                }
 1645                            })?;
 1646
 1647                            let Some(buffer) = buffer else { continue };
 1648                            let operations =
 1649                                buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
 1650                            let operations = operations.await;
 1651                            let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
 1652
 1653                            let initial_state = proto::CreateBufferForPeer {
 1654                                project_id,
 1655                                peer_id: Some(peer_id),
 1656                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
 1657                            };
 1658                            if client.send(initial_state).log_err().is_some() {
 1659                                let client = client.clone();
 1660                                cx.background_executor()
 1661                                    .spawn(async move {
 1662                                        let mut chunks = split_operations(operations).peekable();
 1663                                        while let Some(chunk) = chunks.next() {
 1664                                            let is_last = chunks.peek().is_none();
 1665                                            client.send(proto::CreateBufferForPeer {
 1666                                                project_id,
 1667                                                peer_id: Some(peer_id),
 1668                                                variant: Some(
 1669                                                    proto::create_buffer_for_peer::Variant::Chunk(
 1670                                                        proto::BufferChunk {
 1671                                                            buffer_id: buffer_id.into(),
 1672                                                            operations: chunk,
 1673                                                            is_last,
 1674                                                        },
 1675                                                    ),
 1676                                                ),
 1677                                            })?;
 1678                                        }
 1679                                        anyhow::Ok(())
 1680                                    })
 1681                                    .await
 1682                                    .log_err();
 1683                            }
 1684                        }
 1685                    }
 1686                }
 1687                Ok(())
 1688            }),
 1689        };
 1690
 1691        self.metadata_changed(cx);
 1692        cx.emit(Event::RemoteIdChanged(Some(project_id)));
 1693        cx.notify();
 1694        Ok(())
 1695    }
 1696
 1697    pub fn reshared(
 1698        &mut self,
 1699        message: proto::ResharedProject,
 1700        cx: &mut ModelContext<Self>,
 1701    ) -> Result<()> {
 1702        self.shared_buffers.clear();
 1703        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1704        self.metadata_changed(cx);
 1705        Ok(())
 1706    }
 1707
 1708    pub fn rejoined(
 1709        &mut self,
 1710        message: proto::RejoinedProject,
 1711        message_id: u32,
 1712        cx: &mut ModelContext<Self>,
 1713    ) -> Result<()> {
 1714        cx.update_global::<SettingsStore, _>(|store, cx| {
 1715            for worktree in &self.worktrees {
 1716                store
 1717                    .clear_local_settings(worktree.handle_id(), cx)
 1718                    .log_err();
 1719            }
 1720        });
 1721
 1722        self.join_project_response_message_id = message_id;
 1723        self.set_worktrees_from_proto(message.worktrees, cx)?;
 1724        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1725        self.language_server_statuses = message
 1726            .language_servers
 1727            .into_iter()
 1728            .map(|server| {
 1729                (
 1730                    LanguageServerId(server.id as usize),
 1731                    LanguageServerStatus {
 1732                        name: server.name,
 1733                        pending_work: Default::default(),
 1734                        has_pending_diagnostic_updates: false,
 1735                        progress_tokens: Default::default(),
 1736                    },
 1737                )
 1738            })
 1739            .collect();
 1740        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 1741            .unwrap();
 1742        cx.notify();
 1743        Ok(())
 1744    }
 1745
 1746    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
 1747        self.unshare_internal(cx)?;
 1748        self.metadata_changed(cx);
 1749        cx.notify();
 1750        Ok(())
 1751    }
 1752
 1753    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
 1754        if self.is_remote() {
 1755            if self.dev_server_project_id().is_some() {
 1756                if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
 1757                    *in_room = false
 1758                }
 1759                return Ok(());
 1760            } else {
 1761                return Err(anyhow!("attempted to unshare a remote project"));
 1762            }
 1763        }
 1764
 1765        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
 1766            self.client_state = ProjectClientState::Local;
 1767            self.collaborators.clear();
 1768            self.shared_buffers.clear();
 1769            self.client_subscriptions.clear();
 1770
 1771            for worktree_handle in self.worktrees.iter_mut() {
 1772                if let WorktreeHandle::Strong(worktree) = worktree_handle {
 1773                    let is_visible = worktree.update(cx, |worktree, _| {
 1774                        worktree.stop_observing_updates();
 1775                        worktree.is_visible()
 1776                    });
 1777                    if !is_visible {
 1778                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 1779                    }
 1780                }
 1781            }
 1782
 1783            for open_buffer in self.opened_buffers.values_mut() {
 1784                // Wake up any tasks waiting for peers' edits to this buffer.
 1785                if let Some(buffer) = open_buffer.upgrade() {
 1786                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1787                }
 1788
 1789                if let OpenBuffer::Strong(buffer) = open_buffer {
 1790                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1791                }
 1792            }
 1793
 1794            self.client.send(proto::UnshareProject {
 1795                project_id: remote_id,
 1796            })?;
 1797
 1798            Ok(())
 1799        } else {
 1800            Err(anyhow!("attempted to unshare an unshared project"))
 1801        }
 1802    }
 1803
 1804    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
 1805        if self.is_disconnected() {
 1806            return;
 1807        }
 1808        self.disconnected_from_host_internal(cx);
 1809        cx.emit(Event::DisconnectedFromHost);
 1810        cx.notify();
 1811    }
 1812
 1813    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
 1814        let new_capability =
 1815            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
 1816                Capability::ReadWrite
 1817            } else {
 1818                Capability::ReadOnly
 1819            };
 1820        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
 1821            if *capability == new_capability {
 1822                return;
 1823            }
 1824
 1825            *capability = new_capability;
 1826            for buffer in self.opened_buffers() {
 1827                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
 1828            }
 1829        }
 1830    }
 1831
 1832    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
 1833        if let ProjectClientState::Remote {
 1834            sharing_has_stopped,
 1835            ..
 1836        } = &mut self.client_state
 1837        {
 1838            *sharing_has_stopped = true;
 1839
 1840            self.collaborators.clear();
 1841
 1842            for worktree in &self.worktrees {
 1843                if let Some(worktree) = worktree.upgrade() {
 1844                    worktree.update(cx, |worktree, _| {
 1845                        if let Some(worktree) = worktree.as_remote_mut() {
 1846                            worktree.disconnected_from_host();
 1847                        }
 1848                    });
 1849                }
 1850            }
 1851
 1852            for open_buffer in self.opened_buffers.values_mut() {
 1853                // Wake up any tasks waiting for peers' edits to this buffer.
 1854                if let Some(buffer) = open_buffer.upgrade() {
 1855                    buffer.update(cx, |buffer, cx| {
 1856                        buffer.give_up_waiting();
 1857                        buffer.set_capability(Capability::ReadOnly, cx)
 1858                    });
 1859                }
 1860
 1861                if let OpenBuffer::Strong(buffer) = open_buffer {
 1862                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1863                }
 1864            }
 1865
 1866            // Wake up all futures currently waiting on a buffer to get opened,
 1867            // to give them a chance to fail now that we've disconnected.
 1868            self.loading_buffers.clear();
 1869            // self.opened_buffer.send(OpenedBufferEvent::Disconnected);
 1870        }
 1871    }
 1872
 1873    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 1874        cx.emit(Event::Closed);
 1875    }
 1876
 1877    pub fn is_disconnected(&self) -> bool {
 1878        match &self.client_state {
 1879            ProjectClientState::Remote {
 1880                sharing_has_stopped,
 1881                ..
 1882            } => *sharing_has_stopped,
 1883            _ => false,
 1884        }
 1885    }
 1886
 1887    pub fn capability(&self) -> Capability {
 1888        match &self.client_state {
 1889            ProjectClientState::Remote { capability, .. } => *capability,
 1890            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
 1891        }
 1892    }
 1893
 1894    pub fn is_read_only(&self) -> bool {
 1895        self.is_disconnected() || self.capability() == Capability::ReadOnly
 1896    }
 1897
 1898    pub fn is_local(&self) -> bool {
 1899        match &self.client_state {
 1900            ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
 1901            ProjectClientState::Remote { .. } => false,
 1902        }
 1903    }
 1904
 1905    pub fn is_remote(&self) -> bool {
 1906        !self.is_local()
 1907    }
 1908
 1909    pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
 1910        if self.is_remote() {
 1911            let create = self.client.request(proto::OpenNewBuffer {
 1912                project_id: self.remote_id().unwrap(),
 1913            });
 1914            cx.spawn(|this, mut cx| async move {
 1915                let response = create.await?;
 1916                let buffer_id = BufferId::new(response.buffer_id)?;
 1917
 1918                this.update(&mut cx, |this, cx| {
 1919                    this.wait_for_remote_buffer(buffer_id, cx)
 1920                })?
 1921                .await
 1922            })
 1923        } else {
 1924            Task::ready(Ok(self.create_local_buffer("", None, cx)))
 1925        }
 1926    }
 1927
 1928    pub fn create_local_buffer(
 1929        &mut self,
 1930        text: &str,
 1931        language: Option<Arc<Language>>,
 1932        cx: &mut ModelContext<Self>,
 1933    ) -> Model<Buffer> {
 1934        if self.is_remote() {
 1935            panic!("called create_local_buffer on a remote project")
 1936        }
 1937        let buffer = cx.new_model(|cx| {
 1938            Buffer::local(text, cx)
 1939                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
 1940        });
 1941        self.register_buffer(&buffer, cx)
 1942            .expect("creating local buffers always succeeds");
 1943        buffer
 1944    }
 1945
 1946    pub fn open_path(
 1947        &mut self,
 1948        path: ProjectPath,
 1949        cx: &mut ModelContext<Self>,
 1950    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
 1951        let task = self.open_buffer(path.clone(), cx);
 1952        cx.spawn(move |_, cx| async move {
 1953            let buffer = task.await?;
 1954            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
 1955                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
 1956            })?;
 1957
 1958            let buffer: &AnyModel = &buffer;
 1959            Ok((project_entry_id, buffer.clone()))
 1960        })
 1961    }
 1962
 1963    pub fn open_buffer_for_full_path(
 1964        &mut self,
 1965        path: &Path,
 1966        cx: &mut ModelContext<Self>,
 1967    ) -> Task<Result<Model<Buffer>>> {
 1968        if let Some(worktree_name) = path.components().next() {
 1969            let worktree = self.worktrees().find(|worktree| {
 1970                OsStr::new(worktree.read(cx).root_name()) == worktree_name.as_os_str()
 1971            });
 1972            if let Some(worktree) = worktree {
 1973                let worktree = worktree.read(cx);
 1974                let worktree_root_path = Path::new(worktree.root_name());
 1975                if let Ok(path) = path.strip_prefix(worktree_root_path) {
 1976                    let project_path = ProjectPath {
 1977                        worktree_id: worktree.id(),
 1978                        path: path.into(),
 1979                    };
 1980                    return self.open_buffer(project_path, cx);
 1981                }
 1982            }
 1983        }
 1984        Task::ready(Err(anyhow!("buffer not found for {:?}", path)))
 1985    }
 1986
 1987    pub fn open_local_buffer(
 1988        &mut self,
 1989        abs_path: impl AsRef<Path>,
 1990        cx: &mut ModelContext<Self>,
 1991    ) -> Task<Result<Model<Buffer>>> {
 1992        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
 1993            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
 1994        } else {
 1995            Task::ready(Err(anyhow!("no such path")))
 1996        }
 1997    }
 1998
 1999    pub fn open_buffer(
 2000        &mut self,
 2001        path: impl Into<ProjectPath>,
 2002        cx: &mut ModelContext<Self>,
 2003    ) -> Task<Result<Model<Buffer>>> {
 2004        let project_path = path.into();
 2005        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
 2006            worktree
 2007        } else {
 2008            return Task::ready(Err(anyhow!("no such worktree")));
 2009        };
 2010
 2011        // If there is already a buffer for the given path, then return it.
 2012        let existing_buffer = self.get_open_buffer(&project_path, cx);
 2013        if let Some(existing_buffer) = existing_buffer {
 2014            return Task::ready(Ok(existing_buffer));
 2015        }
 2016
 2017        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
 2018            // If the given path is already being loaded, then wait for that existing
 2019            // task to complete and return the same buffer.
 2020            hash_map::Entry::Occupied(e) => e.get().clone(),
 2021
 2022            // Otherwise, record the fact that this path is now being loaded.
 2023            hash_map::Entry::Vacant(entry) => {
 2024                let (mut tx, rx) = postage::watch::channel();
 2025                entry.insert(rx.clone());
 2026
 2027                let project_path = project_path.clone();
 2028                let load_buffer = if worktree.read(cx).is_local() {
 2029                    self.open_local_buffer_internal(project_path.path.clone(), worktree, cx)
 2030                } else {
 2031                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
 2032                };
 2033
 2034                cx.spawn(move |this, mut cx| async move {
 2035                    let load_result = load_buffer.await;
 2036                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
 2037                        // Record the fact that the buffer is no longer loading.
 2038                        this.loading_buffers_by_path.remove(&project_path);
 2039                        let buffer = load_result.map_err(Arc::new)?;
 2040                        Ok(buffer)
 2041                    })?);
 2042                    anyhow::Ok(())
 2043                })
 2044                .detach();
 2045                rx
 2046            }
 2047        };
 2048
 2049        cx.background_executor().spawn(async move {
 2050            wait_for_loading_buffer(loading_watch)
 2051                .await
 2052                .map_err(|e| e.cloned())
 2053        })
 2054    }
 2055
 2056    fn open_local_buffer_internal(
 2057        &mut self,
 2058        path: Arc<Path>,
 2059        worktree: Model<Worktree>,
 2060        cx: &mut ModelContext<Self>,
 2061    ) -> Task<Result<Model<Buffer>>> {
 2062        let load_buffer = worktree.update(cx, |worktree, cx| {
 2063            let load_file = worktree.load_file(path.as_ref(), cx);
 2064            let reservation = cx.reserve_model();
 2065            let buffer_id = BufferId::from(reservation.entity_id().as_non_zero_u64());
 2066            cx.spawn(move |_, mut cx| async move {
 2067                let loaded = load_file.await?;
 2068                let text_buffer = cx
 2069                    .background_executor()
 2070                    .spawn(async move { text::Buffer::new(0, buffer_id, loaded.text) })
 2071                    .await;
 2072                cx.insert_model(reservation, |_| {
 2073                    Buffer::build(
 2074                        text_buffer,
 2075                        loaded.diff_base,
 2076                        Some(loaded.file),
 2077                        Capability::ReadWrite,
 2078                    )
 2079                })
 2080            })
 2081        });
 2082
 2083        cx.spawn(move |this, mut cx| async move {
 2084            let buffer = match load_buffer.await {
 2085                Ok(buffer) => Ok(buffer),
 2086                Err(error) if is_not_found_error(&error) => cx.new_model(|cx| {
 2087                    let buffer_id = BufferId::from(cx.entity_id().as_non_zero_u64());
 2088                    let text_buffer = text::Buffer::new(0, buffer_id, "".into());
 2089                    Buffer::build(
 2090                        text_buffer,
 2091                        None,
 2092                        Some(Arc::new(File {
 2093                            worktree,
 2094                            path,
 2095                            mtime: None,
 2096                            entry_id: None,
 2097                            is_local: true,
 2098                            is_deleted: false,
 2099                            is_private: false,
 2100                        })),
 2101                        Capability::ReadWrite,
 2102                    )
 2103                }),
 2104                Err(e) => Err(e),
 2105            }?;
 2106            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
 2107            Ok(buffer)
 2108        })
 2109    }
 2110
 2111    fn open_remote_buffer_internal(
 2112        &mut self,
 2113        path: &Arc<Path>,
 2114        worktree: &Model<Worktree>,
 2115        cx: &mut ModelContext<Self>,
 2116    ) -> Task<Result<Model<Buffer>>> {
 2117        let rpc = self.client.clone();
 2118        let project_id = self.remote_id().unwrap();
 2119        let remote_worktree_id = worktree.read(cx).id();
 2120        let path = path.clone();
 2121        let path_string = path.to_string_lossy().to_string();
 2122        if self.is_disconnected() {
 2123            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
 2124        }
 2125        cx.spawn(move |this, mut cx| async move {
 2126            let response = rpc
 2127                .request(proto::OpenBufferByPath {
 2128                    project_id,
 2129                    worktree_id: remote_worktree_id.to_proto(),
 2130                    path: path_string,
 2131                })
 2132                .await?;
 2133            let buffer_id = BufferId::new(response.buffer_id)?;
 2134            this.update(&mut cx, |this, cx| {
 2135                this.wait_for_remote_buffer(buffer_id, cx)
 2136            })?
 2137            .await
 2138        })
 2139    }
 2140
 2141    /// LanguageServerName is owned, because it is inserted into a map
 2142    pub fn open_local_buffer_via_lsp(
 2143        &mut self,
 2144        abs_path: lsp::Uri,
 2145        language_server_id: LanguageServerId,
 2146        language_server_name: LanguageServerName,
 2147        cx: &mut ModelContext<Self>,
 2148    ) -> Task<Result<Model<Buffer>>> {
 2149        cx.spawn(move |this, mut cx| async move {
 2150            let abs_path = abs_path
 2151                .to_file_path()
 2152                .map_err(|_| anyhow!("can't convert URI to path"))?;
 2153            let (worktree, relative_path) = if let Some(result) =
 2154                this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
 2155            {
 2156                result
 2157            } else {
 2158                let worktree = this
 2159                    .update(&mut cx, |this, cx| {
 2160                        this.create_local_worktree(&abs_path, false, cx)
 2161                    })?
 2162                    .await?;
 2163                this.update(&mut cx, |this, cx| {
 2164                    this.language_server_ids.insert(
 2165                        (worktree.read(cx).id(), language_server_name),
 2166                        language_server_id,
 2167                    );
 2168                })
 2169                .ok();
 2170                (worktree, PathBuf::new())
 2171            };
 2172
 2173            let project_path = ProjectPath {
 2174                worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
 2175                path: relative_path.into(),
 2176            };
 2177            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
 2178                .await
 2179        })
 2180    }
 2181
 2182    pub fn open_buffer_by_id(
 2183        &mut self,
 2184        id: BufferId,
 2185        cx: &mut ModelContext<Self>,
 2186    ) -> Task<Result<Model<Buffer>>> {
 2187        if let Some(buffer) = self.buffer_for_id(id) {
 2188            Task::ready(Ok(buffer))
 2189        } else if self.is_local() {
 2190            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
 2191        } else if let Some(project_id) = self.remote_id() {
 2192            let request = self.client.request(proto::OpenBufferById {
 2193                project_id,
 2194                id: id.into(),
 2195            });
 2196            cx.spawn(move |this, mut cx| async move {
 2197                let buffer_id = BufferId::new(request.await?.buffer_id)?;
 2198                this.update(&mut cx, |this, cx| {
 2199                    this.wait_for_remote_buffer(buffer_id, cx)
 2200                })?
 2201                .await
 2202            })
 2203        } else {
 2204            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
 2205        }
 2206    }
 2207
 2208    pub fn save_buffers(
 2209        &self,
 2210        buffers: HashSet<Model<Buffer>>,
 2211        cx: &mut ModelContext<Self>,
 2212    ) -> Task<Result<()>> {
 2213        cx.spawn(move |this, mut cx| async move {
 2214            let save_tasks = buffers.into_iter().filter_map(|buffer| {
 2215                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
 2216                    .ok()
 2217            });
 2218            try_join_all(save_tasks).await?;
 2219            Ok(())
 2220        })
 2221    }
 2222
 2223    pub fn save_buffer(
 2224        &self,
 2225        buffer: Model<Buffer>,
 2226        cx: &mut ModelContext<Self>,
 2227    ) -> Task<Result<()>> {
 2228        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2229            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 2230        };
 2231        let worktree = file.worktree.clone();
 2232        let path = file.path.clone();
 2233        if self.is_local() {
 2234            self.save_local_buffer(worktree, buffer, path, false, cx)
 2235        } else {
 2236            self.save_remote_buffer(buffer, None, cx)
 2237        }
 2238    }
 2239
 2240    pub fn save_buffer_as(
 2241        &mut self,
 2242        buffer: Model<Buffer>,
 2243        path: ProjectPath,
 2244        cx: &mut ModelContext<Self>,
 2245    ) -> Task<Result<()>> {
 2246        let old_file = File::from_dyn(buffer.read(cx).file()).cloned();
 2247        let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) else {
 2248            return Task::ready(Err(anyhow!("worktree does not exist")));
 2249        };
 2250
 2251        cx.spawn(move |this, mut cx| async move {
 2252            this.update(&mut cx, |this, cx| {
 2253                if this.is_local() {
 2254                    if let Some(old_file) = &old_file {
 2255                        this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
 2256                    }
 2257                    this.save_local_buffer(worktree, buffer.clone(), path.path, true, cx)
 2258                } else {
 2259                    this.save_remote_buffer(buffer.clone(), Some(path.to_proto()), cx)
 2260                }
 2261            })?
 2262            .await?;
 2263
 2264            this.update(&mut cx, |this, cx| {
 2265                this.detect_language_for_buffer(&buffer, cx);
 2266                this.register_buffer_with_language_servers(&buffer, cx);
 2267            })?;
 2268            Ok(())
 2269        })
 2270    }
 2271
 2272    pub fn save_local_buffer(
 2273        &self,
 2274        worktree: Model<Worktree>,
 2275        buffer_handle: Model<Buffer>,
 2276        path: Arc<Path>,
 2277        mut has_changed_file: bool,
 2278        cx: &mut ModelContext<Self>,
 2279    ) -> Task<Result<()>> {
 2280        let buffer = buffer_handle.read(cx);
 2281        let buffer_id = buffer.remote_id();
 2282        let text = buffer.as_rope().clone();
 2283        let line_ending = buffer.line_ending();
 2284        let version = buffer.version();
 2285        if buffer.file().is_some_and(|file| !file.is_created()) {
 2286            has_changed_file = true;
 2287        }
 2288
 2289        let save = worktree.update(cx, |worktree, cx| {
 2290            worktree.write_file(path.as_ref(), text, line_ending, cx)
 2291        });
 2292
 2293        let client = self.client.clone();
 2294        let project_id = self.remote_id();
 2295        cx.spawn(move |_, mut cx| async move {
 2296            let new_file = save.await?;
 2297            let mtime = new_file.mtime;
 2298            if has_changed_file {
 2299                if let Some(project_id) = project_id {
 2300                    client
 2301                        .send(proto::UpdateBufferFile {
 2302                            project_id,
 2303                            buffer_id: buffer_id.into(),
 2304                            file: Some(new_file.to_proto()),
 2305                        })
 2306                        .log_err();
 2307                }
 2308
 2309                buffer_handle.update(&mut cx, |buffer, cx| {
 2310                    if has_changed_file {
 2311                        buffer.file_updated(new_file, cx);
 2312                    }
 2313                })?;
 2314            }
 2315
 2316            if let Some(project_id) = project_id {
 2317                client.send(proto::BufferSaved {
 2318                    project_id,
 2319                    buffer_id: buffer_id.into(),
 2320                    version: serialize_version(&version),
 2321                    mtime: mtime.map(|time| time.into()),
 2322                })?;
 2323            }
 2324
 2325            buffer_handle.update(&mut cx, |buffer, cx| {
 2326                buffer.did_save(version.clone(), mtime, cx);
 2327            })?;
 2328
 2329            Ok(())
 2330        })
 2331    }
 2332
 2333    pub fn save_remote_buffer(
 2334        &self,
 2335        buffer_handle: Model<Buffer>,
 2336        new_path: Option<proto::ProjectPath>,
 2337        cx: &mut ModelContext<Self>,
 2338    ) -> Task<Result<()>> {
 2339        let buffer = buffer_handle.read(cx);
 2340        let buffer_id = buffer.remote_id().into();
 2341        let version = buffer.version();
 2342        let rpc = self.client.clone();
 2343        let project_id = self.remote_id();
 2344        cx.spawn(move |_, mut cx| async move {
 2345            let response = rpc
 2346                .request(proto::SaveBuffer {
 2347                    project_id: project_id.ok_or_else(|| anyhow!("project_id is not set"))?,
 2348                    buffer_id,
 2349                    new_path,
 2350                    version: serialize_version(&version),
 2351                })
 2352                .await?;
 2353            let version = deserialize_version(&response.version);
 2354            let mtime = response.mtime.map(|mtime| mtime.into());
 2355
 2356            buffer_handle.update(&mut cx, |buffer, cx| {
 2357                buffer.did_save(version.clone(), mtime, cx);
 2358            })?;
 2359
 2360            Ok(())
 2361        })
 2362    }
 2363
 2364    pub fn get_open_buffer(
 2365        &mut self,
 2366        path: &ProjectPath,
 2367        cx: &mut ModelContext<Self>,
 2368    ) -> Option<Model<Buffer>> {
 2369        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
 2370        self.opened_buffers.values().find_map(|buffer| {
 2371            let buffer = buffer.upgrade()?;
 2372            let file = File::from_dyn(buffer.read(cx).file())?;
 2373            if file.worktree == worktree && file.path() == &path.path {
 2374                Some(buffer)
 2375            } else {
 2376                None
 2377            }
 2378        })
 2379    }
 2380
 2381    fn register_buffer(
 2382        &mut self,
 2383        buffer: &Model<Buffer>,
 2384        cx: &mut ModelContext<Self>,
 2385    ) -> Result<()> {
 2386        self.request_buffer_diff_recalculation(buffer, cx);
 2387        buffer.update(cx, |buffer, _| {
 2388            buffer.set_language_registry(self.languages.clone())
 2389        });
 2390
 2391        let remote_id = buffer.read(cx).remote_id();
 2392        let is_remote = self.is_remote();
 2393        let open_buffer = if is_remote || self.is_shared() {
 2394            OpenBuffer::Strong(buffer.clone())
 2395        } else {
 2396            OpenBuffer::Weak(buffer.downgrade())
 2397        };
 2398
 2399        match self.opened_buffers.entry(remote_id) {
 2400            hash_map::Entry::Vacant(entry) => {
 2401                entry.insert(open_buffer);
 2402            }
 2403            hash_map::Entry::Occupied(mut entry) => {
 2404                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 2405                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
 2406                } else if entry.get().upgrade().is_some() {
 2407                    if is_remote {
 2408                        return Ok(());
 2409                    } else {
 2410                        debug_panic!("buffer {} was already registered", remote_id);
 2411                        Err(anyhow!("buffer {} was already registered", remote_id))?;
 2412                    }
 2413                }
 2414                entry.insert(open_buffer);
 2415            }
 2416        }
 2417        cx.subscribe(buffer, |this, buffer, event, cx| {
 2418            this.on_buffer_event(buffer, event, cx);
 2419        })
 2420        .detach();
 2421
 2422        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 2423            if file.is_local {
 2424                self.local_buffer_ids_by_path.insert(
 2425                    ProjectPath {
 2426                        worktree_id: file.worktree_id(cx),
 2427                        path: file.path.clone(),
 2428                    },
 2429                    remote_id,
 2430                );
 2431
 2432                if let Some(entry_id) = file.entry_id {
 2433                    self.local_buffer_ids_by_entry_id
 2434                        .insert(entry_id, remote_id);
 2435                }
 2436            }
 2437        }
 2438
 2439        self.detect_language_for_buffer(buffer, cx);
 2440        self.register_buffer_with_language_servers(buffer, cx);
 2441        cx.observe_release(buffer, |this, buffer, cx| {
 2442            if let Some(file) = File::from_dyn(buffer.file()) {
 2443                if file.is_local() {
 2444                    let uri = lsp::Uri::from_file_path(file.abs_path(cx)).unwrap();
 2445                    for server in this.language_servers_for_buffer(buffer, cx) {
 2446                        server
 2447                            .1
 2448                            .notify::<lsp::notification::DidCloseTextDocument>(
 2449                                lsp::DidCloseTextDocumentParams {
 2450                                    text_document: lsp::TextDocumentIdentifier::new(
 2451                                        uri.clone().into(),
 2452                                    ),
 2453                                },
 2454                            )
 2455                            .log_err();
 2456                    }
 2457                }
 2458            }
 2459        })
 2460        .detach();
 2461
 2462        if let Some(senders) = self.loading_buffers.remove(&remote_id) {
 2463            for sender in senders {
 2464                sender.send(Ok(buffer.clone())).ok();
 2465            }
 2466        }
 2467        Ok(())
 2468    }
 2469
 2470    fn register_buffer_with_language_servers(
 2471        &mut self,
 2472        buffer_handle: &Model<Buffer>,
 2473        cx: &mut ModelContext<Self>,
 2474    ) {
 2475        let buffer = buffer_handle.read(cx);
 2476        let buffer_id = buffer.remote_id();
 2477
 2478        if let Some(file) = File::from_dyn(buffer.file()) {
 2479            if !file.is_local() {
 2480                return;
 2481            }
 2482
 2483            let abs_path = file.abs_path(cx);
 2484            let Some(uri) = lsp::Uri::from_file_path(&abs_path).log_err() else {
 2485                return;
 2486            };
 2487            let initial_snapshot = buffer.text_snapshot();
 2488            let language = buffer.language().cloned();
 2489            let worktree_id = file.worktree_id(cx);
 2490
 2491            if let Some(diagnostics) = self.diagnostics.get(&worktree_id) {
 2492                for (server_id, diagnostics) in
 2493                    diagnostics.get(file.path()).cloned().unwrap_or_default()
 2494                {
 2495                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
 2496                        .log_err();
 2497                }
 2498            }
 2499
 2500            if let Some(language) = language {
 2501                for adapter in self.languages.lsp_adapters(&language) {
 2502                    let server = self
 2503                        .language_server_ids
 2504                        .get(&(worktree_id, adapter.name.clone()))
 2505                        .and_then(|id| self.language_servers.get(id))
 2506                        .and_then(|server_state| {
 2507                            if let LanguageServerState::Running { server, .. } = server_state {
 2508                                Some(server.clone())
 2509                            } else {
 2510                                None
 2511                            }
 2512                        });
 2513                    let server = match server {
 2514                        Some(server) => server,
 2515                        None => continue,
 2516                    };
 2517
 2518                    server
 2519                        .notify::<lsp::notification::DidOpenTextDocument>(
 2520                            lsp::DidOpenTextDocumentParams {
 2521                                text_document: lsp::TextDocumentItem::new(
 2522                                    uri.clone().into(),
 2523                                    adapter.language_id(&language),
 2524                                    0,
 2525                                    initial_snapshot.text(),
 2526                                ),
 2527                            },
 2528                        )
 2529                        .log_err();
 2530
 2531                    buffer_handle.update(cx, |buffer, cx| {
 2532                        buffer.set_completion_triggers(
 2533                            server
 2534                                .capabilities()
 2535                                .completion_provider
 2536                                .as_ref()
 2537                                .and_then(|provider| provider.trigger_characters.clone())
 2538                                .unwrap_or_default(),
 2539                            cx,
 2540                        );
 2541                    });
 2542
 2543                    let snapshot = LspBufferSnapshot {
 2544                        version: 0,
 2545                        snapshot: initial_snapshot.clone(),
 2546                    };
 2547                    self.buffer_snapshots
 2548                        .entry(buffer_id)
 2549                        .or_default()
 2550                        .insert(server.server_id(), vec![snapshot]);
 2551                }
 2552            }
 2553        }
 2554    }
 2555
 2556    fn unregister_buffer_from_language_servers(
 2557        &mut self,
 2558        buffer: &Model<Buffer>,
 2559        old_file: &File,
 2560        cx: &mut ModelContext<Self>,
 2561    ) {
 2562        let old_path = match old_file.as_local() {
 2563            Some(local) => local.abs_path(cx),
 2564            None => return,
 2565        };
 2566
 2567        buffer.update(cx, |buffer, cx| {
 2568            let worktree_id = old_file.worktree_id(cx);
 2569            let ids = &self.language_server_ids;
 2570
 2571            if let Some(language) = buffer.language().cloned() {
 2572                for adapter in self.languages.lsp_adapters(&language) {
 2573                    if let Some(server_id) = ids.get(&(worktree_id, adapter.name.clone())) {
 2574                        buffer.update_diagnostics(*server_id, Default::default(), cx);
 2575                    }
 2576                }
 2577            }
 2578
 2579            self.buffer_snapshots.remove(&buffer.remote_id());
 2580            let file_url = lsp::Uri::from_file_path(old_path).unwrap();
 2581            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
 2582                language_server
 2583                    .notify::<lsp::notification::DidCloseTextDocument>(
 2584                        lsp::DidCloseTextDocumentParams {
 2585                            text_document: lsp::TextDocumentIdentifier::new(
 2586                                file_url.clone().into(),
 2587                            ),
 2588                        },
 2589                    )
 2590                    .log_err();
 2591            }
 2592        });
 2593    }
 2594
 2595    async fn send_buffer_ordered_messages(
 2596        this: WeakModel<Self>,
 2597        rx: UnboundedReceiver<BufferOrderedMessage>,
 2598        mut cx: AsyncAppContext,
 2599    ) -> Result<()> {
 2600        const MAX_BATCH_SIZE: usize = 128;
 2601
 2602        let mut operations_by_buffer_id = HashMap::default();
 2603        async fn flush_operations(
 2604            this: &WeakModel<Project>,
 2605            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
 2606            needs_resync_with_host: &mut bool,
 2607            is_local: bool,
 2608            cx: &mut AsyncAppContext,
 2609        ) -> Result<()> {
 2610            for (buffer_id, operations) in operations_by_buffer_id.drain() {
 2611                let request = this.update(cx, |this, _| {
 2612                    let project_id = this.remote_id()?;
 2613                    Some(this.client.request(proto::UpdateBuffer {
 2614                        buffer_id: buffer_id.into(),
 2615                        project_id,
 2616                        operations,
 2617                    }))
 2618                })?;
 2619                if let Some(request) = request {
 2620                    if request.await.is_err() && !is_local {
 2621                        *needs_resync_with_host = true;
 2622                        break;
 2623                    }
 2624                }
 2625            }
 2626            Ok(())
 2627        }
 2628
 2629        let mut needs_resync_with_host = false;
 2630        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
 2631
 2632        while let Some(changes) = changes.next().await {
 2633            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
 2634
 2635            for change in changes {
 2636                match change {
 2637                    BufferOrderedMessage::Operation {
 2638                        buffer_id,
 2639                        operation,
 2640                    } => {
 2641                        if needs_resync_with_host {
 2642                            continue;
 2643                        }
 2644
 2645                        operations_by_buffer_id
 2646                            .entry(buffer_id)
 2647                            .or_insert(Vec::new())
 2648                            .push(operation);
 2649                    }
 2650
 2651                    BufferOrderedMessage::Resync => {
 2652                        operations_by_buffer_id.clear();
 2653                        if this
 2654                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
 2655                            .await
 2656                            .is_ok()
 2657                        {
 2658                            needs_resync_with_host = false;
 2659                        }
 2660                    }
 2661
 2662                    BufferOrderedMessage::LanguageServerUpdate {
 2663                        language_server_id,
 2664                        message,
 2665                    } => {
 2666                        flush_operations(
 2667                            &this,
 2668                            &mut operations_by_buffer_id,
 2669                            &mut needs_resync_with_host,
 2670                            is_local,
 2671                            &mut cx,
 2672                        )
 2673                        .await?;
 2674
 2675                        this.update(&mut cx, |this, _| {
 2676                            if let Some(project_id) = this.remote_id() {
 2677                                this.client
 2678                                    .send(proto::UpdateLanguageServer {
 2679                                        project_id,
 2680                                        language_server_id: language_server_id.0 as u64,
 2681                                        variant: Some(message),
 2682                                    })
 2683                                    .log_err();
 2684                            }
 2685                        })?;
 2686                    }
 2687                }
 2688            }
 2689
 2690            flush_operations(
 2691                &this,
 2692                &mut operations_by_buffer_id,
 2693                &mut needs_resync_with_host,
 2694                is_local,
 2695                &mut cx,
 2696            )
 2697            .await?;
 2698        }
 2699
 2700        Ok(())
 2701    }
 2702
 2703    fn on_buffer_event(
 2704        &mut self,
 2705        buffer: Model<Buffer>,
 2706        event: &BufferEvent,
 2707        cx: &mut ModelContext<Self>,
 2708    ) -> Option<()> {
 2709        if matches!(
 2710            event,
 2711            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
 2712        ) {
 2713            self.request_buffer_diff_recalculation(&buffer, cx);
 2714        }
 2715
 2716        match event {
 2717            BufferEvent::Operation(operation) => {
 2718                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
 2719                    buffer_id: buffer.read(cx).remote_id(),
 2720                    operation: language::proto::serialize_operation(operation),
 2721                })
 2722                .ok();
 2723            }
 2724
 2725            BufferEvent::Reloaded => {
 2726                if self.is_local() {
 2727                    if let Some(project_id) = self.remote_id() {
 2728                        let buffer = buffer.read(cx);
 2729                        self.client
 2730                            .send(proto::BufferReloaded {
 2731                                project_id,
 2732                                buffer_id: buffer.remote_id().to_proto(),
 2733                                version: serialize_version(&buffer.version()),
 2734                                mtime: buffer.saved_mtime().map(|t| t.into()),
 2735                                line_ending: serialize_line_ending(buffer.line_ending()) as i32,
 2736                            })
 2737                            .log_err();
 2738                    }
 2739                }
 2740            }
 2741
 2742            BufferEvent::Edited { .. } => {
 2743                let buffer = buffer.read(cx);
 2744                let file = File::from_dyn(buffer.file())?;
 2745                let abs_path = file.as_local()?.abs_path(cx);
 2746                let uri = lsp::Uri::from_file_path(abs_path).unwrap();
 2747                let next_snapshot = buffer.text_snapshot();
 2748
 2749                let language_servers: Vec<_> = self
 2750                    .language_servers_for_buffer(buffer, cx)
 2751                    .map(|i| i.1.clone())
 2752                    .collect();
 2753
 2754                for language_server in language_servers {
 2755                    let language_server = language_server.clone();
 2756
 2757                    let buffer_snapshots = self
 2758                        .buffer_snapshots
 2759                        .get_mut(&buffer.remote_id())
 2760                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
 2761                    let previous_snapshot = buffer_snapshots.last()?;
 2762
 2763                    let build_incremental_change = || {
 2764                        buffer
 2765                            .edits_since::<(PointUtf16, usize)>(
 2766                                previous_snapshot.snapshot.version(),
 2767                            )
 2768                            .map(|edit| {
 2769                                let edit_start = edit.new.start.0;
 2770                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 2771                                let new_text = next_snapshot
 2772                                    .text_for_range(edit.new.start.1..edit.new.end.1)
 2773                                    .collect();
 2774                                lsp::TextDocumentContentChangeEvent {
 2775                                    range: Some(lsp::Range::new(
 2776                                        point_to_lsp(edit_start),
 2777                                        point_to_lsp(edit_end),
 2778                                    )),
 2779                                    range_length: None,
 2780                                    text: new_text,
 2781                                }
 2782                            })
 2783                            .collect()
 2784                    };
 2785
 2786                    let document_sync_kind = language_server
 2787                        .capabilities()
 2788                        .text_document_sync
 2789                        .as_ref()
 2790                        .and_then(|sync| match sync {
 2791                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
 2792                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
 2793                        });
 2794
 2795                    let content_changes: Vec<_> = match document_sync_kind {
 2796                        Some(lsp::TextDocumentSyncKind::FULL) => {
 2797                            vec![lsp::TextDocumentContentChangeEvent {
 2798                                range: None,
 2799                                range_length: None,
 2800                                text: next_snapshot.text(),
 2801                            }]
 2802                        }
 2803                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
 2804                        _ => {
 2805                            #[cfg(any(test, feature = "test-support"))]
 2806                            {
 2807                                build_incremental_change()
 2808                            }
 2809
 2810                            #[cfg(not(any(test, feature = "test-support")))]
 2811                            {
 2812                                continue;
 2813                            }
 2814                        }
 2815                    };
 2816
 2817                    let next_version = previous_snapshot.version + 1;
 2818                    buffer_snapshots.push(LspBufferSnapshot {
 2819                        version: next_version,
 2820                        snapshot: next_snapshot.clone(),
 2821                    });
 2822
 2823                    language_server
 2824                        .notify::<lsp::notification::DidChangeTextDocument>(
 2825                            lsp::DidChangeTextDocumentParams {
 2826                                text_document: lsp::VersionedTextDocumentIdentifier::new(
 2827                                    uri.clone().into(),
 2828                                    next_version,
 2829                                ),
 2830                                content_changes,
 2831                            },
 2832                        )
 2833                        .log_err();
 2834                }
 2835            }
 2836
 2837            BufferEvent::Saved => {
 2838                let file = File::from_dyn(buffer.read(cx).file())?;
 2839                let worktree_id = file.worktree_id(cx);
 2840                let abs_path = file.as_local()?.abs_path(cx);
 2841                let text_document = lsp::TextDocumentIdentifier {
 2842                    uri: lsp::Uri::from_file_path(abs_path).unwrap().into(),
 2843                };
 2844
 2845                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
 2846                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
 2847                    server
 2848                        .notify::<lsp::notification::DidSaveTextDocument>(
 2849                            lsp::DidSaveTextDocumentParams {
 2850                                text_document: text_document.clone(),
 2851                                text,
 2852                            },
 2853                        )
 2854                        .log_err();
 2855                }
 2856
 2857                for language_server_id in self.language_server_ids_for_buffer(buffer.read(cx), cx) {
 2858                    self.simulate_disk_based_diagnostics_events_if_needed(language_server_id, cx);
 2859                }
 2860            }
 2861            BufferEvent::FileHandleChanged => {
 2862                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2863                    return None;
 2864                };
 2865
 2866                let remote_id = buffer.read(cx).remote_id();
 2867                if let Some(entry_id) = file.entry_id {
 2868                    match self.local_buffer_ids_by_entry_id.get(&entry_id) {
 2869                        Some(_) => {
 2870                            return None;
 2871                        }
 2872                        None => {
 2873                            self.local_buffer_ids_by_entry_id
 2874                                .insert(entry_id, remote_id);
 2875                        }
 2876                    }
 2877                };
 2878                self.local_buffer_ids_by_path.insert(
 2879                    ProjectPath {
 2880                        worktree_id: file.worktree_id(cx),
 2881                        path: file.path.clone(),
 2882                    },
 2883                    remote_id,
 2884                );
 2885            }
 2886            _ => {}
 2887        }
 2888
 2889        None
 2890    }
 2891
 2892    // After saving a buffer using a language server that doesn't provide a disk-based progress token,
 2893    // kick off a timer that will reset every time the buffer is saved. If the timer eventually fires,
 2894    // simulate disk-based diagnostics being finished so that other pieces of UI (e.g., project
 2895    // diagnostics view, diagnostic status bar) can update. We don't emit an event right away because
 2896    // the language server might take some time to publish diagnostics.
 2897    fn simulate_disk_based_diagnostics_events_if_needed(
 2898        &mut self,
 2899        language_server_id: LanguageServerId,
 2900        cx: &mut ModelContext<Self>,
 2901    ) {
 2902        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
 2903
 2904        let Some(LanguageServerState::Running {
 2905            simulate_disk_based_diagnostics_completion,
 2906            adapter,
 2907            ..
 2908        }) = self.language_servers.get_mut(&language_server_id)
 2909        else {
 2910            return;
 2911        };
 2912
 2913        if adapter.disk_based_diagnostics_progress_token.is_some() {
 2914            return;
 2915        }
 2916
 2917        let prev_task = simulate_disk_based_diagnostics_completion.replace(cx.spawn(
 2918            move |this, mut cx| async move {
 2919                cx.background_executor()
 2920                    .timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE)
 2921                    .await;
 2922
 2923                this.update(&mut cx, |this, cx| {
 2924                    this.disk_based_diagnostics_finished(language_server_id, cx);
 2925
 2926                    if let Some(LanguageServerState::Running {
 2927                        simulate_disk_based_diagnostics_completion,
 2928                        ..
 2929                    }) = this.language_servers.get_mut(&language_server_id)
 2930                    {
 2931                        *simulate_disk_based_diagnostics_completion = None;
 2932                    }
 2933                })
 2934                .ok();
 2935            },
 2936        ));
 2937
 2938        if prev_task.is_none() {
 2939            self.disk_based_diagnostics_started(language_server_id, cx);
 2940        }
 2941    }
 2942
 2943    fn request_buffer_diff_recalculation(
 2944        &mut self,
 2945        buffer: &Model<Buffer>,
 2946        cx: &mut ModelContext<Self>,
 2947    ) {
 2948        self.buffers_needing_diff.insert(buffer.downgrade());
 2949        let first_insertion = self.buffers_needing_diff.len() == 1;
 2950
 2951        let settings = ProjectSettings::get_global(cx);
 2952        let delay = if let Some(delay) = settings.git.gutter_debounce {
 2953            delay
 2954        } else {
 2955            if first_insertion {
 2956                let this = cx.weak_model();
 2957                cx.defer(move |cx| {
 2958                    if let Some(this) = this.upgrade() {
 2959                        this.update(cx, |this, cx| {
 2960                            this.recalculate_buffer_diffs(cx).detach();
 2961                        });
 2962                    }
 2963                });
 2964            }
 2965            return;
 2966        };
 2967
 2968        const MIN_DELAY: u64 = 50;
 2969        let delay = delay.max(MIN_DELAY);
 2970        let duration = Duration::from_millis(delay);
 2971
 2972        self.git_diff_debouncer
 2973            .fire_new(duration, cx, move |this, cx| {
 2974                this.recalculate_buffer_diffs(cx)
 2975            });
 2976    }
 2977
 2978    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
 2979        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
 2980        cx.spawn(move |this, mut cx| async move {
 2981            let tasks: Vec<_> = buffers
 2982                .iter()
 2983                .filter_map(|buffer| {
 2984                    let buffer = buffer.upgrade()?;
 2985                    buffer
 2986                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
 2987                        .ok()
 2988                        .flatten()
 2989                })
 2990                .collect();
 2991
 2992            futures::future::join_all(tasks).await;
 2993
 2994            this.update(&mut cx, |this, cx| {
 2995                if this.buffers_needing_diff.is_empty() {
 2996                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
 2997                    for buffer in buffers {
 2998                        if let Some(buffer) = buffer.upgrade() {
 2999                            buffer.update(cx, |_, cx| cx.notify());
 3000                        }
 3001                    }
 3002                } else {
 3003                    this.recalculate_buffer_diffs(cx).detach();
 3004                }
 3005            })
 3006            .ok();
 3007        })
 3008    }
 3009
 3010    fn language_servers_for_worktree(
 3011        &self,
 3012        worktree_id: WorktreeId,
 3013    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
 3014        self.language_server_ids
 3015            .iter()
 3016            .filter_map(move |((language_server_worktree_id, _), id)| {
 3017                if *language_server_worktree_id == worktree_id {
 3018                    if let Some(LanguageServerState::Running {
 3019                        adapter,
 3020                        language,
 3021                        server,
 3022                        ..
 3023                    }) = self.language_servers.get(id)
 3024                    {
 3025                        return Some((adapter, language, server));
 3026                    }
 3027                }
 3028                None
 3029            })
 3030    }
 3031
 3032    fn maintain_buffer_languages(
 3033        languages: Arc<LanguageRegistry>,
 3034        cx: &mut ModelContext<Project>,
 3035    ) -> Task<()> {
 3036        let mut subscription = languages.subscribe();
 3037        let mut prev_reload_count = languages.reload_count();
 3038        cx.spawn(move |project, mut cx| async move {
 3039            while let Some(()) = subscription.next().await {
 3040                if let Some(project) = project.upgrade() {
 3041                    // If the language registry has been reloaded, then remove and
 3042                    // re-assign the languages on all open buffers.
 3043                    let reload_count = languages.reload_count();
 3044                    if reload_count > prev_reload_count {
 3045                        prev_reload_count = reload_count;
 3046                        project
 3047                            .update(&mut cx, |this, cx| {
 3048                                let buffers = this
 3049                                    .opened_buffers
 3050                                    .values()
 3051                                    .filter_map(|b| b.upgrade())
 3052                                    .collect::<Vec<_>>();
 3053                                for buffer in buffers {
 3054                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
 3055                                    {
 3056                                        this.unregister_buffer_from_language_servers(
 3057                                            &buffer, &f, cx,
 3058                                        );
 3059                                        buffer
 3060                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
 3061                                    }
 3062                                }
 3063                            })
 3064                            .ok();
 3065                    }
 3066
 3067                    project
 3068                        .update(&mut cx, |project, cx| {
 3069                            let mut plain_text_buffers = Vec::new();
 3070                            let mut buffers_with_unknown_injections = Vec::new();
 3071                            for buffer in project.opened_buffers.values() {
 3072                                if let Some(handle) = buffer.upgrade() {
 3073                                    let buffer = &handle.read(cx);
 3074                                    if buffer.language().is_none()
 3075                                        || buffer.language() == Some(&*language::PLAIN_TEXT)
 3076                                    {
 3077                                        plain_text_buffers.push(handle);
 3078                                    } else if buffer.contains_unknown_injections() {
 3079                                        buffers_with_unknown_injections.push(handle);
 3080                                    }
 3081                                }
 3082                            }
 3083
 3084                            for buffer in plain_text_buffers {
 3085                                project.detect_language_for_buffer(&buffer, cx);
 3086                                project.register_buffer_with_language_servers(&buffer, cx);
 3087                            }
 3088
 3089                            for buffer in buffers_with_unknown_injections {
 3090                                buffer.update(cx, |buffer, cx| buffer.reparse(cx));
 3091                            }
 3092                        })
 3093                        .ok();
 3094                }
 3095            }
 3096        })
 3097    }
 3098
 3099    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
 3100        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
 3101        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
 3102
 3103        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
 3104            *settings_changed_tx.borrow_mut() = ();
 3105        });
 3106
 3107        cx.spawn(move |this, mut cx| async move {
 3108            while let Some(()) = settings_changed_rx.next().await {
 3109                let servers = this.update(&mut cx, |this, cx| {
 3110                    this.language_server_ids
 3111                        .iter()
 3112                        .filter_map(|((worktree_id, _), server_id)| {
 3113                            let worktree = this.worktree_for_id(*worktree_id, cx)?;
 3114                            let state = this.language_servers.get(server_id)?;
 3115                            let delegate = ProjectLspAdapterDelegate::new(this, &worktree, cx);
 3116                            match state {
 3117                                LanguageServerState::Starting(_) => None,
 3118                                LanguageServerState::Running {
 3119                                    adapter, server, ..
 3120                                } => Some((
 3121                                    adapter.adapter.clone(),
 3122                                    server.clone(),
 3123                                    delegate as Arc<dyn LspAdapterDelegate>,
 3124                                )),
 3125                            }
 3126                        })
 3127                        .collect::<Vec<_>>()
 3128                })?;
 3129
 3130                for (adapter, server, delegate) in servers {
 3131                    let settings = adapter.workspace_configuration(&delegate, &mut cx).await?;
 3132
 3133                    server
 3134                        .notify::<lsp::notification::DidChangeConfiguration>(
 3135                            lsp::DidChangeConfigurationParams { settings },
 3136                        )
 3137                        .ok();
 3138                }
 3139            }
 3140
 3141            drop(settings_observation);
 3142            anyhow::Ok(())
 3143        })
 3144    }
 3145
 3146    fn detect_language_for_buffer(
 3147        &mut self,
 3148        buffer_handle: &Model<Buffer>,
 3149        cx: &mut ModelContext<Self>,
 3150    ) {
 3151        // If the buffer has a language, set it and start the language server if we haven't already.
 3152        let buffer = buffer_handle.read(cx);
 3153        let Some(file) = buffer.file() else {
 3154            return;
 3155        };
 3156        let content = buffer.as_rope();
 3157        let Some(new_language_result) = self
 3158            .languages
 3159            .language_for_file(file, Some(content), cx)
 3160            .now_or_never()
 3161        else {
 3162            return;
 3163        };
 3164
 3165        match new_language_result {
 3166            Err(e) => {
 3167                if e.is::<language::LanguageNotFound>() {
 3168                    cx.emit(Event::LanguageNotFound(buffer_handle.clone()))
 3169                }
 3170            }
 3171            Ok(new_language) => {
 3172                self.set_language_for_buffer(buffer_handle, new_language, cx);
 3173            }
 3174        };
 3175    }
 3176
 3177    pub fn set_language_for_buffer(
 3178        &mut self,
 3179        buffer: &Model<Buffer>,
 3180        new_language: Arc<Language>,
 3181        cx: &mut ModelContext<Self>,
 3182    ) {
 3183        buffer.update(cx, |buffer, cx| {
 3184            if buffer.language().map_or(true, |old_language| {
 3185                !Arc::ptr_eq(old_language, &new_language)
 3186            }) {
 3187                buffer.set_language(Some(new_language.clone()), cx);
 3188            }
 3189        });
 3190
 3191        let buffer_file = buffer.read(cx).file().cloned();
 3192        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
 3193        let buffer_file = File::from_dyn(buffer_file.as_ref());
 3194        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
 3195        if let Some(prettier_plugins) = prettier_support::prettier_plugins_for_language(&settings) {
 3196            self.install_default_prettier(
 3197                worktree,
 3198                prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
 3199                cx,
 3200            );
 3201        };
 3202        if let Some(file) = buffer_file {
 3203            let worktree = file.worktree.clone();
 3204            if worktree.read(cx).is_local() {
 3205                self.start_language_servers(&worktree, new_language, cx);
 3206            }
 3207        }
 3208    }
 3209
 3210    fn start_language_servers(
 3211        &mut self,
 3212        worktree: &Model<Worktree>,
 3213        language: Arc<Language>,
 3214        cx: &mut ModelContext<Self>,
 3215    ) {
 3216        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
 3217        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
 3218        if !settings.enable_language_server {
 3219            return;
 3220        }
 3221
 3222        let available_lsp_adapters = self.languages.clone().lsp_adapters(&language);
 3223        let available_language_servers = available_lsp_adapters
 3224            .iter()
 3225            .map(|lsp_adapter| lsp_adapter.name.clone())
 3226            .collect::<Vec<_>>();
 3227
 3228        let desired_language_servers =
 3229            settings.customized_language_servers(&available_language_servers);
 3230
 3231        let mut enabled_lsp_adapters: Vec<Arc<CachedLspAdapter>> = Vec::new();
 3232        for desired_language_server in desired_language_servers {
 3233            if let Some(adapter) = available_lsp_adapters
 3234                .iter()
 3235                .find(|adapter| adapter.name == desired_language_server)
 3236            {
 3237                enabled_lsp_adapters.push(adapter.clone());
 3238                continue;
 3239            }
 3240
 3241            if let Some(adapter) = self
 3242                .languages
 3243                .load_available_lsp_adapter(&desired_language_server)
 3244            {
 3245                self.languages()
 3246                    .register_lsp_adapter(language.name(), adapter.adapter.clone());
 3247                enabled_lsp_adapters.push(adapter);
 3248                continue;
 3249            }
 3250
 3251            log::warn!(
 3252                "no language server found matching '{}'",
 3253                desired_language_server.0
 3254            );
 3255        }
 3256
 3257        log::info!(
 3258            "starting language servers for {language}: {adapters}",
 3259            language = language.name(),
 3260            adapters = enabled_lsp_adapters
 3261                .iter()
 3262                .map(|adapter| adapter.name.0.as_ref())
 3263                .join(", ")
 3264        );
 3265
 3266        for adapter in enabled_lsp_adapters {
 3267            self.start_language_server(worktree, adapter, language.clone(), cx);
 3268        }
 3269    }
 3270
 3271    fn start_language_server(
 3272        &mut self,
 3273        worktree_handle: &Model<Worktree>,
 3274        adapter: Arc<CachedLspAdapter>,
 3275        language: Arc<Language>,
 3276        cx: &mut ModelContext<Self>,
 3277    ) {
 3278        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3279            return;
 3280        }
 3281
 3282        let worktree = worktree_handle.read(cx);
 3283        let worktree_id = worktree.id();
 3284        let worktree_path = worktree.abs_path();
 3285        let key = (worktree_id, adapter.name.clone());
 3286        if self.language_server_ids.contains_key(&key) {
 3287            return;
 3288        }
 3289
 3290        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
 3291        let lsp_adapter_delegate = ProjectLspAdapterDelegate::new(self, worktree_handle, cx);
 3292        let pending_server = match self.languages.create_pending_language_server(
 3293            stderr_capture.clone(),
 3294            language.clone(),
 3295            adapter.clone(),
 3296            Arc::clone(&worktree_path),
 3297            lsp_adapter_delegate.clone(),
 3298            cx,
 3299        ) {
 3300            Some(pending_server) => pending_server,
 3301            None => return,
 3302        };
 3303
 3304        let project_settings = ProjectSettings::get(
 3305            Some(SettingsLocation {
 3306                worktree_id: worktree_id.to_proto() as usize,
 3307                path: Path::new(""),
 3308            }),
 3309            cx,
 3310        );
 3311        let lsp = project_settings.lsp.get(&adapter.name.0);
 3312        let override_options = lsp.and_then(|s| s.initialization_options.clone());
 3313
 3314        let server_id = pending_server.server_id;
 3315        let container_dir = pending_server.container_dir.clone();
 3316        let state = LanguageServerState::Starting({
 3317            let adapter = adapter.clone();
 3318            let server_name = adapter.name.0.clone();
 3319            let language = language.clone();
 3320            let key = key.clone();
 3321
 3322            cx.spawn(move |this, mut cx| async move {
 3323                let result = Self::setup_and_insert_language_server(
 3324                    this.clone(),
 3325                    lsp_adapter_delegate,
 3326                    override_options,
 3327                    pending_server,
 3328                    adapter.clone(),
 3329                    language.clone(),
 3330                    server_id,
 3331                    key,
 3332                    &mut cx,
 3333                )
 3334                .await;
 3335
 3336                match result {
 3337                    Ok(server) => {
 3338                        stderr_capture.lock().take();
 3339                        server
 3340                    }
 3341
 3342                    Err(err) => {
 3343                        log::error!("failed to start language server {server_name:?}: {err}");
 3344                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
 3345
 3346                        let this = this.upgrade()?;
 3347                        let container_dir = container_dir?;
 3348
 3349                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
 3350                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3351                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
 3352                            log::error!("Hit {max} reinstallation attempts for {server_name:?}");
 3353                            return None;
 3354                        }
 3355
 3356                        log::info!(
 3357                            "retrying installation of language server {server_name:?} in {}s",
 3358                            SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
 3359                        );
 3360                        cx.background_executor()
 3361                            .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
 3362                            .await;
 3363
 3364                        let installation_test_binary = adapter
 3365                            .installation_test_binary(container_dir.to_path_buf())
 3366                            .await;
 3367
 3368                        this.update(&mut cx, |_, cx| {
 3369                            Self::check_errored_server(
 3370                                language,
 3371                                adapter,
 3372                                server_id,
 3373                                installation_test_binary,
 3374                                cx,
 3375                            )
 3376                        })
 3377                        .ok();
 3378
 3379                        None
 3380                    }
 3381                }
 3382            })
 3383        });
 3384
 3385        self.language_servers.insert(server_id, state);
 3386        self.language_server_ids.insert(key, server_id);
 3387    }
 3388
 3389    fn reinstall_language_server(
 3390        &mut self,
 3391        language: Arc<Language>,
 3392        adapter: Arc<CachedLspAdapter>,
 3393        server_id: LanguageServerId,
 3394        cx: &mut ModelContext<Self>,
 3395    ) -> Option<Task<()>> {
 3396        log::info!("beginning to reinstall server");
 3397
 3398        let existing_server = match self.language_servers.remove(&server_id) {
 3399            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3400            _ => None,
 3401        };
 3402
 3403        for worktree in &self.worktrees {
 3404            if let Some(worktree) = worktree.upgrade() {
 3405                let key = (worktree.read(cx).id(), adapter.name.clone());
 3406                self.language_server_ids.remove(&key);
 3407            }
 3408        }
 3409
 3410        Some(cx.spawn(move |this, mut cx| async move {
 3411            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
 3412                log::info!("shutting down existing server");
 3413                task.await;
 3414            }
 3415
 3416            // TODO: This is race-safe with regards to preventing new instances from
 3417            // starting while deleting, but existing instances in other projects are going
 3418            // to be very confused and messed up
 3419            let Some(task) = this
 3420                .update(&mut cx, |this, cx| {
 3421                    this.languages.delete_server_container(adapter.clone(), cx)
 3422                })
 3423                .log_err()
 3424            else {
 3425                return;
 3426            };
 3427            task.await;
 3428
 3429            this.update(&mut cx, |this, cx| {
 3430                let worktrees = this.worktrees.clone();
 3431                for worktree in worktrees {
 3432                    if let Some(worktree) = worktree.upgrade() {
 3433                        this.start_language_server(
 3434                            &worktree,
 3435                            adapter.clone(),
 3436                            language.clone(),
 3437                            cx,
 3438                        );
 3439                    }
 3440                }
 3441            })
 3442            .ok();
 3443        }))
 3444    }
 3445
 3446    #[allow(clippy::too_many_arguments)]
 3447    async fn setup_and_insert_language_server(
 3448        this: WeakModel<Self>,
 3449        delegate: Arc<dyn LspAdapterDelegate>,
 3450        override_initialization_options: Option<serde_json::Value>,
 3451        pending_server: PendingLanguageServer,
 3452        adapter: Arc<CachedLspAdapter>,
 3453        language: Arc<Language>,
 3454        server_id: LanguageServerId,
 3455        key: (WorktreeId, LanguageServerName),
 3456        cx: &mut AsyncAppContext,
 3457    ) -> Result<Option<Arc<LanguageServer>>> {
 3458        let language_server = Self::setup_pending_language_server(
 3459            this.clone(),
 3460            override_initialization_options,
 3461            pending_server,
 3462            delegate,
 3463            adapter.clone(),
 3464            server_id,
 3465            cx,
 3466        )
 3467        .await?;
 3468
 3469        let this = match this.upgrade() {
 3470            Some(this) => this,
 3471            None => return Err(anyhow!("failed to upgrade project handle")),
 3472        };
 3473
 3474        this.update(cx, |this, cx| {
 3475            this.insert_newly_running_language_server(
 3476                language,
 3477                adapter,
 3478                language_server.clone(),
 3479                server_id,
 3480                key,
 3481                cx,
 3482            )
 3483        })??;
 3484
 3485        Ok(Some(language_server))
 3486    }
 3487
 3488    async fn setup_pending_language_server(
 3489        this: WeakModel<Self>,
 3490        override_options: Option<serde_json::Value>,
 3491        pending_server: PendingLanguageServer,
 3492        delegate: Arc<dyn LspAdapterDelegate>,
 3493        adapter: Arc<CachedLspAdapter>,
 3494        server_id: LanguageServerId,
 3495        cx: &mut AsyncAppContext,
 3496    ) -> Result<Arc<LanguageServer>> {
 3497        let workspace_config = adapter
 3498            .adapter
 3499            .clone()
 3500            .workspace_configuration(&delegate, cx)
 3501            .await?;
 3502        let (language_server, mut initialization_options) = pending_server.task.await?;
 3503
 3504        let name = language_server.name();
 3505        language_server
 3506            .on_notification::<lsp::notification::PublishDiagnostics, _>({
 3507                let adapter = adapter.clone();
 3508                let this = this.clone();
 3509                move |mut params, mut cx| {
 3510                    let adapter = adapter.clone();
 3511                    if let Some(this) = this.upgrade() {
 3512                        adapter.process_diagnostics(&mut params);
 3513                        this.update(&mut cx, |this, cx| {
 3514                            this.update_diagnostics(
 3515                                server_id,
 3516                                params,
 3517                                &adapter.disk_based_diagnostic_sources,
 3518                                cx,
 3519                            )
 3520                            .log_err();
 3521                        })
 3522                        .ok();
 3523                    }
 3524                }
 3525            })
 3526            .detach();
 3527
 3528        language_server
 3529            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
 3530                let adapter = adapter.adapter.clone();
 3531                let delegate = delegate.clone();
 3532                move |params, mut cx| {
 3533                    let adapter = adapter.clone();
 3534                    let delegate = delegate.clone();
 3535                    async move {
 3536                        let workspace_config =
 3537                            adapter.workspace_configuration(&delegate, &mut cx).await?;
 3538                        Ok(params
 3539                            .items
 3540                            .into_iter()
 3541                            .map(|item| {
 3542                                if let Some(section) = &item.section {
 3543                                    workspace_config
 3544                                        .get(section)
 3545                                        .cloned()
 3546                                        .unwrap_or(serde_json::Value::Null)
 3547                                } else {
 3548                                    workspace_config.clone()
 3549                                }
 3550                            })
 3551                            .collect())
 3552                    }
 3553                }
 3554            })
 3555            .detach();
 3556
 3557        // Even though we don't have handling for these requests, respond to them to
 3558        // avoid stalling any language server like `gopls` which waits for a response
 3559        // to these requests when initializing.
 3560        language_server
 3561            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
 3562                let this = this.clone();
 3563                move |params, mut cx| {
 3564                    let this = this.clone();
 3565                    async move {
 3566                        this.update(&mut cx, |this, _| {
 3567                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
 3568                            {
 3569                                if let lsp::NumberOrString::String(token) = params.token {
 3570                                    status.progress_tokens.insert(token);
 3571                                }
 3572                            }
 3573                        })?;
 3574
 3575                        Ok(())
 3576                    }
 3577                }
 3578            })
 3579            .detach();
 3580
 3581        language_server
 3582            .on_request::<lsp::request::RegisterCapability, _, _>({
 3583                let this = this.clone();
 3584                move |params, mut cx| {
 3585                    let this = this.clone();
 3586                    async move {
 3587                        for reg in params.registrations {
 3588                            if reg.method == "workspace/didChangeWatchedFiles" {
 3589                                if let Some(options) = reg.register_options {
 3590                                    let options = serde_json::from_value(options)?;
 3591                                    this.update(&mut cx, |this, cx| {
 3592                                        this.on_lsp_did_change_watched_files(
 3593                                            server_id, &reg.id, options, cx,
 3594                                        );
 3595                                    })?;
 3596                                }
 3597                            }
 3598                        }
 3599                        Ok(())
 3600                    }
 3601                }
 3602            })
 3603            .detach();
 3604
 3605        language_server
 3606            .on_request::<lsp::request::UnregisterCapability, _, _>({
 3607                let this = this.clone();
 3608                move |params, mut cx| {
 3609                    let this = this.clone();
 3610                    async move {
 3611                        for unreg in params.unregisterations.iter() {
 3612                            if unreg.method == "workspace/didChangeWatchedFiles" {
 3613                                this.update(&mut cx, |this, cx| {
 3614                                    this.on_lsp_unregister_did_change_watched_files(
 3615                                        server_id, &unreg.id, cx,
 3616                                    );
 3617                                })?;
 3618                            }
 3619                        }
 3620                        Ok(())
 3621                    }
 3622                }
 3623            })
 3624            .detach();
 3625
 3626        language_server
 3627            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
 3628                let adapter = adapter.clone();
 3629                let this = this.clone();
 3630                move |params, cx| {
 3631                    Self::on_lsp_workspace_edit(
 3632                        this.clone(),
 3633                        params,
 3634                        server_id,
 3635                        adapter.clone(),
 3636                        cx,
 3637                    )
 3638                }
 3639            })
 3640            .detach();
 3641
 3642        language_server
 3643            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
 3644                let this = this.clone();
 3645                move |(), mut cx| {
 3646                    let this = this.clone();
 3647                    async move {
 3648                        this.update(&mut cx, |project, cx| {
 3649                            cx.emit(Event::RefreshInlayHints);
 3650                            project.remote_id().map(|project_id| {
 3651                                project.client.send(proto::RefreshInlayHints { project_id })
 3652                            })
 3653                        })?
 3654                        .transpose()?;
 3655                        Ok(())
 3656                    }
 3657                }
 3658            })
 3659            .detach();
 3660
 3661        language_server
 3662            .on_request::<lsp::request::ShowMessageRequest, _, _>({
 3663                let this = this.clone();
 3664                let name = name.to_string();
 3665                move |params, mut cx| {
 3666                    let this = this.clone();
 3667                    let name = name.to_string();
 3668                    async move {
 3669                        if let Some(actions) = params.actions {
 3670                            let (tx, mut rx) = smol::channel::bounded(1);
 3671                            let request = LanguageServerPromptRequest {
 3672                                level: match params.typ {
 3673                                    lsp::MessageType::ERROR => PromptLevel::Critical,
 3674                                    lsp::MessageType::WARNING => PromptLevel::Warning,
 3675                                    _ => PromptLevel::Info,
 3676                                },
 3677                                message: params.message,
 3678                                actions,
 3679                                response_channel: tx,
 3680                                lsp_name: name.clone(),
 3681                            };
 3682
 3683                            if let Ok(_) = this.update(&mut cx, |_, cx| {
 3684                                cx.emit(Event::LanguageServerPrompt(request));
 3685                            }) {
 3686                                let response = rx.next().await;
 3687
 3688                                Ok(response)
 3689                            } else {
 3690                                Ok(None)
 3691                            }
 3692                        } else {
 3693                            Ok(None)
 3694                        }
 3695                    }
 3696                }
 3697            })
 3698            .detach();
 3699
 3700        let disk_based_diagnostics_progress_token =
 3701            adapter.disk_based_diagnostics_progress_token.clone();
 3702
 3703        language_server
 3704            .on_notification::<ServerStatus, _>({
 3705                let this = this.clone();
 3706                let name = name.to_string();
 3707                move |params, mut cx| {
 3708                    let this = this.clone();
 3709                    let name = name.to_string();
 3710                    if let Some(ref message) = params.message {
 3711                        let message = message.trim();
 3712                        if !message.is_empty() {
 3713                            let formatted_message = format!(
 3714                                "Language server {name} (id {server_id}) status update: {message}"
 3715                            );
 3716                            match params.health {
 3717                                ServerHealthStatus::Ok => log::info!("{}", formatted_message),
 3718                                ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
 3719                                ServerHealthStatus::Error => {
 3720                                    log::error!("{}", formatted_message);
 3721                                    let (tx, _rx) = smol::channel::bounded(1);
 3722                                    let request = LanguageServerPromptRequest {
 3723                                        level: PromptLevel::Critical,
 3724                                        message: params.message.unwrap_or_default(),
 3725                                        actions: Vec::new(),
 3726                                        response_channel: tx,
 3727                                        lsp_name: name.clone(),
 3728                                    };
 3729                                    let _ = this
 3730                                        .update(&mut cx, |_, cx| {
 3731                                            cx.emit(Event::LanguageServerPrompt(request));
 3732                                        })
 3733                                        .ok();
 3734                                }
 3735                                ServerHealthStatus::Other(status) => {
 3736                                    log::info!(
 3737                                        "Unknown server health: {status}\n{formatted_message}"
 3738                                    )
 3739                                }
 3740                            }
 3741                        }
 3742                    }
 3743                }
 3744            })
 3745            .detach();
 3746
 3747        language_server
 3748            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
 3749                if let Some(this) = this.upgrade() {
 3750                    this.update(&mut cx, |this, cx| {
 3751                        this.on_lsp_progress(
 3752                            params,
 3753                            server_id,
 3754                            disk_based_diagnostics_progress_token.clone(),
 3755                            cx,
 3756                        );
 3757                    })
 3758                    .ok();
 3759                }
 3760            })
 3761            .detach();
 3762
 3763        match (&mut initialization_options, override_options) {
 3764            (Some(initialization_options), Some(override_options)) => {
 3765                merge_json_value_into(override_options, initialization_options);
 3766            }
 3767            (None, override_options) => initialization_options = override_options,
 3768            _ => {}
 3769        }
 3770        let language_server = cx
 3771            .update(|cx| language_server.initialize(initialization_options, cx))?
 3772            .await?;
 3773
 3774        language_server
 3775            .notify::<lsp::notification::DidChangeConfiguration>(
 3776                lsp::DidChangeConfigurationParams {
 3777                    settings: workspace_config,
 3778                },
 3779            )
 3780            .ok();
 3781
 3782        Ok(language_server)
 3783    }
 3784
 3785    fn insert_newly_running_language_server(
 3786        &mut self,
 3787        language: Arc<Language>,
 3788        adapter: Arc<CachedLspAdapter>,
 3789        language_server: Arc<LanguageServer>,
 3790        server_id: LanguageServerId,
 3791        key: (WorktreeId, LanguageServerName),
 3792        cx: &mut ModelContext<Self>,
 3793    ) -> Result<()> {
 3794        // If the language server for this key doesn't match the server id, don't store the
 3795        // server. Which will cause it to be dropped, killing the process
 3796        if self
 3797            .language_server_ids
 3798            .get(&key)
 3799            .map(|id| id != &server_id)
 3800            .unwrap_or(false)
 3801        {
 3802            return Ok(());
 3803        }
 3804
 3805        // Update language_servers collection with Running variant of LanguageServerState
 3806        // indicating that the server is up and running and ready
 3807        self.language_servers.insert(
 3808            server_id,
 3809            LanguageServerState::Running {
 3810                adapter: adapter.clone(),
 3811                language: language.clone(),
 3812                server: language_server.clone(),
 3813                simulate_disk_based_diagnostics_completion: None,
 3814            },
 3815        );
 3816
 3817        self.language_server_statuses.insert(
 3818            server_id,
 3819            LanguageServerStatus {
 3820                name: language_server.name().to_string(),
 3821                pending_work: Default::default(),
 3822                has_pending_diagnostic_updates: false,
 3823                progress_tokens: Default::default(),
 3824            },
 3825        );
 3826
 3827        cx.emit(Event::LanguageServerAdded(server_id));
 3828
 3829        if let Some(project_id) = self.remote_id() {
 3830            self.client.send(proto::StartLanguageServer {
 3831                project_id,
 3832                server: Some(proto::LanguageServer {
 3833                    id: server_id.0 as u64,
 3834                    name: language_server.name().to_string(),
 3835                }),
 3836            })?;
 3837        }
 3838
 3839        // Tell the language server about every open buffer in the worktree that matches the language.
 3840        for buffer in self.opened_buffers.values() {
 3841            if let Some(buffer_handle) = buffer.upgrade() {
 3842                let buffer = buffer_handle.read(cx);
 3843                let file = match File::from_dyn(buffer.file()) {
 3844                    Some(file) => file,
 3845                    None => continue,
 3846                };
 3847                let language = match buffer.language() {
 3848                    Some(language) => language,
 3849                    None => continue,
 3850                };
 3851
 3852                if file.worktree.read(cx).id() != key.0
 3853                    || !self
 3854                        .languages
 3855                        .lsp_adapters(&language)
 3856                        .iter()
 3857                        .any(|a| a.name == key.1)
 3858                {
 3859                    continue;
 3860                }
 3861
 3862                let file = match file.as_local() {
 3863                    Some(file) => file,
 3864                    None => continue,
 3865                };
 3866
 3867                let versions = self
 3868                    .buffer_snapshots
 3869                    .entry(buffer.remote_id())
 3870                    .or_default()
 3871                    .entry(server_id)
 3872                    .or_insert_with(|| {
 3873                        vec![LspBufferSnapshot {
 3874                            version: 0,
 3875                            snapshot: buffer.text_snapshot(),
 3876                        }]
 3877                    });
 3878
 3879                let snapshot = versions.last().unwrap();
 3880                let version = snapshot.version;
 3881                let initial_snapshot = &snapshot.snapshot;
 3882                let uri = lsp::Uri::from_file_path(file.abs_path(cx)).unwrap();
 3883                language_server.notify::<lsp::notification::DidOpenTextDocument>(
 3884                    lsp::DidOpenTextDocumentParams {
 3885                        text_document: lsp::TextDocumentItem::new(
 3886                            uri.into(),
 3887                            adapter.language_id(&language),
 3888                            version,
 3889                            initial_snapshot.text(),
 3890                        ),
 3891                    },
 3892                )?;
 3893
 3894                buffer_handle.update(cx, |buffer, cx| {
 3895                    buffer.set_completion_triggers(
 3896                        language_server
 3897                            .capabilities()
 3898                            .completion_provider
 3899                            .as_ref()
 3900                            .and_then(|provider| provider.trigger_characters.clone())
 3901                            .unwrap_or_default(),
 3902                        cx,
 3903                    )
 3904                });
 3905            }
 3906        }
 3907
 3908        cx.notify();
 3909        Ok(())
 3910    }
 3911
 3912    // Returns a list of all of the worktrees which no longer have a language server and the root path
 3913    // for the stopped server
 3914    fn stop_language_server(
 3915        &mut self,
 3916        worktree_id: WorktreeId,
 3917        adapter_name: LanguageServerName,
 3918        cx: &mut ModelContext<Self>,
 3919    ) -> Task<Vec<WorktreeId>> {
 3920        let key = (worktree_id, adapter_name);
 3921        if let Some(server_id) = self.language_server_ids.remove(&key) {
 3922            let name = key.1 .0;
 3923            log::info!("stopping language server {name}");
 3924
 3925            // Remove other entries for this language server as well
 3926            let mut orphaned_worktrees = vec![worktree_id];
 3927            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
 3928            for other_key in other_keys {
 3929                if self.language_server_ids.get(&other_key) == Some(&server_id) {
 3930                    self.language_server_ids.remove(&other_key);
 3931                    orphaned_worktrees.push(other_key.0);
 3932                }
 3933            }
 3934
 3935            for buffer in self.opened_buffers.values() {
 3936                if let Some(buffer) = buffer.upgrade() {
 3937                    buffer.update(cx, |buffer, cx| {
 3938                        buffer.update_diagnostics(server_id, Default::default(), cx);
 3939                    });
 3940                }
 3941            }
 3942
 3943            let project_id = self.remote_id();
 3944            for (worktree_id, summaries) in self.diagnostic_summaries.iter_mut() {
 3945                summaries.retain(|path, summaries_by_server_id| {
 3946                    if summaries_by_server_id.remove(&server_id).is_some() {
 3947                        if let Some(project_id) = project_id {
 3948                            self.client
 3949                                .send(proto::UpdateDiagnosticSummary {
 3950                                    project_id,
 3951                                    worktree_id: worktree_id.to_proto(),
 3952                                    summary: Some(proto::DiagnosticSummary {
 3953                                        path: path.to_string_lossy().to_string(),
 3954                                        language_server_id: server_id.0 as u64,
 3955                                        error_count: 0,
 3956                                        warning_count: 0,
 3957                                    }),
 3958                                })
 3959                                .log_err();
 3960                        }
 3961                        !summaries_by_server_id.is_empty()
 3962                    } else {
 3963                        true
 3964                    }
 3965                });
 3966            }
 3967
 3968            for diagnostics in self.diagnostics.values_mut() {
 3969                diagnostics.retain(|_, diagnostics_by_server_id| {
 3970                    if let Ok(ix) =
 3971                        diagnostics_by_server_id.binary_search_by_key(&server_id, |e| e.0)
 3972                    {
 3973                        diagnostics_by_server_id.remove(ix);
 3974                        !diagnostics_by_server_id.is_empty()
 3975                    } else {
 3976                        true
 3977                    }
 3978                });
 3979            }
 3980
 3981            self.language_server_watched_paths.remove(&server_id);
 3982            self.language_server_statuses.remove(&server_id);
 3983            cx.notify();
 3984
 3985            let server_state = self.language_servers.remove(&server_id);
 3986            cx.emit(Event::LanguageServerRemoved(server_id));
 3987            cx.spawn(move |_, cx| async move {
 3988                Self::shutdown_language_server(server_state, name, cx).await;
 3989                orphaned_worktrees
 3990            })
 3991        } else {
 3992            Task::ready(Vec::new())
 3993        }
 3994    }
 3995
 3996    async fn shutdown_language_server(
 3997        server_state: Option<LanguageServerState>,
 3998        name: Arc<str>,
 3999        cx: AsyncAppContext,
 4000    ) {
 4001        let server = match server_state {
 4002            Some(LanguageServerState::Starting(task)) => {
 4003                let mut timer = cx
 4004                    .background_executor()
 4005                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
 4006                    .fuse();
 4007
 4008                select! {
 4009                    server = task.fuse() => server,
 4010                    _ = timer => {
 4011                        log::info!(
 4012                            "timeout waiting for language server {} to finish launching before stopping",
 4013                            name
 4014                        );
 4015                        None
 4016                    },
 4017                }
 4018            }
 4019
 4020            Some(LanguageServerState::Running { server, .. }) => Some(server),
 4021
 4022            None => None,
 4023        };
 4024
 4025        if let Some(server) = server {
 4026            if let Some(shutdown) = server.shutdown() {
 4027                shutdown.await;
 4028            }
 4029        }
 4030    }
 4031
 4032    async fn handle_restart_language_servers(
 4033        project: Model<Self>,
 4034        envelope: TypedEnvelope<proto::RestartLanguageServers>,
 4035        _: Arc<Client>,
 4036        mut cx: AsyncAppContext,
 4037    ) -> Result<proto::Ack> {
 4038        project.update(&mut cx, |project, cx| {
 4039            let buffers: Vec<_> = envelope
 4040                .payload
 4041                .buffer_ids
 4042                .into_iter()
 4043                .flat_map(|buffer_id| project.buffer_for_id(BufferId::new(buffer_id).log_err()?))
 4044                .collect();
 4045            project.restart_language_servers_for_buffers(buffers, cx)
 4046        })?;
 4047
 4048        Ok(proto::Ack {})
 4049    }
 4050
 4051    pub fn restart_language_servers_for_buffers(
 4052        &mut self,
 4053        buffers: impl IntoIterator<Item = Model<Buffer>>,
 4054        cx: &mut ModelContext<Self>,
 4055    ) {
 4056        if self.is_remote() {
 4057            let request = self.client.request(proto::RestartLanguageServers {
 4058                project_id: self.remote_id().unwrap(),
 4059                buffer_ids: buffers
 4060                    .into_iter()
 4061                    .map(|b| b.read(cx).remote_id().to_proto())
 4062                    .collect(),
 4063            });
 4064            cx.background_executor()
 4065                .spawn(request)
 4066                .detach_and_log_err(cx);
 4067            return;
 4068        }
 4069
 4070        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
 4071            .into_iter()
 4072            .filter_map(|buffer| {
 4073                let buffer = buffer.read(cx);
 4074                let file = buffer.file()?;
 4075                let worktree = File::from_dyn(Some(file))?.worktree.clone();
 4076                let language = self
 4077                    .languages
 4078                    .language_for_file(file, Some(buffer.as_rope()), cx)
 4079                    .now_or_never()?
 4080                    .ok()?;
 4081                Some((worktree, language))
 4082            })
 4083            .collect();
 4084        for (worktree, language) in language_server_lookup_info {
 4085            self.restart_language_servers(worktree, language, cx);
 4086        }
 4087    }
 4088
 4089    fn restart_language_servers(
 4090        &mut self,
 4091        worktree: Model<Worktree>,
 4092        language: Arc<Language>,
 4093        cx: &mut ModelContext<Self>,
 4094    ) {
 4095        let worktree_id = worktree.read(cx).id();
 4096
 4097        let stop_tasks = self
 4098            .languages
 4099            .clone()
 4100            .lsp_adapters(&language)
 4101            .iter()
 4102            .map(|adapter| {
 4103                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
 4104                (stop_task, adapter.name.clone())
 4105            })
 4106            .collect::<Vec<_>>();
 4107        if stop_tasks.is_empty() {
 4108            return;
 4109        }
 4110
 4111        cx.spawn(move |this, mut cx| async move {
 4112            // For each stopped language server, record all of the worktrees with which
 4113            // it was associated.
 4114            let mut affected_worktrees = Vec::new();
 4115            for (stop_task, language_server_name) in stop_tasks {
 4116                for affected_worktree_id in stop_task.await {
 4117                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
 4118                }
 4119            }
 4120
 4121            this.update(&mut cx, |this, cx| {
 4122                // Restart the language server for the given worktree.
 4123                this.start_language_servers(&worktree, language.clone(), cx);
 4124
 4125                // Lookup new server ids and set them for each of the orphaned worktrees
 4126                for (affected_worktree_id, language_server_name) in affected_worktrees {
 4127                    if let Some(new_server_id) = this
 4128                        .language_server_ids
 4129                        .get(&(worktree_id, language_server_name.clone()))
 4130                        .cloned()
 4131                    {
 4132                        this.language_server_ids
 4133                            .insert((affected_worktree_id, language_server_name), new_server_id);
 4134                    }
 4135                }
 4136            })
 4137            .ok();
 4138        })
 4139        .detach();
 4140    }
 4141
 4142    pub fn cancel_language_server_work_for_buffers(
 4143        &mut self,
 4144        buffers: impl IntoIterator<Item = Model<Buffer>>,
 4145        cx: &mut ModelContext<Self>,
 4146    ) {
 4147        let servers = buffers
 4148            .into_iter()
 4149            .flat_map(|buffer| {
 4150                self.language_server_ids_for_buffer(buffer.read(cx), cx)
 4151                    .into_iter()
 4152            })
 4153            .collect::<HashSet<_>>();
 4154
 4155        for server_id in servers {
 4156            let status = self.language_server_statuses.get(&server_id);
 4157            let server = self.language_servers.get(&server_id);
 4158            if let Some((server, status)) = server.zip(status) {
 4159                if let LanguageServerState::Running { server, .. } = server {
 4160                    for (token, progress) in &status.pending_work {
 4161                        if progress.is_cancellable {
 4162                            server
 4163                                .notify::<lsp::notification::WorkDoneProgressCancel>(
 4164                                    WorkDoneProgressCancelParams {
 4165                                        token: lsp::NumberOrString::String(token.clone()),
 4166                                    },
 4167                                )
 4168                                .ok();
 4169                        }
 4170                    }
 4171                }
 4172            }
 4173        }
 4174    }
 4175
 4176    fn check_errored_server(
 4177        language: Arc<Language>,
 4178        adapter: Arc<CachedLspAdapter>,
 4179        server_id: LanguageServerId,
 4180        installation_test_binary: Option<LanguageServerBinary>,
 4181        cx: &mut ModelContext<Self>,
 4182    ) {
 4183        if !adapter.can_be_reinstalled() {
 4184            log::info!(
 4185                "Validation check requested for {:?} but it cannot be reinstalled",
 4186                adapter.name.0
 4187            );
 4188            return;
 4189        }
 4190
 4191        cx.spawn(move |this, mut cx| async move {
 4192            log::info!("About to spawn test binary");
 4193
 4194            // A lack of test binary counts as a failure
 4195            let process = installation_test_binary.and_then(|binary| {
 4196                smol::process::Command::new(&binary.path)
 4197                    .current_dir(&binary.path)
 4198                    .args(binary.arguments)
 4199                    .stdin(Stdio::piped())
 4200                    .stdout(Stdio::piped())
 4201                    .stderr(Stdio::inherit())
 4202                    .kill_on_drop(true)
 4203                    .spawn()
 4204                    .ok()
 4205            });
 4206
 4207            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
 4208            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
 4209
 4210            let mut errored = false;
 4211            if let Some(mut process) = process {
 4212                futures::select! {
 4213                    status = process.status().fuse() => match status {
 4214                        Ok(status) => errored = !status.success(),
 4215                        Err(_) => errored = true,
 4216                    },
 4217
 4218                    _ = timeout => {
 4219                        log::info!("test binary time-ed out, this counts as a success");
 4220                        _ = process.kill();
 4221                    }
 4222                }
 4223            } else {
 4224                log::warn!("test binary failed to launch");
 4225                errored = true;
 4226            }
 4227
 4228            if errored {
 4229                log::warn!("test binary check failed");
 4230                let task = this
 4231                    .update(&mut cx, move |this, cx| {
 4232                        this.reinstall_language_server(language, adapter, server_id, cx)
 4233                    })
 4234                    .ok()
 4235                    .flatten();
 4236
 4237                if let Some(task) = task {
 4238                    task.await;
 4239                }
 4240            }
 4241        })
 4242        .detach();
 4243    }
 4244
 4245    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
 4246        self.buffer_ordered_messages_tx
 4247            .unbounded_send(message)
 4248            .map_err(|e| anyhow!(e))
 4249    }
 4250
 4251    fn on_lsp_progress(
 4252        &mut self,
 4253        progress: lsp::ProgressParams,
 4254        language_server_id: LanguageServerId,
 4255        disk_based_diagnostics_progress_token: Option<String>,
 4256        cx: &mut ModelContext<Self>,
 4257    ) {
 4258        let token = match progress.token {
 4259            lsp::NumberOrString::String(token) => token,
 4260            lsp::NumberOrString::Number(token) => {
 4261                log::info!("skipping numeric progress token {}", token);
 4262                return;
 4263            }
 4264        };
 4265
 4266        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
 4267        let language_server_status =
 4268            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4269                status
 4270            } else {
 4271                return;
 4272            };
 4273
 4274        if !language_server_status.progress_tokens.contains(&token) {
 4275            return;
 4276        }
 4277
 4278        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 4279            .as_ref()
 4280            .map_or(false, |disk_based_token| {
 4281                token.starts_with(disk_based_token)
 4282            });
 4283
 4284        match progress {
 4285            lsp::WorkDoneProgress::Begin(report) => {
 4286                if is_disk_based_diagnostics_progress {
 4287                    self.disk_based_diagnostics_started(language_server_id, cx);
 4288                }
 4289                self.on_lsp_work_start(
 4290                    language_server_id,
 4291                    token.clone(),
 4292                    LanguageServerProgress {
 4293                        title: Some(report.title),
 4294                        is_disk_based_diagnostics_progress,
 4295                        is_cancellable: report.cancellable.unwrap_or(false),
 4296                        message: report.message.clone(),
 4297                        percentage: report.percentage.map(|p| p as usize),
 4298                        last_update_at: cx.background_executor().now(),
 4299                    },
 4300                    cx,
 4301                );
 4302            }
 4303            lsp::WorkDoneProgress::Report(report) => {
 4304                if self.on_lsp_work_progress(
 4305                    language_server_id,
 4306                    token.clone(),
 4307                    LanguageServerProgress {
 4308                        title: None,
 4309                        is_disk_based_diagnostics_progress,
 4310                        is_cancellable: report.cancellable.unwrap_or(false),
 4311                        message: report.message.clone(),
 4312                        percentage: report.percentage.map(|p| p as usize),
 4313                        last_update_at: cx.background_executor().now(),
 4314                    },
 4315                    cx,
 4316                ) {
 4317                    self.enqueue_buffer_ordered_message(
 4318                        BufferOrderedMessage::LanguageServerUpdate {
 4319                            language_server_id,
 4320                            message: proto::update_language_server::Variant::WorkProgress(
 4321                                proto::LspWorkProgress {
 4322                                    token,
 4323                                    message: report.message,
 4324                                    percentage: report.percentage,
 4325                                },
 4326                            ),
 4327                        },
 4328                    )
 4329                    .ok();
 4330                }
 4331            }
 4332            lsp::WorkDoneProgress::End(_) => {
 4333                language_server_status.progress_tokens.remove(&token);
 4334                self.on_lsp_work_end(language_server_id, token.clone(), cx);
 4335                if is_disk_based_diagnostics_progress {
 4336                    self.disk_based_diagnostics_finished(language_server_id, cx);
 4337                }
 4338            }
 4339        }
 4340    }
 4341
 4342    fn on_lsp_work_start(
 4343        &mut self,
 4344        language_server_id: LanguageServerId,
 4345        token: String,
 4346        progress: LanguageServerProgress,
 4347        cx: &mut ModelContext<Self>,
 4348    ) {
 4349        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4350            status.pending_work.insert(token.clone(), progress.clone());
 4351            cx.notify();
 4352        }
 4353
 4354        if self.is_local() {
 4355            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 4356                language_server_id,
 4357                message: proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
 4358                    token,
 4359                    title: progress.title,
 4360                    message: progress.message,
 4361                    percentage: progress.percentage.map(|p| p as u32),
 4362                }),
 4363            })
 4364            .ok();
 4365        }
 4366    }
 4367
 4368    fn on_lsp_work_progress(
 4369        &mut self,
 4370        language_server_id: LanguageServerId,
 4371        token: String,
 4372        progress: LanguageServerProgress,
 4373        cx: &mut ModelContext<Self>,
 4374    ) -> bool {
 4375        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4376            match status.pending_work.entry(token) {
 4377                btree_map::Entry::Vacant(entry) => {
 4378                    entry.insert(progress);
 4379                    cx.notify();
 4380                    return true;
 4381                }
 4382                btree_map::Entry::Occupied(mut entry) => {
 4383                    let entry = entry.get_mut();
 4384                    if (progress.last_update_at - entry.last_update_at)
 4385                        >= SERVER_PROGRESS_THROTTLE_TIMEOUT
 4386                    {
 4387                        entry.last_update_at = progress.last_update_at;
 4388                        if progress.message.is_some() {
 4389                            entry.message = progress.message;
 4390                        }
 4391                        if progress.percentage.is_some() {
 4392                            entry.percentage = progress.percentage;
 4393                        }
 4394                        cx.notify();
 4395                        return true;
 4396                    }
 4397                }
 4398            }
 4399        }
 4400
 4401        false
 4402    }
 4403
 4404    fn on_lsp_work_end(
 4405        &mut self,
 4406        language_server_id: LanguageServerId,
 4407        token: String,
 4408        cx: &mut ModelContext<Self>,
 4409    ) {
 4410        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4411            if let Some(work) = status.pending_work.remove(&token) {
 4412                if !work.is_disk_based_diagnostics_progress {
 4413                    cx.emit(Event::RefreshInlayHints);
 4414                }
 4415            }
 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            cx.update(|cx| {
 7202                sort_search_matches(&mut matching_paths, cx);
 7203            })?;
 7204
 7205            let mut range_count = 0;
 7206            let query = Arc::new(query);
 7207
 7208            // Now that we know what paths match the query, we will load at most
 7209            // 64 buffers at a time to avoid overwhelming the main thread. For each
 7210            // opened buffer, we will spawn a background task that retrieves all the
 7211            // ranges in the buffer matched by the query.
 7212            'outer: for matching_paths_chunk in matching_paths.chunks(64) {
 7213                let mut chunk_results = Vec::new();
 7214                for matching_path in matching_paths_chunk {
 7215                    let query = query.clone();
 7216                    let buffer = match matching_path {
 7217                        SearchMatchCandidate::OpenBuffer { buffer, .. } => {
 7218                            Task::ready(Ok(buffer.clone()))
 7219                        }
 7220                        SearchMatchCandidate::Path {
 7221                            worktree_id, path, ..
 7222                        } => this.update(&mut cx, |this, cx| {
 7223                            this.open_buffer((*worktree_id, path.clone()), cx)
 7224                        })?,
 7225                    };
 7226
 7227                    chunk_results.push(cx.spawn(|cx| async move {
 7228                        let buffer = buffer.await?;
 7229                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
 7230                        let ranges = cx
 7231                            .background_executor()
 7232                            .spawn(async move {
 7233                                query
 7234                                    .search(&snapshot, None)
 7235                                    .await
 7236                                    .iter()
 7237                                    .map(|range| {
 7238                                        snapshot.anchor_before(range.start)
 7239                                            ..snapshot.anchor_after(range.end)
 7240                                    })
 7241                                    .collect::<Vec<_>>()
 7242                            })
 7243                            .await;
 7244                        anyhow::Ok((buffer, ranges))
 7245                    }));
 7246                }
 7247
 7248                let chunk_results = futures::future::join_all(chunk_results).await;
 7249                for result in chunk_results {
 7250                    if let Some((buffer, ranges)) = result.log_err() {
 7251                        range_count += ranges.len();
 7252                        result_tx
 7253                            .send(SearchResult::Buffer { buffer, ranges })
 7254                            .await?;
 7255                        if range_count > MAX_SEARCH_RESULT_RANGES {
 7256                            limit_reached = true;
 7257                            break 'outer;
 7258                        }
 7259                    }
 7260                }
 7261            }
 7262
 7263            if limit_reached {
 7264                result_tx.send(SearchResult::LimitReached).await?;
 7265            }
 7266
 7267            anyhow::Ok(())
 7268        })
 7269        .detach();
 7270
 7271        result_rx
 7272    }
 7273
 7274    /// Pick paths that might potentially contain a match of a given search query.
 7275    #[allow(clippy::too_many_arguments)]
 7276    async fn background_search(
 7277        unnamed_buffers: Vec<Model<Buffer>>,
 7278        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
 7279        executor: BackgroundExecutor,
 7280        fs: Arc<dyn Fs>,
 7281        workers: usize,
 7282        query: SearchQuery,
 7283        include_root: bool,
 7284        path_count: usize,
 7285        snapshots: Vec<(Snapshot, WorktreeSettings)>,
 7286        matching_paths_tx: Sender<SearchMatchCandidate>,
 7287    ) {
 7288        let fs = &fs;
 7289        let query = &query;
 7290        let matching_paths_tx = &matching_paths_tx;
 7291        let snapshots = &snapshots;
 7292        for buffer in unnamed_buffers {
 7293            matching_paths_tx
 7294                .send(SearchMatchCandidate::OpenBuffer {
 7295                    buffer: buffer.clone(),
 7296                    path: None,
 7297                })
 7298                .await
 7299                .log_err();
 7300        }
 7301        for (path, (buffer, _)) in opened_buffers.iter() {
 7302            matching_paths_tx
 7303                .send(SearchMatchCandidate::OpenBuffer {
 7304                    buffer: buffer.clone(),
 7305                    path: Some(path.clone()),
 7306                })
 7307                .await
 7308                .log_err();
 7309        }
 7310
 7311        let paths_per_worker = (path_count + workers - 1) / workers;
 7312
 7313        executor
 7314            .scoped(|scope| {
 7315                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
 7316
 7317                for worker_ix in 0..workers {
 7318                    let worker_start_ix = worker_ix * paths_per_worker;
 7319                    let worker_end_ix = worker_start_ix + paths_per_worker;
 7320                    let opened_buffers = opened_buffers.clone();
 7321                    let limiter = Arc::clone(&max_concurrent_workers);
 7322                    scope.spawn({
 7323                        async move {
 7324                            let _guard = limiter.acquire().await;
 7325                            search_snapshots(
 7326                                snapshots,
 7327                                worker_start_ix,
 7328                                worker_end_ix,
 7329                                query,
 7330                                matching_paths_tx,
 7331                                &opened_buffers,
 7332                                include_root,
 7333                                fs,
 7334                            )
 7335                            .await;
 7336                        }
 7337                    });
 7338                }
 7339
 7340                if query.include_ignored() {
 7341                    for (snapshot, settings) in snapshots {
 7342                        for ignored_entry in snapshot.entries(true, 0).filter(|e| e.is_ignored) {
 7343                            let limiter = Arc::clone(&max_concurrent_workers);
 7344                            scope.spawn(async move {
 7345                                let _guard = limiter.acquire().await;
 7346                                search_ignored_entry(
 7347                                    snapshot,
 7348                                    settings,
 7349                                    ignored_entry,
 7350                                    fs,
 7351                                    query,
 7352                                    matching_paths_tx,
 7353                                )
 7354                                .await;
 7355                            });
 7356                        }
 7357                    }
 7358                }
 7359            })
 7360            .await;
 7361    }
 7362
 7363    pub fn request_lsp<R: LspCommand>(
 7364        &self,
 7365        buffer_handle: Model<Buffer>,
 7366        server: LanguageServerToQuery,
 7367        request: R,
 7368        cx: &mut ModelContext<Self>,
 7369    ) -> Task<Result<R::Response>>
 7370    where
 7371        <R::LspRequest as lsp::request::Request>::Result: Send,
 7372        <R::LspRequest as lsp::request::Request>::Params: Send,
 7373    {
 7374        let buffer = buffer_handle.read(cx);
 7375        if self.is_local() {
 7376            let language_server = match server {
 7377                LanguageServerToQuery::Primary => {
 7378                    match self.primary_language_server_for_buffer(buffer, cx) {
 7379                        Some((_, server)) => Some(Arc::clone(server)),
 7380                        None => return Task::ready(Ok(Default::default())),
 7381                    }
 7382                }
 7383                LanguageServerToQuery::Other(id) => self
 7384                    .language_server_for_buffer(buffer, id, cx)
 7385                    .map(|(_, server)| Arc::clone(server)),
 7386            };
 7387            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 7388            if let (Some(file), Some(language_server)) = (file, language_server) {
 7389                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
 7390                let status = request.status();
 7391                return cx.spawn(move |this, cx| async move {
 7392                    if !request.check_capabilities(language_server.capabilities()) {
 7393                        return Ok(Default::default());
 7394                    }
 7395
 7396                    let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
 7397
 7398                    let id = lsp_request.id();
 7399                    let _cleanup = if status.is_some() {
 7400                        cx.update(|cx| {
 7401                            this.update(cx, |this, cx| {
 7402                                this.on_lsp_work_start(
 7403                                    language_server.server_id(),
 7404                                    id.to_string(),
 7405                                    LanguageServerProgress {
 7406                                        is_disk_based_diagnostics_progress: false,
 7407                                        is_cancellable: false,
 7408                                        title: None,
 7409                                        message: status.clone(),
 7410                                        percentage: None,
 7411                                        last_update_at: cx.background_executor().now(),
 7412                                    },
 7413                                    cx,
 7414                                );
 7415                            })
 7416                        })
 7417                        .log_err();
 7418
 7419                        Some(defer(|| {
 7420                            cx.update(|cx| {
 7421                                this.update(cx, |this, cx| {
 7422                                    this.on_lsp_work_end(
 7423                                        language_server.server_id(),
 7424                                        id.to_string(),
 7425                                        cx,
 7426                                    );
 7427                                })
 7428                            })
 7429                            .log_err();
 7430                        }))
 7431                    } else {
 7432                        None
 7433                    };
 7434
 7435                    let result = lsp_request.await;
 7436
 7437                    let response = result.map_err(|err| {
 7438                        log::warn!(
 7439                            "Generic lsp request to {} failed: {}",
 7440                            language_server.name(),
 7441                            err
 7442                        );
 7443                        err
 7444                    })?;
 7445
 7446                    request
 7447                        .response_from_lsp(
 7448                            response,
 7449                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 7450                            buffer_handle,
 7451                            language_server.server_id(),
 7452                            cx.clone(),
 7453                        )
 7454                        .await
 7455                });
 7456            }
 7457        } else if let Some(project_id) = self.remote_id() {
 7458            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
 7459        }
 7460
 7461        Task::ready(Ok(Default::default()))
 7462    }
 7463
 7464    fn request_multiple_lsp_locally<P, R>(
 7465        &self,
 7466        buffer: &Model<Buffer>,
 7467        position: Option<P>,
 7468        server_capabilities_check: fn(&ServerCapabilities) -> bool,
 7469        request: R,
 7470        cx: &mut ModelContext<'_, Self>,
 7471    ) -> Task<Vec<R::Response>>
 7472    where
 7473        P: ToOffset,
 7474        R: LspCommand + Clone,
 7475        <R::LspRequest as lsp::request::Request>::Result: Send,
 7476        <R::LspRequest as lsp::request::Request>::Params: Send,
 7477    {
 7478        if !self.is_local() {
 7479            debug_panic!("Should not request multiple lsp commands in non-local project");
 7480            return Task::ready(Vec::new());
 7481        }
 7482        let snapshot = buffer.read(cx).snapshot();
 7483        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 7484        let mut response_results = self
 7485            .language_servers_for_buffer(buffer.read(cx), cx)
 7486            .filter(|(_, server)| server_capabilities_check(server.capabilities()))
 7487            .filter(|(adapter, _)| {
 7488                scope
 7489                    .as_ref()
 7490                    .map(|scope| scope.language_allowed(&adapter.name))
 7491                    .unwrap_or(true)
 7492            })
 7493            .map(|(_, server)| server.server_id())
 7494            .map(|server_id| {
 7495                self.request_lsp(
 7496                    buffer.clone(),
 7497                    LanguageServerToQuery::Other(server_id),
 7498                    request.clone(),
 7499                    cx,
 7500                )
 7501            })
 7502            .collect::<FuturesUnordered<_>>();
 7503
 7504        return cx.spawn(|_, _| async move {
 7505            let mut responses = Vec::with_capacity(response_results.len());
 7506            while let Some(response_result) = response_results.next().await {
 7507                if let Some(response) = response_result.log_err() {
 7508                    responses.push(response);
 7509                }
 7510            }
 7511            responses
 7512        });
 7513    }
 7514
 7515    fn send_lsp_proto_request<R: LspCommand>(
 7516        &self,
 7517        buffer: Model<Buffer>,
 7518        project_id: u64,
 7519        request: R,
 7520        cx: &mut ModelContext<'_, Project>,
 7521    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
 7522        let rpc = self.client.clone();
 7523        let message = request.to_proto(project_id, buffer.read(cx));
 7524        cx.spawn(move |this, mut cx| async move {
 7525            // Ensure the project is still alive by the time the task
 7526            // is scheduled.
 7527            this.upgrade().context("project dropped")?;
 7528            let response = rpc.request(message).await?;
 7529            let this = this.upgrade().context("project dropped")?;
 7530            if this.update(&mut cx, |this, _| this.is_disconnected())? {
 7531                Err(anyhow!("disconnected before completing request"))
 7532            } else {
 7533                request
 7534                    .response_from_proto(response, this, buffer, cx)
 7535                    .await
 7536            }
 7537        })
 7538    }
 7539
 7540    /// Move a worktree to a new position in the worktree order.
 7541    ///
 7542    /// The worktree will moved to the opposite side of the destination worktree.
 7543    ///
 7544    /// # Example
 7545    ///
 7546    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
 7547    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
 7548    ///
 7549    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
 7550    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
 7551    ///
 7552    /// # Errors
 7553    ///
 7554    /// An error will be returned if the worktree or destination worktree are not found.
 7555    pub fn move_worktree(
 7556        &mut self,
 7557        source: WorktreeId,
 7558        destination: WorktreeId,
 7559        cx: &mut ModelContext<'_, Self>,
 7560    ) -> Result<()> {
 7561        if source == destination {
 7562            return Ok(());
 7563        }
 7564
 7565        let mut source_index = None;
 7566        let mut destination_index = None;
 7567        for (i, worktree) in self.worktrees.iter().enumerate() {
 7568            if let Some(worktree) = worktree.upgrade() {
 7569                let worktree_id = worktree.read(cx).id();
 7570                if worktree_id == source {
 7571                    source_index = Some(i);
 7572                    if destination_index.is_some() {
 7573                        break;
 7574                    }
 7575                } else if worktree_id == destination {
 7576                    destination_index = Some(i);
 7577                    if source_index.is_some() {
 7578                        break;
 7579                    }
 7580                }
 7581            }
 7582        }
 7583
 7584        let source_index =
 7585            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
 7586        let destination_index =
 7587            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
 7588
 7589        if source_index == destination_index {
 7590            return Ok(());
 7591        }
 7592
 7593        let worktree_to_move = self.worktrees.remove(source_index);
 7594        self.worktrees.insert(destination_index, worktree_to_move);
 7595        self.worktrees_reordered = true;
 7596        cx.emit(Event::WorktreeOrderChanged);
 7597        cx.notify();
 7598        Ok(())
 7599    }
 7600
 7601    pub fn find_or_create_local_worktree(
 7602        &mut self,
 7603        abs_path: impl AsRef<Path>,
 7604        visible: bool,
 7605        cx: &mut ModelContext<Self>,
 7606    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
 7607        let abs_path = abs_path.as_ref();
 7608        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
 7609            Task::ready(Ok((tree, relative_path)))
 7610        } else {
 7611            let worktree = self.create_local_worktree(abs_path, visible, cx);
 7612            cx.background_executor()
 7613                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
 7614        }
 7615    }
 7616
 7617    pub fn find_local_worktree(
 7618        &self,
 7619        abs_path: &Path,
 7620        cx: &AppContext,
 7621    ) -> Option<(Model<Worktree>, PathBuf)> {
 7622        for tree in &self.worktrees {
 7623            if let Some(tree) = tree.upgrade() {
 7624                if let Some(relative_path) = tree
 7625                    .read(cx)
 7626                    .as_local()
 7627                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 7628                {
 7629                    return Some((tree.clone(), relative_path.into()));
 7630                }
 7631            }
 7632        }
 7633        None
 7634    }
 7635
 7636    pub fn is_shared(&self) -> bool {
 7637        match &self.client_state {
 7638            ProjectClientState::Shared { .. } => true,
 7639            ProjectClientState::Local => false,
 7640            ProjectClientState::Remote { in_room, .. } => *in_room,
 7641        }
 7642    }
 7643
 7644    fn create_local_worktree(
 7645        &mut self,
 7646        abs_path: impl AsRef<Path>,
 7647        visible: bool,
 7648        cx: &mut ModelContext<Self>,
 7649    ) -> Task<Result<Model<Worktree>>> {
 7650        let fs = self.fs.clone();
 7651        let next_entry_id = self.next_entry_id.clone();
 7652        let path: Arc<Path> = abs_path.as_ref().into();
 7653        let task = self
 7654            .loading_local_worktrees
 7655            .entry(path.clone())
 7656            .or_insert_with(|| {
 7657                cx.spawn(move |project, mut cx| {
 7658                    async move {
 7659                        let worktree =
 7660                            Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx)
 7661                                .await;
 7662
 7663                        project.update(&mut cx, |project, _| {
 7664                            project.loading_local_worktrees.remove(&path);
 7665                        })?;
 7666
 7667                        let worktree = worktree?;
 7668                        project
 7669                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
 7670
 7671                        if visible {
 7672                            cx.update(|cx| {
 7673                                cx.add_recent_document(&path);
 7674                            })
 7675                            .log_err();
 7676                        }
 7677
 7678                        Ok(worktree)
 7679                    }
 7680                    .map_err(Arc::new)
 7681                })
 7682                .shared()
 7683            })
 7684            .clone();
 7685        cx.background_executor().spawn(async move {
 7686            match task.await {
 7687                Ok(worktree) => Ok(worktree),
 7688                Err(err) => Err(anyhow!("{}", err)),
 7689            }
 7690        })
 7691    }
 7692
 7693    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
 7694        self.diagnostics.remove(&id_to_remove);
 7695        self.diagnostic_summaries.remove(&id_to_remove);
 7696
 7697        let mut servers_to_remove = HashMap::default();
 7698        let mut servers_to_preserve = HashSet::default();
 7699        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
 7700            if worktree_id == &id_to_remove {
 7701                servers_to_remove.insert(server_id, server_name.clone());
 7702            } else {
 7703                servers_to_preserve.insert(server_id);
 7704            }
 7705        }
 7706        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
 7707        for (server_id_to_remove, server_name) in servers_to_remove {
 7708            self.language_server_ids
 7709                .remove(&(id_to_remove, server_name));
 7710            self.language_server_statuses.remove(&server_id_to_remove);
 7711            self.language_server_watched_paths
 7712                .remove(&server_id_to_remove);
 7713            self.last_workspace_edits_by_language_server
 7714                .remove(&server_id_to_remove);
 7715            self.language_servers.remove(&server_id_to_remove);
 7716            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
 7717        }
 7718
 7719        let mut prettier_instances_to_clean = FuturesUnordered::new();
 7720        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
 7721            for path in prettier_paths.iter().flatten() {
 7722                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
 7723                    prettier_instances_to_clean.push(async move {
 7724                        prettier_instance
 7725                            .server()
 7726                            .await
 7727                            .map(|server| server.server_id())
 7728                    });
 7729                }
 7730            }
 7731        }
 7732        cx.spawn(|project, mut cx| async move {
 7733            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
 7734                if let Some(prettier_server_id) = prettier_server_id {
 7735                    project
 7736                        .update(&mut cx, |project, cx| {
 7737                            project
 7738                                .supplementary_language_servers
 7739                                .remove(&prettier_server_id);
 7740                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
 7741                        })
 7742                        .ok();
 7743                }
 7744            }
 7745        })
 7746        .detach();
 7747
 7748        self.task_inventory().update(cx, |inventory, _| {
 7749            inventory.remove_worktree_sources(id_to_remove);
 7750        });
 7751
 7752        self.worktrees.retain(|worktree| {
 7753            if let Some(worktree) = worktree.upgrade() {
 7754                let id = worktree.read(cx).id();
 7755                if id == id_to_remove {
 7756                    cx.emit(Event::WorktreeRemoved(id));
 7757                    false
 7758                } else {
 7759                    true
 7760                }
 7761            } else {
 7762                false
 7763            }
 7764        });
 7765
 7766        self.metadata_changed(cx);
 7767    }
 7768
 7769    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
 7770        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
 7771        cx.subscribe(worktree, |this, worktree, event, cx| {
 7772            let is_local = worktree.read(cx).is_local();
 7773            match event {
 7774                worktree::Event::UpdatedEntries(changes) => {
 7775                    if is_local {
 7776                        this.update_local_worktree_buffers(&worktree, changes, cx);
 7777                        this.update_local_worktree_language_servers(&worktree, changes, cx);
 7778                        this.update_local_worktree_settings(&worktree, changes, cx);
 7779                        this.update_prettier_settings(&worktree, changes, cx);
 7780                    }
 7781
 7782                    cx.emit(Event::WorktreeUpdatedEntries(
 7783                        worktree.read(cx).id(),
 7784                        changes.clone(),
 7785                    ));
 7786
 7787                    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
 7788                    this.client()
 7789                        .telemetry()
 7790                        .report_discovered_project_events(worktree_id, changes);
 7791                }
 7792                worktree::Event::UpdatedGitRepositories(updated_repos) => {
 7793                    if is_local {
 7794                        this.update_local_worktree_buffers_git_repos(
 7795                            worktree.clone(),
 7796                            updated_repos,
 7797                            cx,
 7798                        )
 7799                    }
 7800                    cx.emit(Event::WorktreeUpdatedGitRepositories);
 7801                }
 7802            }
 7803        })
 7804        .detach();
 7805
 7806        let push_strong_handle = {
 7807            let worktree = worktree.read(cx);
 7808            self.is_shared() || worktree.is_visible() || worktree.is_remote()
 7809        };
 7810        let handle = if push_strong_handle {
 7811            WorktreeHandle::Strong(worktree.clone())
 7812        } else {
 7813            WorktreeHandle::Weak(worktree.downgrade())
 7814        };
 7815        if self.worktrees_reordered {
 7816            self.worktrees.push(handle);
 7817        } else {
 7818            let i = match self
 7819                .worktrees
 7820                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
 7821                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
 7822                }) {
 7823                Ok(i) | Err(i) => i,
 7824            };
 7825            self.worktrees.insert(i, handle);
 7826        }
 7827
 7828        let handle_id = worktree.entity_id();
 7829        cx.observe_release(worktree, move |this, worktree, cx| {
 7830            let _ = this.remove_worktree(worktree.id(), cx);
 7831            cx.update_global::<SettingsStore, _>(|store, cx| {
 7832                store
 7833                    .clear_local_settings(handle_id.as_u64() as usize, cx)
 7834                    .log_err()
 7835            });
 7836        })
 7837        .detach();
 7838
 7839        cx.emit(Event::WorktreeAdded);
 7840        self.metadata_changed(cx);
 7841    }
 7842
 7843    fn update_local_worktree_buffers(
 7844        &mut self,
 7845        worktree_handle: &Model<Worktree>,
 7846        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7847        cx: &mut ModelContext<Self>,
 7848    ) {
 7849        let snapshot = worktree_handle.read(cx).snapshot();
 7850
 7851        let mut renamed_buffers = Vec::new();
 7852        for (path, entry_id, _) in changes {
 7853            let worktree_id = worktree_handle.read(cx).id();
 7854            let project_path = ProjectPath {
 7855                worktree_id,
 7856                path: path.clone(),
 7857            };
 7858
 7859            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
 7860                Some(&buffer_id) => buffer_id,
 7861                None => match self.local_buffer_ids_by_path.get(&project_path) {
 7862                    Some(&buffer_id) => buffer_id,
 7863                    None => {
 7864                        continue;
 7865                    }
 7866                },
 7867            };
 7868
 7869            let open_buffer = self.opened_buffers.get(&buffer_id);
 7870            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
 7871                buffer
 7872            } else {
 7873                self.opened_buffers.remove(&buffer_id);
 7874                self.local_buffer_ids_by_path.remove(&project_path);
 7875                self.local_buffer_ids_by_entry_id.remove(entry_id);
 7876                continue;
 7877            };
 7878
 7879            buffer.update(cx, |buffer, cx| {
 7880                if let Some(old_file) = File::from_dyn(buffer.file()) {
 7881                    if old_file.worktree != *worktree_handle {
 7882                        return;
 7883                    }
 7884
 7885                    let new_file = if let Some(entry) = old_file
 7886                        .entry_id
 7887                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 7888                    {
 7889                        File {
 7890                            is_local: true,
 7891                            entry_id: Some(entry.id),
 7892                            mtime: entry.mtime,
 7893                            path: entry.path.clone(),
 7894                            worktree: worktree_handle.clone(),
 7895                            is_deleted: false,
 7896                            is_private: entry.is_private,
 7897                        }
 7898                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
 7899                        File {
 7900                            is_local: true,
 7901                            entry_id: Some(entry.id),
 7902                            mtime: entry.mtime,
 7903                            path: entry.path.clone(),
 7904                            worktree: worktree_handle.clone(),
 7905                            is_deleted: false,
 7906                            is_private: entry.is_private,
 7907                        }
 7908                    } else {
 7909                        File {
 7910                            is_local: true,
 7911                            entry_id: old_file.entry_id,
 7912                            path: old_file.path().clone(),
 7913                            mtime: old_file.mtime(),
 7914                            worktree: worktree_handle.clone(),
 7915                            is_deleted: true,
 7916                            is_private: old_file.is_private,
 7917                        }
 7918                    };
 7919
 7920                    let old_path = old_file.abs_path(cx);
 7921                    if new_file.abs_path(cx) != old_path {
 7922                        renamed_buffers.push((cx.handle(), old_file.clone()));
 7923                        self.local_buffer_ids_by_path.remove(&project_path);
 7924                        self.local_buffer_ids_by_path.insert(
 7925                            ProjectPath {
 7926                                worktree_id,
 7927                                path: path.clone(),
 7928                            },
 7929                            buffer_id,
 7930                        );
 7931                    }
 7932
 7933                    if new_file.entry_id != Some(*entry_id) {
 7934                        self.local_buffer_ids_by_entry_id.remove(entry_id);
 7935                        if let Some(entry_id) = new_file.entry_id {
 7936                            self.local_buffer_ids_by_entry_id
 7937                                .insert(entry_id, buffer_id);
 7938                        }
 7939                    }
 7940
 7941                    if new_file != *old_file {
 7942                        if let Some(project_id) = self.remote_id() {
 7943                            self.client
 7944                                .send(proto::UpdateBufferFile {
 7945                                    project_id,
 7946                                    buffer_id: buffer_id.into(),
 7947                                    file: Some(new_file.to_proto()),
 7948                                })
 7949                                .log_err();
 7950                        }
 7951
 7952                        buffer.file_updated(Arc::new(new_file), cx);
 7953                    }
 7954                }
 7955            });
 7956        }
 7957
 7958        for (buffer, old_file) in renamed_buffers {
 7959            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
 7960            self.detect_language_for_buffer(&buffer, cx);
 7961            self.register_buffer_with_language_servers(&buffer, cx);
 7962        }
 7963    }
 7964
 7965    fn update_local_worktree_language_servers(
 7966        &mut self,
 7967        worktree_handle: &Model<Worktree>,
 7968        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7969        cx: &mut ModelContext<Self>,
 7970    ) {
 7971        if changes.is_empty() {
 7972            return;
 7973        }
 7974
 7975        let worktree_id = worktree_handle.read(cx).id();
 7976        let mut language_server_ids = self
 7977            .language_server_ids
 7978            .iter()
 7979            .filter_map(|((server_worktree_id, _), server_id)| {
 7980                (*server_worktree_id == worktree_id).then_some(*server_id)
 7981            })
 7982            .collect::<Vec<_>>();
 7983        language_server_ids.sort();
 7984        language_server_ids.dedup();
 7985
 7986        let abs_path = worktree_handle.read(cx).abs_path();
 7987        for server_id in &language_server_ids {
 7988            if let Some(LanguageServerState::Running { server, .. }) =
 7989                self.language_servers.get(server_id)
 7990            {
 7991                if let Some(watched_paths) = self
 7992                    .language_server_watched_paths
 7993                    .get(&server_id)
 7994                    .and_then(|paths| paths.get(&worktree_id))
 7995                {
 7996                    let params = lsp::DidChangeWatchedFilesParams {
 7997                        changes: changes
 7998                            .iter()
 7999                            .filter_map(|(path, _, change)| {
 8000                                if !watched_paths.is_match(&path) {
 8001                                    return None;
 8002                                }
 8003                                let typ = match change {
 8004                                    PathChange::Loaded => return None,
 8005                                    PathChange::Added => lsp::FileChangeType::CREATED,
 8006                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 8007                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 8008                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 8009                                };
 8010                                Some(lsp::FileEvent {
 8011                                    uri: lsp::Uri::from_file_path(abs_path.join(path))
 8012                                        .unwrap()
 8013                                        .into(),
 8014                                    typ,
 8015                                })
 8016                            })
 8017                            .collect(),
 8018                    };
 8019                    if !params.changes.is_empty() {
 8020                        server
 8021                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
 8022                            .log_err();
 8023                    }
 8024                }
 8025            }
 8026        }
 8027    }
 8028
 8029    fn update_local_worktree_buffers_git_repos(
 8030        &mut self,
 8031        worktree_handle: Model<Worktree>,
 8032        changed_repos: &UpdatedGitRepositoriesSet,
 8033        cx: &mut ModelContext<Self>,
 8034    ) {
 8035        debug_assert!(worktree_handle.read(cx).is_local());
 8036
 8037        // Identify the loading buffers whose containing repository that has changed.
 8038        let future_buffers = self
 8039            .loading_buffers_by_path
 8040            .iter()
 8041            .filter_map(|(project_path, receiver)| {
 8042                if project_path.worktree_id != worktree_handle.read(cx).id() {
 8043                    return None;
 8044                }
 8045                let path = &project_path.path;
 8046                changed_repos
 8047                    .iter()
 8048                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 8049                let receiver = receiver.clone();
 8050                let path = path.clone();
 8051                let abs_path = worktree_handle.read(cx).absolutize(&path).ok()?;
 8052                Some(async move {
 8053                    wait_for_loading_buffer(receiver)
 8054                        .await
 8055                        .ok()
 8056                        .map(|buffer| (buffer, path, abs_path))
 8057                })
 8058            })
 8059            .collect::<FuturesUnordered<_>>();
 8060
 8061        // Identify the current buffers whose containing repository has changed.
 8062        let current_buffers = self
 8063            .opened_buffers
 8064            .values()
 8065            .filter_map(|buffer| {
 8066                let buffer = buffer.upgrade()?;
 8067                let file = File::from_dyn(buffer.read(cx).file())?;
 8068                if file.worktree != worktree_handle {
 8069                    return None;
 8070                }
 8071                let path = file.path();
 8072                changed_repos
 8073                    .iter()
 8074                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 8075                Some((buffer, path.clone(), file.abs_path(cx)))
 8076            })
 8077            .collect::<Vec<_>>();
 8078
 8079        if future_buffers.len() + current_buffers.len() == 0 {
 8080            return;
 8081        }
 8082
 8083        let remote_id = self.remote_id();
 8084        let client = self.client.clone();
 8085        let fs = self.fs.clone();
 8086        cx.spawn(move |_, mut cx| async move {
 8087            // Wait for all of the buffers to load.
 8088            let future_buffers = future_buffers.collect::<Vec<_>>().await;
 8089
 8090            // Reload the diff base for every buffer whose containing git repository has changed.
 8091            let snapshot =
 8092                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
 8093            let diff_bases_by_buffer = cx
 8094                .background_executor()
 8095                .spawn(async move {
 8096                    let mut diff_base_tasks = future_buffers
 8097                        .into_iter()
 8098                        .flatten()
 8099                        .chain(current_buffers)
 8100                        .filter_map(|(buffer, path, abs_path)| {
 8101                            let (repo_entry, local_repo_entry) = snapshot.repo_for_path(&path)?;
 8102                            Some((buffer, path, abs_path, repo_entry, local_repo_entry))
 8103                        })
 8104                        .map(|(buffer, path, abs_path, repo, local_repo_entry)| {
 8105                            let fs = fs.clone();
 8106                            let snapshot = snapshot.clone();
 8107                            async move {
 8108                                let abs_path_metadata = fs
 8109                                    .metadata(&abs_path)
 8110                                    .await
 8111                                    .with_context(|| {
 8112                                        format!("loading file and FS metadata for {path:?}")
 8113                                    })
 8114                                    .log_err()
 8115                                    .flatten()?;
 8116                                let base_text = if abs_path_metadata.is_dir
 8117                                    || abs_path_metadata.is_symlink
 8118                                {
 8119                                    None
 8120                                } else {
 8121                                    let relative_path = repo.relativize(&snapshot, &path).ok()?;
 8122                                    local_repo_entry.repo().load_index_text(&relative_path)
 8123                                };
 8124                                Some((buffer, base_text))
 8125                            }
 8126                        })
 8127                        .collect::<FuturesUnordered<_>>();
 8128
 8129                    let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
 8130                    while let Some(diff_base) = diff_base_tasks.next().await {
 8131                        if let Some(diff_base) = diff_base {
 8132                            diff_bases.push(diff_base);
 8133                        }
 8134                    }
 8135                    diff_bases
 8136                })
 8137                .await;
 8138
 8139            // Assign the new diff bases on all of the buffers.
 8140            for (buffer, diff_base) in diff_bases_by_buffer {
 8141                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
 8142                    buffer.set_diff_base(diff_base.clone(), cx);
 8143                    buffer.remote_id().into()
 8144                })?;
 8145                if let Some(project_id) = remote_id {
 8146                    client
 8147                        .send(proto::UpdateDiffBase {
 8148                            project_id,
 8149                            buffer_id,
 8150                            diff_base,
 8151                        })
 8152                        .log_err();
 8153                }
 8154            }
 8155
 8156            anyhow::Ok(())
 8157        })
 8158        .detach();
 8159    }
 8160
 8161    fn update_local_worktree_settings(
 8162        &mut self,
 8163        worktree: &Model<Worktree>,
 8164        changes: &UpdatedEntriesSet,
 8165        cx: &mut ModelContext<Self>,
 8166    ) {
 8167        if worktree.read(cx).is_remote() {
 8168            return;
 8169        }
 8170        let project_id = self.remote_id();
 8171        let worktree_id = worktree.entity_id();
 8172        let remote_worktree_id = worktree.read(cx).id();
 8173
 8174        let mut settings_contents = Vec::new();
 8175        for (path, _, change) in changes.iter() {
 8176            let removed = change == &PathChange::Removed;
 8177            let abs_path = match worktree.read(cx).absolutize(path) {
 8178                Ok(abs_path) => abs_path,
 8179                Err(e) => {
 8180                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 8181                    continue;
 8182                }
 8183            };
 8184
 8185            if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
 8186                let settings_dir = Arc::from(
 8187                    path.ancestors()
 8188                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
 8189                        .unwrap(),
 8190                );
 8191                let fs = self.fs.clone();
 8192                settings_contents.push(async move {
 8193                    (
 8194                        settings_dir,
 8195                        if removed {
 8196                            None
 8197                        } else {
 8198                            Some(async move { fs.load(&abs_path).await }.await)
 8199                        },
 8200                    )
 8201                });
 8202            } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
 8203                self.task_inventory().update(cx, |task_inventory, cx| {
 8204                    if removed {
 8205                        task_inventory.remove_local_static_source(&abs_path);
 8206                    } else {
 8207                        let fs = self.fs.clone();
 8208                        let task_abs_path = abs_path.clone();
 8209                        let tasks_file_rx =
 8210                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 8211                        task_inventory.add_source(
 8212                            TaskSourceKind::Worktree {
 8213                                id: remote_worktree_id,
 8214                                abs_path,
 8215                                id_base: "local_tasks_for_worktree".into(),
 8216                            },
 8217                            |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
 8218                            cx,
 8219                        );
 8220                    }
 8221                })
 8222            } else if abs_path.ends_with(&*LOCAL_VSCODE_TASKS_RELATIVE_PATH) {
 8223                self.task_inventory().update(cx, |task_inventory, cx| {
 8224                    if removed {
 8225                        task_inventory.remove_local_static_source(&abs_path);
 8226                    } else {
 8227                        let fs = self.fs.clone();
 8228                        let task_abs_path = abs_path.clone();
 8229                        let tasks_file_rx =
 8230                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 8231                        task_inventory.add_source(
 8232                            TaskSourceKind::Worktree {
 8233                                id: remote_worktree_id,
 8234                                abs_path,
 8235                                id_base: "local_vscode_tasks_for_worktree".into(),
 8236                            },
 8237                            |tx, cx| {
 8238                                StaticSource::new(TrackedFile::new_convertible::<
 8239                                    task::VsCodeTaskFile,
 8240                                >(
 8241                                    tasks_file_rx, tx, cx
 8242                                ))
 8243                            },
 8244                            cx,
 8245                        );
 8246                    }
 8247                })
 8248            }
 8249        }
 8250
 8251        if settings_contents.is_empty() {
 8252            return;
 8253        }
 8254
 8255        let client = self.client.clone();
 8256        cx.spawn(move |_, cx| async move {
 8257            let settings_contents: Vec<(Arc<Path>, _)> =
 8258                futures::future::join_all(settings_contents).await;
 8259            cx.update(|cx| {
 8260                cx.update_global::<SettingsStore, _>(|store, cx| {
 8261                    for (directory, file_content) in settings_contents {
 8262                        let file_content = file_content.and_then(|content| content.log_err());
 8263                        store
 8264                            .set_local_settings(
 8265                                worktree_id.as_u64() as usize,
 8266                                directory.clone(),
 8267                                file_content.as_deref(),
 8268                                cx,
 8269                            )
 8270                            .log_err();
 8271                        if let Some(remote_id) = project_id {
 8272                            client
 8273                                .send(proto::UpdateWorktreeSettings {
 8274                                    project_id: remote_id,
 8275                                    worktree_id: remote_worktree_id.to_proto(),
 8276                                    path: directory.to_string_lossy().into_owned(),
 8277                                    content: file_content,
 8278                                })
 8279                                .log_err();
 8280                        }
 8281                    }
 8282                });
 8283            })
 8284            .ok();
 8285        })
 8286        .detach();
 8287    }
 8288
 8289    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 8290        let new_active_entry = entry.and_then(|project_path| {
 8291            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 8292            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 8293            Some(entry.id)
 8294        });
 8295        if new_active_entry != self.active_entry {
 8296            self.active_entry = new_active_entry;
 8297            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 8298        }
 8299    }
 8300
 8301    pub fn language_servers_running_disk_based_diagnostics(
 8302        &self,
 8303    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 8304        self.language_server_statuses
 8305            .iter()
 8306            .filter_map(|(id, status)| {
 8307                if status.has_pending_diagnostic_updates {
 8308                    Some(*id)
 8309                } else {
 8310                    None
 8311                }
 8312            })
 8313    }
 8314
 8315    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 8316        let mut summary = DiagnosticSummary::default();
 8317        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 8318            summary.error_count += path_summary.error_count;
 8319            summary.warning_count += path_summary.warning_count;
 8320        }
 8321        summary
 8322    }
 8323
 8324    pub fn diagnostic_summaries<'a>(
 8325        &'a self,
 8326        include_ignored: bool,
 8327        cx: &'a AppContext,
 8328    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 8329        self.visible_worktrees(cx)
 8330            .filter_map(|worktree| {
 8331                let worktree = worktree.read(cx);
 8332                Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
 8333            })
 8334            .flat_map(move |(worktree, summaries)| {
 8335                let worktree_id = worktree.id();
 8336                summaries
 8337                    .iter()
 8338                    .filter(move |(path, _)| {
 8339                        include_ignored
 8340                            || worktree
 8341                                .entry_for_path(path.as_ref())
 8342                                .map_or(false, |entry| !entry.is_ignored)
 8343                    })
 8344                    .flat_map(move |(path, summaries)| {
 8345                        summaries.iter().map(move |(server_id, summary)| {
 8346                            (
 8347                                ProjectPath {
 8348                                    worktree_id,
 8349                                    path: path.clone(),
 8350                                },
 8351                                *server_id,
 8352                                *summary,
 8353                            )
 8354                        })
 8355                    })
 8356            })
 8357    }
 8358
 8359    pub fn disk_based_diagnostics_started(
 8360        &mut self,
 8361        language_server_id: LanguageServerId,
 8362        cx: &mut ModelContext<Self>,
 8363    ) {
 8364        if let Some(language_server_status) =
 8365            self.language_server_statuses.get_mut(&language_server_id)
 8366        {
 8367            language_server_status.has_pending_diagnostic_updates = true;
 8368        }
 8369
 8370        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 8371        if self.is_local() {
 8372            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8373                language_server_id,
 8374                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 8375                    Default::default(),
 8376                ),
 8377            })
 8378            .ok();
 8379        }
 8380    }
 8381
 8382    pub fn disk_based_diagnostics_finished(
 8383        &mut self,
 8384        language_server_id: LanguageServerId,
 8385        cx: &mut ModelContext<Self>,
 8386    ) {
 8387        if let Some(language_server_status) =
 8388            self.language_server_statuses.get_mut(&language_server_id)
 8389        {
 8390            language_server_status.has_pending_diagnostic_updates = false;
 8391        }
 8392
 8393        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 8394
 8395        if self.is_local() {
 8396            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8397                language_server_id,
 8398                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 8399                    Default::default(),
 8400                ),
 8401            })
 8402            .ok();
 8403        }
 8404    }
 8405
 8406    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 8407        self.active_entry
 8408    }
 8409
 8410    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 8411        self.worktree_for_id(path.worktree_id, cx)?
 8412            .read(cx)
 8413            .entry_for_path(&path.path)
 8414            .cloned()
 8415    }
 8416
 8417    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 8418        let worktree = self.worktree_for_entry(entry_id, cx)?;
 8419        let worktree = worktree.read(cx);
 8420        let worktree_id = worktree.id();
 8421        let path = worktree.entry_for_id(entry_id)?.path.clone();
 8422        Some(ProjectPath { worktree_id, path })
 8423    }
 8424
 8425    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 8426        let workspace_root = self
 8427            .worktree_for_id(project_path.worktree_id, cx)?
 8428            .read(cx)
 8429            .abs_path();
 8430        let project_path = project_path.path.as_ref();
 8431
 8432        Some(if project_path == Path::new("") {
 8433            workspace_root.to_path_buf()
 8434        } else {
 8435            workspace_root.join(project_path)
 8436        })
 8437    }
 8438
 8439    pub fn project_path_for_absolute_path(
 8440        &self,
 8441        abs_path: &Path,
 8442        cx: &AppContext,
 8443    ) -> Option<ProjectPath> {
 8444        self.find_local_worktree(abs_path, cx)
 8445            .map(|(worktree, relative_path)| ProjectPath {
 8446                worktree_id: worktree.read(cx).id(),
 8447                path: relative_path.into(),
 8448            })
 8449    }
 8450
 8451    pub fn get_workspace_root(
 8452        &self,
 8453        project_path: &ProjectPath,
 8454        cx: &AppContext,
 8455    ) -> Option<PathBuf> {
 8456        Some(
 8457            self.worktree_for_id(project_path.worktree_id, cx)?
 8458                .read(cx)
 8459                .abs_path()
 8460                .to_path_buf(),
 8461        )
 8462    }
 8463
 8464    pub fn get_repo(
 8465        &self,
 8466        project_path: &ProjectPath,
 8467        cx: &AppContext,
 8468    ) -> Option<Arc<dyn GitRepository>> {
 8469        self.worktree_for_id(project_path.worktree_id, cx)?
 8470            .read(cx)
 8471            .as_local()?
 8472            .local_git_repo(&project_path.path)
 8473    }
 8474
 8475    pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
 8476        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
 8477        let root_entry = worktree.root_git_entry()?;
 8478        worktree.get_local_repo(&root_entry)?.repo().clone().into()
 8479    }
 8480
 8481    pub fn blame_buffer(
 8482        &self,
 8483        buffer: &Model<Buffer>,
 8484        version: Option<clock::Global>,
 8485        cx: &AppContext,
 8486    ) -> Task<Result<Blame>> {
 8487        if self.is_local() {
 8488            let blame_params = maybe!({
 8489                let buffer = buffer.read(cx);
 8490                let buffer_project_path = buffer
 8491                    .project_path(cx)
 8492                    .context("failed to get buffer project path")?;
 8493
 8494                let worktree = self
 8495                    .worktree_for_id(buffer_project_path.worktree_id, cx)
 8496                    .context("failed to get worktree")?
 8497                    .read(cx)
 8498                    .as_local()
 8499                    .context("worktree was not local")?
 8500                    .snapshot();
 8501
 8502                let (repo_entry, local_repo_entry) =
 8503                    match worktree.repo_for_path(&buffer_project_path.path) {
 8504                        Some(repo_for_path) => repo_for_path,
 8505                        None => anyhow::bail!(NoRepositoryError {}),
 8506                    };
 8507
 8508                let relative_path = repo_entry
 8509                    .relativize(&worktree, &buffer_project_path.path)
 8510                    .context("failed to relativize buffer path")?;
 8511
 8512                let repo = local_repo_entry.repo().clone();
 8513
 8514                let content = match version {
 8515                    Some(version) => buffer.rope_for_version(&version).clone(),
 8516                    None => buffer.as_rope().clone(),
 8517                };
 8518
 8519                anyhow::Ok((repo, relative_path, content))
 8520            });
 8521
 8522            cx.background_executor().spawn(async move {
 8523                let (repo, relative_path, content) = blame_params?;
 8524                repo.blame(&relative_path, content)
 8525                    .with_context(|| format!("Failed to blame {:?}", relative_path.0))
 8526            })
 8527        } else {
 8528            let project_id = self.remote_id();
 8529            let buffer_id = buffer.read(cx).remote_id();
 8530            let client = self.client.clone();
 8531            let version = buffer.read(cx).version();
 8532
 8533            cx.spawn(|_| async move {
 8534                let project_id = project_id.context("unable to get project id for buffer")?;
 8535                let response = client
 8536                    .request(proto::BlameBuffer {
 8537                        project_id,
 8538                        buffer_id: buffer_id.into(),
 8539                        version: serialize_version(&version),
 8540                    })
 8541                    .await?;
 8542
 8543                Ok(deserialize_blame_buffer_response(response))
 8544            })
 8545        }
 8546    }
 8547
 8548    // RPC message handlers
 8549
 8550    async fn handle_blame_buffer(
 8551        this: Model<Self>,
 8552        envelope: TypedEnvelope<proto::BlameBuffer>,
 8553        _: Arc<Client>,
 8554        mut cx: AsyncAppContext,
 8555    ) -> Result<proto::BlameBufferResponse> {
 8556        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8557        let version = deserialize_version(&envelope.payload.version);
 8558
 8559        let buffer = this.update(&mut cx, |this, _cx| {
 8560            this.opened_buffers
 8561                .get(&buffer_id)
 8562                .and_then(|buffer| buffer.upgrade())
 8563                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8564        })??;
 8565
 8566        buffer
 8567            .update(&mut cx, |buffer, _| {
 8568                buffer.wait_for_version(version.clone())
 8569            })?
 8570            .await?;
 8571
 8572        let blame = this
 8573            .update(&mut cx, |this, cx| {
 8574                this.blame_buffer(&buffer, Some(version), cx)
 8575            })?
 8576            .await?;
 8577
 8578        Ok(serialize_blame_buffer_response(blame))
 8579    }
 8580
 8581    async fn handle_multi_lsp_query(
 8582        project: Model<Self>,
 8583        envelope: TypedEnvelope<proto::MultiLspQuery>,
 8584        _: Arc<Client>,
 8585        mut cx: AsyncAppContext,
 8586    ) -> Result<proto::MultiLspQueryResponse> {
 8587        let sender_id = envelope.original_sender_id()?;
 8588        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8589        let version = deserialize_version(&envelope.payload.version);
 8590        let buffer = project.update(&mut cx, |project, _cx| {
 8591            project
 8592                .opened_buffers
 8593                .get(&buffer_id)
 8594                .and_then(|buffer| buffer.upgrade())
 8595                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8596        })??;
 8597        buffer
 8598            .update(&mut cx, |buffer, _| {
 8599                buffer.wait_for_version(version.clone())
 8600            })?
 8601            .await?;
 8602        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 8603        match envelope
 8604            .payload
 8605            .strategy
 8606            .context("invalid request without the strategy")?
 8607        {
 8608            proto::multi_lsp_query::Strategy::All(_) => {
 8609                // currently, there's only one multiple language servers query strategy,
 8610                // so just ensure it's specified correctly
 8611            }
 8612        }
 8613        match envelope.payload.request {
 8614            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 8615                let get_hover =
 8616                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 8617                        .await?;
 8618                let all_hovers = project
 8619                    .update(&mut cx, |project, cx| {
 8620                        project.request_multiple_lsp_locally(
 8621                            &buffer,
 8622                            Some(get_hover.position),
 8623                            |server_capabilities| match server_capabilities.hover_provider {
 8624                                Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 8625                                Some(lsp::HoverProviderCapability::Options(_)) => true,
 8626                                None => false,
 8627                            },
 8628                            get_hover,
 8629                            cx,
 8630                        )
 8631                    })?
 8632                    .await
 8633                    .into_iter()
 8634                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 8635                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8636                    responses: all_hovers
 8637                        .map(|hover| proto::LspResponse {
 8638                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 8639                                GetHover::response_to_proto(
 8640                                    Some(hover),
 8641                                    project,
 8642                                    sender_id,
 8643                                    &buffer_version,
 8644                                    cx,
 8645                                ),
 8646                            )),
 8647                        })
 8648                        .collect(),
 8649                })
 8650            }
 8651            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 8652                let get_code_actions = GetCodeActions::from_proto(
 8653                    get_code_actions,
 8654                    project.clone(),
 8655                    buffer.clone(),
 8656                    cx.clone(),
 8657                )
 8658                .await?;
 8659
 8660                let all_actions = project
 8661                    .update(&mut cx, |project, cx| {
 8662                        project.request_multiple_lsp_locally(
 8663                            &buffer,
 8664                            Some(get_code_actions.range.start),
 8665                            GetCodeActions::supports_code_actions,
 8666                            get_code_actions,
 8667                            cx,
 8668                        )
 8669                    })?
 8670                    .await
 8671                    .into_iter();
 8672
 8673                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8674                    responses: all_actions
 8675                        .map(|code_actions| proto::LspResponse {
 8676                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8677                                GetCodeActions::response_to_proto(
 8678                                    code_actions,
 8679                                    project,
 8680                                    sender_id,
 8681                                    &buffer_version,
 8682                                    cx,
 8683                                ),
 8684                            )),
 8685                        })
 8686                        .collect(),
 8687                })
 8688            }
 8689            None => anyhow::bail!("empty multi lsp query request"),
 8690        }
 8691    }
 8692
 8693    async fn handle_unshare_project(
 8694        this: Model<Self>,
 8695        _: TypedEnvelope<proto::UnshareProject>,
 8696        _: Arc<Client>,
 8697        mut cx: AsyncAppContext,
 8698    ) -> Result<()> {
 8699        this.update(&mut cx, |this, cx| {
 8700            if this.is_local() {
 8701                this.unshare(cx)?;
 8702            } else {
 8703                this.disconnected_from_host(cx);
 8704            }
 8705            Ok(())
 8706        })?
 8707    }
 8708
 8709    async fn handle_add_collaborator(
 8710        this: Model<Self>,
 8711        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 8712        _: Arc<Client>,
 8713        mut cx: AsyncAppContext,
 8714    ) -> Result<()> {
 8715        let collaborator = envelope
 8716            .payload
 8717            .collaborator
 8718            .take()
 8719            .ok_or_else(|| anyhow!("empty collaborator"))?;
 8720
 8721        let collaborator = Collaborator::from_proto(collaborator)?;
 8722        this.update(&mut cx, |this, cx| {
 8723            this.shared_buffers.remove(&collaborator.peer_id);
 8724            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 8725            this.collaborators
 8726                .insert(collaborator.peer_id, collaborator);
 8727            cx.notify();
 8728        })?;
 8729
 8730        Ok(())
 8731    }
 8732
 8733    async fn handle_update_project_collaborator(
 8734        this: Model<Self>,
 8735        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 8736        _: Arc<Client>,
 8737        mut cx: AsyncAppContext,
 8738    ) -> Result<()> {
 8739        let old_peer_id = envelope
 8740            .payload
 8741            .old_peer_id
 8742            .ok_or_else(|| anyhow!("missing old peer id"))?;
 8743        let new_peer_id = envelope
 8744            .payload
 8745            .new_peer_id
 8746            .ok_or_else(|| anyhow!("missing new peer id"))?;
 8747        this.update(&mut cx, |this, cx| {
 8748            let collaborator = this
 8749                .collaborators
 8750                .remove(&old_peer_id)
 8751                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 8752            let is_host = collaborator.replica_id == 0;
 8753            this.collaborators.insert(new_peer_id, collaborator);
 8754
 8755            let buffers = this.shared_buffers.remove(&old_peer_id);
 8756            log::info!(
 8757                "peer {} became {}. moving buffers {:?}",
 8758                old_peer_id,
 8759                new_peer_id,
 8760                &buffers
 8761            );
 8762            if let Some(buffers) = buffers {
 8763                this.shared_buffers.insert(new_peer_id, buffers);
 8764            }
 8765
 8766            if is_host {
 8767                this.opened_buffers
 8768                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
 8769                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 8770                    .unwrap();
 8771            }
 8772
 8773            cx.emit(Event::CollaboratorUpdated {
 8774                old_peer_id,
 8775                new_peer_id,
 8776            });
 8777            cx.notify();
 8778            Ok(())
 8779        })?
 8780    }
 8781
 8782    async fn handle_remove_collaborator(
 8783        this: Model<Self>,
 8784        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 8785        _: Arc<Client>,
 8786        mut cx: AsyncAppContext,
 8787    ) -> Result<()> {
 8788        this.update(&mut cx, |this, cx| {
 8789            let peer_id = envelope
 8790                .payload
 8791                .peer_id
 8792                .ok_or_else(|| anyhow!("invalid peer id"))?;
 8793            let replica_id = this
 8794                .collaborators
 8795                .remove(&peer_id)
 8796                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 8797                .replica_id;
 8798            for buffer in this.opened_buffers.values() {
 8799                if let Some(buffer) = buffer.upgrade() {
 8800                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 8801                }
 8802            }
 8803            this.shared_buffers.remove(&peer_id);
 8804
 8805            cx.emit(Event::CollaboratorLeft(peer_id));
 8806            cx.notify();
 8807            Ok(())
 8808        })?
 8809    }
 8810
 8811    async fn handle_update_project(
 8812        this: Model<Self>,
 8813        envelope: TypedEnvelope<proto::UpdateProject>,
 8814        _: Arc<Client>,
 8815        mut cx: AsyncAppContext,
 8816    ) -> Result<()> {
 8817        this.update(&mut cx, |this, cx| {
 8818            // Don't handle messages that were sent before the response to us joining the project
 8819            if envelope.message_id > this.join_project_response_message_id {
 8820                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 8821            }
 8822            Ok(())
 8823        })?
 8824    }
 8825
 8826    async fn handle_update_worktree(
 8827        this: Model<Self>,
 8828        envelope: TypedEnvelope<proto::UpdateWorktree>,
 8829        _: Arc<Client>,
 8830        mut cx: AsyncAppContext,
 8831    ) -> Result<()> {
 8832        this.update(&mut cx, |this, cx| {
 8833            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8834            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8835                worktree.update(cx, |worktree, _| {
 8836                    let worktree = worktree.as_remote_mut().unwrap();
 8837                    worktree.update_from_remote(envelope.payload);
 8838                });
 8839            }
 8840            Ok(())
 8841        })?
 8842    }
 8843
 8844    async fn handle_update_worktree_settings(
 8845        this: Model<Self>,
 8846        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 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                cx.update_global::<SettingsStore, _>(|store, cx| {
 8854                    store
 8855                        .set_local_settings(
 8856                            worktree.entity_id().as_u64() as usize,
 8857                            PathBuf::from(&envelope.payload.path).into(),
 8858                            envelope.payload.content.as_deref(),
 8859                            cx,
 8860                        )
 8861                        .log_err();
 8862                });
 8863            }
 8864            Ok(())
 8865        })?
 8866    }
 8867
 8868    async fn handle_create_project_entry(
 8869        this: Model<Self>,
 8870        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 8871        _: Arc<Client>,
 8872        mut cx: AsyncAppContext,
 8873    ) -> Result<proto::ProjectEntryResponse> {
 8874        let worktree = this.update(&mut cx, |this, cx| {
 8875            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8876            this.worktree_for_id(worktree_id, cx)
 8877                .ok_or_else(|| anyhow!("worktree not found"))
 8878        })??;
 8879        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
 8880    }
 8881
 8882    async fn handle_rename_project_entry(
 8883        this: Model<Self>,
 8884        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8885        _: Arc<Client>,
 8886        mut cx: AsyncAppContext,
 8887    ) -> Result<proto::ProjectEntryResponse> {
 8888        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8889        let worktree = this.update(&mut cx, |this, cx| {
 8890            this.worktree_for_entry(entry_id, cx)
 8891                .ok_or_else(|| anyhow!("worktree not found"))
 8892        })??;
 8893        Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
 8894    }
 8895
 8896    async fn handle_copy_project_entry(
 8897        this: Model<Self>,
 8898        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 8899        _: Arc<Client>,
 8900        mut cx: AsyncAppContext,
 8901    ) -> Result<proto::ProjectEntryResponse> {
 8902        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8903        let worktree = this.update(&mut cx, |this, cx| {
 8904            this.worktree_for_entry(entry_id, cx)
 8905                .ok_or_else(|| anyhow!("worktree not found"))
 8906        })??;
 8907        Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
 8908    }
 8909
 8910    async fn handle_delete_project_entry(
 8911        this: Model<Self>,
 8912        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 8913        _: Arc<Client>,
 8914        mut cx: AsyncAppContext,
 8915    ) -> Result<proto::ProjectEntryResponse> {
 8916        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8917        let worktree = this.update(&mut cx, |this, cx| {
 8918            this.worktree_for_entry(entry_id, cx)
 8919                .ok_or_else(|| anyhow!("worktree not found"))
 8920        })??;
 8921        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
 8922        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
 8923    }
 8924
 8925    async fn handle_expand_project_entry(
 8926        this: Model<Self>,
 8927        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
 8928        _: Arc<Client>,
 8929        mut cx: AsyncAppContext,
 8930    ) -> Result<proto::ExpandProjectEntryResponse> {
 8931        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8932        let worktree = this
 8933            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
 8934            .ok_or_else(|| anyhow!("invalid request"))?;
 8935        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
 8936    }
 8937
 8938    async fn handle_update_diagnostic_summary(
 8939        this: Model<Self>,
 8940        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8941        _: Arc<Client>,
 8942        mut cx: AsyncAppContext,
 8943    ) -> Result<()> {
 8944        this.update(&mut cx, |this, cx| {
 8945            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8946            if let Some(message) = envelope.payload.summary {
 8947                let project_path = ProjectPath {
 8948                    worktree_id,
 8949                    path: Path::new(&message.path).into(),
 8950                };
 8951                let path = project_path.path.clone();
 8952                let server_id = LanguageServerId(message.language_server_id as usize);
 8953                let summary = DiagnosticSummary {
 8954                    error_count: message.error_count as usize,
 8955                    warning_count: message.warning_count as usize,
 8956                };
 8957
 8958                if summary.is_empty() {
 8959                    if let Some(worktree_summaries) =
 8960                        this.diagnostic_summaries.get_mut(&worktree_id)
 8961                    {
 8962                        if let Some(summaries) = worktree_summaries.get_mut(&path) {
 8963                            summaries.remove(&server_id);
 8964                            if summaries.is_empty() {
 8965                                worktree_summaries.remove(&path);
 8966                            }
 8967                        }
 8968                    }
 8969                } else {
 8970                    this.diagnostic_summaries
 8971                        .entry(worktree_id)
 8972                        .or_default()
 8973                        .entry(path)
 8974                        .or_default()
 8975                        .insert(server_id, summary);
 8976                }
 8977                cx.emit(Event::DiagnosticsUpdated {
 8978                    language_server_id: LanguageServerId(message.language_server_id as usize),
 8979                    path: project_path,
 8980                });
 8981            }
 8982            Ok(())
 8983        })?
 8984    }
 8985
 8986    async fn handle_start_language_server(
 8987        this: Model<Self>,
 8988        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8989        _: Arc<Client>,
 8990        mut cx: AsyncAppContext,
 8991    ) -> Result<()> {
 8992        let server = envelope
 8993            .payload
 8994            .server
 8995            .ok_or_else(|| anyhow!("invalid server"))?;
 8996        this.update(&mut cx, |this, cx| {
 8997            this.language_server_statuses.insert(
 8998                LanguageServerId(server.id as usize),
 8999                LanguageServerStatus {
 9000                    name: server.name,
 9001                    pending_work: Default::default(),
 9002                    has_pending_diagnostic_updates: false,
 9003                    progress_tokens: Default::default(),
 9004                },
 9005            );
 9006            cx.notify();
 9007        })?;
 9008        Ok(())
 9009    }
 9010
 9011    async fn handle_update_language_server(
 9012        this: Model<Self>,
 9013        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 9014        _: Arc<Client>,
 9015        mut cx: AsyncAppContext,
 9016    ) -> Result<()> {
 9017        this.update(&mut cx, |this, cx| {
 9018            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 9019
 9020            match envelope
 9021                .payload
 9022                .variant
 9023                .ok_or_else(|| anyhow!("invalid variant"))?
 9024            {
 9025                proto::update_language_server::Variant::WorkStart(payload) => {
 9026                    this.on_lsp_work_start(
 9027                        language_server_id,
 9028                        payload.token,
 9029                        LanguageServerProgress {
 9030                            title: payload.title,
 9031                            is_disk_based_diagnostics_progress: false,
 9032                            is_cancellable: false,
 9033                            message: payload.message,
 9034                            percentage: payload.percentage.map(|p| p as usize),
 9035                            last_update_at: cx.background_executor().now(),
 9036                        },
 9037                        cx,
 9038                    );
 9039                }
 9040
 9041                proto::update_language_server::Variant::WorkProgress(payload) => {
 9042                    this.on_lsp_work_progress(
 9043                        language_server_id,
 9044                        payload.token,
 9045                        LanguageServerProgress {
 9046                            title: None,
 9047                            is_disk_based_diagnostics_progress: false,
 9048                            is_cancellable: false,
 9049                            message: payload.message,
 9050                            percentage: payload.percentage.map(|p| p as usize),
 9051                            last_update_at: cx.background_executor().now(),
 9052                        },
 9053                        cx,
 9054                    );
 9055                }
 9056
 9057                proto::update_language_server::Variant::WorkEnd(payload) => {
 9058                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 9059                }
 9060
 9061                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 9062                    this.disk_based_diagnostics_started(language_server_id, cx);
 9063                }
 9064
 9065                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 9066                    this.disk_based_diagnostics_finished(language_server_id, cx)
 9067                }
 9068            }
 9069
 9070            Ok(())
 9071        })?
 9072    }
 9073
 9074    async fn handle_update_buffer(
 9075        this: Model<Self>,
 9076        envelope: TypedEnvelope<proto::UpdateBuffer>,
 9077        _: Arc<Client>,
 9078        mut cx: AsyncAppContext,
 9079    ) -> Result<proto::Ack> {
 9080        this.update(&mut cx, |this, cx| {
 9081            let payload = envelope.payload.clone();
 9082            let buffer_id = BufferId::new(payload.buffer_id)?;
 9083            let ops = payload
 9084                .operations
 9085                .into_iter()
 9086                .map(language::proto::deserialize_operation)
 9087                .collect::<Result<Vec<_>, _>>()?;
 9088            let is_remote = this.is_remote();
 9089            match this.opened_buffers.entry(buffer_id) {
 9090                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
 9091                    OpenBuffer::Strong(buffer) => {
 9092                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 9093                    }
 9094                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
 9095                    OpenBuffer::Weak(_) => {}
 9096                },
 9097                hash_map::Entry::Vacant(e) => {
 9098                    if !is_remote {
 9099                        debug_panic!(
 9100                            "received buffer update from {:?}",
 9101                            envelope.original_sender_id
 9102                        );
 9103                        return Err(anyhow!("received buffer update for non-remote project"));
 9104                    }
 9105                    e.insert(OpenBuffer::Operations(ops));
 9106                }
 9107            }
 9108            Ok(proto::Ack {})
 9109        })?
 9110    }
 9111
 9112    async fn handle_create_buffer_for_peer(
 9113        this: Model<Self>,
 9114        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 9115        _: Arc<Client>,
 9116        mut cx: AsyncAppContext,
 9117    ) -> Result<()> {
 9118        this.update(&mut cx, |this, cx| {
 9119            match envelope
 9120                .payload
 9121                .variant
 9122                .ok_or_else(|| anyhow!("missing variant"))?
 9123            {
 9124                proto::create_buffer_for_peer::Variant::State(mut state) => {
 9125                    let buffer_id = BufferId::new(state.id)?;
 9126
 9127                    let buffer_result = maybe!({
 9128                        let mut buffer_file = None;
 9129                        if let Some(file) = state.file.take() {
 9130                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
 9131                            let worktree =
 9132                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
 9133                                    anyhow!("no worktree found for id {}", file.worktree_id)
 9134                                })?;
 9135                            buffer_file =
 9136                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
 9137                                    as Arc<dyn language::File>);
 9138                        }
 9139                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
 9140                    });
 9141
 9142                    match buffer_result {
 9143                        Ok(buffer) => {
 9144                            let buffer = cx.new_model(|_| buffer);
 9145                            this.incomplete_remote_buffers.insert(buffer_id, buffer);
 9146                        }
 9147                        Err(error) => {
 9148                            if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 9149                                for listener in listeners {
 9150                                    listener.send(Err(anyhow!(error.cloned()))).ok();
 9151                                }
 9152                            }
 9153                        }
 9154                    };
 9155                }
 9156                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 9157                    let buffer_id = BufferId::new(chunk.buffer_id)?;
 9158                    let buffer = this
 9159                        .incomplete_remote_buffers
 9160                        .get(&buffer_id)
 9161                        .cloned()
 9162                        .ok_or_else(|| {
 9163                            anyhow!(
 9164                                "received chunk for buffer {} without initial state",
 9165                                chunk.buffer_id
 9166                            )
 9167                        })?;
 9168
 9169                    let result = maybe!({
 9170                        let operations = chunk
 9171                            .operations
 9172                            .into_iter()
 9173                            .map(language::proto::deserialize_operation)
 9174                            .collect::<Result<Vec<_>>>()?;
 9175                        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))
 9176                    });
 9177
 9178                    if let Err(error) = result {
 9179                        this.incomplete_remote_buffers.remove(&buffer_id);
 9180                        if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 9181                            for listener in listeners {
 9182                                listener.send(Err(error.cloned())).ok();
 9183                            }
 9184                        }
 9185                    } else {
 9186                        if chunk.is_last {
 9187                            this.incomplete_remote_buffers.remove(&buffer_id);
 9188                            this.register_buffer(&buffer, cx)?;
 9189                        }
 9190                    }
 9191                }
 9192            }
 9193
 9194            Ok(())
 9195        })?
 9196    }
 9197
 9198    async fn handle_update_diff_base(
 9199        this: Model<Self>,
 9200        envelope: TypedEnvelope<proto::UpdateDiffBase>,
 9201        _: Arc<Client>,
 9202        mut cx: AsyncAppContext,
 9203    ) -> Result<()> {
 9204        this.update(&mut cx, |this, cx| {
 9205            let buffer_id = envelope.payload.buffer_id;
 9206            let buffer_id = BufferId::new(buffer_id)?;
 9207            if let Some(buffer) = this
 9208                .opened_buffers
 9209                .get_mut(&buffer_id)
 9210                .and_then(|b| b.upgrade())
 9211                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 9212            {
 9213                buffer.update(cx, |buffer, cx| {
 9214                    buffer.set_diff_base(envelope.payload.diff_base, cx)
 9215                });
 9216            }
 9217            Ok(())
 9218        })?
 9219    }
 9220
 9221    async fn handle_update_buffer_file(
 9222        this: Model<Self>,
 9223        envelope: TypedEnvelope<proto::UpdateBufferFile>,
 9224        _: Arc<Client>,
 9225        mut cx: AsyncAppContext,
 9226    ) -> Result<()> {
 9227        let buffer_id = envelope.payload.buffer_id;
 9228        let buffer_id = BufferId::new(buffer_id)?;
 9229
 9230        this.update(&mut cx, |this, cx| {
 9231            let payload = envelope.payload.clone();
 9232            if let Some(buffer) = this
 9233                .opened_buffers
 9234                .get(&buffer_id)
 9235                .and_then(|b| b.upgrade())
 9236                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 9237            {
 9238                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
 9239                let worktree = this
 9240                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
 9241                    .ok_or_else(|| anyhow!("no such worktree"))?;
 9242                let file = File::from_proto(file, worktree, cx)?;
 9243                buffer.update(cx, |buffer, cx| {
 9244                    buffer.file_updated(Arc::new(file), cx);
 9245                });
 9246                this.detect_language_for_buffer(&buffer, cx);
 9247            }
 9248            Ok(())
 9249        })?
 9250    }
 9251
 9252    async fn handle_save_buffer(
 9253        this: Model<Self>,
 9254        envelope: TypedEnvelope<proto::SaveBuffer>,
 9255        _: Arc<Client>,
 9256        mut cx: AsyncAppContext,
 9257    ) -> Result<proto::BufferSaved> {
 9258        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9259        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
 9260            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
 9261            let buffer = this
 9262                .opened_buffers
 9263                .get(&buffer_id)
 9264                .and_then(|buffer| buffer.upgrade())
 9265                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9266            anyhow::Ok((project_id, buffer))
 9267        })??;
 9268        buffer
 9269            .update(&mut cx, |buffer, _| {
 9270                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9271            })?
 9272            .await?;
 9273        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
 9274
 9275        if let Some(new_path) = envelope.payload.new_path {
 9276            let new_path = ProjectPath::from_proto(new_path);
 9277            this.update(&mut cx, |this, cx| {
 9278                this.save_buffer_as(buffer.clone(), new_path, cx)
 9279            })?
 9280            .await?;
 9281        } else {
 9282            this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
 9283                .await?;
 9284        }
 9285
 9286        buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
 9287            project_id,
 9288            buffer_id: buffer_id.into(),
 9289            version: serialize_version(buffer.saved_version()),
 9290            mtime: buffer.saved_mtime().map(|time| time.into()),
 9291        })
 9292    }
 9293
 9294    async fn handle_reload_buffers(
 9295        this: Model<Self>,
 9296        envelope: TypedEnvelope<proto::ReloadBuffers>,
 9297        _: Arc<Client>,
 9298        mut cx: AsyncAppContext,
 9299    ) -> Result<proto::ReloadBuffersResponse> {
 9300        let sender_id = envelope.original_sender_id()?;
 9301        let reload = this.update(&mut cx, |this, cx| {
 9302            let mut buffers = HashSet::default();
 9303            for buffer_id in &envelope.payload.buffer_ids {
 9304                let buffer_id = BufferId::new(*buffer_id)?;
 9305                buffers.insert(
 9306                    this.opened_buffers
 9307                        .get(&buffer_id)
 9308                        .and_then(|buffer| buffer.upgrade())
 9309                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 9310                );
 9311            }
 9312            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 9313        })??;
 9314
 9315        let project_transaction = reload.await?;
 9316        let project_transaction = this.update(&mut cx, |this, cx| {
 9317            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9318        })?;
 9319        Ok(proto::ReloadBuffersResponse {
 9320            transaction: Some(project_transaction),
 9321        })
 9322    }
 9323
 9324    async fn handle_synchronize_buffers(
 9325        this: Model<Self>,
 9326        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 9327        _: Arc<Client>,
 9328        mut cx: AsyncAppContext,
 9329    ) -> Result<proto::SynchronizeBuffersResponse> {
 9330        let project_id = envelope.payload.project_id;
 9331        let mut response = proto::SynchronizeBuffersResponse {
 9332            buffers: Default::default(),
 9333        };
 9334
 9335        this.update(&mut cx, |this, cx| {
 9336            let Some(guest_id) = envelope.original_sender_id else {
 9337                error!("missing original_sender_id on SynchronizeBuffers request");
 9338                bail!("missing original_sender_id on SynchronizeBuffers request");
 9339            };
 9340
 9341            this.shared_buffers.entry(guest_id).or_default().clear();
 9342            for buffer in envelope.payload.buffers {
 9343                let buffer_id = BufferId::new(buffer.id)?;
 9344                let remote_version = language::proto::deserialize_version(&buffer.version);
 9345                if let Some(buffer) = this.buffer_for_id(buffer_id) {
 9346                    this.shared_buffers
 9347                        .entry(guest_id)
 9348                        .or_default()
 9349                        .insert(buffer_id);
 9350
 9351                    let buffer = buffer.read(cx);
 9352                    response.buffers.push(proto::BufferVersion {
 9353                        id: buffer_id.into(),
 9354                        version: language::proto::serialize_version(&buffer.version),
 9355                    });
 9356
 9357                    let operations = buffer.serialize_ops(Some(remote_version), cx);
 9358                    let client = this.client.clone();
 9359                    if let Some(file) = buffer.file() {
 9360                        client
 9361                            .send(proto::UpdateBufferFile {
 9362                                project_id,
 9363                                buffer_id: buffer_id.into(),
 9364                                file: Some(file.to_proto()),
 9365                            })
 9366                            .log_err();
 9367                    }
 9368
 9369                    client
 9370                        .send(proto::UpdateDiffBase {
 9371                            project_id,
 9372                            buffer_id: buffer_id.into(),
 9373                            diff_base: buffer.diff_base().map(ToString::to_string),
 9374                        })
 9375                        .log_err();
 9376
 9377                    client
 9378                        .send(proto::BufferReloaded {
 9379                            project_id,
 9380                            buffer_id: buffer_id.into(),
 9381                            version: language::proto::serialize_version(buffer.saved_version()),
 9382                            mtime: buffer.saved_mtime().map(|time| time.into()),
 9383                            line_ending: language::proto::serialize_line_ending(
 9384                                buffer.line_ending(),
 9385                            ) as i32,
 9386                        })
 9387                        .log_err();
 9388
 9389                    cx.background_executor()
 9390                        .spawn(
 9391                            async move {
 9392                                let operations = operations.await;
 9393                                for chunk in split_operations(operations) {
 9394                                    client
 9395                                        .request(proto::UpdateBuffer {
 9396                                            project_id,
 9397                                            buffer_id: buffer_id.into(),
 9398                                            operations: chunk,
 9399                                        })
 9400                                        .await?;
 9401                                }
 9402                                anyhow::Ok(())
 9403                            }
 9404                            .log_err(),
 9405                        )
 9406                        .detach();
 9407                }
 9408            }
 9409            Ok(())
 9410        })??;
 9411
 9412        Ok(response)
 9413    }
 9414
 9415    async fn handle_format_buffers(
 9416        this: Model<Self>,
 9417        envelope: TypedEnvelope<proto::FormatBuffers>,
 9418        _: Arc<Client>,
 9419        mut cx: AsyncAppContext,
 9420    ) -> Result<proto::FormatBuffersResponse> {
 9421        let sender_id = envelope.original_sender_id()?;
 9422        let format = this.update(&mut cx, |this, cx| {
 9423            let mut buffers = HashSet::default();
 9424            for buffer_id in &envelope.payload.buffer_ids {
 9425                let buffer_id = BufferId::new(*buffer_id)?;
 9426                buffers.insert(
 9427                    this.opened_buffers
 9428                        .get(&buffer_id)
 9429                        .and_then(|buffer| buffer.upgrade())
 9430                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 9431                );
 9432            }
 9433            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 9434            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 9435        })??;
 9436
 9437        let project_transaction = format.await?;
 9438        let project_transaction = this.update(&mut cx, |this, cx| {
 9439            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9440        })?;
 9441        Ok(proto::FormatBuffersResponse {
 9442            transaction: Some(project_transaction),
 9443        })
 9444    }
 9445
 9446    async fn handle_apply_additional_edits_for_completion(
 9447        this: Model<Self>,
 9448        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 9449        _: Arc<Client>,
 9450        mut cx: AsyncAppContext,
 9451    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 9452        let (buffer, completion) = this.update(&mut cx, |this, _| {
 9453            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9454            let buffer = this
 9455                .opened_buffers
 9456                .get(&buffer_id)
 9457                .and_then(|buffer| buffer.upgrade())
 9458                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9459            let completion = Self::deserialize_completion(
 9460                envelope
 9461                    .payload
 9462                    .completion
 9463                    .ok_or_else(|| anyhow!("invalid completion"))?,
 9464            )?;
 9465            anyhow::Ok((buffer, completion))
 9466        })??;
 9467
 9468        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 9469            this.apply_additional_edits_for_completion(
 9470                buffer,
 9471                Completion {
 9472                    old_range: completion.old_range,
 9473                    new_text: completion.new_text,
 9474                    lsp_completion: completion.lsp_completion,
 9475                    server_id: completion.server_id,
 9476                    documentation: None,
 9477                    label: CodeLabel {
 9478                        text: Default::default(),
 9479                        runs: Default::default(),
 9480                        filter_range: Default::default(),
 9481                    },
 9482                    confirm: None,
 9483                    show_new_completions_on_confirm: false,
 9484                },
 9485                false,
 9486                cx,
 9487            )
 9488        })?;
 9489
 9490        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 9491            transaction: apply_additional_edits
 9492                .await?
 9493                .as_ref()
 9494                .map(language::proto::serialize_transaction),
 9495        })
 9496    }
 9497
 9498    async fn handle_resolve_completion_documentation(
 9499        this: Model<Self>,
 9500        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 9501        _: Arc<Client>,
 9502        mut cx: AsyncAppContext,
 9503    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 9504        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 9505
 9506        let completion = this
 9507            .read_with(&mut cx, |this, _| {
 9508                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 9509                let Some(server) = this.language_server_for_id(id) else {
 9510                    return Err(anyhow!("No language server {id}"));
 9511                };
 9512
 9513                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 9514            })??
 9515            .await?;
 9516
 9517        let mut documentation_is_markdown = false;
 9518        let documentation = match completion.documentation {
 9519            Some(lsp::Documentation::String(text)) => text,
 9520
 9521            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 9522                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 9523                value
 9524            }
 9525
 9526            _ => String::new(),
 9527        };
 9528
 9529        // If we have a new buffer_id, that means we're talking to a new client
 9530        // and want to check for new text_edits in the completion too.
 9531        let mut old_start = None;
 9532        let mut old_end = None;
 9533        let mut new_text = String::default();
 9534        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 9535            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 9536                let buffer = this
 9537                    .opened_buffers
 9538                    .get(&buffer_id)
 9539                    .and_then(|buffer| buffer.upgrade())
 9540                    .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9541                anyhow::Ok(buffer.read(cx).snapshot())
 9542            })??;
 9543
 9544            if let Some(text_edit) = completion.text_edit.as_ref() {
 9545                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 9546
 9547                if let Some((old_range, mut text_edit_new_text)) = edit {
 9548                    LineEnding::normalize(&mut text_edit_new_text);
 9549
 9550                    new_text = text_edit_new_text;
 9551                    old_start = Some(serialize_anchor(&old_range.start));
 9552                    old_end = Some(serialize_anchor(&old_range.end));
 9553                }
 9554            }
 9555        }
 9556
 9557        Ok(proto::ResolveCompletionDocumentationResponse {
 9558            documentation,
 9559            documentation_is_markdown,
 9560            old_start,
 9561            old_end,
 9562            new_text,
 9563        })
 9564    }
 9565
 9566    async fn handle_apply_code_action(
 9567        this: Model<Self>,
 9568        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 9569        _: Arc<Client>,
 9570        mut cx: AsyncAppContext,
 9571    ) -> Result<proto::ApplyCodeActionResponse> {
 9572        let sender_id = envelope.original_sender_id()?;
 9573        let action = Self::deserialize_code_action(
 9574            envelope
 9575                .payload
 9576                .action
 9577                .ok_or_else(|| anyhow!("invalid action"))?,
 9578        )?;
 9579        let apply_code_action = this.update(&mut cx, |this, cx| {
 9580            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9581            let buffer = this
 9582                .opened_buffers
 9583                .get(&buffer_id)
 9584                .and_then(|buffer| buffer.upgrade())
 9585                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
 9586            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
 9587        })??;
 9588
 9589        let project_transaction = apply_code_action.await?;
 9590        let project_transaction = this.update(&mut cx, |this, cx| {
 9591            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9592        })?;
 9593        Ok(proto::ApplyCodeActionResponse {
 9594            transaction: Some(project_transaction),
 9595        })
 9596    }
 9597
 9598    async fn handle_on_type_formatting(
 9599        this: Model<Self>,
 9600        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 9601        _: Arc<Client>,
 9602        mut cx: AsyncAppContext,
 9603    ) -> Result<proto::OnTypeFormattingResponse> {
 9604        let on_type_formatting = this.update(&mut cx, |this, cx| {
 9605            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9606            let buffer = this
 9607                .opened_buffers
 9608                .get(&buffer_id)
 9609                .and_then(|buffer| buffer.upgrade())
 9610                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 9611            let position = envelope
 9612                .payload
 9613                .position
 9614                .and_then(deserialize_anchor)
 9615                .ok_or_else(|| anyhow!("invalid position"))?;
 9616            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 9617                buffer,
 9618                position,
 9619                envelope.payload.trigger.clone(),
 9620                cx,
 9621            ))
 9622        })??;
 9623
 9624        let transaction = on_type_formatting
 9625            .await?
 9626            .as_ref()
 9627            .map(language::proto::serialize_transaction);
 9628        Ok(proto::OnTypeFormattingResponse { transaction })
 9629    }
 9630
 9631    async fn handle_inlay_hints(
 9632        this: Model<Self>,
 9633        envelope: TypedEnvelope<proto::InlayHints>,
 9634        _: Arc<Client>,
 9635        mut cx: AsyncAppContext,
 9636    ) -> Result<proto::InlayHintsResponse> {
 9637        let sender_id = envelope.original_sender_id()?;
 9638        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9639        let buffer = this.update(&mut cx, |this, _| {
 9640            this.opened_buffers
 9641                .get(&buffer_id)
 9642                .and_then(|buffer| buffer.upgrade())
 9643                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
 9644        })??;
 9645        buffer
 9646            .update(&mut cx, |buffer, _| {
 9647                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9648            })?
 9649            .await
 9650            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 9651
 9652        let start = envelope
 9653            .payload
 9654            .start
 9655            .and_then(deserialize_anchor)
 9656            .context("missing range start")?;
 9657        let end = envelope
 9658            .payload
 9659            .end
 9660            .and_then(deserialize_anchor)
 9661            .context("missing range end")?;
 9662        let buffer_hints = this
 9663            .update(&mut cx, |project, cx| {
 9664                project.inlay_hints(buffer.clone(), start..end, cx)
 9665            })?
 9666            .await
 9667            .context("inlay hints fetch")?;
 9668
 9669        this.update(&mut cx, |project, cx| {
 9670            InlayHints::response_to_proto(
 9671                buffer_hints,
 9672                project,
 9673                sender_id,
 9674                &buffer.read(cx).version(),
 9675                cx,
 9676            )
 9677        })
 9678    }
 9679
 9680    async fn handle_resolve_inlay_hint(
 9681        this: Model<Self>,
 9682        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 9683        _: Arc<Client>,
 9684        mut cx: AsyncAppContext,
 9685    ) -> Result<proto::ResolveInlayHintResponse> {
 9686        let proto_hint = envelope
 9687            .payload
 9688            .hint
 9689            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9690        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9691            .context("resolved proto inlay hint conversion")?;
 9692        let buffer = this.update(&mut cx, |this, _cx| {
 9693            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9694            this.opened_buffers
 9695                .get(&buffer_id)
 9696                .and_then(|buffer| buffer.upgrade())
 9697                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9698        })??;
 9699        let response_hint = this
 9700            .update(&mut cx, |project, cx| {
 9701                project.resolve_inlay_hint(
 9702                    hint,
 9703                    buffer,
 9704                    LanguageServerId(envelope.payload.language_server_id as usize),
 9705                    cx,
 9706                )
 9707            })?
 9708            .await
 9709            .context("inlay hints fetch")?;
 9710        Ok(proto::ResolveInlayHintResponse {
 9711            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9712        })
 9713    }
 9714
 9715    async fn handle_task_context_for_location(
 9716        project: Model<Self>,
 9717        envelope: TypedEnvelope<proto::TaskContextForLocation>,
 9718        _: Arc<Client>,
 9719        mut cx: AsyncAppContext,
 9720    ) -> Result<proto::TaskContext> {
 9721        let location = envelope
 9722            .payload
 9723            .location
 9724            .context("no location given for task context handling")?;
 9725        let location = cx
 9726            .update(|cx| deserialize_location(&project, location, cx))?
 9727            .await?;
 9728        let context_task = project.update(&mut cx, |project, cx| {
 9729            let captured_variables = {
 9730                let mut variables = TaskVariables::default();
 9731                for range in location
 9732                    .buffer
 9733                    .read(cx)
 9734                    .snapshot()
 9735                    .runnable_ranges(location.range.clone())
 9736                {
 9737                    for (capture_name, value) in range.extra_captures {
 9738                        variables.insert(VariableName::Custom(capture_name.into()), value);
 9739                    }
 9740                }
 9741                variables
 9742            };
 9743            project.task_context_for_location(captured_variables, location, cx)
 9744        })?;
 9745        let task_context = context_task.await.unwrap_or_default();
 9746        Ok(proto::TaskContext {
 9747            cwd: task_context
 9748                .cwd
 9749                .map(|cwd| cwd.to_string_lossy().to_string()),
 9750            task_variables: task_context
 9751                .task_variables
 9752                .into_iter()
 9753                .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
 9754                .collect(),
 9755        })
 9756    }
 9757
 9758    async fn handle_task_templates(
 9759        project: Model<Self>,
 9760        envelope: TypedEnvelope<proto::TaskTemplates>,
 9761        _: Arc<Client>,
 9762        mut cx: AsyncAppContext,
 9763    ) -> Result<proto::TaskTemplatesResponse> {
 9764        let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
 9765        let location = match envelope.payload.location {
 9766            Some(location) => Some(
 9767                cx.update(|cx| deserialize_location(&project, location, cx))?
 9768                    .await
 9769                    .context("task templates request location deserializing")?,
 9770            ),
 9771            None => None,
 9772        };
 9773
 9774        let templates = project
 9775            .update(&mut cx, |project, cx| {
 9776                project.task_templates(worktree, location, cx)
 9777            })?
 9778            .await
 9779            .context("receiving task templates")?
 9780            .into_iter()
 9781            .map(|(kind, template)| {
 9782                let kind = Some(match kind {
 9783                    TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
 9784                        proto::task_source_kind::UserInput {},
 9785                    ),
 9786                    TaskSourceKind::Worktree {
 9787                        id,
 9788                        abs_path,
 9789                        id_base,
 9790                    } => {
 9791                        proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
 9792                            id: id.to_proto(),
 9793                            abs_path: abs_path.to_string_lossy().to_string(),
 9794                            id_base: id_base.to_string(),
 9795                        })
 9796                    }
 9797                    TaskSourceKind::AbsPath { id_base, abs_path } => {
 9798                        proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
 9799                            abs_path: abs_path.to_string_lossy().to_string(),
 9800                            id_base: id_base.to_string(),
 9801                        })
 9802                    }
 9803                    TaskSourceKind::Language { name } => {
 9804                        proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
 9805                            name: name.to_string(),
 9806                        })
 9807                    }
 9808                });
 9809                let kind = Some(proto::TaskSourceKind { kind });
 9810                let template = Some(proto::TaskTemplate {
 9811                    label: template.label,
 9812                    command: template.command,
 9813                    args: template.args,
 9814                    env: template.env.into_iter().collect(),
 9815                    cwd: template.cwd,
 9816                    use_new_terminal: template.use_new_terminal,
 9817                    allow_concurrent_runs: template.allow_concurrent_runs,
 9818                    reveal: match template.reveal {
 9819                        RevealStrategy::Always => proto::RevealStrategy::Always as i32,
 9820                        RevealStrategy::Never => proto::RevealStrategy::Never as i32,
 9821                    },
 9822                    tags: template.tags,
 9823                });
 9824                proto::TemplatePair { kind, template }
 9825            })
 9826            .collect();
 9827
 9828        Ok(proto::TaskTemplatesResponse { templates })
 9829    }
 9830
 9831    async fn try_resolve_code_action(
 9832        lang_server: &LanguageServer,
 9833        action: &mut CodeAction,
 9834    ) -> anyhow::Result<()> {
 9835        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 9836            if action.lsp_action.data.is_some()
 9837                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 9838            {
 9839                action.lsp_action = lang_server
 9840                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 9841                    .await?;
 9842            }
 9843        }
 9844
 9845        anyhow::Ok(())
 9846    }
 9847
 9848    async fn execute_code_actions_on_servers(
 9849        project: &WeakModel<Project>,
 9850        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 9851        code_actions: Vec<lsp::CodeActionKind>,
 9852        buffer: &Model<Buffer>,
 9853        push_to_history: bool,
 9854        project_transaction: &mut ProjectTransaction,
 9855        cx: &mut AsyncAppContext,
 9856    ) -> Result<(), anyhow::Error> {
 9857        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 9858            let code_actions = code_actions.clone();
 9859
 9860            let actions = project
 9861                .update(cx, move |this, cx| {
 9862                    let request = GetCodeActions {
 9863                        range: text::Anchor::MIN..text::Anchor::MAX,
 9864                        kinds: Some(code_actions),
 9865                    };
 9866                    let server = LanguageServerToQuery::Other(language_server.server_id());
 9867                    this.request_lsp(buffer.clone(), server, request, cx)
 9868                })?
 9869                .await?;
 9870
 9871            for mut action in actions {
 9872                Self::try_resolve_code_action(&language_server, &mut action)
 9873                    .await
 9874                    .context("resolving a formatting code action")?;
 9875
 9876                if let Some(edit) = action.lsp_action.edit {
 9877                    if edit.changes.is_none() && edit.document_changes.is_none() {
 9878                        continue;
 9879                    }
 9880
 9881                    let new = Self::deserialize_workspace_edit(
 9882                        project
 9883                            .upgrade()
 9884                            .ok_or_else(|| anyhow!("project dropped"))?,
 9885                        edit,
 9886                        push_to_history,
 9887                        lsp_adapter.clone(),
 9888                        language_server.clone(),
 9889                        cx,
 9890                    )
 9891                    .await?;
 9892                    project_transaction.0.extend(new.0);
 9893                }
 9894
 9895                if let Some(command) = action.lsp_action.command {
 9896                    project.update(cx, |this, _| {
 9897                        this.last_workspace_edits_by_language_server
 9898                            .remove(&language_server.server_id());
 9899                    })?;
 9900
 9901                    language_server
 9902                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 9903                            command: command.command,
 9904                            arguments: command.arguments.unwrap_or_default(),
 9905                            ..Default::default()
 9906                        })
 9907                        .await?;
 9908
 9909                    project.update(cx, |this, _| {
 9910                        project_transaction.0.extend(
 9911                            this.last_workspace_edits_by_language_server
 9912                                .remove(&language_server.server_id())
 9913                                .unwrap_or_default()
 9914                                .0,
 9915                        )
 9916                    })?;
 9917                }
 9918            }
 9919        }
 9920
 9921        Ok(())
 9922    }
 9923
 9924    async fn handle_refresh_inlay_hints(
 9925        this: Model<Self>,
 9926        _: TypedEnvelope<proto::RefreshInlayHints>,
 9927        _: Arc<Client>,
 9928        mut cx: AsyncAppContext,
 9929    ) -> Result<proto::Ack> {
 9930        this.update(&mut cx, |_, cx| {
 9931            cx.emit(Event::RefreshInlayHints);
 9932        })?;
 9933        Ok(proto::Ack {})
 9934    }
 9935
 9936    async fn handle_lsp_command<T: LspCommand>(
 9937        this: Model<Self>,
 9938        envelope: TypedEnvelope<T::ProtoRequest>,
 9939        _: Arc<Client>,
 9940        mut cx: AsyncAppContext,
 9941    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 9942    where
 9943        <T::LspRequest as lsp::request::Request>::Params: Send,
 9944        <T::LspRequest as lsp::request::Request>::Result: Send,
 9945    {
 9946        let sender_id = envelope.original_sender_id()?;
 9947        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 9948        let buffer_handle = this.update(&mut cx, |this, _cx| {
 9949            this.opened_buffers
 9950                .get(&buffer_id)
 9951                .and_then(|buffer| buffer.upgrade())
 9952                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 9953        })??;
 9954        let request = T::from_proto(
 9955            envelope.payload,
 9956            this.clone(),
 9957            buffer_handle.clone(),
 9958            cx.clone(),
 9959        )
 9960        .await?;
 9961        let response = this
 9962            .update(&mut cx, |this, cx| {
 9963                this.request_lsp(
 9964                    buffer_handle.clone(),
 9965                    LanguageServerToQuery::Primary,
 9966                    request,
 9967                    cx,
 9968                )
 9969            })?
 9970            .await?;
 9971        this.update(&mut cx, |this, cx| {
 9972            Ok(T::response_to_proto(
 9973                response,
 9974                this,
 9975                sender_id,
 9976                &buffer_handle.read(cx).version(),
 9977                cx,
 9978            ))
 9979        })?
 9980    }
 9981
 9982    async fn handle_get_project_symbols(
 9983        this: Model<Self>,
 9984        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9985        _: Arc<Client>,
 9986        mut cx: AsyncAppContext,
 9987    ) -> Result<proto::GetProjectSymbolsResponse> {
 9988        let symbols = this
 9989            .update(&mut cx, |this, cx| {
 9990                this.symbols(&envelope.payload.query, cx)
 9991            })?
 9992            .await?;
 9993
 9994        Ok(proto::GetProjectSymbolsResponse {
 9995            symbols: symbols.iter().map(serialize_symbol).collect(),
 9996        })
 9997    }
 9998
 9999    async fn handle_search_project(
10000        this: Model<Self>,
10001        envelope: TypedEnvelope<proto::SearchProject>,
10002        _: Arc<Client>,
10003        mut cx: AsyncAppContext,
10004    ) -> Result<proto::SearchProjectResponse> {
10005        let peer_id = envelope.original_sender_id()?;
10006        let query = SearchQuery::from_proto(envelope.payload)?;
10007        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
10008
10009        cx.spawn(move |mut cx| async move {
10010            let mut locations = Vec::new();
10011            let mut limit_reached = false;
10012            while let Some(result) = result.next().await {
10013                match result {
10014                    SearchResult::Buffer { buffer, ranges } => {
10015                        for range in ranges {
10016                            let start = serialize_anchor(&range.start);
10017                            let end = serialize_anchor(&range.end);
10018                            let buffer_id = this.update(&mut cx, |this, cx| {
10019                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
10020                            })?;
10021                            locations.push(proto::Location {
10022                                buffer_id,
10023                                start: Some(start),
10024                                end: Some(end),
10025                            });
10026                        }
10027                    }
10028                    SearchResult::LimitReached => limit_reached = true,
10029                }
10030            }
10031            Ok(proto::SearchProjectResponse {
10032                locations,
10033                limit_reached,
10034            })
10035        })
10036        .await
10037    }
10038
10039    async fn handle_open_buffer_for_symbol(
10040        this: Model<Self>,
10041        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
10042        _: Arc<Client>,
10043        mut cx: AsyncAppContext,
10044    ) -> Result<proto::OpenBufferForSymbolResponse> {
10045        let peer_id = envelope.original_sender_id()?;
10046        let symbol = envelope
10047            .payload
10048            .symbol
10049            .ok_or_else(|| anyhow!("invalid symbol"))?;
10050        let symbol = Self::deserialize_symbol(symbol)?;
10051        let symbol = this.update(&mut cx, |this, _| {
10052            let signature = this.symbol_signature(&symbol.path);
10053            if signature == symbol.signature {
10054                Ok(symbol)
10055            } else {
10056                Err(anyhow!("invalid symbol signature"))
10057            }
10058        })??;
10059        let buffer = this
10060            .update(&mut cx, |this, cx| {
10061                this.open_buffer_for_symbol(
10062                    &Symbol {
10063                        language_server_name: symbol.language_server_name,
10064                        source_worktree_id: symbol.source_worktree_id,
10065                        path: symbol.path,
10066                        name: symbol.name,
10067                        kind: symbol.kind,
10068                        range: symbol.range,
10069                        signature: symbol.signature,
10070                        label: CodeLabel {
10071                            text: Default::default(),
10072                            runs: Default::default(),
10073                            filter_range: Default::default(),
10074                        },
10075                    },
10076                    cx,
10077                )
10078            })?
10079            .await?;
10080
10081        this.update(&mut cx, |this, cx| {
10082            let is_private = buffer
10083                .read(cx)
10084                .file()
10085                .map(|f| f.is_private())
10086                .unwrap_or_default();
10087            if is_private {
10088                Err(anyhow!(ErrorCode::UnsharedItem))
10089            } else {
10090                Ok(proto::OpenBufferForSymbolResponse {
10091                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
10092                })
10093            }
10094        })?
10095    }
10096
10097    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
10098        let mut hasher = Sha256::new();
10099        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
10100        hasher.update(project_path.path.to_string_lossy().as_bytes());
10101        hasher.update(self.nonce.to_be_bytes());
10102        hasher.finalize().as_slice().try_into().unwrap()
10103    }
10104
10105    async fn handle_open_buffer_by_id(
10106        this: Model<Self>,
10107        envelope: TypedEnvelope<proto::OpenBufferById>,
10108        _: Arc<Client>,
10109        mut cx: AsyncAppContext,
10110    ) -> Result<proto::OpenBufferResponse> {
10111        let peer_id = envelope.original_sender_id()?;
10112        let buffer_id = BufferId::new(envelope.payload.id)?;
10113        let buffer = this
10114            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
10115            .await?;
10116        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
10117    }
10118
10119    async fn handle_open_buffer_by_path(
10120        this: Model<Self>,
10121        envelope: TypedEnvelope<proto::OpenBufferByPath>,
10122        _: Arc<Client>,
10123        mut cx: AsyncAppContext,
10124    ) -> Result<proto::OpenBufferResponse> {
10125        let peer_id = envelope.original_sender_id()?;
10126        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
10127        let open_buffer = this.update(&mut cx, |this, cx| {
10128            this.open_buffer(
10129                ProjectPath {
10130                    worktree_id,
10131                    path: PathBuf::from(envelope.payload.path).into(),
10132                },
10133                cx,
10134            )
10135        })?;
10136
10137        let buffer = open_buffer.await?;
10138        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
10139    }
10140
10141    async fn handle_open_new_buffer(
10142        this: Model<Self>,
10143        envelope: TypedEnvelope<proto::OpenNewBuffer>,
10144        _: Arc<Client>,
10145        mut cx: AsyncAppContext,
10146    ) -> Result<proto::OpenBufferResponse> {
10147        let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
10148        let peer_id = envelope.original_sender_id()?;
10149
10150        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
10151    }
10152
10153    fn respond_to_open_buffer_request(
10154        this: Model<Self>,
10155        buffer: Model<Buffer>,
10156        peer_id: proto::PeerId,
10157        cx: &mut AsyncAppContext,
10158    ) -> Result<proto::OpenBufferResponse> {
10159        this.update(cx, |this, cx| {
10160            let is_private = buffer
10161                .read(cx)
10162                .file()
10163                .map(|f| f.is_private())
10164                .unwrap_or_default();
10165            if is_private {
10166                Err(anyhow!(ErrorCode::UnsharedItem))
10167            } else {
10168                Ok(proto::OpenBufferResponse {
10169                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
10170                })
10171            }
10172        })?
10173    }
10174
10175    fn serialize_project_transaction_for_peer(
10176        &mut self,
10177        project_transaction: ProjectTransaction,
10178        peer_id: proto::PeerId,
10179        cx: &mut AppContext,
10180    ) -> proto::ProjectTransaction {
10181        let mut serialized_transaction = proto::ProjectTransaction {
10182            buffer_ids: Default::default(),
10183            transactions: Default::default(),
10184        };
10185        for (buffer, transaction) in project_transaction.0 {
10186            serialized_transaction
10187                .buffer_ids
10188                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
10189            serialized_transaction
10190                .transactions
10191                .push(language::proto::serialize_transaction(&transaction));
10192        }
10193        serialized_transaction
10194    }
10195
10196    fn deserialize_project_transaction(
10197        &mut self,
10198        message: proto::ProjectTransaction,
10199        push_to_history: bool,
10200        cx: &mut ModelContext<Self>,
10201    ) -> Task<Result<ProjectTransaction>> {
10202        cx.spawn(move |this, mut cx| async move {
10203            let mut project_transaction = ProjectTransaction::default();
10204            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
10205            {
10206                let buffer_id = BufferId::new(buffer_id)?;
10207                let buffer = this
10208                    .update(&mut cx, |this, cx| {
10209                        this.wait_for_remote_buffer(buffer_id, cx)
10210                    })?
10211                    .await?;
10212                let transaction = language::proto::deserialize_transaction(transaction)?;
10213                project_transaction.0.insert(buffer, transaction);
10214            }
10215
10216            for (buffer, transaction) in &project_transaction.0 {
10217                buffer
10218                    .update(&mut cx, |buffer, _| {
10219                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
10220                    })?
10221                    .await?;
10222
10223                if push_to_history {
10224                    buffer.update(&mut cx, |buffer, _| {
10225                        buffer.push_transaction(transaction.clone(), Instant::now());
10226                    })?;
10227                }
10228            }
10229
10230            Ok(project_transaction)
10231        })
10232    }
10233
10234    fn create_buffer_for_peer(
10235        &mut self,
10236        buffer: &Model<Buffer>,
10237        peer_id: proto::PeerId,
10238        cx: &mut AppContext,
10239    ) -> BufferId {
10240        let buffer_id = buffer.read(cx).remote_id();
10241        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
10242            updates_tx
10243                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
10244                .ok();
10245        }
10246        buffer_id
10247    }
10248
10249    fn wait_for_remote_buffer(
10250        &mut self,
10251        id: BufferId,
10252        cx: &mut ModelContext<Self>,
10253    ) -> Task<Result<Model<Buffer>>> {
10254        let buffer = self
10255            .opened_buffers
10256            .get(&id)
10257            .and_then(|buffer| buffer.upgrade());
10258
10259        if let Some(buffer) = buffer {
10260            return Task::ready(Ok(buffer));
10261        }
10262
10263        let (tx, rx) = oneshot::channel();
10264        self.loading_buffers.entry(id).or_default().push(tx);
10265
10266        cx.background_executor().spawn(async move { rx.await? })
10267    }
10268
10269    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
10270        let project_id = match self.client_state {
10271            ProjectClientState::Remote {
10272                sharing_has_stopped,
10273                remote_id,
10274                ..
10275            } => {
10276                if sharing_has_stopped {
10277                    return Task::ready(Err(anyhow!(
10278                        "can't synchronize remote buffers on a readonly project"
10279                    )));
10280                } else {
10281                    remote_id
10282                }
10283            }
10284            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
10285                return Task::ready(Err(anyhow!(
10286                    "can't synchronize remote buffers on a local project"
10287                )))
10288            }
10289        };
10290
10291        let client = self.client.clone();
10292        cx.spawn(move |this, mut cx| async move {
10293            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
10294                let buffers = this
10295                    .opened_buffers
10296                    .iter()
10297                    .filter_map(|(id, buffer)| {
10298                        let buffer = buffer.upgrade()?;
10299                        Some(proto::BufferVersion {
10300                            id: (*id).into(),
10301                            version: language::proto::serialize_version(&buffer.read(cx).version),
10302                        })
10303                    })
10304                    .collect();
10305                let incomplete_buffer_ids = this
10306                    .incomplete_remote_buffers
10307                    .keys()
10308                    .copied()
10309                    .collect::<Vec<_>>();
10310
10311                (buffers, incomplete_buffer_ids)
10312            })?;
10313            let response = client
10314                .request(proto::SynchronizeBuffers {
10315                    project_id,
10316                    buffers,
10317                })
10318                .await?;
10319
10320            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
10321                response
10322                    .buffers
10323                    .into_iter()
10324                    .map(|buffer| {
10325                        let client = client.clone();
10326                        let buffer_id = match BufferId::new(buffer.id) {
10327                            Ok(id) => id,
10328                            Err(e) => {
10329                                return Task::ready(Err(e));
10330                            }
10331                        };
10332                        let remote_version = language::proto::deserialize_version(&buffer.version);
10333                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
10334                            let operations =
10335                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
10336                            cx.background_executor().spawn(async move {
10337                                let operations = operations.await;
10338                                for chunk in split_operations(operations) {
10339                                    client
10340                                        .request(proto::UpdateBuffer {
10341                                            project_id,
10342                                            buffer_id: buffer_id.into(),
10343                                            operations: chunk,
10344                                        })
10345                                        .await?;
10346                                }
10347                                anyhow::Ok(())
10348                            })
10349                        } else {
10350                            Task::ready(Ok(()))
10351                        }
10352                    })
10353                    .collect::<Vec<_>>()
10354            })?;
10355
10356            // Any incomplete buffers have open requests waiting. Request that the host sends
10357            // creates these buffers for us again to unblock any waiting futures.
10358            for id in incomplete_buffer_ids {
10359                cx.background_executor()
10360                    .spawn(client.request(proto::OpenBufferById {
10361                        project_id,
10362                        id: id.into(),
10363                    }))
10364                    .detach();
10365            }
10366
10367            futures::future::join_all(send_updates_for_buffers)
10368                .await
10369                .into_iter()
10370                .collect()
10371        })
10372    }
10373
10374    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
10375        self.worktrees()
10376            .map(|worktree| {
10377                let worktree = worktree.read(cx);
10378                proto::WorktreeMetadata {
10379                    id: worktree.id().to_proto(),
10380                    root_name: worktree.root_name().into(),
10381                    visible: worktree.is_visible(),
10382                    abs_path: worktree.abs_path().to_string_lossy().into(),
10383                }
10384            })
10385            .collect()
10386    }
10387
10388    fn set_worktrees_from_proto(
10389        &mut self,
10390        worktrees: Vec<proto::WorktreeMetadata>,
10391        cx: &mut ModelContext<Project>,
10392    ) -> Result<()> {
10393        let replica_id = self.replica_id();
10394        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
10395
10396        let mut old_worktrees_by_id = self
10397            .worktrees
10398            .drain(..)
10399            .filter_map(|worktree| {
10400                let worktree = worktree.upgrade()?;
10401                Some((worktree.read(cx).id(), worktree))
10402            })
10403            .collect::<HashMap<_, _>>();
10404
10405        for worktree in worktrees {
10406            if let Some(old_worktree) =
10407                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
10408            {
10409                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
10410            } else {
10411                self.add_worktree(
10412                    &Worktree::remote(
10413                        remote_id,
10414                        replica_id,
10415                        worktree,
10416                        Box::new(CollabRemoteWorktreeClient(self.client.clone())),
10417                        cx,
10418                    ),
10419                    cx,
10420                );
10421            }
10422        }
10423
10424        self.metadata_changed(cx);
10425        for id in old_worktrees_by_id.keys() {
10426            cx.emit(Event::WorktreeRemoved(*id));
10427        }
10428
10429        Ok(())
10430    }
10431
10432    fn set_collaborators_from_proto(
10433        &mut self,
10434        messages: Vec<proto::Collaborator>,
10435        cx: &mut ModelContext<Self>,
10436    ) -> Result<()> {
10437        let mut collaborators = HashMap::default();
10438        for message in messages {
10439            let collaborator = Collaborator::from_proto(message)?;
10440            collaborators.insert(collaborator.peer_id, collaborator);
10441        }
10442        for old_peer_id in self.collaborators.keys() {
10443            if !collaborators.contains_key(old_peer_id) {
10444                cx.emit(Event::CollaboratorLeft(*old_peer_id));
10445            }
10446        }
10447        self.collaborators = collaborators;
10448        Ok(())
10449    }
10450
10451    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
10452        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
10453        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
10454        let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
10455        let path = ProjectPath {
10456            worktree_id,
10457            path: PathBuf::from(serialized_symbol.path).into(),
10458        };
10459
10460        let start = serialized_symbol
10461            .start
10462            .ok_or_else(|| anyhow!("invalid start"))?;
10463        let end = serialized_symbol
10464            .end
10465            .ok_or_else(|| anyhow!("invalid end"))?;
10466        Ok(CoreSymbol {
10467            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
10468            source_worktree_id,
10469            path,
10470            name: serialized_symbol.name,
10471            range: Unclipped(PointUtf16::new(start.row, start.column))
10472                ..Unclipped(PointUtf16::new(end.row, end.column)),
10473            kind,
10474            signature: serialized_symbol
10475                .signature
10476                .try_into()
10477                .map_err(|_| anyhow!("invalid signature"))?,
10478        })
10479    }
10480
10481    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
10482        proto::Completion {
10483            old_start: Some(serialize_anchor(&completion.old_range.start)),
10484            old_end: Some(serialize_anchor(&completion.old_range.end)),
10485            new_text: completion.new_text.clone(),
10486            server_id: completion.server_id.0 as u64,
10487            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
10488        }
10489    }
10490
10491    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
10492        let old_start = completion
10493            .old_start
10494            .and_then(deserialize_anchor)
10495            .ok_or_else(|| anyhow!("invalid old start"))?;
10496        let old_end = completion
10497            .old_end
10498            .and_then(deserialize_anchor)
10499            .ok_or_else(|| anyhow!("invalid old end"))?;
10500        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
10501
10502        Ok(CoreCompletion {
10503            old_range: old_start..old_end,
10504            new_text: completion.new_text,
10505            server_id: LanguageServerId(completion.server_id as usize),
10506            lsp_completion,
10507        })
10508    }
10509
10510    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
10511        proto::CodeAction {
10512            server_id: action.server_id.0 as u64,
10513            start: Some(serialize_anchor(&action.range.start)),
10514            end: Some(serialize_anchor(&action.range.end)),
10515            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
10516        }
10517    }
10518
10519    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
10520        let start = action
10521            .start
10522            .and_then(deserialize_anchor)
10523            .ok_or_else(|| anyhow!("invalid start"))?;
10524        let end = action
10525            .end
10526            .and_then(deserialize_anchor)
10527            .ok_or_else(|| anyhow!("invalid end"))?;
10528        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
10529        Ok(CodeAction {
10530            server_id: LanguageServerId(action.server_id as usize),
10531            range: start..end,
10532            lsp_action,
10533        })
10534    }
10535
10536    async fn handle_buffer_saved(
10537        this: Model<Self>,
10538        envelope: TypedEnvelope<proto::BufferSaved>,
10539        _: Arc<Client>,
10540        mut cx: AsyncAppContext,
10541    ) -> Result<()> {
10542        let version = deserialize_version(&envelope.payload.version);
10543        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
10544        let mtime = envelope.payload.mtime.map(|time| time.into());
10545
10546        this.update(&mut cx, |this, cx| {
10547            let buffer = this
10548                .opened_buffers
10549                .get(&buffer_id)
10550                .and_then(|buffer| buffer.upgrade())
10551                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
10552            if let Some(buffer) = buffer {
10553                buffer.update(cx, |buffer, cx| {
10554                    buffer.did_save(version, mtime, cx);
10555                });
10556            }
10557            Ok(())
10558        })?
10559    }
10560
10561    async fn handle_buffer_reloaded(
10562        this: Model<Self>,
10563        envelope: TypedEnvelope<proto::BufferReloaded>,
10564        _: Arc<Client>,
10565        mut cx: AsyncAppContext,
10566    ) -> Result<()> {
10567        let payload = envelope.payload;
10568        let version = deserialize_version(&payload.version);
10569        let line_ending = deserialize_line_ending(
10570            proto::LineEnding::from_i32(payload.line_ending)
10571                .ok_or_else(|| anyhow!("missing line ending"))?,
10572        );
10573        let mtime = payload.mtime.map(|time| time.into());
10574        let buffer_id = BufferId::new(payload.buffer_id)?;
10575        this.update(&mut cx, |this, cx| {
10576            let buffer = this
10577                .opened_buffers
10578                .get(&buffer_id)
10579                .and_then(|buffer| buffer.upgrade())
10580                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
10581            if let Some(buffer) = buffer {
10582                buffer.update(cx, |buffer, cx| {
10583                    buffer.did_reload(version, line_ending, mtime, cx);
10584                });
10585            }
10586            Ok(())
10587        })?
10588    }
10589
10590    #[allow(clippy::type_complexity)]
10591    fn edits_from_lsp(
10592        &mut self,
10593        buffer: &Model<Buffer>,
10594        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
10595        server_id: LanguageServerId,
10596        version: Option<i32>,
10597        cx: &mut ModelContext<Self>,
10598    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
10599        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
10600        cx.background_executor().spawn(async move {
10601            let snapshot = snapshot?;
10602            let mut lsp_edits = lsp_edits
10603                .into_iter()
10604                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
10605                .collect::<Vec<_>>();
10606            lsp_edits.sort_by_key(|(range, _)| range.start);
10607
10608            let mut lsp_edits = lsp_edits.into_iter().peekable();
10609            let mut edits = Vec::new();
10610            while let Some((range, mut new_text)) = lsp_edits.next() {
10611                // Clip invalid ranges provided by the language server.
10612                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
10613                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
10614
10615                // Combine any LSP edits that are adjacent.
10616                //
10617                // Also, combine LSP edits that are separated from each other by only
10618                // a newline. This is important because for some code actions,
10619                // Rust-analyzer rewrites the entire buffer via a series of edits that
10620                // are separated by unchanged newline characters.
10621                //
10622                // In order for the diffing logic below to work properly, any edits that
10623                // cancel each other out must be combined into one.
10624                while let Some((next_range, next_text)) = lsp_edits.peek() {
10625                    if next_range.start.0 > range.end {
10626                        if next_range.start.0.row > range.end.row + 1
10627                            || next_range.start.0.column > 0
10628                            || snapshot.clip_point_utf16(
10629                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
10630                                Bias::Left,
10631                            ) > range.end
10632                        {
10633                            break;
10634                        }
10635                        new_text.push('\n');
10636                    }
10637                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
10638                    new_text.push_str(next_text);
10639                    lsp_edits.next();
10640                }
10641
10642                // For multiline edits, perform a diff of the old and new text so that
10643                // we can identify the changes more precisely, preserving the locations
10644                // of any anchors positioned in the unchanged regions.
10645                if range.end.row > range.start.row {
10646                    let mut offset = range.start.to_offset(&snapshot);
10647                    let old_text = snapshot.text_for_range(range).collect::<String>();
10648
10649                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
10650                    let mut moved_since_edit = true;
10651                    for change in diff.iter_all_changes() {
10652                        let tag = change.tag();
10653                        let value = change.value();
10654                        match tag {
10655                            ChangeTag::Equal => {
10656                                offset += value.len();
10657                                moved_since_edit = true;
10658                            }
10659                            ChangeTag::Delete => {
10660                                let start = snapshot.anchor_after(offset);
10661                                let end = snapshot.anchor_before(offset + value.len());
10662                                if moved_since_edit {
10663                                    edits.push((start..end, String::new()));
10664                                } else {
10665                                    edits.last_mut().unwrap().0.end = end;
10666                                }
10667                                offset += value.len();
10668                                moved_since_edit = false;
10669                            }
10670                            ChangeTag::Insert => {
10671                                if moved_since_edit {
10672                                    let anchor = snapshot.anchor_after(offset);
10673                                    edits.push((anchor..anchor, value.to_string()));
10674                                } else {
10675                                    edits.last_mut().unwrap().1.push_str(value);
10676                                }
10677                                moved_since_edit = false;
10678                            }
10679                        }
10680                    }
10681                } else if range.end == range.start {
10682                    let anchor = snapshot.anchor_after(range.start);
10683                    edits.push((anchor..anchor, new_text));
10684                } else {
10685                    let edit_start = snapshot.anchor_after(range.start);
10686                    let edit_end = snapshot.anchor_before(range.end);
10687                    edits.push((edit_start..edit_end, new_text));
10688                }
10689            }
10690
10691            Ok(edits)
10692        })
10693    }
10694
10695    fn buffer_snapshot_for_lsp_version(
10696        &mut self,
10697        buffer: &Model<Buffer>,
10698        server_id: LanguageServerId,
10699        version: Option<i32>,
10700        cx: &AppContext,
10701    ) -> Result<TextBufferSnapshot> {
10702        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
10703
10704        if let Some(version) = version {
10705            let buffer_id = buffer.read(cx).remote_id();
10706            let snapshots = self
10707                .buffer_snapshots
10708                .get_mut(&buffer_id)
10709                .and_then(|m| m.get_mut(&server_id))
10710                .ok_or_else(|| {
10711                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
10712                })?;
10713
10714            let found_snapshot = snapshots
10715                .binary_search_by_key(&version, |e| e.version)
10716                .map(|ix| snapshots[ix].snapshot.clone())
10717                .map_err(|_| {
10718                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
10719                })?;
10720
10721            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
10722            Ok(found_snapshot)
10723        } else {
10724            Ok((buffer.read(cx)).text_snapshot())
10725        }
10726    }
10727
10728    pub fn language_servers(
10729        &self,
10730    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
10731        self.language_server_ids
10732            .iter()
10733            .map(|((worktree_id, server_name), server_id)| {
10734                (*server_id, server_name.clone(), *worktree_id)
10735            })
10736    }
10737
10738    pub fn supplementary_language_servers(
10739        &self,
10740    ) -> impl '_
10741           + Iterator<
10742        Item = (
10743            &LanguageServerId,
10744            &(LanguageServerName, Arc<LanguageServer>),
10745        ),
10746    > {
10747        self.supplementary_language_servers.iter()
10748    }
10749
10750    pub fn language_server_adapter_for_id(
10751        &self,
10752        id: LanguageServerId,
10753    ) -> Option<Arc<CachedLspAdapter>> {
10754        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
10755            Some(adapter.clone())
10756        } else {
10757            None
10758        }
10759    }
10760
10761    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
10762        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
10763            Some(server.clone())
10764        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
10765            Some(Arc::clone(server))
10766        } else {
10767            None
10768        }
10769    }
10770
10771    pub fn language_servers_for_buffer(
10772        &self,
10773        buffer: &Buffer,
10774        cx: &AppContext,
10775    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10776        self.language_server_ids_for_buffer(buffer, cx)
10777            .into_iter()
10778            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
10779                LanguageServerState::Running {
10780                    adapter, server, ..
10781                } => Some((adapter, server)),
10782                _ => None,
10783            })
10784    }
10785
10786    fn primary_language_server_for_buffer(
10787        &self,
10788        buffer: &Buffer,
10789        cx: &AppContext,
10790    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10791        self.language_servers_for_buffer(buffer, cx)
10792            .find(|s| s.0.is_primary)
10793    }
10794
10795    pub fn language_server_for_buffer(
10796        &self,
10797        buffer: &Buffer,
10798        server_id: LanguageServerId,
10799        cx: &AppContext,
10800    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10801        self.language_servers_for_buffer(buffer, cx)
10802            .find(|(_, s)| s.server_id() == server_id)
10803    }
10804
10805    fn language_server_ids_for_buffer(
10806        &self,
10807        buffer: &Buffer,
10808        cx: &AppContext,
10809    ) -> Vec<LanguageServerId> {
10810        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
10811            let worktree_id = file.worktree_id(cx);
10812            self.languages
10813                .lsp_adapters(&language)
10814                .iter()
10815                .flat_map(|adapter| {
10816                    let key = (worktree_id, adapter.name.clone());
10817                    self.language_server_ids.get(&key).copied()
10818                })
10819                .collect()
10820        } else {
10821            Vec::new()
10822        }
10823    }
10824
10825    pub fn task_context_for_location(
10826        &self,
10827        captured_variables: TaskVariables,
10828        location: Location,
10829        cx: &mut ModelContext<'_, Project>,
10830    ) -> Task<Option<TaskContext>> {
10831        if self.is_local() {
10832            let cwd = self.task_cwd(cx).log_err().flatten();
10833
10834            cx.spawn(|project, cx| async move {
10835                let mut task_variables = cx
10836                    .update(|cx| {
10837                        combine_task_variables(
10838                            captured_variables,
10839                            location,
10840                            BasicContextProvider::new(project.upgrade()?),
10841                            cx,
10842                        )
10843                        .log_err()
10844                    })
10845                    .ok()
10846                    .flatten()?;
10847                // Remove all custom entries starting with _, as they're not intended for use by the end user.
10848                task_variables.sweep();
10849                Some(TaskContext {
10850                    cwd,
10851                    task_variables,
10852                })
10853            })
10854        } else if let Some(project_id) = self
10855            .remote_id()
10856            .filter(|_| self.ssh_connection_string(cx).is_some())
10857        {
10858            let task_context = self.client().request(proto::TaskContextForLocation {
10859                project_id,
10860                location: Some(proto::Location {
10861                    buffer_id: location.buffer.read(cx).remote_id().into(),
10862                    start: Some(serialize_anchor(&location.range.start)),
10863                    end: Some(serialize_anchor(&location.range.end)),
10864                }),
10865            });
10866            cx.background_executor().spawn(async move {
10867                let task_context = task_context.await.log_err()?;
10868                Some(TaskContext {
10869                    cwd: task_context.cwd.map(PathBuf::from),
10870                    task_variables: task_context
10871                        .task_variables
10872                        .into_iter()
10873                        .filter_map(
10874                            |(variable_name, variable_value)| match variable_name.parse() {
10875                                Ok(variable_name) => Some((variable_name, variable_value)),
10876                                Err(()) => {
10877                                    log::error!("Unknown variable name: {variable_name}");
10878                                    None
10879                                }
10880                            },
10881                        )
10882                        .collect(),
10883                })
10884            })
10885        } else {
10886            Task::ready(None)
10887        }
10888    }
10889
10890    pub fn task_templates(
10891        &self,
10892        worktree: Option<WorktreeId>,
10893        location: Option<Location>,
10894        cx: &mut ModelContext<Self>,
10895    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10896        if self.is_local() {
10897            let language = location
10898                .and_then(|location| location.buffer.read(cx).language_at(location.range.start));
10899            Task::ready(Ok(self
10900                .task_inventory()
10901                .read(cx)
10902                .list_tasks(language, worktree)))
10903        } else if let Some(project_id) = self
10904            .remote_id()
10905            .filter(|_| self.ssh_connection_string(cx).is_some())
10906        {
10907            let remote_templates =
10908                self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
10909            cx.background_executor().spawn(remote_templates)
10910        } else {
10911            Task::ready(Ok(Vec::new()))
10912        }
10913    }
10914
10915    pub fn query_remote_task_templates(
10916        &self,
10917        project_id: u64,
10918        worktree: Option<WorktreeId>,
10919        location: Option<&Location>,
10920        cx: &AppContext,
10921    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10922        let client = self.client();
10923        let location = location.map(|location| serialize_location(location, cx));
10924        cx.spawn(|_| async move {
10925            let response = client
10926                .request(proto::TaskTemplates {
10927                    project_id,
10928                    worktree_id: worktree.map(|id| id.to_proto()),
10929                    location,
10930                })
10931                .await?;
10932
10933            Ok(response
10934                .templates
10935                .into_iter()
10936                .filter_map(|template_pair| {
10937                    let task_source_kind = match template_pair.kind?.kind? {
10938                        proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
10939                        proto::task_source_kind::Kind::Worktree(worktree) => {
10940                            TaskSourceKind::Worktree {
10941                                id: WorktreeId::from_proto(worktree.id),
10942                                abs_path: PathBuf::from(worktree.abs_path),
10943                                id_base: Cow::Owned(worktree.id_base),
10944                            }
10945                        }
10946                        proto::task_source_kind::Kind::AbsPath(abs_path) => {
10947                            TaskSourceKind::AbsPath {
10948                                id_base: Cow::Owned(abs_path.id_base),
10949                                abs_path: PathBuf::from(abs_path.abs_path),
10950                            }
10951                        }
10952                        proto::task_source_kind::Kind::Language(language) => {
10953                            TaskSourceKind::Language {
10954                                name: language.name.into(),
10955                            }
10956                        }
10957                    };
10958
10959                    let proto_template = template_pair.template?;
10960                    let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
10961                        .unwrap_or(proto::RevealStrategy::Always)
10962                    {
10963                        proto::RevealStrategy::Always => RevealStrategy::Always,
10964                        proto::RevealStrategy::Never => RevealStrategy::Never,
10965                    };
10966                    let task_template = TaskTemplate {
10967                        label: proto_template.label,
10968                        command: proto_template.command,
10969                        args: proto_template.args,
10970                        env: proto_template.env.into_iter().collect(),
10971                        cwd: proto_template.cwd,
10972                        use_new_terminal: proto_template.use_new_terminal,
10973                        allow_concurrent_runs: proto_template.allow_concurrent_runs,
10974                        reveal,
10975                        tags: proto_template.tags,
10976                    };
10977                    Some((task_source_kind, task_template))
10978                })
10979                .collect())
10980        })
10981    }
10982
10983    fn task_cwd(&self, cx: &AppContext) -> anyhow::Result<Option<PathBuf>> {
10984        let available_worktrees = self
10985            .worktrees()
10986            .filter(|worktree| {
10987                let worktree = worktree.read(cx);
10988                worktree.is_visible()
10989                    && worktree.is_local()
10990                    && worktree.root_entry().map_or(false, |e| e.is_dir())
10991            })
10992            .collect::<Vec<_>>();
10993        let cwd = match available_worktrees.len() {
10994            0 => None,
10995            1 => Some(available_worktrees[0].read(cx).abs_path()),
10996            _ => {
10997                let cwd_for_active_entry = self.active_entry().and_then(|entry_id| {
10998                    available_worktrees.into_iter().find_map(|worktree| {
10999                        let worktree = worktree.read(cx);
11000                        if worktree.contains_entry(entry_id) {
11001                            Some(worktree.abs_path())
11002                        } else {
11003                            None
11004                        }
11005                    })
11006                });
11007                anyhow::ensure!(
11008                    cwd_for_active_entry.is_some(),
11009                    "Cannot determine task cwd for multiple worktrees"
11010                );
11011                cwd_for_active_entry
11012            }
11013        };
11014        Ok(cwd.map(|path| path.to_path_buf()))
11015    }
11016}
11017
11018fn combine_task_variables(
11019    mut captured_variables: TaskVariables,
11020    location: Location,
11021    baseline: BasicContextProvider,
11022    cx: &mut AppContext,
11023) -> anyhow::Result<TaskVariables> {
11024    let language_context_provider = location
11025        .buffer
11026        .read(cx)
11027        .language()
11028        .and_then(|language| language.context_provider());
11029    let baseline = baseline
11030        .build_context(&captured_variables, &location, cx)
11031        .context("building basic default context")?;
11032    captured_variables.extend(baseline);
11033    if let Some(provider) = language_context_provider {
11034        captured_variables.extend(
11035            provider
11036                .build_context(&captured_variables, &location, cx)
11037                .context("building provider context")?,
11038        );
11039    }
11040    Ok(captured_variables)
11041}
11042
11043async fn populate_labels_for_symbols(
11044    symbols: Vec<CoreSymbol>,
11045    language_registry: &Arc<LanguageRegistry>,
11046    default_language: Option<Arc<Language>>,
11047    lsp_adapter: Option<Arc<CachedLspAdapter>>,
11048    output: &mut Vec<Symbol>,
11049) {
11050    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
11051
11052    let mut unknown_path = None;
11053    for symbol in symbols {
11054        let language = language_registry
11055            .language_for_file_path(&symbol.path.path)
11056            .await
11057            .ok()
11058            .or_else(|| {
11059                unknown_path.get_or_insert(symbol.path.path.clone());
11060                default_language.clone()
11061            });
11062        symbols_by_language
11063            .entry(language)
11064            .or_default()
11065            .push(symbol);
11066    }
11067
11068    if let Some(unknown_path) = unknown_path {
11069        log::info!(
11070            "no language found for symbol path {}",
11071            unknown_path.display()
11072        );
11073    }
11074
11075    let mut label_params = Vec::new();
11076    for (language, mut symbols) in symbols_by_language {
11077        label_params.clear();
11078        label_params.extend(
11079            symbols
11080                .iter_mut()
11081                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
11082        );
11083
11084        let mut labels = Vec::new();
11085        if let Some(language) = language {
11086            let lsp_adapter = lsp_adapter
11087                .clone()
11088                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
11089            if let Some(lsp_adapter) = lsp_adapter {
11090                labels = lsp_adapter
11091                    .labels_for_symbols(&label_params, &language)
11092                    .await
11093                    .log_err()
11094                    .unwrap_or_default();
11095            }
11096        }
11097
11098        for ((symbol, (name, _)), label) in symbols
11099            .into_iter()
11100            .zip(label_params.drain(..))
11101            .zip(labels.into_iter().chain(iter::repeat(None)))
11102        {
11103            output.push(Symbol {
11104                language_server_name: symbol.language_server_name,
11105                source_worktree_id: symbol.source_worktree_id,
11106                path: symbol.path,
11107                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
11108                name,
11109                kind: symbol.kind,
11110                range: symbol.range,
11111                signature: symbol.signature,
11112            });
11113        }
11114    }
11115}
11116
11117async fn populate_labels_for_completions(
11118    mut new_completions: Vec<CoreCompletion>,
11119    language_registry: &Arc<LanguageRegistry>,
11120    language: Option<Arc<Language>>,
11121    lsp_adapter: Option<Arc<CachedLspAdapter>>,
11122    completions: &mut Vec<Completion>,
11123) {
11124    let lsp_completions = new_completions
11125        .iter_mut()
11126        .map(|completion| mem::take(&mut completion.lsp_completion))
11127        .collect::<Vec<_>>();
11128
11129    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
11130        lsp_adapter
11131            .labels_for_completions(&lsp_completions, language)
11132            .await
11133            .log_err()
11134            .unwrap_or_default()
11135    } else {
11136        Vec::new()
11137    };
11138
11139    for ((completion, lsp_completion), label) in new_completions
11140        .into_iter()
11141        .zip(lsp_completions)
11142        .zip(labels.into_iter().chain(iter::repeat(None)))
11143    {
11144        let documentation = if let Some(docs) = &lsp_completion.documentation {
11145            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
11146        } else {
11147            None
11148        };
11149
11150        completions.push(Completion {
11151            old_range: completion.old_range,
11152            new_text: completion.new_text,
11153            label: label.unwrap_or_else(|| {
11154                CodeLabel::plain(
11155                    lsp_completion.label.clone(),
11156                    lsp_completion.filter_text.as_deref(),
11157                )
11158            }),
11159            server_id: completion.server_id,
11160            documentation,
11161            lsp_completion,
11162            confirm: None,
11163            show_new_completions_on_confirm: false,
11164        })
11165    }
11166}
11167
11168fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
11169    code_actions
11170        .iter()
11171        .flat_map(|(kind, enabled)| {
11172            if *enabled {
11173                Some(kind.clone().into())
11174            } else {
11175                None
11176            }
11177        })
11178        .collect()
11179}
11180
11181#[allow(clippy::too_many_arguments)]
11182async fn search_snapshots(
11183    snapshots: &Vec<(Snapshot, WorktreeSettings)>,
11184    worker_start_ix: usize,
11185    worker_end_ix: usize,
11186    query: &SearchQuery,
11187    results_tx: &Sender<SearchMatchCandidate>,
11188    opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
11189    include_root: bool,
11190    fs: &Arc<dyn Fs>,
11191) {
11192    let mut snapshot_start_ix = 0;
11193    let mut abs_path = PathBuf::new();
11194
11195    for (snapshot, _) in snapshots {
11196        let snapshot_end_ix = snapshot_start_ix
11197            + if query.include_ignored() {
11198                snapshot.file_count()
11199            } else {
11200                snapshot.visible_file_count()
11201            };
11202        if worker_end_ix <= snapshot_start_ix {
11203            break;
11204        } else if worker_start_ix > snapshot_end_ix {
11205            snapshot_start_ix = snapshot_end_ix;
11206            continue;
11207        } else {
11208            let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
11209            let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
11210
11211            for entry in snapshot
11212                .files(false, start_in_snapshot)
11213                .take(end_in_snapshot - start_in_snapshot)
11214            {
11215                if results_tx.is_closed() {
11216                    break;
11217                }
11218                if opened_buffers.contains_key(&entry.path) {
11219                    continue;
11220                }
11221
11222                let matched_path = if include_root {
11223                    let mut full_path = PathBuf::from(snapshot.root_name());
11224                    full_path.push(&entry.path);
11225                    query.file_matches(Some(&full_path))
11226                } else {
11227                    query.file_matches(Some(&entry.path))
11228                };
11229
11230                let matches = if matched_path {
11231                    abs_path.clear();
11232                    abs_path.push(&snapshot.abs_path());
11233                    abs_path.push(&entry.path);
11234                    if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
11235                        query.detect(file).unwrap_or(false)
11236                    } else {
11237                        false
11238                    }
11239                } else {
11240                    false
11241                };
11242
11243                if matches {
11244                    let project_path = SearchMatchCandidate::Path {
11245                        worktree_id: snapshot.id(),
11246                        path: entry.path.clone(),
11247                        is_ignored: entry.is_ignored,
11248                        is_file: entry.is_file(),
11249                    };
11250                    if results_tx.send(project_path).await.is_err() {
11251                        return;
11252                    }
11253                }
11254            }
11255
11256            snapshot_start_ix = snapshot_end_ix;
11257        }
11258    }
11259}
11260
11261async fn search_ignored_entry(
11262    snapshot: &Snapshot,
11263    settings: &WorktreeSettings,
11264    ignored_entry: &Entry,
11265    fs: &Arc<dyn Fs>,
11266    query: &SearchQuery,
11267    counter_tx: &Sender<SearchMatchCandidate>,
11268) {
11269    let mut ignored_paths_to_process =
11270        VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
11271
11272    while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
11273        let metadata = fs
11274            .metadata(&ignored_abs_path)
11275            .await
11276            .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
11277            .log_err()
11278            .flatten();
11279
11280        if let Some(fs_metadata) = metadata {
11281            if fs_metadata.is_dir {
11282                let files = fs
11283                    .read_dir(&ignored_abs_path)
11284                    .await
11285                    .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
11286                    .log_err();
11287
11288                if let Some(mut subfiles) = files {
11289                    while let Some(subfile) = subfiles.next().await {
11290                        if let Some(subfile) = subfile.log_err() {
11291                            ignored_paths_to_process.push_back(subfile);
11292                        }
11293                    }
11294                }
11295            } else if !fs_metadata.is_symlink {
11296                if !query.file_matches(Some(&ignored_abs_path))
11297                    || settings.is_path_excluded(&ignored_entry.path)
11298                {
11299                    continue;
11300                }
11301                let matches = if let Some(file) = fs
11302                    .open_sync(&ignored_abs_path)
11303                    .await
11304                    .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
11305                    .log_err()
11306                {
11307                    query.detect(file).unwrap_or(false)
11308                } else {
11309                    false
11310                };
11311
11312                if matches {
11313                    let project_path = SearchMatchCandidate::Path {
11314                        worktree_id: snapshot.id(),
11315                        path: Arc::from(
11316                            ignored_abs_path
11317                                .strip_prefix(snapshot.abs_path())
11318                                .expect("scanning worktree-related files"),
11319                        ),
11320                        is_ignored: true,
11321                        is_file: ignored_entry.is_file(),
11322                    };
11323                    if counter_tx.send(project_path).await.is_err() {
11324                        return;
11325                    }
11326                }
11327            }
11328        }
11329    }
11330}
11331
11332fn glob_literal_prefix(glob: &str) -> &str {
11333    let mut literal_end = 0;
11334    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
11335        if part.contains(&['*', '?', '{', '}']) {
11336            break;
11337        } else {
11338            if i > 0 {
11339                // Account for separator prior to this part
11340                literal_end += path::MAIN_SEPARATOR.len_utf8();
11341            }
11342            literal_end += part.len();
11343        }
11344    }
11345    &glob[..literal_end]
11346}
11347
11348impl WorktreeHandle {
11349    pub fn upgrade(&self) -> Option<Model<Worktree>> {
11350        match self {
11351            WorktreeHandle::Strong(handle) => Some(handle.clone()),
11352            WorktreeHandle::Weak(handle) => handle.upgrade(),
11353        }
11354    }
11355
11356    pub fn handle_id(&self) -> usize {
11357        match self {
11358            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
11359            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
11360        }
11361    }
11362}
11363
11364impl OpenBuffer {
11365    pub fn upgrade(&self) -> Option<Model<Buffer>> {
11366        match self {
11367            OpenBuffer::Strong(handle) => Some(handle.clone()),
11368            OpenBuffer::Weak(handle) => handle.upgrade(),
11369            OpenBuffer::Operations(_) => None,
11370        }
11371    }
11372}
11373
11374pub struct CollabRemoteWorktreeClient(Arc<Client>);
11375
11376impl RemoteWorktreeClient for CollabRemoteWorktreeClient {
11377    fn request(
11378        &self,
11379        envelope: proto::Envelope,
11380        request_type: &'static str,
11381    ) -> BoxFuture<'static, Result<proto::Envelope>> {
11382        self.0.request_dynamic(envelope, request_type).boxed()
11383    }
11384}
11385
11386pub struct PathMatchCandidateSet {
11387    pub snapshot: Snapshot,
11388    pub include_ignored: bool,
11389    pub include_root_name: bool,
11390    pub candidates: Candidates,
11391}
11392
11393pub enum Candidates {
11394    /// Only consider directories.
11395    Directories,
11396    /// Only consider files.
11397    Files,
11398    /// Consider directories and files.
11399    Entries,
11400}
11401
11402impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
11403    type Candidates = PathMatchCandidateSetIter<'a>;
11404
11405    fn id(&self) -> usize {
11406        self.snapshot.id().to_usize()
11407    }
11408
11409    fn len(&self) -> usize {
11410        if self.include_ignored {
11411            self.snapshot.file_count()
11412        } else {
11413            self.snapshot.visible_file_count()
11414        }
11415    }
11416
11417    fn prefix(&self) -> Arc<str> {
11418        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
11419            self.snapshot.root_name().into()
11420        } else if self.include_root_name {
11421            format!("{}/", self.snapshot.root_name()).into()
11422        } else {
11423            "".into()
11424        }
11425    }
11426
11427    fn candidates(&'a self, start: usize) -> Self::Candidates {
11428        PathMatchCandidateSetIter {
11429            traversal: match self.candidates {
11430                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
11431                Candidates::Files => self.snapshot.files(self.include_ignored, start),
11432                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
11433            },
11434        }
11435    }
11436}
11437
11438pub struct PathMatchCandidateSetIter<'a> {
11439    traversal: Traversal<'a>,
11440}
11441
11442impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
11443    type Item = fuzzy::PathMatchCandidate<'a>;
11444
11445    fn next(&mut self) -> Option<Self::Item> {
11446        self.traversal.next().map(|entry| match entry.kind {
11447            EntryKind::Dir => fuzzy::PathMatchCandidate {
11448                path: &entry.path,
11449                char_bag: CharBag::from_iter(entry.path.to_string_lossy().to_lowercase().chars()),
11450            },
11451            EntryKind::File(char_bag) => fuzzy::PathMatchCandidate {
11452                path: &entry.path,
11453                char_bag,
11454            },
11455            EntryKind::UnloadedDir | EntryKind::PendingDir => unreachable!(),
11456        })
11457    }
11458}
11459
11460impl EventEmitter<Event> for Project {}
11461
11462impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
11463    fn into(self) -> SettingsLocation<'a> {
11464        SettingsLocation {
11465            worktree_id: self.worktree_id.to_usize(),
11466            path: self.path.as_ref(),
11467        }
11468    }
11469}
11470
11471impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
11472    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
11473        Self {
11474            worktree_id,
11475            path: path.as_ref().into(),
11476        }
11477    }
11478}
11479
11480pub struct ProjectLspAdapterDelegate {
11481    project: WeakModel<Project>,
11482    worktree: worktree::Snapshot,
11483    fs: Arc<dyn Fs>,
11484    http_client: Arc<dyn HttpClient>,
11485    language_registry: Arc<LanguageRegistry>,
11486    shell_env: Mutex<Option<HashMap<String, String>>>,
11487}
11488
11489impl ProjectLspAdapterDelegate {
11490    pub fn new(
11491        project: &Project,
11492        worktree: &Model<Worktree>,
11493        cx: &ModelContext<Project>,
11494    ) -> Arc<Self> {
11495        Arc::new(Self {
11496            project: cx.weak_model(),
11497            worktree: worktree.read(cx).snapshot(),
11498            fs: project.fs.clone(),
11499            http_client: project.client.http_client(),
11500            language_registry: project.languages.clone(),
11501            shell_env: Default::default(),
11502        })
11503    }
11504
11505    async fn load_shell_env(&self) {
11506        let worktree_abs_path = self.worktree.abs_path();
11507        let shell_env = load_shell_environment(&worktree_abs_path)
11508            .await
11509            .with_context(|| {
11510                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
11511            })
11512            .log_err()
11513            .unwrap_or_default();
11514        *self.shell_env.lock() = Some(shell_env);
11515    }
11516}
11517
11518#[async_trait]
11519impl LspAdapterDelegate for ProjectLspAdapterDelegate {
11520    fn show_notification(&self, message: &str, cx: &mut AppContext) {
11521        self.project
11522            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
11523            .ok();
11524    }
11525
11526    fn http_client(&self) -> Arc<dyn HttpClient> {
11527        self.http_client.clone()
11528    }
11529
11530    fn worktree_id(&self) -> u64 {
11531        self.worktree.id().to_proto()
11532    }
11533
11534    fn worktree_root_path(&self) -> &Path {
11535        self.worktree.abs_path().as_ref()
11536    }
11537
11538    async fn shell_env(&self) -> HashMap<String, String> {
11539        self.load_shell_env().await;
11540        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
11541    }
11542
11543    #[cfg(not(target_os = "windows"))]
11544    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11545        let worktree_abs_path = self.worktree.abs_path();
11546        self.load_shell_env().await;
11547        let shell_path = self
11548            .shell_env
11549            .lock()
11550            .as_ref()
11551            .and_then(|shell_env| shell_env.get("PATH").cloned());
11552        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
11553    }
11554
11555    #[cfg(target_os = "windows")]
11556    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
11557        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
11558        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
11559        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
11560        which::which(command).ok()
11561    }
11562
11563    fn update_status(
11564        &self,
11565        server_name: LanguageServerName,
11566        status: language::LanguageServerBinaryStatus,
11567    ) {
11568        self.language_registry
11569            .update_lsp_status(server_name, status);
11570    }
11571
11572    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
11573        if self.worktree.entry_for_path(&path).is_none() {
11574            return Err(anyhow!("no such path {path:?}"));
11575        }
11576        let path = self.worktree.absolutize(path.as_ref())?;
11577        let content = self.fs.load(&path).await?;
11578        Ok(content)
11579    }
11580}
11581
11582fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
11583    proto::Symbol {
11584        language_server_name: symbol.language_server_name.0.to_string(),
11585        source_worktree_id: symbol.source_worktree_id.to_proto(),
11586        worktree_id: symbol.path.worktree_id.to_proto(),
11587        path: symbol.path.path.to_string_lossy().to_string(),
11588        name: symbol.name.clone(),
11589        kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
11590        start: Some(proto::PointUtf16 {
11591            row: symbol.range.start.0.row,
11592            column: symbol.range.start.0.column,
11593        }),
11594        end: Some(proto::PointUtf16 {
11595            row: symbol.range.end.0.row,
11596            column: symbol.range.end.0.column,
11597        }),
11598        signature: symbol.signature.to_vec(),
11599    }
11600}
11601
11602fn relativize_path(base: &Path, path: &Path) -> PathBuf {
11603    let mut path_components = path.components();
11604    let mut base_components = base.components();
11605    let mut components: Vec<Component> = Vec::new();
11606    loop {
11607        match (path_components.next(), base_components.next()) {
11608            (None, None) => break,
11609            (Some(a), None) => {
11610                components.push(a);
11611                components.extend(path_components.by_ref());
11612                break;
11613            }
11614            (None, _) => components.push(Component::ParentDir),
11615            (Some(a), Some(b)) if components.is_empty() && a == b => (),
11616            (Some(a), Some(Component::CurDir)) => components.push(a),
11617            (Some(a), Some(_)) => {
11618                components.push(Component::ParentDir);
11619                for _ in base_components {
11620                    components.push(Component::ParentDir);
11621                }
11622                components.push(a);
11623                components.extend(path_components.by_ref());
11624                break;
11625            }
11626        }
11627    }
11628    components.iter().map(|c| c.as_os_str()).collect()
11629}
11630
11631fn resolve_path(base: &Path, path: &Path) -> PathBuf {
11632    let mut result = base.to_path_buf();
11633    for component in path.components() {
11634        match component {
11635            Component::ParentDir => {
11636                result.pop();
11637            }
11638            Component::CurDir => (),
11639            _ => result.push(component),
11640        }
11641    }
11642    result
11643}
11644
11645impl Item for Buffer {
11646    fn try_open(
11647        project: &Model<Project>,
11648        path: &ProjectPath,
11649        cx: &mut AppContext,
11650    ) -> Option<Task<Result<Model<Self>>>> {
11651        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
11652    }
11653
11654    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
11655        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
11656    }
11657
11658    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
11659        File::from_dyn(self.file()).map(|file| ProjectPath {
11660            worktree_id: file.worktree_id(cx),
11661            path: file.path().clone(),
11662        })
11663    }
11664}
11665
11666impl Completion {
11667    /// A key that can be used to sort completions when displaying
11668    /// them to the user.
11669    pub fn sort_key(&self) -> (usize, &str) {
11670        let kind_key = match self.lsp_completion.kind {
11671            Some(lsp::CompletionItemKind::KEYWORD) => 0,
11672            Some(lsp::CompletionItemKind::VARIABLE) => 1,
11673            _ => 2,
11674        };
11675        (kind_key, &self.label.text[self.label.filter_range.clone()])
11676    }
11677
11678    /// Whether this completion is a snippet.
11679    pub fn is_snippet(&self) -> bool {
11680        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
11681    }
11682}
11683
11684async fn wait_for_loading_buffer(
11685    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
11686) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
11687    loop {
11688        if let Some(result) = receiver.borrow().as_ref() {
11689            match result {
11690                Ok(buffer) => return Ok(buffer.to_owned()),
11691                Err(e) => return Err(e.to_owned()),
11692            }
11693        }
11694        receiver.next().await;
11695    }
11696}
11697
11698fn is_not_found_error(error: &anyhow::Error) -> bool {
11699    error
11700        .root_cause()
11701        .downcast_ref::<io::Error>()
11702        .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
11703}
11704
11705fn include_text(server: &lsp::LanguageServer) -> bool {
11706    server
11707        .capabilities()
11708        .text_document_sync
11709        .as_ref()
11710        .and_then(|sync| match sync {
11711            lsp::TextDocumentSyncCapability::Kind(_) => None,
11712            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
11713        })
11714        .and_then(|save_options| match save_options {
11715            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
11716            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
11717        })
11718        .unwrap_or(false)
11719}
11720
11721async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
11722    let marker = "ZED_SHELL_START";
11723    let shell = env::var("SHELL").context(
11724        "SHELL environment variable is not assigned so we can't source login environment variables",
11725    )?;
11726
11727    // What we're doing here is to spawn a shell and then `cd` into
11728    // the project directory to get the env in there as if the user
11729    // `cd`'d into it. We do that because tools like direnv, asdf, ...
11730    // hook into `cd` and only set up the env after that.
11731    //
11732    // In certain shells we need to execute additional_command in order to
11733    // trigger the behavior of direnv, etc.
11734    //
11735    //
11736    // The `exit 0` is the result of hours of debugging, trying to find out
11737    // why running this command here, without `exit 0`, would mess
11738    // up signal process for our process so that `ctrl-c` doesn't work
11739    // anymore.
11740    //
11741    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
11742    // do that, but it does, and `exit 0` helps.
11743    let additional_command = PathBuf::from(&shell)
11744        .file_name()
11745        .and_then(|f| f.to_str())
11746        .and_then(|shell| match shell {
11747            "fish" => Some("emit fish_prompt;"),
11748            _ => None,
11749        });
11750
11751    let command = format!(
11752        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
11753        dir.display(),
11754        additional_command.unwrap_or("")
11755    );
11756
11757    let output = smol::process::Command::new(&shell)
11758        .args(["-i", "-c", &command])
11759        .output()
11760        .await
11761        .context("failed to spawn login shell to source login environment variables")?;
11762
11763    anyhow::ensure!(
11764        output.status.success(),
11765        "login shell exited with error {:?}",
11766        output.status
11767    );
11768
11769    let stdout = String::from_utf8_lossy(&output.stdout);
11770    let env_output_start = stdout.find(marker).ok_or_else(|| {
11771        anyhow!(
11772            "failed to parse output of `env` command in login shell: {}",
11773            stdout
11774        )
11775    })?;
11776
11777    let mut parsed_env = HashMap::default();
11778    let env_output = &stdout[env_output_start + marker.len()..];
11779
11780    parse_env_output(env_output, |key, value| {
11781        parsed_env.insert(key, value);
11782    });
11783
11784    Ok(parsed_env)
11785}
11786
11787fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
11788    let entries = blame
11789        .entries
11790        .into_iter()
11791        .map(|entry| proto::BlameEntry {
11792            sha: entry.sha.as_bytes().into(),
11793            start_line: entry.range.start,
11794            end_line: entry.range.end,
11795            original_line_number: entry.original_line_number,
11796            author: entry.author.clone(),
11797            author_mail: entry.author_mail.clone(),
11798            author_time: entry.author_time,
11799            author_tz: entry.author_tz.clone(),
11800            committer: entry.committer.clone(),
11801            committer_mail: entry.committer_mail.clone(),
11802            committer_time: entry.committer_time,
11803            committer_tz: entry.committer_tz.clone(),
11804            summary: entry.summary.clone(),
11805            previous: entry.previous.clone(),
11806            filename: entry.filename.clone(),
11807        })
11808        .collect::<Vec<_>>();
11809
11810    let messages = blame
11811        .messages
11812        .into_iter()
11813        .map(|(oid, message)| proto::CommitMessage {
11814            oid: oid.as_bytes().into(),
11815            message,
11816        })
11817        .collect::<Vec<_>>();
11818
11819    let permalinks = blame
11820        .permalinks
11821        .into_iter()
11822        .map(|(oid, url)| proto::CommitPermalink {
11823            oid: oid.as_bytes().into(),
11824            permalink: url.to_string(),
11825        })
11826        .collect::<Vec<_>>();
11827
11828    proto::BlameBufferResponse {
11829        entries,
11830        messages,
11831        permalinks,
11832        remote_url: blame.remote_url,
11833    }
11834}
11835
11836fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
11837    let entries = response
11838        .entries
11839        .into_iter()
11840        .filter_map(|entry| {
11841            Some(git::blame::BlameEntry {
11842                sha: git::Oid::from_bytes(&entry.sha).ok()?,
11843                range: entry.start_line..entry.end_line,
11844                original_line_number: entry.original_line_number,
11845                committer: entry.committer,
11846                committer_time: entry.committer_time,
11847                committer_tz: entry.committer_tz,
11848                committer_mail: entry.committer_mail,
11849                author: entry.author,
11850                author_mail: entry.author_mail,
11851                author_time: entry.author_time,
11852                author_tz: entry.author_tz,
11853                summary: entry.summary,
11854                previous: entry.previous,
11855                filename: entry.filename,
11856            })
11857        })
11858        .collect::<Vec<_>>();
11859
11860    let messages = response
11861        .messages
11862        .into_iter()
11863        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
11864        .collect::<HashMap<_, _>>();
11865
11866    let permalinks = response
11867        .permalinks
11868        .into_iter()
11869        .filter_map(|permalink| {
11870            Some((
11871                git::Oid::from_bytes(&permalink.oid).ok()?,
11872                Url::from_str(&permalink.permalink).ok()?,
11873            ))
11874        })
11875        .collect::<HashMap<_, _>>();
11876
11877    Blame {
11878        entries,
11879        permalinks,
11880        messages,
11881        remote_url: response.remote_url,
11882    }
11883}
11884
11885fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
11886    hover
11887        .contents
11888        .retain(|hover_block| !hover_block.text.trim().is_empty());
11889    if hover.contents.is_empty() {
11890        None
11891    } else {
11892        Some(hover)
11893    }
11894}
11895
11896#[derive(Debug)]
11897pub struct NoRepositoryError {}
11898
11899impl std::fmt::Display for NoRepositoryError {
11900    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11901        write!(f, "no git repository for worktree found")
11902    }
11903}
11904
11905impl std::error::Error for NoRepositoryError {}
11906
11907fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
11908    proto::Location {
11909        buffer_id: location.buffer.read(cx).remote_id().into(),
11910        start: Some(serialize_anchor(&location.range.start)),
11911        end: Some(serialize_anchor(&location.range.end)),
11912    }
11913}
11914
11915fn deserialize_location(
11916    project: &Model<Project>,
11917    location: proto::Location,
11918    cx: &mut AppContext,
11919) -> Task<Result<Location>> {
11920    let buffer_id = match BufferId::new(location.buffer_id) {
11921        Ok(id) => id,
11922        Err(e) => return Task::ready(Err(e)),
11923    };
11924    let buffer_task = project.update(cx, |project, cx| {
11925        project.wait_for_remote_buffer(buffer_id, cx)
11926    });
11927    cx.spawn(|_| async move {
11928        let buffer = buffer_task.await?;
11929        let start = location
11930            .start
11931            .and_then(deserialize_anchor)
11932            .context("missing task context location start")?;
11933        let end = location
11934            .end
11935            .and_then(deserialize_anchor)
11936            .context("missing task context location end")?;
11937        Ok(Location {
11938            buffer,
11939            range: start..end,
11940        })
11941    })
11942}
11943
11944#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
11945pub struct DiagnosticSummary {
11946    pub error_count: usize,
11947    pub warning_count: usize,
11948}
11949
11950impl DiagnosticSummary {
11951    pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
11952        let mut this = Self {
11953            error_count: 0,
11954            warning_count: 0,
11955        };
11956
11957        for entry in diagnostics {
11958            if entry.diagnostic.is_primary {
11959                match entry.diagnostic.severity {
11960                    DiagnosticSeverity::ERROR => this.error_count += 1,
11961                    DiagnosticSeverity::WARNING => this.warning_count += 1,
11962                    _ => {}
11963                }
11964            }
11965        }
11966
11967        this
11968    }
11969
11970    pub fn is_empty(&self) -> bool {
11971        self.error_count == 0 && self.warning_count == 0
11972    }
11973
11974    pub fn to_proto(
11975        &self,
11976        language_server_id: LanguageServerId,
11977        path: &Path,
11978    ) -> proto::DiagnosticSummary {
11979        proto::DiagnosticSummary {
11980            path: path.to_string_lossy().to_string(),
11981            language_server_id: language_server_id.0 as u64,
11982            error_count: self.error_count as u32,
11983            warning_count: self.warning_count as u32,
11984        }
11985    }
11986}
11987
11988pub fn sort_worktree_entries(entries: &mut Vec<Entry>) {
11989    entries.sort_by(|entry_a, entry_b| {
11990        compare_paths(
11991            (&entry_a.path, entry_a.is_file()),
11992            (&entry_b.path, entry_b.is_file()),
11993        )
11994    });
11995}
11996
11997fn sort_search_matches(search_matches: &mut Vec<SearchMatchCandidate>, cx: &AppContext) {
11998    search_matches.sort_by(|entry_a, entry_b| match (entry_a, entry_b) {
11999        (
12000            SearchMatchCandidate::OpenBuffer {
12001                buffer: buffer_a,
12002                path: None,
12003            },
12004            SearchMatchCandidate::OpenBuffer {
12005                buffer: buffer_b,
12006                path: None,
12007            },
12008        ) => buffer_a
12009            .read(cx)
12010            .remote_id()
12011            .cmp(&buffer_b.read(cx).remote_id()),
12012        (
12013            SearchMatchCandidate::OpenBuffer { path: None, .. },
12014            SearchMatchCandidate::Path { .. }
12015            | SearchMatchCandidate::OpenBuffer { path: Some(_), .. },
12016        ) => Ordering::Less,
12017        (
12018            SearchMatchCandidate::OpenBuffer { path: Some(_), .. }
12019            | SearchMatchCandidate::Path { .. },
12020            SearchMatchCandidate::OpenBuffer { path: None, .. },
12021        ) => Ordering::Greater,
12022        (
12023            SearchMatchCandidate::OpenBuffer {
12024                path: Some(path_a), ..
12025            },
12026            SearchMatchCandidate::Path {
12027                is_file: is_file_b,
12028                path: path_b,
12029                ..
12030            },
12031        ) => compare_paths((path_a.as_ref(), true), (path_b.as_ref(), *is_file_b)),
12032        (
12033            SearchMatchCandidate::Path {
12034                is_file: is_file_a,
12035                path: path_a,
12036                ..
12037            },
12038            SearchMatchCandidate::OpenBuffer {
12039                path: Some(path_b), ..
12040            },
12041        ) => compare_paths((path_a.as_ref(), *is_file_a), (path_b.as_ref(), true)),
12042        (
12043            SearchMatchCandidate::OpenBuffer {
12044                path: Some(path_a), ..
12045            },
12046            SearchMatchCandidate::OpenBuffer {
12047                path: Some(path_b), ..
12048            },
12049        ) => compare_paths((path_a.as_ref(), true), (path_b.as_ref(), true)),
12050        (
12051            SearchMatchCandidate::Path {
12052                worktree_id: worktree_id_a,
12053                is_file: is_file_a,
12054                path: path_a,
12055                ..
12056            },
12057            SearchMatchCandidate::Path {
12058                worktree_id: worktree_id_b,
12059                is_file: is_file_b,
12060                path: path_b,
12061                ..
12062            },
12063        ) => worktree_id_a.cmp(&worktree_id_b).then_with(|| {
12064            compare_paths((path_a.as_ref(), *is_file_a), (path_b.as_ref(), *is_file_b))
12065        }),
12066    });
12067}
12068
12069fn compare_paths(
12070    (path_a, a_is_file): (&Path, bool),
12071    (path_b, b_is_file): (&Path, bool),
12072) -> cmp::Ordering {
12073    let mut components_a = path_a.components().peekable();
12074    let mut components_b = path_b.components().peekable();
12075    loop {
12076        match (components_a.next(), components_b.next()) {
12077            (Some(component_a), Some(component_b)) => {
12078                let a_is_file = components_a.peek().is_none() && a_is_file;
12079                let b_is_file = components_b.peek().is_none() && b_is_file;
12080                let ordering = a_is_file.cmp(&b_is_file).then_with(|| {
12081                    let maybe_numeric_ordering = maybe!({
12082                        let num_and_remainder_a = Path::new(component_a.as_os_str())
12083                            .file_stem()
12084                            .and_then(|s| s.to_str())
12085                            .and_then(NumericPrefixWithSuffix::from_numeric_prefixed_str)?;
12086                        let num_and_remainder_b = Path::new(component_b.as_os_str())
12087                            .file_stem()
12088                            .and_then(|s| s.to_str())
12089                            .and_then(NumericPrefixWithSuffix::from_numeric_prefixed_str)?;
12090
12091                        num_and_remainder_a.partial_cmp(&num_and_remainder_b)
12092                    });
12093
12094                    maybe_numeric_ordering.unwrap_or_else(|| {
12095                        let name_a = UniCase::new(component_a.as_os_str().to_string_lossy());
12096                        let name_b = UniCase::new(component_b.as_os_str().to_string_lossy());
12097
12098                        name_a.cmp(&name_b)
12099                    })
12100                });
12101                if !ordering.is_eq() {
12102                    return ordering;
12103                }
12104            }
12105            (Some(_), None) => break cmp::Ordering::Greater,
12106            (None, Some(_)) => break cmp::Ordering::Less,
12107            (None, None) => break cmp::Ordering::Equal,
12108        }
12109    }
12110}