project.rs

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