project.rs

   1pub mod buffer_store;
   2pub mod connection_manager;
   3pub mod debounced_delay;
   4pub mod lsp_command;
   5pub mod lsp_ext_command;
   6pub mod lsp_store;
   7mod prettier_support;
   8pub mod project_settings;
   9pub mod search;
  10mod task_inventory;
  11pub mod terminals;
  12pub mod worktree_store;
  13
  14#[cfg(test)]
  15mod project_tests;
  16
  17mod environment;
  18pub mod search_history;
  19mod yarn;
  20
  21use anyhow::{anyhow, Context as _, Result};
  22use buffer_store::{BufferStore, BufferStoreEvent};
  23use client::{
  24    proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
  25    TypedEnvelope, UserStore,
  26};
  27use clock::ReplicaId;
  28use collections::{BTreeSet, HashMap, HashSet};
  29use debounced_delay::DebouncedDelay;
  30pub use environment::ProjectEnvironment;
  31use futures::{
  32    channel::mpsc::{self, UnboundedReceiver},
  33    future::try_join_all,
  34    stream::FuturesUnordered,
  35    AsyncWriteExt, FutureExt, StreamExt,
  36};
  37
  38use git::{blame::Blame, repository::GitRepository};
  39use gpui::{
  40    AnyModel, AppContext, AsyncAppContext, BorrowAppContext, Context, Entity, EventEmitter, Model,
  41    ModelContext, SharedString, Task, WeakModel, WindowContext,
  42};
  43use itertools::Itertools;
  44use language::{
  45    language_settings::{
  46        language_settings, FormatOnSave, Formatter, InlayHintKind, LanguageSettings,
  47        SelectedFormatter,
  48    },
  49    proto::{
  50        deserialize_anchor, serialize_anchor, serialize_line_ending, serialize_version,
  51        split_operations,
  52    },
  53    Buffer, CachedLspAdapter, Capability, CodeLabel, ContextProvider, DiagnosticEntry, Diff,
  54    Documentation, Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName,
  55    PointUtf16, ToOffset, ToPointUtf16, Transaction, Unclipped,
  56};
  57use lsp::{CompletionContext, DocumentHighlightKind, LanguageServer, LanguageServerId};
  58use lsp_command::*;
  59use node_runtime::NodeRuntime;
  60use parking_lot::{Mutex, RwLock};
  61use paths::{local_tasks_file_relative_path, local_vscode_tasks_file_relative_path};
  62use prettier_support::{DefaultPrettier, PrettierInstance};
  63use project_settings::{LspSettings, ProjectSettings, SettingsObserver};
  64use remote::SshSession;
  65use rpc::{
  66    proto::{AnyProtoClient, SSH_PROJECT_ID},
  67    ErrorCode,
  68};
  69use search::{SearchInputKind, SearchQuery, SearchResult};
  70use search_history::SearchHistory;
  71use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
  72use smol::channel::Receiver;
  73use snippet::Snippet;
  74use snippet_provider::SnippetProvider;
  75use std::{
  76    borrow::Cow,
  77    ops::Range,
  78    path::{Component, Path, PathBuf},
  79    str,
  80    sync::Arc,
  81    time::Duration,
  82};
  83use task::{
  84    static_source::{StaticSource, TrackedFile},
  85    HideStrategy, RevealStrategy, Shell, TaskContext, TaskTemplate, TaskVariables, VariableName,
  86};
  87use terminals::Terminals;
  88use text::{Anchor, BufferId};
  89use util::{defer, paths::compare_paths, ResultExt as _};
  90use worktree::{CreatedEntry, Snapshot, Traversal};
  91use worktree_store::{WorktreeStore, WorktreeStoreEvent};
  92
  93pub use fs::*;
  94pub use language::Location;
  95#[cfg(any(test, feature = "test-support"))]
  96pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  97pub use task_inventory::{
  98    BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
  99};
 100pub use worktree::{
 101    Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, RepositoryEntry,
 102    UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
 103    FS_WATCH_LATENCY,
 104};
 105
 106pub use buffer_store::ProjectTransaction;
 107pub use lsp_store::{
 108    DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
 109    LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
 110    ProjectLspAdapterDelegate, SERVER_PROGRESS_THROTTLE_TIMEOUT,
 111};
 112
 113const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
 114const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 115const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 116
 117pub trait Item {
 118    fn try_open(
 119        project: &Model<Project>,
 120        path: &ProjectPath,
 121        cx: &mut AppContext,
 122    ) -> Option<Task<Result<Model<Self>>>>
 123    where
 124        Self: Sized;
 125    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
 126    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 127}
 128
 129#[derive(Clone)]
 130pub enum OpenedBufferEvent {
 131    Disconnected,
 132    Ok(BufferId),
 133    Err(BufferId, Arc<anyhow::Error>),
 134}
 135
 136/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
 137/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
 138/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
 139///
 140/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
 141pub struct Project {
 142    active_entry: Option<ProjectEntryId>,
 143    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 144    languages: Arc<LanguageRegistry>,
 145    client: Arc<client::Client>,
 146    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
 147    join_project_response_message_id: u32,
 148    user_store: Model<UserStore>,
 149    fs: Arc<dyn Fs>,
 150    ssh_session: Option<Arc<SshSession>>,
 151    client_state: ProjectClientState,
 152    collaborators: HashMap<proto::PeerId, Collaborator>,
 153    client_subscriptions: Vec<client::Subscription>,
 154    worktree_store: Model<WorktreeStore>,
 155    buffer_store: Model<BufferStore>,
 156    lsp_store: Model<LspStore>,
 157    _subscriptions: Vec<gpui::Subscription>,
 158    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
 159    git_diff_debouncer: DebouncedDelay<Self>,
 160    remotely_created_buffers: Arc<Mutex<RemotelyCreatedBuffers>>,
 161    terminals: Terminals,
 162    node: Option<Arc<dyn NodeRuntime>>,
 163    default_prettier: DefaultPrettier,
 164    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
 165    prettier_instances: HashMap<PathBuf, PrettierInstance>,
 166    tasks: Model<Inventory>,
 167    hosted_project_id: Option<ProjectId>,
 168    dev_server_project_id: Option<client::DevServerProjectId>,
 169    search_history: SearchHistory,
 170    search_included_history: SearchHistory,
 171    search_excluded_history: SearchHistory,
 172    snippets: Model<SnippetProvider>,
 173    last_formatting_failure: Option<String>,
 174    buffers_being_formatted: HashSet<BufferId>,
 175    environment: Model<ProjectEnvironment>,
 176    settings_observer: Model<SettingsObserver>,
 177}
 178
 179#[derive(Default)]
 180struct RemotelyCreatedBuffers {
 181    buffers: Vec<Model<Buffer>>,
 182    retain_count: usize,
 183}
 184
 185struct RemotelyCreatedBufferGuard {
 186    remote_buffers: std::sync::Weak<Mutex<RemotelyCreatedBuffers>>,
 187}
 188
 189impl Drop for RemotelyCreatedBufferGuard {
 190    fn drop(&mut self) {
 191        if let Some(remote_buffers) = self.remote_buffers.upgrade() {
 192            let mut remote_buffers = remote_buffers.lock();
 193            assert!(
 194                remote_buffers.retain_count > 0,
 195                "RemotelyCreatedBufferGuard dropped too many times"
 196            );
 197            remote_buffers.retain_count -= 1;
 198            if remote_buffers.retain_count == 0 {
 199                remote_buffers.buffers.clear();
 200            }
 201        }
 202    }
 203}
 204/// Message ordered with respect to buffer operations
 205#[derive(Debug)]
 206enum BufferOrderedMessage {
 207    Operation {
 208        buffer_id: BufferId,
 209        operation: proto::Operation,
 210    },
 211    LanguageServerUpdate {
 212        language_server_id: LanguageServerId,
 213        message: proto::update_language_server::Variant,
 214    },
 215    Resync,
 216}
 217
 218#[derive(Debug)]
 219enum ProjectClientState {
 220    Local,
 221    Shared {
 222        remote_id: u64,
 223    },
 224    Remote {
 225        sharing_has_stopped: bool,
 226        capability: Capability,
 227        remote_id: u64,
 228        replica_id: ReplicaId,
 229        in_room: bool,
 230    },
 231}
 232
 233#[derive(Clone, Debug, PartialEq)]
 234pub enum Event {
 235    LanguageServerAdded(LanguageServerId),
 236    LanguageServerRemoved(LanguageServerId),
 237    LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
 238    Notification(String),
 239    LanguageServerPrompt(LanguageServerPromptRequest),
 240    LanguageNotFound(Model<Buffer>),
 241    ActiveEntryChanged(Option<ProjectEntryId>),
 242    ActivateProjectPanel,
 243    WorktreeAdded,
 244    WorktreeOrderChanged,
 245    WorktreeRemoved(WorktreeId),
 246    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 247    WorktreeUpdatedGitRepositories,
 248    DiskBasedDiagnosticsStarted {
 249        language_server_id: LanguageServerId,
 250    },
 251    DiskBasedDiagnosticsFinished {
 252        language_server_id: LanguageServerId,
 253    },
 254    DiagnosticsUpdated {
 255        path: ProjectPath,
 256        language_server_id: LanguageServerId,
 257    },
 258    RemoteIdChanged(Option<u64>),
 259    DisconnectedFromHost,
 260    Closed,
 261    DeletedEntry(ProjectEntryId),
 262    CollaboratorUpdated {
 263        old_peer_id: proto::PeerId,
 264        new_peer_id: proto::PeerId,
 265    },
 266    CollaboratorJoined(proto::PeerId),
 267    CollaboratorLeft(proto::PeerId),
 268    HostReshared,
 269    Reshared,
 270    Rejoined,
 271    RefreshInlayHints,
 272    RevealInProjectPanel(ProjectEntryId),
 273    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
 274}
 275
 276#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 277pub struct ProjectPath {
 278    pub worktree_id: WorktreeId,
 279    pub path: Arc<Path>,
 280}
 281
 282impl ProjectPath {
 283    pub fn from_proto(p: proto::ProjectPath) -> Self {
 284        Self {
 285            worktree_id: WorktreeId::from_proto(p.worktree_id),
 286            path: Arc::from(PathBuf::from(p.path)),
 287        }
 288    }
 289
 290    pub fn to_proto(&self) -> proto::ProjectPath {
 291        proto::ProjectPath {
 292            worktree_id: self.worktree_id.to_proto(),
 293            path: self.path.to_string_lossy().to_string(),
 294        }
 295    }
 296}
 297
 298#[derive(Debug, Clone, PartialEq, Eq)]
 299pub struct InlayHint {
 300    pub position: language::Anchor,
 301    pub label: InlayHintLabel,
 302    pub kind: Option<InlayHintKind>,
 303    pub padding_left: bool,
 304    pub padding_right: bool,
 305    pub tooltip: Option<InlayHintTooltip>,
 306    pub resolve_state: ResolveState,
 307}
 308
 309/// The user's intent behind a given completion confirmation
 310#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
 311pub enum CompletionIntent {
 312    /// The user intends to 'commit' this result, if possible
 313    /// completion confirmations should run side effects
 314    Complete,
 315    /// The user intends to continue 'composing' this completion
 316    /// completion confirmations should not run side effects and
 317    /// let the user continue composing their action
 318    Compose,
 319}
 320
 321impl CompletionIntent {
 322    pub fn is_complete(&self) -> bool {
 323        self == &Self::Complete
 324    }
 325
 326    pub fn is_compose(&self) -> bool {
 327        self == &Self::Compose
 328    }
 329}
 330
 331/// A completion provided by a language server
 332#[derive(Clone)]
 333pub struct Completion {
 334    /// The range of the buffer that will be replaced.
 335    pub old_range: Range<Anchor>,
 336    /// The new text that will be inserted.
 337    pub new_text: String,
 338    /// A label for this completion that is shown in the menu.
 339    pub label: CodeLabel,
 340    /// The id of the language server that produced this completion.
 341    pub server_id: LanguageServerId,
 342    /// The documentation for this completion.
 343    pub documentation: Option<Documentation>,
 344    /// The raw completion provided by the language server.
 345    pub lsp_completion: lsp::CompletionItem,
 346    /// An optional callback to invoke when this completion is confirmed.
 347    /// Returns, whether new completions should be retriggered after the current one.
 348    /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
 349    /// if no confirmation is provided or `false` is returned, the completion will be committed.
 350    pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut WindowContext) -> bool>>,
 351}
 352
 353impl std::fmt::Debug for Completion {
 354    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 355        f.debug_struct("Completion")
 356            .field("old_range", &self.old_range)
 357            .field("new_text", &self.new_text)
 358            .field("label", &self.label)
 359            .field("server_id", &self.server_id)
 360            .field("documentation", &self.documentation)
 361            .field("lsp_completion", &self.lsp_completion)
 362            .finish()
 363    }
 364}
 365
 366/// A completion provided by a language server
 367#[derive(Clone, Debug)]
 368pub(crate) struct CoreCompletion {
 369    old_range: Range<Anchor>,
 370    new_text: String,
 371    server_id: LanguageServerId,
 372    lsp_completion: lsp::CompletionItem,
 373}
 374
 375/// A code action provided by a language server.
 376#[derive(Clone, Debug)]
 377pub struct CodeAction {
 378    /// The id of the language server that produced this code action.
 379    pub server_id: LanguageServerId,
 380    /// The range of the buffer where this code action is applicable.
 381    pub range: Range<Anchor>,
 382    /// The raw code action provided by the language server.
 383    pub lsp_action: lsp::CodeAction,
 384}
 385
 386#[derive(Debug, Clone, PartialEq, Eq)]
 387pub enum ResolveState {
 388    Resolved,
 389    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 390    Resolving,
 391}
 392
 393impl InlayHint {
 394    pub fn text(&self) -> String {
 395        match &self.label {
 396            InlayHintLabel::String(s) => s.to_owned(),
 397            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 398        }
 399    }
 400}
 401
 402#[derive(Debug, Clone, PartialEq, Eq)]
 403pub enum InlayHintLabel {
 404    String(String),
 405    LabelParts(Vec<InlayHintLabelPart>),
 406}
 407
 408#[derive(Debug, Clone, PartialEq, Eq)]
 409pub struct InlayHintLabelPart {
 410    pub value: String,
 411    pub tooltip: Option<InlayHintLabelPartTooltip>,
 412    pub location: Option<(LanguageServerId, lsp::Location)>,
 413}
 414
 415#[derive(Debug, Clone, PartialEq, Eq)]
 416pub enum InlayHintTooltip {
 417    String(String),
 418    MarkupContent(MarkupContent),
 419}
 420
 421#[derive(Debug, Clone, PartialEq, Eq)]
 422pub enum InlayHintLabelPartTooltip {
 423    String(String),
 424    MarkupContent(MarkupContent),
 425}
 426
 427#[derive(Debug, Clone, PartialEq, Eq)]
 428pub struct MarkupContent {
 429    pub kind: HoverBlockKind,
 430    pub value: String,
 431}
 432
 433#[derive(Debug, Clone)]
 434pub struct LocationLink {
 435    pub origin: Option<Location>,
 436    pub target: Location,
 437}
 438
 439#[derive(Debug)]
 440pub struct DocumentHighlight {
 441    pub range: Range<language::Anchor>,
 442    pub kind: DocumentHighlightKind,
 443}
 444
 445#[derive(Clone, Debug)]
 446pub struct Symbol {
 447    pub language_server_name: LanguageServerName,
 448    pub source_worktree_id: WorktreeId,
 449    pub path: ProjectPath,
 450    pub label: CodeLabel,
 451    pub name: String,
 452    pub kind: lsp::SymbolKind,
 453    pub range: Range<Unclipped<PointUtf16>>,
 454    pub signature: [u8; 32],
 455}
 456
 457#[derive(Clone, Debug, PartialEq)]
 458pub struct HoverBlock {
 459    pub text: String,
 460    pub kind: HoverBlockKind,
 461}
 462
 463#[derive(Clone, Debug, PartialEq, Eq)]
 464pub enum HoverBlockKind {
 465    PlainText,
 466    Markdown,
 467    Code { language: String },
 468}
 469
 470#[derive(Debug, Clone)]
 471pub struct Hover {
 472    pub contents: Vec<HoverBlock>,
 473    pub range: Option<Range<language::Anchor>>,
 474    pub language: Option<Arc<Language>>,
 475}
 476
 477impl Hover {
 478    pub fn is_empty(&self) -> bool {
 479        self.contents.iter().all(|block| block.text.is_empty())
 480    }
 481}
 482
 483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 484pub enum FormatTrigger {
 485    Save,
 486    Manual,
 487}
 488
 489// Currently, formatting operations are represented differently depending on
 490// whether they come from a language server or an external command.
 491#[derive(Debug)]
 492enum FormatOperation {
 493    Lsp(Vec<(Range<Anchor>, String)>),
 494    External(Diff),
 495    Prettier(Diff),
 496}
 497
 498impl FormatTrigger {
 499    fn from_proto(value: i32) -> FormatTrigger {
 500        match value {
 501            0 => FormatTrigger::Save,
 502            1 => FormatTrigger::Manual,
 503            _ => FormatTrigger::Save,
 504        }
 505    }
 506}
 507
 508enum EntitySubscription {
 509    Project(PendingEntitySubscription<Project>),
 510    BufferStore(PendingEntitySubscription<BufferStore>),
 511    WorktreeStore(PendingEntitySubscription<WorktreeStore>),
 512    LspStore(PendingEntitySubscription<LspStore>),
 513    SettingsObserver(PendingEntitySubscription<SettingsObserver>),
 514}
 515
 516#[derive(Clone)]
 517pub enum DirectoryLister {
 518    Project(Model<Project>),
 519    Local(Arc<dyn Fs>),
 520}
 521
 522impl DirectoryLister {
 523    pub fn is_local(&self, cx: &AppContext) -> bool {
 524        match self {
 525            DirectoryLister::Local(_) => true,
 526            DirectoryLister::Project(project) => project.read(cx).is_local_or_ssh(),
 527        }
 528    }
 529
 530    pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &AppContext) -> Cow<'a, str> {
 531        if self.is_local(cx) {
 532            shellexpand::tilde(path)
 533        } else {
 534            Cow::from(path)
 535        }
 536    }
 537
 538    pub fn default_query(&self, cx: &mut AppContext) -> String {
 539        if let DirectoryLister::Project(project) = self {
 540            if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
 541                return worktree.read(cx).abs_path().to_string_lossy().to_string();
 542            }
 543        };
 544        "~/".to_string()
 545    }
 546
 547    pub fn list_directory(&self, path: String, cx: &mut AppContext) -> Task<Result<Vec<PathBuf>>> {
 548        match self {
 549            DirectoryLister::Project(project) => {
 550                project.update(cx, |project, cx| project.list_directory(path, cx))
 551            }
 552            DirectoryLister::Local(fs) => {
 553                let fs = fs.clone();
 554                cx.background_executor().spawn(async move {
 555                    let mut results = vec![];
 556                    let expanded = shellexpand::tilde(&path);
 557                    let query = Path::new(expanded.as_ref());
 558                    let mut response = fs.read_dir(query).await?;
 559                    while let Some(path) = response.next().await {
 560                        if let Some(file_name) = path?.file_name() {
 561                            results.push(PathBuf::from(file_name.to_os_string()));
 562                        }
 563                    }
 564                    Ok(results)
 565                })
 566            }
 567        }
 568    }
 569}
 570
 571#[cfg(any(test, feature = "test-support"))]
 572pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
 573    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
 574    trigger_character: None,
 575};
 576
 577impl Project {
 578    pub fn init_settings(cx: &mut AppContext) {
 579        WorktreeSettings::register(cx);
 580        ProjectSettings::register(cx);
 581    }
 582
 583    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 584        connection_manager::init(client.clone(), cx);
 585        Self::init_settings(cx);
 586
 587        let client: AnyProtoClient = client.clone().into();
 588        client.add_model_message_handler(Self::handle_add_collaborator);
 589        client.add_model_message_handler(Self::handle_update_project_collaborator);
 590        client.add_model_message_handler(Self::handle_remove_collaborator);
 591        client.add_model_message_handler(Self::handle_update_project);
 592        client.add_model_message_handler(Self::handle_unshare_project);
 593        client.add_model_request_handler(Self::handle_update_buffer);
 594        client.add_model_message_handler(Self::handle_update_worktree);
 595        client.add_model_request_handler(Self::handle_reload_buffers);
 596        client.add_model_request_handler(Self::handle_synchronize_buffers);
 597        client.add_model_request_handler(Self::handle_format_buffers);
 598        client.add_model_request_handler(Self::handle_search_project);
 599        client.add_model_request_handler(Self::handle_search_candidate_buffers);
 600        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 601        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 602        client.add_model_request_handler(Self::handle_open_new_buffer);
 603        client.add_model_request_handler(Self::handle_task_context_for_location);
 604        client.add_model_request_handler(Self::handle_task_templates);
 605        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 606
 607        WorktreeStore::init(&client);
 608        BufferStore::init(&client);
 609        LspStore::init(&client);
 610        SettingsObserver::init(&client);
 611    }
 612
 613    pub fn local(
 614        client: Arc<Client>,
 615        node: Arc<dyn NodeRuntime>,
 616        user_store: Model<UserStore>,
 617        languages: Arc<LanguageRegistry>,
 618        fs: Arc<dyn Fs>,
 619        env: Option<HashMap<String, String>>,
 620        cx: &mut AppContext,
 621    ) -> Model<Self> {
 622        cx.new_model(|cx: &mut ModelContext<Self>| {
 623            let (tx, rx) = mpsc::unbounded();
 624            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 625                .detach();
 626            let tasks = Inventory::new(cx);
 627            let global_snippets_dir = paths::config_dir().join("snippets");
 628            let snippets =
 629                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
 630
 631            let worktree_store = cx.new_model(|_| WorktreeStore::new(false, fs.clone()));
 632            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 633                .detach();
 634
 635            let buffer_store =
 636                cx.new_model(|cx| BufferStore::new(worktree_store.clone(), None, cx));
 637            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 638                .detach();
 639
 640            let settings_observer = cx.new_model(|cx| {
 641                SettingsObserver::new_local(fs.clone(), worktree_store.clone(), cx)
 642            });
 643
 644            let environment = ProjectEnvironment::new(&worktree_store, env, cx);
 645            let lsp_store = cx.new_model(|cx| {
 646                LspStore::new_local(
 647                    buffer_store.clone(),
 648                    worktree_store.clone(),
 649                    environment.clone(),
 650                    languages.clone(),
 651                    Some(client.http_client()),
 652                    fs.clone(),
 653                    cx,
 654                )
 655            });
 656            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 657
 658            Self {
 659                buffer_ordered_messages_tx: tx,
 660                collaborators: Default::default(),
 661                worktree_store,
 662                buffer_store,
 663                lsp_store,
 664                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 665                join_project_response_message_id: 0,
 666                client_state: ProjectClientState::Local,
 667                client_subscriptions: Vec::new(),
 668                _subscriptions: vec![
 669                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
 670                    cx.on_release(Self::release),
 671                ],
 672                active_entry: None,
 673                snippets,
 674                languages,
 675                client,
 676                user_store,
 677                settings_observer,
 678                fs,
 679                ssh_session: None,
 680                buffers_needing_diff: Default::default(),
 681                git_diff_debouncer: DebouncedDelay::new(),
 682                terminals: Terminals {
 683                    local_handles: Vec::new(),
 684                },
 685                node: Some(node),
 686                default_prettier: DefaultPrettier::default(),
 687                prettiers_per_worktree: HashMap::default(),
 688                prettier_instances: HashMap::default(),
 689                tasks,
 690                hosted_project_id: None,
 691                dev_server_project_id: None,
 692                search_history: Self::new_search_history(),
 693                environment,
 694                remotely_created_buffers: Default::default(),
 695                last_formatting_failure: None,
 696                buffers_being_formatted: Default::default(),
 697                search_included_history: Self::new_search_history(),
 698                search_excluded_history: Self::new_search_history(),
 699            }
 700        })
 701    }
 702
 703    pub fn ssh(
 704        ssh: Arc<SshSession>,
 705        client: Arc<Client>,
 706        node: Arc<dyn NodeRuntime>,
 707        user_store: Model<UserStore>,
 708        languages: Arc<LanguageRegistry>,
 709        fs: Arc<dyn Fs>,
 710        cx: &mut AppContext,
 711    ) -> Model<Self> {
 712        cx.new_model(|cx: &mut ModelContext<Self>| {
 713            let (tx, rx) = mpsc::unbounded();
 714            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 715                .detach();
 716            let tasks = Inventory::new(cx);
 717            let global_snippets_dir = paths::config_dir().join("snippets");
 718            let snippets =
 719                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
 720
 721            let worktree_store = cx.new_model(|_| {
 722                let mut worktree_store = WorktreeStore::new(false, fs.clone());
 723                worktree_store.set_upstream_client(ssh.clone().into());
 724                worktree_store
 725            });
 726            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 727                .detach();
 728
 729            let buffer_store =
 730                cx.new_model(|cx| BufferStore::new(worktree_store.clone(), None, cx));
 731            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 732                .detach();
 733
 734            let settings_observer = cx.new_model(|cx| {
 735                SettingsObserver::new_ssh(ssh.clone().into(), worktree_store.clone(), cx)
 736            });
 737
 738            let environment = ProjectEnvironment::new(&worktree_store, None, cx);
 739            let lsp_store = cx.new_model(|cx| {
 740                LspStore::new_remote(
 741                    buffer_store.clone(),
 742                    worktree_store.clone(),
 743                    languages.clone(),
 744                    ssh.clone().into(),
 745                    0,
 746                    cx,
 747                )
 748            });
 749            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 750
 751            let this = Self {
 752                buffer_ordered_messages_tx: tx,
 753                collaborators: Default::default(),
 754                worktree_store,
 755                buffer_store,
 756                lsp_store,
 757                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 758                join_project_response_message_id: 0,
 759                client_state: ProjectClientState::Local,
 760                client_subscriptions: Vec::new(),
 761                _subscriptions: vec![
 762                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
 763                    cx.on_release(Self::release),
 764                ],
 765                active_entry: None,
 766                snippets,
 767                languages,
 768                client,
 769                user_store,
 770                settings_observer,
 771                fs,
 772                ssh_session: Some(ssh.clone()),
 773                buffers_needing_diff: Default::default(),
 774                git_diff_debouncer: DebouncedDelay::new(),
 775                terminals: Terminals {
 776                    local_handles: Vec::new(),
 777                },
 778                node: Some(node),
 779                default_prettier: DefaultPrettier::default(),
 780                prettiers_per_worktree: HashMap::default(),
 781                prettier_instances: HashMap::default(),
 782                tasks,
 783                hosted_project_id: None,
 784                dev_server_project_id: None,
 785                search_history: Self::new_search_history(),
 786                environment,
 787                remotely_created_buffers: Default::default(),
 788                last_formatting_failure: None,
 789                buffers_being_formatted: Default::default(),
 790                search_included_history: Self::new_search_history(),
 791                search_excluded_history: Self::new_search_history(),
 792            };
 793
 794            let client: AnyProtoClient = ssh.clone().into();
 795
 796            ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
 797            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
 798            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
 799            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
 800            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
 801            client.add_model_message_handler(Self::handle_update_worktree);
 802            client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 803            client.add_model_message_handler(BufferStore::handle_update_buffer_file);
 804            client.add_model_message_handler(BufferStore::handle_update_diff_base);
 805            LspStore::init(&client);
 806            SettingsObserver::init(&client);
 807
 808            this
 809        })
 810    }
 811
 812    pub async fn remote(
 813        remote_id: u64,
 814        client: Arc<Client>,
 815        user_store: Model<UserStore>,
 816        languages: Arc<LanguageRegistry>,
 817        fs: Arc<dyn Fs>,
 818        cx: AsyncAppContext,
 819    ) -> Result<Model<Self>> {
 820        let project =
 821            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
 822        cx.update(|cx| {
 823            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
 824                manager.maintain_project_connection(&project, cx)
 825            })
 826        })?;
 827        Ok(project)
 828    }
 829
 830    pub async fn in_room(
 831        remote_id: u64,
 832        client: Arc<Client>,
 833        user_store: Model<UserStore>,
 834        languages: Arc<LanguageRegistry>,
 835        fs: Arc<dyn Fs>,
 836        cx: AsyncAppContext,
 837    ) -> Result<Model<Self>> {
 838        client.authenticate_and_connect(true, &cx).await?;
 839
 840        let subscriptions = [
 841            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
 842            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
 843            EntitySubscription::WorktreeStore(
 844                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
 845            ),
 846            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
 847            EntitySubscription::SettingsObserver(
 848                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
 849            ),
 850        ];
 851        let response = client
 852            .request_envelope(proto::JoinProject {
 853                project_id: remote_id,
 854            })
 855            .await?;
 856        Self::from_join_project_response(
 857            response,
 858            subscriptions,
 859            client,
 860            user_store,
 861            languages,
 862            fs,
 863            cx,
 864        )
 865        .await
 866    }
 867
 868    async fn from_join_project_response(
 869        response: TypedEnvelope<proto::JoinProjectResponse>,
 870        subscriptions: [EntitySubscription; 5],
 871        client: Arc<Client>,
 872        user_store: Model<UserStore>,
 873        languages: Arc<LanguageRegistry>,
 874        fs: Arc<dyn Fs>,
 875        mut cx: AsyncAppContext,
 876    ) -> Result<Model<Self>> {
 877        let remote_id = response.payload.project_id;
 878        let role = response.payload.role();
 879
 880        let worktree_store = cx.new_model(|_| {
 881            let mut store = WorktreeStore::new(true, fs.clone());
 882            store.set_upstream_client(client.clone().into());
 883            if let Some(dev_server_project_id) = response.payload.dev_server_project_id {
 884                store.set_dev_server_project_id(DevServerProjectId(dev_server_project_id));
 885            }
 886            store
 887        })?;
 888        let buffer_store =
 889            cx.new_model(|cx| BufferStore::new(worktree_store.clone(), Some(remote_id), cx))?;
 890
 891        let lsp_store = cx.new_model(|cx| {
 892            let mut lsp_store = LspStore::new_remote(
 893                buffer_store.clone(),
 894                worktree_store.clone(),
 895                languages.clone(),
 896                client.clone().into(),
 897                remote_id,
 898                cx,
 899            );
 900            lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
 901            lsp_store
 902        })?;
 903
 904        let settings_observer =
 905            cx.new_model(|cx| SettingsObserver::new_remote(worktree_store.clone(), cx))?;
 906
 907        let this = cx.new_model(|cx| {
 908            let replica_id = response.payload.replica_id as ReplicaId;
 909            let tasks = Inventory::new(cx);
 910            let global_snippets_dir = paths::config_dir().join("snippets");
 911            let snippets =
 912                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
 913
 914            let mut worktrees = Vec::new();
 915            for worktree in response.payload.worktrees {
 916                let worktree =
 917                    Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
 918                worktrees.push(worktree);
 919            }
 920
 921            let (tx, rx) = mpsc::unbounded();
 922            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 923                .detach();
 924
 925            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 926                .detach();
 927            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 928
 929            let mut this = Self {
 930                buffer_ordered_messages_tx: tx,
 931                buffer_store: buffer_store.clone(),
 932                worktree_store: worktree_store.clone(),
 933                lsp_store: lsp_store.clone(),
 934                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 935                active_entry: None,
 936                collaborators: Default::default(),
 937                join_project_response_message_id: response.message_id,
 938                languages,
 939                user_store: user_store.clone(),
 940                snippets,
 941                fs,
 942                ssh_session: None,
 943                settings_observer: settings_observer.clone(),
 944                client_subscriptions: Default::default(),
 945                _subscriptions: vec![cx.on_release(Self::release)],
 946                client: client.clone(),
 947                client_state: ProjectClientState::Remote {
 948                    sharing_has_stopped: false,
 949                    capability: Capability::ReadWrite,
 950                    remote_id,
 951                    replica_id,
 952                    in_room: response.payload.dev_server_project_id.is_none(),
 953                },
 954                buffers_needing_diff: Default::default(),
 955                git_diff_debouncer: DebouncedDelay::new(),
 956                terminals: Terminals {
 957                    local_handles: Vec::new(),
 958                },
 959                node: None,
 960                default_prettier: DefaultPrettier::default(),
 961                prettiers_per_worktree: HashMap::default(),
 962                prettier_instances: HashMap::default(),
 963                tasks,
 964                hosted_project_id: None,
 965                dev_server_project_id: response
 966                    .payload
 967                    .dev_server_project_id
 968                    .map(|dev_server_project_id| DevServerProjectId(dev_server_project_id)),
 969                search_history: Self::new_search_history(),
 970                search_included_history: Self::new_search_history(),
 971                search_excluded_history: Self::new_search_history(),
 972                environment: ProjectEnvironment::new(&worktree_store, None, cx),
 973                remotely_created_buffers: Arc::new(Mutex::new(RemotelyCreatedBuffers::default())),
 974                last_formatting_failure: None,
 975                buffers_being_formatted: Default::default(),
 976            };
 977            this.set_role(role, cx);
 978            for worktree in worktrees {
 979                let _ = this.add_worktree(&worktree, cx);
 980            }
 981            this
 982        })?;
 983
 984        let subscriptions = subscriptions
 985            .into_iter()
 986            .map(|s| match s {
 987                EntitySubscription::BufferStore(subscription) => {
 988                    subscription.set_model(&buffer_store, &mut cx)
 989                }
 990                EntitySubscription::WorktreeStore(subscription) => {
 991                    subscription.set_model(&worktree_store, &mut cx)
 992                }
 993                EntitySubscription::SettingsObserver(subscription) => {
 994                    subscription.set_model(&settings_observer, &mut cx)
 995                }
 996                EntitySubscription::Project(subscription) => subscription.set_model(&this, &mut cx),
 997                EntitySubscription::LspStore(subscription) => {
 998                    subscription.set_model(&lsp_store, &mut cx)
 999                }
1000            })
1001            .collect::<Vec<_>>();
1002
1003        let user_ids = response
1004            .payload
1005            .collaborators
1006            .iter()
1007            .map(|peer| peer.user_id)
1008            .collect();
1009        user_store
1010            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1011            .await?;
1012
1013        this.update(&mut cx, |this, cx| {
1014            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1015            this.client_subscriptions.extend(subscriptions);
1016            anyhow::Ok(())
1017        })??;
1018
1019        Ok(this)
1020    }
1021
1022    pub async fn hosted(
1023        remote_id: ProjectId,
1024        user_store: Model<UserStore>,
1025        client: Arc<Client>,
1026        languages: Arc<LanguageRegistry>,
1027        fs: Arc<dyn Fs>,
1028        cx: AsyncAppContext,
1029    ) -> Result<Model<Self>> {
1030        client.authenticate_and_connect(true, &cx).await?;
1031
1032        let subscriptions = [
1033            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id.0)?),
1034            EntitySubscription::BufferStore(
1035                client.subscribe_to_entity::<BufferStore>(remote_id.0)?,
1036            ),
1037            EntitySubscription::WorktreeStore(
1038                client.subscribe_to_entity::<WorktreeStore>(remote_id.0)?,
1039            ),
1040            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id.0)?),
1041            EntitySubscription::SettingsObserver(
1042                client.subscribe_to_entity::<SettingsObserver>(remote_id.0)?,
1043            ),
1044        ];
1045        let response = client
1046            .request_envelope(proto::JoinHostedProject {
1047                project_id: remote_id.0,
1048            })
1049            .await?;
1050        Self::from_join_project_response(
1051            response,
1052            subscriptions,
1053            client,
1054            user_store,
1055            languages,
1056            fs,
1057            cx,
1058        )
1059        .await
1060    }
1061
1062    fn new_search_history() -> SearchHistory {
1063        SearchHistory::new(
1064            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1065            search_history::QueryInsertionBehavior::AlwaysInsert,
1066        )
1067    }
1068
1069    fn release(&mut self, cx: &mut AppContext) {
1070        match &self.client_state {
1071            ProjectClientState::Local => {}
1072            ProjectClientState::Shared { .. } => {
1073                let _ = self.unshare_internal(cx);
1074            }
1075            ProjectClientState::Remote { remote_id, .. } => {
1076                let _ = self.client.send(proto::LeaveProject {
1077                    project_id: *remote_id,
1078                });
1079                self.disconnected_from_host_internal(cx);
1080            }
1081        }
1082    }
1083
1084    #[cfg(any(test, feature = "test-support"))]
1085    pub async fn example(
1086        root_paths: impl IntoIterator<Item = &Path>,
1087        cx: &mut AsyncAppContext,
1088    ) -> Model<Project> {
1089        use clock::FakeSystemClock;
1090
1091        let fs = Arc::new(RealFs::default());
1092        let languages = LanguageRegistry::test(cx.background_executor().clone());
1093        let clock = Arc::new(FakeSystemClock::default());
1094        let http_client = http_client::FakeHttpClient::with_404_response();
1095        let client = cx
1096            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1097            .unwrap();
1098        let user_store = cx
1099            .new_model(|cx| UserStore::new(client.clone(), cx))
1100            .unwrap();
1101        let project = cx
1102            .update(|cx| {
1103                Project::local(
1104                    client,
1105                    node_runtime::FakeNodeRuntime::new(),
1106                    user_store,
1107                    Arc::new(languages),
1108                    fs,
1109                    None,
1110                    cx,
1111                )
1112            })
1113            .unwrap();
1114        for path in root_paths {
1115            let (tree, _) = project
1116                .update(cx, |project, cx| {
1117                    project.find_or_create_worktree(path, true, cx)
1118                })
1119                .unwrap()
1120                .await
1121                .unwrap();
1122            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1123                .unwrap()
1124                .await;
1125        }
1126        project
1127    }
1128
1129    #[cfg(any(test, feature = "test-support"))]
1130    pub async fn test(
1131        fs: Arc<dyn Fs>,
1132        root_paths: impl IntoIterator<Item = &Path>,
1133        cx: &mut gpui::TestAppContext,
1134    ) -> Model<Project> {
1135        use clock::FakeSystemClock;
1136
1137        let languages = LanguageRegistry::test(cx.executor());
1138        let clock = Arc::new(FakeSystemClock::default());
1139        let http_client = http_client::FakeHttpClient::with_404_response();
1140        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1141        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
1142        let project = cx.update(|cx| {
1143            Project::local(
1144                client,
1145                node_runtime::FakeNodeRuntime::new(),
1146                user_store,
1147                Arc::new(languages),
1148                fs,
1149                None,
1150                cx,
1151            )
1152        });
1153        for path in root_paths {
1154            let (tree, _) = project
1155                .update(cx, |project, cx| {
1156                    project.find_or_create_worktree(path, true, cx)
1157                })
1158                .await
1159                .unwrap();
1160
1161            project.update(cx, |project, cx| {
1162                let tree_id = tree.read(cx).id();
1163                project.environment.update(cx, |environment, _| {
1164                    environment.set_cached(&[(tree_id, HashMap::default())])
1165                });
1166            });
1167
1168            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1169                .await;
1170        }
1171        project
1172    }
1173
1174    pub fn lsp_store(&self) -> Model<LspStore> {
1175        self.lsp_store.clone()
1176    }
1177
1178    pub fn worktree_store(&self) -> Model<WorktreeStore> {
1179        self.worktree_store.clone()
1180    }
1181
1182    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
1183        let mut language_servers_to_start = Vec::new();
1184        let mut language_formatters_to_check = Vec::new();
1185        for buffer in self.buffer_store.read(cx).buffers() {
1186            let buffer = buffer.read(cx);
1187            let buffer_file = File::from_dyn(buffer.file());
1188            let buffer_language = buffer.language();
1189            let settings = language_settings(buffer_language, buffer.file(), cx);
1190            if let Some(language) = buffer_language {
1191                if settings.enable_language_server {
1192                    if let Some(file) = buffer_file {
1193                        language_servers_to_start
1194                            .push((file.worktree.clone(), Arc::clone(language)));
1195                    }
1196                }
1197                language_formatters_to_check
1198                    .push((buffer_file.map(|f| f.worktree_id(cx)), settings.clone()));
1199            }
1200        }
1201
1202        let mut language_servers_to_stop = Vec::new();
1203        let mut language_servers_to_restart = Vec::new();
1204        let languages = self.languages.to_vec();
1205
1206        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
1207        let current_lsp_settings = &self.current_lsp_settings;
1208        for (worktree_id, started_lsp_name) in self.lsp_store.read(cx).started_language_servers() {
1209            let language = languages.iter().find_map(|l| {
1210                let adapter = self
1211                    .languages
1212                    .lsp_adapters(l)
1213                    .iter()
1214                    .find(|adapter| adapter.name == started_lsp_name)?
1215                    .clone();
1216                Some((l, adapter))
1217            });
1218            if let Some((language, adapter)) = language {
1219                let worktree = self.worktree_for_id(worktree_id, cx);
1220                let file = worktree.as_ref().and_then(|tree| {
1221                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
1222                });
1223                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
1224                    language_servers_to_stop.push((worktree_id, started_lsp_name.clone()));
1225                } else if let Some(worktree) = worktree {
1226                    let server_name = &adapter.name.0;
1227                    match (
1228                        current_lsp_settings.get(server_name),
1229                        new_lsp_settings.get(server_name),
1230                    ) {
1231                        (None, None) => {}
1232                        (Some(_), None) | (None, Some(_)) => {
1233                            language_servers_to_restart.push((worktree, Arc::clone(language)));
1234                        }
1235                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
1236                            if current_lsp_settings != new_lsp_settings {
1237                                language_servers_to_restart.push((worktree, Arc::clone(language)));
1238                            }
1239                        }
1240                    }
1241                }
1242            }
1243        }
1244        self.current_lsp_settings = new_lsp_settings;
1245
1246        // Stop all newly-disabled language servers.
1247        self.lsp_store.update(cx, |lsp_store, cx| {
1248            for (worktree_id, adapter_name) in language_servers_to_stop {
1249                lsp_store
1250                    .stop_language_server(worktree_id, adapter_name, cx)
1251                    .detach();
1252            }
1253        });
1254
1255        let mut prettier_plugins_by_worktree = HashMap::default();
1256        for (worktree, language_settings) in language_formatters_to_check {
1257            if let Some(plugins) =
1258                prettier_support::prettier_plugins_for_language(&language_settings)
1259            {
1260                prettier_plugins_by_worktree
1261                    .entry(worktree)
1262                    .or_insert_with(|| HashSet::default())
1263                    .extend(plugins.iter().cloned());
1264            }
1265        }
1266        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
1267            self.install_default_prettier(
1268                worktree,
1269                prettier_plugins.into_iter().map(Arc::from),
1270                cx,
1271            );
1272        }
1273
1274        // Start all the newly-enabled language servers.
1275        self.lsp_store.update(cx, |lsp_store, cx| {
1276            for (worktree, language) in language_servers_to_start {
1277                lsp_store.start_language_servers(&worktree, language, cx);
1278            }
1279
1280            // Restart all language servers with changed initialization options.
1281            for (worktree, language) in language_servers_to_restart {
1282                lsp_store.restart_language_servers(worktree, language, cx);
1283            }
1284        });
1285
1286        cx.notify();
1287    }
1288
1289    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &AppContext) -> Option<Model<Buffer>> {
1290        self.buffer_store.read(cx).get(remote_id)
1291    }
1292
1293    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1294        &self.languages
1295    }
1296
1297    pub fn client(&self) -> Arc<Client> {
1298        self.client.clone()
1299    }
1300
1301    pub fn user_store(&self) -> Model<UserStore> {
1302        self.user_store.clone()
1303    }
1304
1305    pub fn node_runtime(&self) -> Option<&Arc<dyn NodeRuntime>> {
1306        self.node.as_ref()
1307    }
1308
1309    pub fn opened_buffers(&self, cx: &AppContext) -> Vec<Model<Buffer>> {
1310        self.buffer_store.read(cx).buffers().collect()
1311    }
1312
1313    pub fn cli_environment(&self, cx: &AppContext) -> Option<HashMap<String, String>> {
1314        self.environment.read(cx).get_cli_environment()
1315    }
1316
1317    #[cfg(any(test, feature = "test-support"))]
1318    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1319        self.buffer_store
1320            .read(cx)
1321            .get_by_path(&path.into(), cx)
1322            .is_some()
1323    }
1324
1325    pub fn fs(&self) -> &Arc<dyn Fs> {
1326        &self.fs
1327    }
1328
1329    pub fn remote_id(&self) -> Option<u64> {
1330        match self.client_state {
1331            ProjectClientState::Local => None,
1332            ProjectClientState::Shared { remote_id, .. }
1333            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1334        }
1335    }
1336
1337    pub fn hosted_project_id(&self) -> Option<ProjectId> {
1338        self.hosted_project_id
1339    }
1340
1341    pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
1342        self.dev_server_project_id
1343    }
1344
1345    pub fn supports_remote_terminal(&self, cx: &AppContext) -> bool {
1346        let Some(id) = self.dev_server_project_id else {
1347            return false;
1348        };
1349        let Some(server) = dev_server_projects::Store::global(cx)
1350            .read(cx)
1351            .dev_server_for_project(id)
1352        else {
1353            return false;
1354        };
1355        server.ssh_connection_string.is_some()
1356    }
1357
1358    pub fn ssh_connection_string(&self, cx: &ModelContext<Self>) -> Option<SharedString> {
1359        if self.is_local_or_ssh() {
1360            return None;
1361        }
1362
1363        let dev_server_id = self.dev_server_project_id()?;
1364        dev_server_projects::Store::global(cx)
1365            .read(cx)
1366            .dev_server_for_project(dev_server_id)?
1367            .ssh_connection_string
1368            .clone()
1369    }
1370
1371    pub fn replica_id(&self) -> ReplicaId {
1372        match self.client_state {
1373            ProjectClientState::Remote { replica_id, .. } => replica_id,
1374            _ => 0,
1375        }
1376    }
1377
1378    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1379        cx.notify();
1380
1381        let ProjectClientState::Shared { remote_id } = self.client_state else {
1382            return;
1383        };
1384        let project_id = remote_id;
1385
1386        let update_project = self.client.request(proto::UpdateProject {
1387            project_id,
1388            worktrees: self.worktree_metadata_protos(cx),
1389        });
1390        cx.spawn(|this, mut cx| async move {
1391            update_project.await?;
1392            this.update(&mut cx, |this, cx| {
1393                let client = this.client.clone();
1394                let worktrees = this.worktree_store.read(cx).worktrees().collect::<Vec<_>>();
1395
1396                for worktree in worktrees {
1397                    worktree.update(cx, |worktree, cx| {
1398                        let client = client.clone();
1399                        worktree.observe_updates(project_id, cx, {
1400                            move |update| client.request(update).map(|result| result.is_ok())
1401                        });
1402
1403                        this.lsp_store.update(cx, |lsp_store, _| {
1404                            lsp_store.send_diagnostic_summaries(worktree)
1405                        })
1406                    })?;
1407                }
1408
1409                anyhow::Ok(())
1410            })
1411        })
1412        .detach_and_log_err(cx);
1413    }
1414
1415    pub fn task_inventory(&self) -> &Model<Inventory> {
1416        &self.tasks
1417    }
1418
1419    pub fn snippets(&self) -> &Model<SnippetProvider> {
1420        &self.snippets
1421    }
1422
1423    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1424        match kind {
1425            SearchInputKind::Query => &self.search_history,
1426            SearchInputKind::Include => &self.search_included_history,
1427            SearchInputKind::Exclude => &self.search_excluded_history,
1428        }
1429    }
1430
1431    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1432        match kind {
1433            SearchInputKind::Query => &mut self.search_history,
1434            SearchInputKind::Include => &mut self.search_included_history,
1435            SearchInputKind::Exclude => &mut self.search_excluded_history,
1436        }
1437    }
1438
1439    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1440        &self.collaborators
1441    }
1442
1443    pub fn host(&self) -> Option<&Collaborator> {
1444        self.collaborators.values().find(|c| c.replica_id == 0)
1445    }
1446
1447    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut AppContext) {
1448        self.worktree_store.update(cx, |store, _| {
1449            store.set_worktrees_reordered(worktrees_reordered);
1450        });
1451    }
1452
1453    /// Collect all worktrees, including ones that don't appear in the project panel
1454    pub fn worktrees<'a>(
1455        &self,
1456        cx: &'a AppContext,
1457    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1458        self.worktree_store.read(cx).worktrees()
1459    }
1460
1461    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1462    pub fn visible_worktrees<'a>(
1463        &'a self,
1464        cx: &'a AppContext,
1465    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1466        self.worktree_store.read(cx).visible_worktrees(cx)
1467    }
1468
1469    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1470        self.visible_worktrees(cx)
1471            .map(|tree| tree.read(cx).root_name())
1472    }
1473
1474    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1475        self.worktree_store.read(cx).worktree_for_id(id, cx)
1476    }
1477
1478    pub fn worktree_for_entry(
1479        &self,
1480        entry_id: ProjectEntryId,
1481        cx: &AppContext,
1482    ) -> Option<Model<Worktree>> {
1483        self.worktree_store
1484            .read(cx)
1485            .worktree_for_entry(entry_id, cx)
1486    }
1487
1488    pub fn worktree_id_for_entry(
1489        &self,
1490        entry_id: ProjectEntryId,
1491        cx: &AppContext,
1492    ) -> Option<WorktreeId> {
1493        self.worktree_for_entry(entry_id, cx)
1494            .map(|worktree| worktree.read(cx).id())
1495    }
1496
1497    /// Checks if the entry is the root of a worktree.
1498    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
1499        self.worktree_for_entry(entry_id, cx)
1500            .map(|worktree| {
1501                worktree
1502                    .read(cx)
1503                    .root_entry()
1504                    .is_some_and(|e| e.id == entry_id)
1505            })
1506            .unwrap_or(false)
1507    }
1508
1509    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
1510        paths
1511            .iter()
1512            .map(|path| self.visibility_for_path(path, cx))
1513            .max()
1514            .flatten()
1515    }
1516
1517    pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
1518        self.worktrees(cx)
1519            .filter_map(|worktree| {
1520                let worktree = worktree.read(cx);
1521                worktree
1522                    .as_local()?
1523                    .contains_abs_path(path)
1524                    .then(|| worktree.is_visible())
1525            })
1526            .max()
1527    }
1528
1529    pub fn create_entry(
1530        &mut self,
1531        project_path: impl Into<ProjectPath>,
1532        is_directory: bool,
1533        cx: &mut ModelContext<Self>,
1534    ) -> Task<Result<CreatedEntry>> {
1535        let project_path = project_path.into();
1536        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1537            return Task::ready(Err(anyhow!(format!(
1538                "No worktree for path {project_path:?}"
1539            ))));
1540        };
1541        worktree.update(cx, |worktree, cx| {
1542            worktree.create_entry(project_path.path, is_directory, cx)
1543        })
1544    }
1545
1546    pub fn copy_entry(
1547        &mut self,
1548        entry_id: ProjectEntryId,
1549        relative_worktree_source_path: Option<PathBuf>,
1550        new_path: impl Into<Arc<Path>>,
1551        cx: &mut ModelContext<Self>,
1552    ) -> Task<Result<Option<Entry>>> {
1553        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1554            return Task::ready(Ok(None));
1555        };
1556        worktree.update(cx, |worktree, cx| {
1557            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1558        })
1559    }
1560
1561    pub fn rename_entry(
1562        &mut self,
1563        entry_id: ProjectEntryId,
1564        new_path: impl Into<Arc<Path>>,
1565        cx: &mut ModelContext<Self>,
1566    ) -> Task<Result<CreatedEntry>> {
1567        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1568            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1569        };
1570        worktree.update(cx, |worktree, cx| {
1571            worktree.rename_entry(entry_id, new_path, cx)
1572        })
1573    }
1574
1575    pub fn delete_entry(
1576        &mut self,
1577        entry_id: ProjectEntryId,
1578        trash: bool,
1579        cx: &mut ModelContext<Self>,
1580    ) -> Option<Task<Result<()>>> {
1581        let worktree = self.worktree_for_entry(entry_id, cx)?;
1582        worktree.update(cx, |worktree, cx| {
1583            worktree.delete_entry(entry_id, trash, cx)
1584        })
1585    }
1586
1587    pub fn expand_entry(
1588        &mut self,
1589        worktree_id: WorktreeId,
1590        entry_id: ProjectEntryId,
1591        cx: &mut ModelContext<Self>,
1592    ) -> Option<Task<Result<()>>> {
1593        let worktree = self.worktree_for_id(worktree_id, cx)?;
1594        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1595    }
1596
1597    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1598        if !matches!(self.client_state, ProjectClientState::Local) {
1599            if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1600                if *in_room || self.dev_server_project_id.is_none() {
1601                    return Err(anyhow!("project was already shared"));
1602                } else {
1603                    *in_room = true;
1604                    return Ok(());
1605                }
1606            } else {
1607                return Err(anyhow!("project was already shared"));
1608            }
1609        }
1610        self.client_subscriptions.extend([
1611            self.client
1612                .subscribe_to_entity(project_id)?
1613                .set_model(&cx.handle(), &mut cx.to_async()),
1614            self.client
1615                .subscribe_to_entity(project_id)?
1616                .set_model(&self.worktree_store, &mut cx.to_async()),
1617            self.client
1618                .subscribe_to_entity(project_id)?
1619                .set_model(&self.buffer_store, &mut cx.to_async()),
1620            self.client
1621                .subscribe_to_entity(project_id)?
1622                .set_model(&self.lsp_store, &mut cx.to_async()),
1623            self.client
1624                .subscribe_to_entity(project_id)?
1625                .set_model(&self.settings_observer, &mut cx.to_async()),
1626        ]);
1627
1628        self.buffer_store.update(cx, |buffer_store, cx| {
1629            buffer_store.shared(project_id, self.client.clone().into(), cx)
1630        });
1631        self.worktree_store.update(cx, |worktree_store, cx| {
1632            worktree_store.set_shared(true, cx);
1633        });
1634        self.lsp_store.update(cx, |lsp_store, cx| {
1635            lsp_store.shared(project_id, self.client.clone().into(), cx)
1636        });
1637        self.settings_observer.update(cx, |settings_observer, cx| {
1638            settings_observer.shared(project_id, self.client.clone().into(), cx)
1639        });
1640
1641        self.client_state = ProjectClientState::Shared {
1642            remote_id: project_id,
1643        };
1644
1645        self.metadata_changed(cx);
1646        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1647        cx.notify();
1648        Ok(())
1649    }
1650
1651    pub fn reshared(
1652        &mut self,
1653        message: proto::ResharedProject,
1654        cx: &mut ModelContext<Self>,
1655    ) -> Result<()> {
1656        self.buffer_store
1657            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1658        self.set_collaborators_from_proto(message.collaborators, cx)?;
1659        self.metadata_changed(cx);
1660        cx.emit(Event::Reshared);
1661        Ok(())
1662    }
1663
1664    pub fn rejoined(
1665        &mut self,
1666        message: proto::RejoinedProject,
1667        message_id: u32,
1668        cx: &mut ModelContext<Self>,
1669    ) -> Result<()> {
1670        cx.update_global::<SettingsStore, _>(|store, cx| {
1671            self.worktree_store.update(cx, |worktree_store, cx| {
1672                for worktree in worktree_store.worktrees() {
1673                    store
1674                        .clear_local_settings(worktree.entity_id().as_u64() as usize, cx)
1675                        .log_err();
1676                }
1677            });
1678        });
1679
1680        self.join_project_response_message_id = message_id;
1681        self.set_worktrees_from_proto(message.worktrees, cx)?;
1682        self.set_collaborators_from_proto(message.collaborators, cx)?;
1683        self.lsp_store.update(cx, |lsp_store, _| {
1684            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1685        });
1686        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1687            .unwrap();
1688        cx.emit(Event::Rejoined);
1689        cx.notify();
1690        Ok(())
1691    }
1692
1693    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1694        self.unshare_internal(cx)?;
1695        self.metadata_changed(cx);
1696        cx.notify();
1697        Ok(())
1698    }
1699
1700    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1701        if self.is_via_collab() {
1702            if self.dev_server_project_id().is_some() {
1703                if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1704                    *in_room = false
1705                }
1706                return Ok(());
1707            } else {
1708                return Err(anyhow!("attempted to unshare a remote project"));
1709            }
1710        }
1711
1712        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1713            self.client_state = ProjectClientState::Local;
1714            self.collaborators.clear();
1715            self.client_subscriptions.clear();
1716            self.worktree_store.update(cx, |store, cx| {
1717                store.set_shared(false, cx);
1718            });
1719            self.buffer_store.update(cx, |buffer_store, cx| {
1720                buffer_store.forget_shared_buffers();
1721                buffer_store.unshared(cx)
1722            });
1723            self.settings_observer.update(cx, |settings_observer, cx| {
1724                settings_observer.unshared(cx);
1725            });
1726            self.client
1727                .send(proto::UnshareProject {
1728                    project_id: remote_id,
1729                })
1730                .ok();
1731            Ok(())
1732        } else {
1733            Err(anyhow!("attempted to unshare an unshared project"))
1734        }
1735    }
1736
1737    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1738        if self.is_disconnected() {
1739            return;
1740        }
1741        self.disconnected_from_host_internal(cx);
1742        cx.emit(Event::DisconnectedFromHost);
1743        cx.notify();
1744    }
1745
1746    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1747        let new_capability =
1748            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1749                Capability::ReadWrite
1750            } else {
1751                Capability::ReadOnly
1752            };
1753        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1754            if *capability == new_capability {
1755                return;
1756            }
1757
1758            *capability = new_capability;
1759            for buffer in self.opened_buffers(cx) {
1760                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1761            }
1762        }
1763    }
1764
1765    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1766        if let ProjectClientState::Remote {
1767            sharing_has_stopped,
1768            ..
1769        } = &mut self.client_state
1770        {
1771            *sharing_has_stopped = true;
1772            self.collaborators.clear();
1773            self.worktree_store.update(cx, |store, cx| {
1774                store.disconnected_from_host(cx);
1775            });
1776            self.buffer_store.update(cx, |buffer_store, cx| {
1777                buffer_store.disconnected_from_host(cx)
1778            });
1779            self.lsp_store
1780                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1781        }
1782    }
1783
1784    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1785        cx.emit(Event::Closed);
1786    }
1787
1788    pub fn is_disconnected(&self) -> bool {
1789        match &self.client_state {
1790            ProjectClientState::Remote {
1791                sharing_has_stopped,
1792                ..
1793            } => *sharing_has_stopped,
1794            _ => false,
1795        }
1796    }
1797
1798    pub fn capability(&self) -> Capability {
1799        match &self.client_state {
1800            ProjectClientState::Remote { capability, .. } => *capability,
1801            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1802        }
1803    }
1804
1805    pub fn is_read_only(&self) -> bool {
1806        self.is_disconnected() || self.capability() == Capability::ReadOnly
1807    }
1808
1809    pub fn is_local(&self) -> bool {
1810        match &self.client_state {
1811            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1812                self.ssh_session.is_none()
1813            }
1814            ProjectClientState::Remote { .. } => false,
1815        }
1816    }
1817
1818    pub fn is_local_or_ssh(&self) -> bool {
1819        match &self.client_state {
1820            ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
1821            ProjectClientState::Remote { .. } => false,
1822        }
1823    }
1824
1825    pub fn is_via_collab(&self) -> bool {
1826        match &self.client_state {
1827            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1828            ProjectClientState::Remote { .. } => true,
1829        }
1830    }
1831
1832    pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
1833        self.buffer_store.update(cx, |buffer_store, cx| {
1834            buffer_store.create_buffer(
1835                if self.is_via_collab() {
1836                    Some((self.client.clone().into(), self.remote_id().unwrap()))
1837                } else {
1838                    None
1839                },
1840                cx,
1841            )
1842        })
1843    }
1844
1845    pub fn create_local_buffer(
1846        &mut self,
1847        text: &str,
1848        language: Option<Arc<Language>>,
1849        cx: &mut ModelContext<Self>,
1850    ) -> Model<Buffer> {
1851        if self.is_via_collab() {
1852            panic!("called create_local_buffer on a remote project")
1853        }
1854        self.buffer_store.update(cx, |buffer_store, cx| {
1855            buffer_store.create_local_buffer(text, language, cx)
1856        })
1857    }
1858
1859    pub fn open_path(
1860        &mut self,
1861        path: ProjectPath,
1862        cx: &mut ModelContext<Self>,
1863    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1864        let task = self.open_buffer(path.clone(), cx);
1865        cx.spawn(move |_, cx| async move {
1866            let buffer = task.await?;
1867            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1868                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1869            })?;
1870
1871            let buffer: &AnyModel = &buffer;
1872            Ok((project_entry_id, buffer.clone()))
1873        })
1874    }
1875
1876    pub fn open_local_buffer(
1877        &mut self,
1878        abs_path: impl AsRef<Path>,
1879        cx: &mut ModelContext<Self>,
1880    ) -> Task<Result<Model<Buffer>>> {
1881        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1882            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1883        } else {
1884            Task::ready(Err(anyhow!("no such path")))
1885        }
1886    }
1887
1888    pub fn open_buffer(
1889        &mut self,
1890        path: impl Into<ProjectPath>,
1891        cx: &mut ModelContext<Self>,
1892    ) -> Task<Result<Model<Buffer>>> {
1893        if self.is_via_collab() && self.is_disconnected() {
1894            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1895        }
1896
1897        self.buffer_store.update(cx, |buffer_store, cx| {
1898            buffer_store.open_buffer(path.into(), cx)
1899        })
1900    }
1901
1902    pub fn open_buffer_by_id(
1903        &mut self,
1904        id: BufferId,
1905        cx: &mut ModelContext<Self>,
1906    ) -> Task<Result<Model<Buffer>>> {
1907        if let Some(buffer) = self.buffer_for_id(id, cx) {
1908            Task::ready(Ok(buffer))
1909        } else if self.is_local_or_ssh() {
1910            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1911        } else if let Some(project_id) = self.remote_id() {
1912            let request = self.client.request(proto::OpenBufferById {
1913                project_id,
1914                id: id.into(),
1915            });
1916            cx.spawn(move |this, mut cx| async move {
1917                let buffer_id = BufferId::new(request.await?.buffer_id)?;
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(Err(anyhow!("cannot open buffer while disconnected")))
1925        }
1926    }
1927
1928    pub fn save_buffers(
1929        &self,
1930        buffers: HashSet<Model<Buffer>>,
1931        cx: &mut ModelContext<Self>,
1932    ) -> Task<Result<()>> {
1933        cx.spawn(move |this, mut cx| async move {
1934            let save_tasks = buffers.into_iter().filter_map(|buffer| {
1935                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1936                    .ok()
1937            });
1938            try_join_all(save_tasks).await?;
1939            Ok(())
1940        })
1941    }
1942
1943    pub fn save_buffer(
1944        &self,
1945        buffer: Model<Buffer>,
1946        cx: &mut ModelContext<Self>,
1947    ) -> Task<Result<()>> {
1948        self.buffer_store
1949            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
1950    }
1951
1952    pub fn save_buffer_as(
1953        &mut self,
1954        buffer: Model<Buffer>,
1955        path: ProjectPath,
1956        cx: &mut ModelContext<Self>,
1957    ) -> Task<Result<()>> {
1958        self.buffer_store.update(cx, |buffer_store, cx| {
1959            buffer_store.save_buffer_as(buffer.clone(), path, cx)
1960        })
1961    }
1962
1963    pub fn get_open_buffer(
1964        &mut self,
1965        path: &ProjectPath,
1966        cx: &mut ModelContext<Self>,
1967    ) -> Option<Model<Buffer>> {
1968        self.buffer_store.read(cx).get_by_path(path, cx)
1969    }
1970
1971    fn register_buffer(
1972        &mut self,
1973        buffer: &Model<Buffer>,
1974        cx: &mut ModelContext<Self>,
1975    ) -> Result<()> {
1976        {
1977            let mut remotely_created_buffers = self.remotely_created_buffers.lock();
1978            if remotely_created_buffers.retain_count > 0 {
1979                remotely_created_buffers.buffers.push(buffer.clone())
1980            }
1981        }
1982
1983        self.request_buffer_diff_recalculation(buffer, cx);
1984
1985        cx.subscribe(buffer, |this, buffer, event, cx| {
1986            this.on_buffer_event(buffer, event, cx);
1987        })
1988        .detach();
1989
1990        Ok(())
1991    }
1992
1993    async fn send_buffer_ordered_messages(
1994        this: WeakModel<Self>,
1995        rx: UnboundedReceiver<BufferOrderedMessage>,
1996        mut cx: AsyncAppContext,
1997    ) -> Result<()> {
1998        const MAX_BATCH_SIZE: usize = 128;
1999
2000        let mut operations_by_buffer_id = HashMap::default();
2001        async fn flush_operations(
2002            this: &WeakModel<Project>,
2003            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2004            needs_resync_with_host: &mut bool,
2005            is_local: bool,
2006            cx: &mut AsyncAppContext,
2007        ) -> Result<()> {
2008            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2009                let request = this.update(cx, |this, _| {
2010                    let project_id = this.remote_id()?;
2011                    Some(this.client.request(proto::UpdateBuffer {
2012                        buffer_id: buffer_id.into(),
2013                        project_id,
2014                        operations,
2015                    }))
2016                })?;
2017                if let Some(request) = request {
2018                    if request.await.is_err() && !is_local {
2019                        *needs_resync_with_host = true;
2020                        break;
2021                    }
2022                }
2023            }
2024            Ok(())
2025        }
2026
2027        let mut needs_resync_with_host = false;
2028        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2029
2030        while let Some(changes) = changes.next().await {
2031            let is_local = this.update(&mut cx, |this, _| this.is_local_or_ssh())?;
2032
2033            for change in changes {
2034                match change {
2035                    BufferOrderedMessage::Operation {
2036                        buffer_id,
2037                        operation,
2038                    } => {
2039                        if needs_resync_with_host {
2040                            continue;
2041                        }
2042
2043                        operations_by_buffer_id
2044                            .entry(buffer_id)
2045                            .or_insert(Vec::new())
2046                            .push(operation);
2047                    }
2048
2049                    BufferOrderedMessage::Resync => {
2050                        operations_by_buffer_id.clear();
2051                        if this
2052                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2053                            .await
2054                            .is_ok()
2055                        {
2056                            needs_resync_with_host = false;
2057                        }
2058                    }
2059
2060                    BufferOrderedMessage::LanguageServerUpdate {
2061                        language_server_id,
2062                        message,
2063                    } => {
2064                        flush_operations(
2065                            &this,
2066                            &mut operations_by_buffer_id,
2067                            &mut needs_resync_with_host,
2068                            is_local,
2069                            &mut cx,
2070                        )
2071                        .await?;
2072
2073                        this.update(&mut cx, |this, _| {
2074                            if let Some(project_id) = this.remote_id() {
2075                                this.client
2076                                    .send(proto::UpdateLanguageServer {
2077                                        project_id,
2078                                        language_server_id: language_server_id.0 as u64,
2079                                        variant: Some(message),
2080                                    })
2081                                    .log_err();
2082                            }
2083                        })?;
2084                    }
2085                }
2086            }
2087
2088            flush_operations(
2089                &this,
2090                &mut operations_by_buffer_id,
2091                &mut needs_resync_with_host,
2092                is_local,
2093                &mut cx,
2094            )
2095            .await?;
2096        }
2097
2098        Ok(())
2099    }
2100
2101    fn on_buffer_store_event(
2102        &mut self,
2103        _: Model<BufferStore>,
2104        event: &BufferStoreEvent,
2105        cx: &mut ModelContext<Self>,
2106    ) {
2107        match event {
2108            BufferStoreEvent::BufferAdded(buffer) => {
2109                self.register_buffer(buffer, cx).log_err();
2110            }
2111            BufferStoreEvent::BufferChangedFilePath { .. } => {}
2112            BufferStoreEvent::BufferDropped(buffer_id) => {
2113                if let Some(ref ssh_session) = self.ssh_session {
2114                    ssh_session
2115                        .send(proto::CloseBuffer {
2116                            project_id: 0,
2117                            buffer_id: buffer_id.to_proto(),
2118                        })
2119                        .log_err();
2120                }
2121            }
2122        }
2123    }
2124
2125    fn on_lsp_store_event(
2126        &mut self,
2127        _: Model<LspStore>,
2128        event: &LspStoreEvent,
2129        cx: &mut ModelContext<Self>,
2130    ) {
2131        match event {
2132            LspStoreEvent::DiagnosticsUpdated {
2133                language_server_id,
2134                path,
2135            } => cx.emit(Event::DiagnosticsUpdated {
2136                path: path.clone(),
2137                language_server_id: *language_server_id,
2138            }),
2139            LspStoreEvent::LanguageServerAdded(language_server_id) => {
2140                cx.emit(Event::LanguageServerAdded(*language_server_id))
2141            }
2142            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2143                cx.emit(Event::LanguageServerAdded(*language_server_id))
2144            }
2145            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2146                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2147            ),
2148            LspStoreEvent::LanguageDetected {
2149                buffer,
2150                new_language,
2151            } => {
2152                let Some(new_language) = new_language else {
2153                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2154                    return;
2155                };
2156                let buffer_file = buffer.read(cx).file().cloned();
2157                let settings =
2158                    language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2159                let buffer_file = File::from_dyn(buffer_file.as_ref());
2160                let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2161                if let Some(prettier_plugins) =
2162                    prettier_support::prettier_plugins_for_language(&settings)
2163                {
2164                    self.install_default_prettier(
2165                        worktree,
2166                        prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
2167                        cx,
2168                    );
2169                };
2170            }
2171            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2172            LspStoreEvent::LanguageServerPrompt(prompt) => {
2173                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2174            }
2175            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2176                cx.emit(Event::DiskBasedDiagnosticsStarted {
2177                    language_server_id: *language_server_id,
2178                });
2179                if self.is_local_or_ssh() {
2180                    self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
2181                        language_server_id: *language_server_id,
2182                        message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2183                            Default::default(),
2184                        ),
2185                    })
2186                    .ok();
2187                }
2188            }
2189            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2190                cx.emit(Event::DiskBasedDiagnosticsFinished {
2191                    language_server_id: *language_server_id,
2192                });
2193                if self.is_local_or_ssh() {
2194                    self.enqueue_buffer_ordered_message(
2195                        BufferOrderedMessage::LanguageServerUpdate {
2196                            language_server_id: *language_server_id,
2197                            message:
2198                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2199                                    Default::default(),
2200                                ),
2201                        },
2202                    )
2203                    .ok();
2204                }
2205            }
2206            LspStoreEvent::LanguageServerUpdate {
2207                language_server_id,
2208                message,
2209            } => {
2210                if self.is_local_or_ssh() {
2211                    self.enqueue_buffer_ordered_message(
2212                        BufferOrderedMessage::LanguageServerUpdate {
2213                            language_server_id: *language_server_id,
2214                            message: message.clone(),
2215                        },
2216                    )
2217                    .ok();
2218                }
2219            }
2220            LspStoreEvent::Notification(message) => cx.emit(Event::Notification(message.clone())),
2221            LspStoreEvent::SnippetEdit {
2222                buffer_id,
2223                edits,
2224                most_recent_edit,
2225            } => {
2226                if most_recent_edit.replica_id == self.replica_id() {
2227                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2228                }
2229            }
2230            LspStoreEvent::StartFormattingLocalBuffer(buffer_id) => {
2231                self.buffers_being_formatted.insert(*buffer_id);
2232            }
2233            LspStoreEvent::FinishFormattingLocalBuffer(buffer_id) => {
2234                self.buffers_being_formatted.remove(buffer_id);
2235            }
2236        }
2237    }
2238
2239    fn on_worktree_store_event(
2240        &mut self,
2241        _: Model<WorktreeStore>,
2242        event: &WorktreeStoreEvent,
2243        cx: &mut ModelContext<Self>,
2244    ) {
2245        match event {
2246            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2247                self.on_worktree_added(worktree, cx);
2248                cx.emit(Event::WorktreeAdded);
2249            }
2250            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2251                self.on_worktree_removed(*id, cx);
2252                cx.emit(Event::WorktreeRemoved(*id));
2253            }
2254            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2255        }
2256    }
2257
2258    fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2259        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2260        cx.subscribe(worktree, |this, worktree, event, cx| {
2261            let is_local = worktree.read(cx).is_local();
2262            match event {
2263                worktree::Event::UpdatedEntries(changes) => {
2264                    if is_local {
2265                        this.update_local_worktree_settings(&worktree, changes, cx);
2266                        this.update_prettier_settings(&worktree, changes, cx);
2267                    }
2268
2269                    cx.emit(Event::WorktreeUpdatedEntries(
2270                        worktree.read(cx).id(),
2271                        changes.clone(),
2272                    ));
2273
2274                    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2275                    this.client()
2276                        .telemetry()
2277                        .report_discovered_project_events(worktree_id, changes);
2278                }
2279                worktree::Event::UpdatedGitRepositories(_) => {
2280                    cx.emit(Event::WorktreeUpdatedGitRepositories);
2281                }
2282                worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2283            }
2284        })
2285        .detach();
2286        self.metadata_changed(cx);
2287    }
2288
2289    fn on_worktree_removed(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2290        if let Some(dev_server_project_id) = self.dev_server_project_id {
2291            let paths: Vec<String> = self
2292                .visible_worktrees(cx)
2293                .filter_map(|worktree| {
2294                    if worktree.read(cx).id() == id_to_remove {
2295                        None
2296                    } else {
2297                        Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2298                    }
2299                })
2300                .collect();
2301            if paths.len() > 0 {
2302                let request = self.client.request(proto::UpdateDevServerProject {
2303                    dev_server_project_id: dev_server_project_id.0,
2304                    paths,
2305                });
2306                cx.background_executor()
2307                    .spawn(request)
2308                    .detach_and_log_err(cx);
2309            }
2310            return;
2311        }
2312
2313        let mut prettier_instances_to_clean = FuturesUnordered::new();
2314        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
2315            for path in prettier_paths.iter().flatten() {
2316                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
2317                    prettier_instances_to_clean.push(async move {
2318                        prettier_instance
2319                            .server()
2320                            .await
2321                            .map(|server| server.server_id())
2322                    });
2323                }
2324            }
2325        }
2326        cx.spawn(|project, mut cx| async move {
2327            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
2328                if let Some(prettier_server_id) = prettier_server_id {
2329                    project
2330                        .update(&mut cx, |project, cx| {
2331                            project.lsp_store.update(cx, |lsp_store, cx| {
2332                                lsp_store.unregister_supplementary_language_server(
2333                                    prettier_server_id,
2334                                    cx,
2335                                );
2336                            });
2337                        })
2338                        .ok();
2339                }
2340            }
2341        })
2342        .detach();
2343
2344        self.task_inventory().update(cx, |inventory, _| {
2345            inventory.remove_worktree_sources(id_to_remove);
2346        });
2347
2348        self.metadata_changed(cx);
2349    }
2350
2351    fn on_buffer_event(
2352        &mut self,
2353        buffer: Model<Buffer>,
2354        event: &BufferEvent,
2355        cx: &mut ModelContext<Self>,
2356    ) -> Option<()> {
2357        if matches!(
2358            event,
2359            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2360        ) {
2361            self.request_buffer_diff_recalculation(&buffer, cx);
2362        }
2363
2364        let buffer_id = buffer.read(cx).remote_id();
2365        match event {
2366            BufferEvent::Operation(operation) => {
2367                let operation = language::proto::serialize_operation(operation);
2368
2369                if let Some(ssh) = &self.ssh_session {
2370                    ssh.send(proto::UpdateBuffer {
2371                        project_id: 0,
2372                        buffer_id: buffer_id.to_proto(),
2373                        operations: vec![operation.clone()],
2374                    })
2375                    .ok();
2376                }
2377
2378                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2379                    buffer_id,
2380                    operation,
2381                })
2382                .ok();
2383            }
2384
2385            BufferEvent::Reloaded => {
2386                if self.is_local_or_ssh() {
2387                    if let Some(project_id) = self.remote_id() {
2388                        let buffer = buffer.read(cx);
2389                        self.client
2390                            .send(proto::BufferReloaded {
2391                                project_id,
2392                                buffer_id: buffer.remote_id().to_proto(),
2393                                version: serialize_version(&buffer.version()),
2394                                mtime: buffer.saved_mtime().map(|t| t.into()),
2395                                line_ending: serialize_line_ending(buffer.line_ending()) as i32,
2396                            })
2397                            .log_err();
2398                    }
2399                }
2400            }
2401
2402            _ => {}
2403        }
2404
2405        None
2406    }
2407
2408    fn request_buffer_diff_recalculation(
2409        &mut self,
2410        buffer: &Model<Buffer>,
2411        cx: &mut ModelContext<Self>,
2412    ) {
2413        self.buffers_needing_diff.insert(buffer.downgrade());
2414        let first_insertion = self.buffers_needing_diff.len() == 1;
2415
2416        let settings = ProjectSettings::get_global(cx);
2417        let delay = if let Some(delay) = settings.git.gutter_debounce {
2418            delay
2419        } else {
2420            if first_insertion {
2421                let this = cx.weak_model();
2422                cx.defer(move |cx| {
2423                    if let Some(this) = this.upgrade() {
2424                        this.update(cx, |this, cx| {
2425                            this.recalculate_buffer_diffs(cx).detach();
2426                        });
2427                    }
2428                });
2429            }
2430            return;
2431        };
2432
2433        const MIN_DELAY: u64 = 50;
2434        let delay = delay.max(MIN_DELAY);
2435        let duration = Duration::from_millis(delay);
2436
2437        self.git_diff_debouncer
2438            .fire_new(duration, cx, move |this, cx| {
2439                this.recalculate_buffer_diffs(cx)
2440            });
2441    }
2442
2443    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2444        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2445        cx.spawn(move |this, mut cx| async move {
2446            let tasks: Vec<_> = buffers
2447                .iter()
2448                .filter_map(|buffer| {
2449                    let buffer = buffer.upgrade()?;
2450                    buffer
2451                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2452                        .ok()
2453                        .flatten()
2454                })
2455                .collect();
2456
2457            futures::future::join_all(tasks).await;
2458
2459            this.update(&mut cx, |this, cx| {
2460                if this.buffers_needing_diff.is_empty() {
2461                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2462                    for buffer in buffers {
2463                        if let Some(buffer) = buffer.upgrade() {
2464                            buffer.update(cx, |_, cx| cx.notify());
2465                        }
2466                    }
2467                } else {
2468                    this.recalculate_buffer_diffs(cx).detach();
2469                }
2470            })
2471            .ok();
2472        })
2473    }
2474
2475    pub fn set_language_for_buffer(
2476        &mut self,
2477        buffer: &Model<Buffer>,
2478        new_language: Arc<Language>,
2479        cx: &mut ModelContext<Self>,
2480    ) {
2481        self.lsp_store.update(cx, |lsp_store, cx| {
2482            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2483        })
2484    }
2485
2486    pub fn restart_language_servers_for_buffers(
2487        &mut self,
2488        buffers: impl IntoIterator<Item = Model<Buffer>>,
2489        cx: &mut ModelContext<Self>,
2490    ) {
2491        self.lsp_store.update(cx, |lsp_store, cx| {
2492            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2493        })
2494    }
2495
2496    pub fn cancel_language_server_work_for_buffers(
2497        &mut self,
2498        buffers: impl IntoIterator<Item = Model<Buffer>>,
2499        cx: &mut ModelContext<Self>,
2500    ) {
2501        self.lsp_store.update(cx, |lsp_store, cx| {
2502            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2503        })
2504    }
2505
2506    pub fn cancel_language_server_work(
2507        &mut self,
2508        server_id: LanguageServerId,
2509        token_to_cancel: Option<String>,
2510        cx: &mut ModelContext<Self>,
2511    ) {
2512        self.lsp_store.update(cx, |lsp_store, cx| {
2513            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2514        })
2515    }
2516
2517    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2518        self.buffer_ordered_messages_tx
2519            .unbounded_send(message)
2520            .map_err(|e| anyhow!(e))
2521    }
2522
2523    pub fn language_server_statuses<'a>(
2524        &'a self,
2525        cx: &'a AppContext,
2526    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2527        self.lsp_store.read(cx).language_server_statuses()
2528    }
2529
2530    pub fn last_formatting_failure(&self) -> Option<&str> {
2531        self.last_formatting_failure.as_deref()
2532    }
2533
2534    pub fn update_diagnostics(
2535        &mut self,
2536        language_server_id: LanguageServerId,
2537        params: lsp::PublishDiagnosticsParams,
2538        disk_based_sources: &[String],
2539        cx: &mut ModelContext<Self>,
2540    ) -> Result<()> {
2541        self.lsp_store.update(cx, |lsp_store, cx| {
2542            lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2543        })
2544    }
2545
2546    pub fn update_diagnostic_entries(
2547        &mut self,
2548        server_id: LanguageServerId,
2549        abs_path: PathBuf,
2550        version: Option<i32>,
2551        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2552        cx: &mut ModelContext<Project>,
2553    ) -> Result<(), anyhow::Error> {
2554        self.lsp_store.update(cx, |lsp_store, cx| {
2555            lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2556        })
2557    }
2558
2559    pub fn reload_buffers(
2560        &self,
2561        buffers: HashSet<Model<Buffer>>,
2562        push_to_history: bool,
2563        cx: &mut ModelContext<Self>,
2564    ) -> Task<Result<ProjectTransaction>> {
2565        let mut local_buffers = Vec::new();
2566        let mut remote_buffers = None;
2567        for buffer_handle in buffers {
2568            let buffer = buffer_handle.read(cx);
2569            if buffer.is_dirty() {
2570                if let Some(file) = File::from_dyn(buffer.file()) {
2571                    if file.is_local() {
2572                        local_buffers.push(buffer_handle);
2573                    } else {
2574                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2575                    }
2576                }
2577            }
2578        }
2579
2580        let remote_buffers = self.remote_id().zip(remote_buffers);
2581        let client = self.client.clone();
2582
2583        cx.spawn(move |this, mut cx| async move {
2584            let mut project_transaction = ProjectTransaction::default();
2585
2586            if let Some((project_id, remote_buffers)) = remote_buffers {
2587                let response = client
2588                    .request(proto::ReloadBuffers {
2589                        project_id,
2590                        buffer_ids: remote_buffers
2591                            .iter()
2592                            .filter_map(|buffer| {
2593                                buffer
2594                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
2595                                    .ok()
2596                            })
2597                            .collect(),
2598                    })
2599                    .await?
2600                    .transaction
2601                    .ok_or_else(|| anyhow!("missing transaction"))?;
2602                BufferStore::deserialize_project_transaction(
2603                    this.read_with(&cx, |this, _| this.buffer_store.downgrade())?,
2604                    response,
2605                    push_to_history,
2606                    cx.clone(),
2607                )
2608                .await?;
2609            }
2610
2611            for buffer in local_buffers {
2612                let transaction = buffer
2613                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
2614                    .await?;
2615                buffer.update(&mut cx, |buffer, cx| {
2616                    if let Some(transaction) = transaction {
2617                        if !push_to_history {
2618                            buffer.forget_transaction(transaction.id);
2619                        }
2620                        project_transaction.0.insert(cx.handle(), transaction);
2621                    }
2622                })?;
2623            }
2624
2625            Ok(project_transaction)
2626        })
2627    }
2628
2629    pub fn format(
2630        &mut self,
2631        buffers: HashSet<Model<Buffer>>,
2632        push_to_history: bool,
2633        trigger: FormatTrigger,
2634        cx: &mut ModelContext<Project>,
2635    ) -> Task<anyhow::Result<ProjectTransaction>> {
2636        if self.is_local_or_ssh() {
2637            let buffers_with_paths = buffers
2638                .into_iter()
2639                .map(|buffer_handle| {
2640                    let buffer = buffer_handle.read(cx);
2641                    let buffer_abs_path = File::from_dyn(buffer.file())
2642                        .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
2643                    (buffer_handle, buffer_abs_path)
2644                })
2645                .collect::<Vec<_>>();
2646
2647            cx.spawn(move |project, mut cx| async move {
2648                let result = Self::format_locally(
2649                    project.clone(),
2650                    buffers_with_paths,
2651                    push_to_history,
2652                    trigger,
2653                    cx.clone(),
2654                )
2655                .await;
2656
2657                project.update(&mut cx, |project, _| match &result {
2658                    Ok(_) => project.last_formatting_failure = None,
2659                    Err(error) => {
2660                        project.last_formatting_failure.replace(error.to_string());
2661                    }
2662                })?;
2663
2664                result
2665            })
2666        } else {
2667            let remote_id = self.remote_id();
2668            let client = self.client.clone();
2669            cx.spawn(move |this, mut cx| async move {
2670                if let Some(project_id) = remote_id {
2671                    let response = client
2672                        .request(proto::FormatBuffers {
2673                            project_id,
2674                            trigger: trigger as i32,
2675                            buffer_ids: buffers
2676                                .iter()
2677                                .map(|buffer| {
2678                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
2679                                })
2680                                .collect::<Result<_>>()?,
2681                        })
2682                        .await?
2683                        .transaction
2684                        .ok_or_else(|| anyhow!("missing transaction"))?;
2685                    BufferStore::deserialize_project_transaction(
2686                        this.read_with(&cx, |this, _| this.buffer_store.downgrade())?,
2687                        response,
2688                        push_to_history,
2689                        cx,
2690                    )
2691                    .await
2692                } else {
2693                    Ok(ProjectTransaction::default())
2694                }
2695            })
2696        }
2697    }
2698
2699    async fn format_locally(
2700        project: WeakModel<Project>,
2701        mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
2702        push_to_history: bool,
2703        trigger: FormatTrigger,
2704        mut cx: AsyncAppContext,
2705    ) -> anyhow::Result<ProjectTransaction> {
2706        // Do not allow multiple concurrent formatting requests for the
2707        // same buffer.
2708        let lsp_store = project.update(&mut cx, |this, cx| {
2709            buffers_with_paths.retain(|(buffer, _)| {
2710                this.buffers_being_formatted
2711                    .insert(buffer.read(cx).remote_id())
2712            });
2713            this.lsp_store.downgrade()
2714        })?;
2715
2716        let _cleanup = defer({
2717            let this = project.clone();
2718            let mut cx = cx.clone();
2719            let buffers = &buffers_with_paths;
2720            move || {
2721                this.update(&mut cx, |this, cx| {
2722                    for (buffer, _) in buffers {
2723                        this.buffers_being_formatted
2724                            .remove(&buffer.read(cx).remote_id());
2725                    }
2726                })
2727                .ok();
2728            }
2729        });
2730
2731        let mut project_transaction = ProjectTransaction::default();
2732        for (buffer, buffer_abs_path) in &buffers_with_paths {
2733            let (primary_adapter_and_server, adapters_and_servers) =
2734                project.update(&mut cx, |project, cx| {
2735                    let buffer = buffer.read(cx);
2736
2737                    let adapters_and_servers = project
2738                        .language_servers_for_buffer(buffer, cx)
2739                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
2740                        .collect::<Vec<_>>();
2741
2742                    let primary_adapter = project
2743                        .lsp_store
2744                        .read(cx)
2745                        .primary_language_server_for_buffer(buffer, cx)
2746                        .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
2747
2748                    (primary_adapter, adapters_and_servers)
2749                })?;
2750
2751            let settings = buffer.update(&mut cx, |buffer, cx| {
2752                language_settings(buffer.language(), buffer.file(), cx).clone()
2753            })?;
2754
2755            let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
2756            let ensure_final_newline = settings.ensure_final_newline_on_save;
2757
2758            // First, format buffer's whitespace according to the settings.
2759            let trailing_whitespace_diff = if remove_trailing_whitespace {
2760                Some(
2761                    buffer
2762                        .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
2763                        .await,
2764                )
2765            } else {
2766                None
2767            };
2768            let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
2769                buffer.finalize_last_transaction();
2770                buffer.start_transaction();
2771                if let Some(diff) = trailing_whitespace_diff {
2772                    buffer.apply_diff(diff, cx);
2773                }
2774                if ensure_final_newline {
2775                    buffer.ensure_final_newline(cx);
2776                }
2777                buffer.end_transaction(cx)
2778            })?;
2779
2780            // Apply the `code_actions_on_format` before we run the formatter.
2781            let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
2782            #[allow(clippy::nonminimal_bool)]
2783            if !code_actions.is_empty()
2784                && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
2785            {
2786                LspStore::execute_code_actions_on_servers(
2787                    &lsp_store,
2788                    &adapters_and_servers,
2789                    code_actions,
2790                    buffer,
2791                    push_to_history,
2792                    &mut project_transaction,
2793                    &mut cx,
2794                )
2795                .await?;
2796            }
2797
2798            // Apply language-specific formatting using either the primary language server
2799            // or external command.
2800            // Except for code actions, which are applied with all connected language servers.
2801            let primary_language_server =
2802                primary_adapter_and_server.map(|(_adapter, server)| server.clone());
2803            let server_and_buffer = primary_language_server
2804                .as_ref()
2805                .zip(buffer_abs_path.as_ref());
2806
2807            let prettier_settings = buffer.read_with(&mut cx, |buffer, cx| {
2808                language_settings(buffer.language(), buffer.file(), cx)
2809                    .prettier
2810                    .clone()
2811            })?;
2812
2813            let mut format_operations: Vec<FormatOperation> = vec![];
2814            {
2815                match trigger {
2816                    FormatTrigger::Save => {
2817                        match &settings.format_on_save {
2818                            FormatOnSave::Off => {
2819                                // nothing
2820                            }
2821                            FormatOnSave::On => {
2822                                match &settings.formatter {
2823                                    SelectedFormatter::Auto => {
2824                                        // do the auto-format: prefer prettier, fallback to primary language server
2825                                        let diff = {
2826                                            if prettier_settings.allowed {
2827                                                Self::perform_format(
2828                                                    &Formatter::Prettier,
2829                                                    server_and_buffer,
2830                                                    project.clone(),
2831                                                    buffer,
2832                                                    buffer_abs_path,
2833                                                    &settings,
2834                                                    &adapters_and_servers,
2835                                                    push_to_history,
2836                                                    &mut project_transaction,
2837                                                    &mut cx,
2838                                                )
2839                                                .await
2840                                            } else {
2841                                                Self::perform_format(
2842                                                    &Formatter::LanguageServer { name: None },
2843                                                    server_and_buffer,
2844                                                    project.clone(),
2845                                                    buffer,
2846                                                    buffer_abs_path,
2847                                                    &settings,
2848                                                    &adapters_and_servers,
2849                                                    push_to_history,
2850                                                    &mut project_transaction,
2851                                                    &mut cx,
2852                                                )
2853                                                .await
2854                                            }
2855                                        }
2856                                        .log_err()
2857                                        .flatten();
2858                                        if let Some(op) = diff {
2859                                            format_operations.push(op);
2860                                        }
2861                                    }
2862                                    SelectedFormatter::List(formatters) => {
2863                                        for formatter in formatters.as_ref() {
2864                                            let diff = Self::perform_format(
2865                                                formatter,
2866                                                server_and_buffer,
2867                                                project.clone(),
2868                                                buffer,
2869                                                buffer_abs_path,
2870                                                &settings,
2871                                                &adapters_and_servers,
2872                                                push_to_history,
2873                                                &mut project_transaction,
2874                                                &mut cx,
2875                                            )
2876                                            .await
2877                                            .log_err()
2878                                            .flatten();
2879                                            if let Some(op) = diff {
2880                                                format_operations.push(op);
2881                                            }
2882
2883                                            // format with formatter
2884                                        }
2885                                    }
2886                                }
2887                            }
2888                            FormatOnSave::List(formatters) => {
2889                                for formatter in formatters.as_ref() {
2890                                    let diff = Self::perform_format(
2891                                        &formatter,
2892                                        server_and_buffer,
2893                                        project.clone(),
2894                                        buffer,
2895                                        buffer_abs_path,
2896                                        &settings,
2897                                        &adapters_and_servers,
2898                                        push_to_history,
2899                                        &mut project_transaction,
2900                                        &mut cx,
2901                                    )
2902                                    .await
2903                                    .log_err()
2904                                    .flatten();
2905                                    if let Some(op) = diff {
2906                                        format_operations.push(op);
2907                                    }
2908                                }
2909                            }
2910                        }
2911                    }
2912                    FormatTrigger::Manual => {
2913                        match &settings.formatter {
2914                            SelectedFormatter::Auto => {
2915                                // do the auto-format: prefer prettier, fallback to primary language server
2916                                let diff = {
2917                                    if prettier_settings.allowed {
2918                                        Self::perform_format(
2919                                            &Formatter::Prettier,
2920                                            server_and_buffer,
2921                                            project.clone(),
2922                                            buffer,
2923                                            buffer_abs_path,
2924                                            &settings,
2925                                            &adapters_and_servers,
2926                                            push_to_history,
2927                                            &mut project_transaction,
2928                                            &mut cx,
2929                                        )
2930                                        .await
2931                                    } else {
2932                                        Self::perform_format(
2933                                            &Formatter::LanguageServer { name: None },
2934                                            server_and_buffer,
2935                                            project.clone(),
2936                                            buffer,
2937                                            buffer_abs_path,
2938                                            &settings,
2939                                            &adapters_and_servers,
2940                                            push_to_history,
2941                                            &mut project_transaction,
2942                                            &mut cx,
2943                                        )
2944                                        .await
2945                                    }
2946                                }
2947                                .log_err()
2948                                .flatten();
2949
2950                                if let Some(op) = diff {
2951                                    format_operations.push(op)
2952                                }
2953                            }
2954                            SelectedFormatter::List(formatters) => {
2955                                for formatter in formatters.as_ref() {
2956                                    // format with formatter
2957                                    let diff = Self::perform_format(
2958                                        formatter,
2959                                        server_and_buffer,
2960                                        project.clone(),
2961                                        buffer,
2962                                        buffer_abs_path,
2963                                        &settings,
2964                                        &adapters_and_servers,
2965                                        push_to_history,
2966                                        &mut project_transaction,
2967                                        &mut cx,
2968                                    )
2969                                    .await
2970                                    .log_err()
2971                                    .flatten();
2972                                    if let Some(op) = diff {
2973                                        format_operations.push(op);
2974                                    }
2975                                }
2976                            }
2977                        }
2978                    }
2979                }
2980            }
2981
2982            buffer.update(&mut cx, |b, cx| {
2983                // If the buffer had its whitespace formatted and was edited while the language-specific
2984                // formatting was being computed, avoid applying the language-specific formatting, because
2985                // it can't be grouped with the whitespace formatting in the undo history.
2986                if let Some(transaction_id) = whitespace_transaction_id {
2987                    if b.peek_undo_stack()
2988                        .map_or(true, |e| e.transaction_id() != transaction_id)
2989                    {
2990                        format_operations.clear();
2991                    }
2992                }
2993
2994                // Apply any language-specific formatting, and group the two formatting operations
2995                // in the buffer's undo history.
2996                for operation in format_operations {
2997                    match operation {
2998                        FormatOperation::Lsp(edits) => {
2999                            b.edit(edits, None, cx);
3000                        }
3001                        FormatOperation::External(diff) => {
3002                            b.apply_diff(diff, cx);
3003                        }
3004                        FormatOperation::Prettier(diff) => {
3005                            b.apply_diff(diff, cx);
3006                        }
3007                    }
3008
3009                    if let Some(transaction_id) = whitespace_transaction_id {
3010                        b.group_until_transaction(transaction_id);
3011                    } else if let Some(transaction) = project_transaction.0.get(buffer) {
3012                        b.group_until_transaction(transaction.id)
3013                    }
3014                }
3015
3016                if let Some(transaction) = b.finalize_last_transaction().cloned() {
3017                    if !push_to_history {
3018                        b.forget_transaction(transaction.id);
3019                    }
3020                    project_transaction.0.insert(buffer.clone(), transaction);
3021                }
3022            })?;
3023        }
3024
3025        Ok(project_transaction)
3026    }
3027
3028    #[allow(clippy::too_many_arguments)]
3029    async fn perform_format(
3030        formatter: &Formatter,
3031        primary_server_and_buffer: Option<(&Arc<LanguageServer>, &PathBuf)>,
3032        project: WeakModel<Project>,
3033        buffer: &Model<Buffer>,
3034        buffer_abs_path: &Option<PathBuf>,
3035        settings: &LanguageSettings,
3036        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
3037        push_to_history: bool,
3038        transaction: &mut ProjectTransaction,
3039        mut cx: &mut AsyncAppContext,
3040    ) -> Result<Option<FormatOperation>, anyhow::Error> {
3041        let result = match formatter {
3042            Formatter::LanguageServer { name } => {
3043                if let Some((language_server, buffer_abs_path)) = primary_server_and_buffer {
3044                    let language_server = if let Some(name) = name {
3045                        adapters_and_servers
3046                            .iter()
3047                            .find_map(|(adapter, server)| {
3048                                adapter.name.0.as_ref().eq(name.as_str()).then_some(server)
3049                            })
3050                            .unwrap_or_else(|| language_server)
3051                    } else {
3052                        language_server
3053                    };
3054
3055                    let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
3056                    Some(FormatOperation::Lsp(
3057                        LspStore::format_via_lsp(
3058                            &lsp_store,
3059                            buffer,
3060                            buffer_abs_path,
3061                            language_server,
3062                            settings,
3063                            cx,
3064                        )
3065                        .await
3066                        .context("failed to format via language server")?,
3067                    ))
3068                } else {
3069                    None
3070                }
3071            }
3072            Formatter::Prettier => {
3073                prettier_support::format_with_prettier(&project, buffer, &mut cx)
3074                    .await
3075                    .transpose()
3076                    .ok()
3077                    .flatten()
3078            }
3079            Formatter::External { command, arguments } => {
3080                let buffer_abs_path = buffer_abs_path.as_ref().map(|path| path.as_path());
3081                Self::format_via_external_command(
3082                    buffer,
3083                    buffer_abs_path,
3084                    &command,
3085                    &arguments,
3086                    &mut cx,
3087                )
3088                .await
3089                .context(format!(
3090                    "failed to format via external command {:?}",
3091                    command
3092                ))?
3093                .map(FormatOperation::External)
3094            }
3095            Formatter::CodeActions(code_actions) => {
3096                let code_actions = deserialize_code_actions(&code_actions);
3097                let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
3098                if !code_actions.is_empty() {
3099                    LspStore::execute_code_actions_on_servers(
3100                        &lsp_store,
3101                        &adapters_and_servers,
3102                        code_actions,
3103                        buffer,
3104                        push_to_history,
3105                        transaction,
3106                        cx,
3107                    )
3108                    .await?;
3109                }
3110                None
3111            }
3112        };
3113        anyhow::Ok(result)
3114    }
3115
3116    async fn format_via_external_command(
3117        buffer: &Model<Buffer>,
3118        buffer_abs_path: Option<&Path>,
3119        command: &str,
3120        arguments: &[String],
3121        cx: &mut AsyncAppContext,
3122    ) -> Result<Option<Diff>> {
3123        let working_dir_path = buffer.update(cx, |buffer, cx| {
3124            let file = File::from_dyn(buffer.file())?;
3125            let worktree = file.worktree.read(cx);
3126            let mut worktree_path = worktree.abs_path().to_path_buf();
3127            if worktree.root_entry()?.is_file() {
3128                worktree_path.pop();
3129            }
3130            Some(worktree_path)
3131        })?;
3132
3133        let mut child = smol::process::Command::new(command);
3134        #[cfg(target_os = "windows")]
3135        {
3136            use smol::process::windows::CommandExt;
3137            child.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
3138        }
3139
3140        if let Some(working_dir_path) = working_dir_path {
3141            child.current_dir(working_dir_path);
3142        }
3143
3144        let mut child = child
3145            .args(arguments.iter().map(|arg| {
3146                if let Some(buffer_abs_path) = buffer_abs_path {
3147                    arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3148                } else {
3149                    arg.replace("{buffer_path}", "Untitled")
3150                }
3151            }))
3152            .stdin(smol::process::Stdio::piped())
3153            .stdout(smol::process::Stdio::piped())
3154            .stderr(smol::process::Stdio::piped())
3155            .spawn()?;
3156
3157        let stdin = child
3158            .stdin
3159            .as_mut()
3160            .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3161        let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
3162        for chunk in text.chunks() {
3163            stdin.write_all(chunk.as_bytes()).await?;
3164        }
3165        stdin.flush().await?;
3166
3167        let output = child.output().await?;
3168        if !output.status.success() {
3169            return Err(anyhow!(
3170                "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3171                output.status.code(),
3172                String::from_utf8_lossy(&output.stdout),
3173                String::from_utf8_lossy(&output.stderr),
3174            ));
3175        }
3176
3177        let stdout = String::from_utf8(output.stdout)?;
3178        Ok(Some(
3179            buffer
3180                .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
3181                .await,
3182        ))
3183    }
3184
3185    #[inline(never)]
3186    fn definition_impl(
3187        &self,
3188        buffer: &Model<Buffer>,
3189        position: PointUtf16,
3190        cx: &mut ModelContext<Self>,
3191    ) -> Task<Result<Vec<LocationLink>>> {
3192        self.request_lsp(
3193            buffer.clone(),
3194            LanguageServerToQuery::Primary,
3195            GetDefinition { position },
3196            cx,
3197        )
3198    }
3199    pub fn definition<T: ToPointUtf16>(
3200        &self,
3201        buffer: &Model<Buffer>,
3202        position: T,
3203        cx: &mut ModelContext<Self>,
3204    ) -> Task<Result<Vec<LocationLink>>> {
3205        let position = position.to_point_utf16(buffer.read(cx));
3206        self.definition_impl(buffer, position, cx)
3207    }
3208
3209    fn declaration_impl(
3210        &self,
3211        buffer: &Model<Buffer>,
3212        position: PointUtf16,
3213        cx: &mut ModelContext<Self>,
3214    ) -> Task<Result<Vec<LocationLink>>> {
3215        self.request_lsp(
3216            buffer.clone(),
3217            LanguageServerToQuery::Primary,
3218            GetDeclaration { position },
3219            cx,
3220        )
3221    }
3222
3223    pub fn declaration<T: ToPointUtf16>(
3224        &self,
3225        buffer: &Model<Buffer>,
3226        position: T,
3227        cx: &mut ModelContext<Self>,
3228    ) -> Task<Result<Vec<LocationLink>>> {
3229        let position = position.to_point_utf16(buffer.read(cx));
3230        self.declaration_impl(buffer, position, cx)
3231    }
3232
3233    fn type_definition_impl(
3234        &self,
3235        buffer: &Model<Buffer>,
3236        position: PointUtf16,
3237        cx: &mut ModelContext<Self>,
3238    ) -> Task<Result<Vec<LocationLink>>> {
3239        self.request_lsp(
3240            buffer.clone(),
3241            LanguageServerToQuery::Primary,
3242            GetTypeDefinition { position },
3243            cx,
3244        )
3245    }
3246
3247    pub fn type_definition<T: ToPointUtf16>(
3248        &self,
3249        buffer: &Model<Buffer>,
3250        position: T,
3251        cx: &mut ModelContext<Self>,
3252    ) -> Task<Result<Vec<LocationLink>>> {
3253        let position = position.to_point_utf16(buffer.read(cx));
3254        self.type_definition_impl(buffer, position, cx)
3255    }
3256
3257    pub fn implementation<T: ToPointUtf16>(
3258        &self,
3259        buffer: &Model<Buffer>,
3260        position: T,
3261        cx: &mut ModelContext<Self>,
3262    ) -> Task<Result<Vec<LocationLink>>> {
3263        let position = position.to_point_utf16(buffer.read(cx));
3264        self.request_lsp(
3265            buffer.clone(),
3266            LanguageServerToQuery::Primary,
3267            GetImplementation { position },
3268            cx,
3269        )
3270    }
3271
3272    pub fn references<T: ToPointUtf16>(
3273        &self,
3274        buffer: &Model<Buffer>,
3275        position: T,
3276        cx: &mut ModelContext<Self>,
3277    ) -> Task<Result<Vec<Location>>> {
3278        let position = position.to_point_utf16(buffer.read(cx));
3279        self.request_lsp(
3280            buffer.clone(),
3281            LanguageServerToQuery::Primary,
3282            GetReferences { position },
3283            cx,
3284        )
3285    }
3286
3287    fn document_highlights_impl(
3288        &self,
3289        buffer: &Model<Buffer>,
3290        position: PointUtf16,
3291        cx: &mut ModelContext<Self>,
3292    ) -> Task<Result<Vec<DocumentHighlight>>> {
3293        self.request_lsp(
3294            buffer.clone(),
3295            LanguageServerToQuery::Primary,
3296            GetDocumentHighlights { position },
3297            cx,
3298        )
3299    }
3300
3301    pub fn document_highlights<T: ToPointUtf16>(
3302        &self,
3303        buffer: &Model<Buffer>,
3304        position: T,
3305        cx: &mut ModelContext<Self>,
3306    ) -> Task<Result<Vec<DocumentHighlight>>> {
3307        let position = position.to_point_utf16(buffer.read(cx));
3308        self.document_highlights_impl(buffer, position, cx)
3309    }
3310
3311    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3312        self.lsp_store
3313            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3314    }
3315
3316    pub fn open_buffer_for_symbol(
3317        &mut self,
3318        symbol: &Symbol,
3319        cx: &mut ModelContext<Self>,
3320    ) -> Task<Result<Model<Buffer>>> {
3321        self.lsp_store.update(cx, |lsp_store, cx| {
3322            lsp_store.open_buffer_for_symbol(symbol, cx)
3323        })
3324    }
3325
3326    pub fn open_local_buffer_via_lsp(
3327        &mut self,
3328        abs_path: lsp::Url,
3329        language_server_id: LanguageServerId,
3330        language_server_name: LanguageServerName,
3331        cx: &mut ModelContext<Self>,
3332    ) -> Task<Result<Model<Buffer>>> {
3333        self.lsp_store.update(cx, |lsp_store, cx| {
3334            lsp_store.open_local_buffer_via_lsp(
3335                abs_path,
3336                language_server_id,
3337                language_server_name,
3338                cx,
3339            )
3340        })
3341    }
3342
3343    pub fn signature_help<T: ToPointUtf16>(
3344        &self,
3345        buffer: &Model<Buffer>,
3346        position: T,
3347        cx: &mut ModelContext<Self>,
3348    ) -> Task<Vec<SignatureHelp>> {
3349        self.lsp_store.update(cx, |lsp_store, cx| {
3350            lsp_store.signature_help(buffer, position, cx)
3351        })
3352    }
3353
3354    pub fn hover<T: ToPointUtf16>(
3355        &self,
3356        buffer: &Model<Buffer>,
3357        position: T,
3358        cx: &mut ModelContext<Self>,
3359    ) -> Task<Vec<Hover>> {
3360        let position = position.to_point_utf16(buffer.read(cx));
3361        self.lsp_store
3362            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3363    }
3364
3365    pub fn linked_edit(
3366        &self,
3367        buffer: &Model<Buffer>,
3368        position: Anchor,
3369        cx: &mut ModelContext<Self>,
3370    ) -> Task<Result<Vec<Range<Anchor>>>> {
3371        self.lsp_store.update(cx, |lsp_store, cx| {
3372            lsp_store.linked_edit(buffer, position, cx)
3373        })
3374    }
3375
3376    pub fn completions<T: ToOffset + ToPointUtf16>(
3377        &self,
3378        buffer: &Model<Buffer>,
3379        position: T,
3380        context: CompletionContext,
3381        cx: &mut ModelContext<Self>,
3382    ) -> Task<Result<Vec<Completion>>> {
3383        let position = position.to_point_utf16(buffer.read(cx));
3384        self.lsp_store.update(cx, |lsp_store, cx| {
3385            lsp_store.completions(buffer, position, context, cx)
3386        })
3387    }
3388
3389    pub fn resolve_completions(
3390        &self,
3391        buffer: Model<Buffer>,
3392        completion_indices: Vec<usize>,
3393        completions: Arc<RwLock<Box<[Completion]>>>,
3394        cx: &mut ModelContext<Self>,
3395    ) -> Task<Result<bool>> {
3396        self.lsp_store.update(cx, |lsp_store, cx| {
3397            lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
3398        })
3399    }
3400
3401    pub fn apply_additional_edits_for_completion(
3402        &self,
3403        buffer_handle: Model<Buffer>,
3404        completion: Completion,
3405        push_to_history: bool,
3406        cx: &mut ModelContext<Self>,
3407    ) -> Task<Result<Option<Transaction>>> {
3408        self.lsp_store.update(cx, |lsp_store, cx| {
3409            lsp_store.apply_additional_edits_for_completion(
3410                buffer_handle,
3411                completion,
3412                push_to_history,
3413                cx,
3414            )
3415        })
3416    }
3417
3418    pub fn code_actions<T: Clone + ToOffset>(
3419        &mut self,
3420        buffer_handle: &Model<Buffer>,
3421        range: Range<T>,
3422        cx: &mut ModelContext<Self>,
3423    ) -> Task<Vec<CodeAction>> {
3424        let buffer = buffer_handle.read(cx);
3425        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3426        self.lsp_store.update(cx, |lsp_store, cx| {
3427            lsp_store.code_actions(buffer_handle, range, cx)
3428        })
3429    }
3430
3431    pub fn apply_code_action(
3432        &self,
3433        buffer_handle: Model<Buffer>,
3434        action: CodeAction,
3435        push_to_history: bool,
3436        cx: &mut ModelContext<Self>,
3437    ) -> Task<Result<ProjectTransaction>> {
3438        self.lsp_store.update(cx, |lsp_store, cx| {
3439            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3440        })
3441    }
3442
3443    fn prepare_rename_impl(
3444        &mut self,
3445        buffer: Model<Buffer>,
3446        position: PointUtf16,
3447        cx: &mut ModelContext<Self>,
3448    ) -> Task<Result<Option<Range<Anchor>>>> {
3449        self.request_lsp(
3450            buffer,
3451            LanguageServerToQuery::Primary,
3452            PrepareRename { position },
3453            cx,
3454        )
3455    }
3456    pub fn prepare_rename<T: ToPointUtf16>(
3457        &mut self,
3458        buffer: Model<Buffer>,
3459        position: T,
3460        cx: &mut ModelContext<Self>,
3461    ) -> Task<Result<Option<Range<Anchor>>>> {
3462        let position = position.to_point_utf16(buffer.read(cx));
3463        self.prepare_rename_impl(buffer, position, cx)
3464    }
3465
3466    fn perform_rename_impl(
3467        &mut self,
3468        buffer: Model<Buffer>,
3469        position: PointUtf16,
3470        new_name: String,
3471        push_to_history: bool,
3472        cx: &mut ModelContext<Self>,
3473    ) -> Task<Result<ProjectTransaction>> {
3474        let position = position.to_point_utf16(buffer.read(cx));
3475        self.request_lsp(
3476            buffer,
3477            LanguageServerToQuery::Primary,
3478            PerformRename {
3479                position,
3480                new_name,
3481                push_to_history,
3482            },
3483            cx,
3484        )
3485    }
3486    pub fn perform_rename<T: ToPointUtf16>(
3487        &mut self,
3488        buffer: Model<Buffer>,
3489        position: T,
3490        new_name: String,
3491        push_to_history: bool,
3492        cx: &mut ModelContext<Self>,
3493    ) -> Task<Result<ProjectTransaction>> {
3494        let position = position.to_point_utf16(buffer.read(cx));
3495        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
3496    }
3497
3498    pub fn on_type_format<T: ToPointUtf16>(
3499        &mut self,
3500        buffer: Model<Buffer>,
3501        position: T,
3502        trigger: String,
3503        push_to_history: bool,
3504        cx: &mut ModelContext<Self>,
3505    ) -> Task<Result<Option<Transaction>>> {
3506        self.lsp_store.update(cx, |lsp_store, cx| {
3507            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3508        })
3509    }
3510
3511    pub fn inlay_hints<T: ToOffset>(
3512        &mut self,
3513        buffer_handle: Model<Buffer>,
3514        range: Range<T>,
3515        cx: &mut ModelContext<Self>,
3516    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3517        let buffer = buffer_handle.read(cx);
3518        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3519        self.lsp_store.update(cx, |lsp_store, cx| {
3520            lsp_store.inlay_hints(buffer_handle, range, cx)
3521        })
3522    }
3523
3524    pub fn resolve_inlay_hint(
3525        &self,
3526        hint: InlayHint,
3527        buffer_handle: Model<Buffer>,
3528        server_id: LanguageServerId,
3529        cx: &mut ModelContext<Self>,
3530    ) -> Task<anyhow::Result<InlayHint>> {
3531        self.lsp_store.update(cx, |lsp_store, cx| {
3532            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3533        })
3534    }
3535
3536    pub fn search(
3537        &mut self,
3538        query: SearchQuery,
3539        cx: &mut ModelContext<Self>,
3540    ) -> Receiver<SearchResult> {
3541        let (result_tx, result_rx) = smol::channel::unbounded();
3542
3543        let matching_buffers_rx = if query.is_opened_only() {
3544            self.sort_candidate_buffers(&query, cx)
3545        } else {
3546            self.search_for_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3547        };
3548
3549        cx.spawn(|_, cx| async move {
3550            let mut range_count = 0;
3551            let mut buffer_count = 0;
3552            let mut limit_reached = false;
3553            let query = Arc::new(query);
3554            let mut chunks = matching_buffers_rx.ready_chunks(64);
3555
3556            // Now that we know what paths match the query, we will load at most
3557            // 64 buffers at a time to avoid overwhelming the main thread. For each
3558            // opened buffer, we will spawn a background task that retrieves all the
3559            // ranges in the buffer matched by the query.
3560            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3561                let mut chunk_results = Vec::new();
3562                for buffer in matching_buffer_chunk {
3563                    let buffer = buffer.clone();
3564                    let query = query.clone();
3565                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3566                    chunk_results.push(cx.background_executor().spawn(async move {
3567                        let ranges = query
3568                            .search(&snapshot, None)
3569                            .await
3570                            .iter()
3571                            .map(|range| {
3572                                snapshot.anchor_before(range.start)
3573                                    ..snapshot.anchor_after(range.end)
3574                            })
3575                            .collect::<Vec<_>>();
3576                        anyhow::Ok((buffer, ranges))
3577                    }));
3578                }
3579
3580                let chunk_results = futures::future::join_all(chunk_results).await;
3581                for result in chunk_results {
3582                    if let Some((buffer, ranges)) = result.log_err() {
3583                        range_count += ranges.len();
3584                        buffer_count += 1;
3585                        result_tx
3586                            .send(SearchResult::Buffer { buffer, ranges })
3587                            .await?;
3588                        if buffer_count > MAX_SEARCH_RESULT_FILES
3589                            || range_count > MAX_SEARCH_RESULT_RANGES
3590                        {
3591                            limit_reached = true;
3592                            break 'outer;
3593                        }
3594                    }
3595                }
3596            }
3597
3598            if limit_reached {
3599                result_tx.send(SearchResult::LimitReached).await?;
3600            }
3601
3602            anyhow::Ok(())
3603        })
3604        .detach();
3605
3606        result_rx
3607    }
3608
3609    fn search_for_candidate_buffers(
3610        &mut self,
3611        query: &SearchQuery,
3612        limit: usize,
3613        cx: &mut ModelContext<Project>,
3614    ) -> Receiver<Model<Buffer>> {
3615        if self.is_local() {
3616            let fs = self.fs.clone();
3617            return self.buffer_store.update(cx, |buffer_store, cx| {
3618                buffer_store.find_search_candidates(query, limit, fs, cx)
3619            });
3620        } else {
3621            self.search_for_candidate_buffers_remote(query, limit, cx)
3622        }
3623    }
3624
3625    fn sort_candidate_buffers(
3626        &mut self,
3627        search_query: &SearchQuery,
3628        cx: &mut ModelContext<Project>,
3629    ) -> Receiver<Model<Buffer>> {
3630        let worktree_store = self.worktree_store.read(cx);
3631        let mut buffers = search_query
3632            .buffers()
3633            .into_iter()
3634            .flatten()
3635            .filter(|buffer| {
3636                let b = buffer.read(cx);
3637                if let Some(file) = b.file() {
3638                    if !search_query.file_matches(file.path()) {
3639                        return false;
3640                    }
3641                    if let Some(entry) = b
3642                        .entry_id(cx)
3643                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3644                    {
3645                        if entry.is_ignored && !search_query.include_ignored() {
3646                            return false;
3647                        }
3648                    }
3649                }
3650                return true;
3651            })
3652            .collect::<Vec<_>>();
3653        let (tx, rx) = smol::channel::unbounded();
3654        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3655            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3656            (None, Some(_)) => std::cmp::Ordering::Less,
3657            (Some(_), None) => std::cmp::Ordering::Greater,
3658            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3659        });
3660        for buffer in buffers {
3661            tx.send_blocking(buffer.clone()).unwrap()
3662        }
3663
3664        rx
3665    }
3666
3667    fn search_for_candidate_buffers_remote(
3668        &mut self,
3669        query: &SearchQuery,
3670        limit: usize,
3671        cx: &mut ModelContext<Project>,
3672    ) -> Receiver<Model<Buffer>> {
3673        let (tx, rx) = smol::channel::unbounded();
3674
3675        let (client, remote_id): (AnyProtoClient, _) =
3676            if let Some(ssh_session) = self.ssh_session.clone() {
3677                (ssh_session.into(), 0)
3678            } else if let Some(remote_id) = self.remote_id() {
3679                (self.client.clone().into(), remote_id)
3680            } else {
3681                return rx;
3682            };
3683
3684        let request = client.request(proto::FindSearchCandidates {
3685            project_id: remote_id,
3686            query: Some(query.to_proto()),
3687            limit: limit as _,
3688        });
3689        let guard = self.retain_remotely_created_buffers(cx);
3690
3691        cx.spawn(move |this, mut cx| async move {
3692            let response = request.await?;
3693            for buffer_id in response.buffer_ids {
3694                let buffer_id = BufferId::new(buffer_id)?;
3695                let buffer = this
3696                    .update(&mut cx, |this, cx| {
3697                        this.wait_for_remote_buffer(buffer_id, cx)
3698                    })?
3699                    .await?;
3700                let _ = tx.send(buffer).await;
3701            }
3702
3703            drop(guard);
3704            anyhow::Ok(())
3705        })
3706        .detach_and_log_err(cx);
3707        rx
3708    }
3709
3710    pub fn request_lsp<R: LspCommand>(
3711        &self,
3712        buffer_handle: Model<Buffer>,
3713        server: LanguageServerToQuery,
3714        request: R,
3715        cx: &mut ModelContext<Self>,
3716    ) -> Task<Result<R::Response>>
3717    where
3718        <R::LspRequest as lsp::request::Request>::Result: Send,
3719        <R::LspRequest as lsp::request::Request>::Params: Send,
3720    {
3721        self.lsp_store.update(cx, |lsp_store, cx| {
3722            lsp_store.request_lsp(buffer_handle, server, request, cx)
3723        })
3724    }
3725
3726    /// Move a worktree to a new position in the worktree order.
3727    ///
3728    /// The worktree will moved to the opposite side of the destination worktree.
3729    ///
3730    /// # Example
3731    ///
3732    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3733    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3734    ///
3735    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3736    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3737    ///
3738    /// # Errors
3739    ///
3740    /// An error will be returned if the worktree or destination worktree are not found.
3741    pub fn move_worktree(
3742        &mut self,
3743        source: WorktreeId,
3744        destination: WorktreeId,
3745        cx: &mut ModelContext<'_, Self>,
3746    ) -> Result<()> {
3747        self.worktree_store.update(cx, |worktree_store, cx| {
3748            worktree_store.move_worktree(source, destination, cx)
3749        })
3750    }
3751
3752    pub fn find_or_create_worktree(
3753        &mut self,
3754        abs_path: impl AsRef<Path>,
3755        visible: bool,
3756        cx: &mut ModelContext<Self>,
3757    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3758        let abs_path = abs_path.as_ref();
3759        if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
3760            Task::ready(Ok((tree, relative_path)))
3761        } else {
3762            let worktree = self.create_worktree(abs_path, visible, cx);
3763            cx.background_executor()
3764                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
3765        }
3766    }
3767
3768    pub fn find_worktree(
3769        &self,
3770        abs_path: &Path,
3771        cx: &AppContext,
3772    ) -> Option<(Model<Worktree>, PathBuf)> {
3773        self.worktree_store.read_with(cx, |worktree_store, cx| {
3774            worktree_store.find_worktree(abs_path, cx)
3775        })
3776    }
3777
3778    pub fn is_shared(&self) -> bool {
3779        match &self.client_state {
3780            ProjectClientState::Shared { .. } => true,
3781            ProjectClientState::Local => false,
3782            ProjectClientState::Remote { in_room, .. } => *in_room,
3783        }
3784    }
3785
3786    // Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3787    pub fn resolve_existing_file_path(
3788        &self,
3789        path: &str,
3790        buffer: &Model<Buffer>,
3791        cx: &mut ModelContext<Self>,
3792    ) -> Task<Option<ResolvedPath>> {
3793        // TODO: ssh based remoting.
3794        if self.ssh_session.is_some() {
3795            return Task::ready(None);
3796        }
3797
3798        if self.is_local_or_ssh() {
3799            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3800
3801            if expanded.is_absolute() {
3802                let fs = self.fs.clone();
3803                cx.background_executor().spawn(async move {
3804                    let path = expanded.as_path();
3805                    let exists = fs.is_file(path).await;
3806
3807                    exists.then(|| ResolvedPath::AbsPath(expanded))
3808                })
3809            } else {
3810                self.resolve_path_in_worktrees(expanded, buffer, cx)
3811            }
3812        } else {
3813            let path = PathBuf::from(path);
3814            if path.is_absolute() || path.starts_with("~") {
3815                return Task::ready(None);
3816            }
3817
3818            self.resolve_path_in_worktrees(path, buffer, cx)
3819        }
3820    }
3821
3822    fn resolve_path_in_worktrees(
3823        &self,
3824        path: PathBuf,
3825        buffer: &Model<Buffer>,
3826        cx: &mut ModelContext<Self>,
3827    ) -> Task<Option<ResolvedPath>> {
3828        let mut candidates = vec![path.clone()];
3829
3830        if let Some(file) = buffer.read(cx).file() {
3831            if let Some(dir) = file.path().parent() {
3832                let joined = dir.to_path_buf().join(path);
3833                candidates.push(joined);
3834            }
3835        }
3836
3837        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3838        cx.spawn(|_, mut cx| async move {
3839            for worktree in worktrees {
3840                for candidate in candidates.iter() {
3841                    let path = worktree
3842                        .update(&mut cx, |worktree, _| {
3843                            let root_entry_path = &worktree.root_entry()?.path;
3844
3845                            let resolved = resolve_path(&root_entry_path, candidate);
3846
3847                            let stripped =
3848                                resolved.strip_prefix(&root_entry_path).unwrap_or(&resolved);
3849
3850                            worktree.entry_for_path(stripped).map(|entry| {
3851                                ResolvedPath::ProjectPath(ProjectPath {
3852                                    worktree_id: worktree.id(),
3853                                    path: entry.path.clone(),
3854                                })
3855                            })
3856                        })
3857                        .ok()?;
3858
3859                    if path.is_some() {
3860                        return path;
3861                    }
3862                }
3863            }
3864            None
3865        })
3866    }
3867
3868    pub fn list_directory(
3869        &self,
3870        query: String,
3871        cx: &mut ModelContext<Self>,
3872    ) -> Task<Result<Vec<PathBuf>>> {
3873        if self.is_local_or_ssh() {
3874            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3875        } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3876            dev_server_projects::Store::global(cx)
3877                .read(cx)
3878                .dev_server_for_project(id)
3879        }) {
3880            let request = proto::ListRemoteDirectory {
3881                dev_server_id: dev_server.id.0,
3882                path: query,
3883            };
3884            let response = self.client.request(request);
3885            cx.background_executor().spawn(async move {
3886                let response = response.await?;
3887                Ok(response.entries.into_iter().map(PathBuf::from).collect())
3888            })
3889        } else {
3890            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3891        }
3892    }
3893
3894    fn create_worktree(
3895        &mut self,
3896        abs_path: impl AsRef<Path>,
3897        visible: bool,
3898        cx: &mut ModelContext<Self>,
3899    ) -> Task<Result<Model<Worktree>>> {
3900        self.worktree_store.update(cx, |worktree_store, cx| {
3901            worktree_store.create_worktree(abs_path, visible, cx)
3902        })
3903    }
3904
3905    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3906        self.worktree_store.update(cx, |worktree_store, cx| {
3907            worktree_store.remove_worktree(id_to_remove, cx);
3908        });
3909    }
3910
3911    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3912        self.worktree_store.update(cx, |worktree_store, cx| {
3913            worktree_store.add(worktree, cx);
3914        });
3915    }
3916
3917    fn update_local_worktree_settings(
3918        &mut self,
3919        worktree: &Model<Worktree>,
3920        changes: &UpdatedEntriesSet,
3921        cx: &mut ModelContext<Self>,
3922    ) {
3923        if worktree.read(cx).is_remote() {
3924            return;
3925        }
3926        let remote_worktree_id = worktree.read(cx).id();
3927
3928        for (path, _, change) in changes.iter() {
3929            let removed = change == &PathChange::Removed;
3930            let abs_path = match worktree.read(cx).absolutize(path) {
3931                Ok(abs_path) => abs_path,
3932                Err(e) => {
3933                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
3934                    continue;
3935                }
3936            };
3937
3938            if path.ends_with(local_tasks_file_relative_path()) {
3939                self.task_inventory().update(cx, |task_inventory, cx| {
3940                    if removed {
3941                        task_inventory.remove_local_static_source(&abs_path);
3942                    } else {
3943                        let fs = self.fs.clone();
3944                        let task_abs_path = abs_path.clone();
3945                        let tasks_file_rx =
3946                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
3947                        task_inventory.add_source(
3948                            TaskSourceKind::Worktree {
3949                                id: remote_worktree_id,
3950                                abs_path,
3951                                id_base: "local_tasks_for_worktree".into(),
3952                            },
3953                            |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
3954                            cx,
3955                        );
3956                    }
3957                })
3958            } else if path.ends_with(local_vscode_tasks_file_relative_path()) {
3959                self.task_inventory().update(cx, |task_inventory, cx| {
3960                    if removed {
3961                        task_inventory.remove_local_static_source(&abs_path);
3962                    } else {
3963                        let fs = self.fs.clone();
3964                        let task_abs_path = abs_path.clone();
3965                        let tasks_file_rx =
3966                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
3967                        task_inventory.add_source(
3968                            TaskSourceKind::Worktree {
3969                                id: remote_worktree_id,
3970                                abs_path,
3971                                id_base: "local_vscode_tasks_for_worktree".into(),
3972                            },
3973                            |tx, cx| {
3974                                StaticSource::new(TrackedFile::new_convertible::<
3975                                    task::VsCodeTaskFile,
3976                                >(
3977                                    tasks_file_rx, tx, cx
3978                                ))
3979                            },
3980                            cx,
3981                        );
3982                    }
3983                })
3984            }
3985        }
3986    }
3987
3988    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3989        let new_active_entry = entry.and_then(|project_path| {
3990            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3991            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3992            Some(entry.id)
3993        });
3994        if new_active_entry != self.active_entry {
3995            self.active_entry = new_active_entry;
3996            self.lsp_store.update(cx, |lsp_store, _| {
3997                lsp_store.set_active_entry(new_active_entry);
3998            });
3999            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4000        }
4001    }
4002
4003    pub fn language_servers_running_disk_based_diagnostics<'a>(
4004        &'a self,
4005        cx: &'a AppContext,
4006    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4007        self.lsp_store
4008            .read(cx)
4009            .language_servers_running_disk_based_diagnostics()
4010    }
4011
4012    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
4013        let mut summary = DiagnosticSummary::default();
4014        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
4015            summary.error_count += path_summary.error_count;
4016            summary.warning_count += path_summary.warning_count;
4017        }
4018        summary
4019    }
4020
4021    pub fn diagnostic_summaries<'a>(
4022        &'a self,
4023        include_ignored: bool,
4024        cx: &'a AppContext,
4025    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4026        self.lsp_store
4027            .read(cx)
4028            .diagnostic_summaries(include_ignored, cx)
4029    }
4030
4031    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4032        self.active_entry
4033    }
4034
4035    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4036        self.worktree_store.read(cx).entry_for_path(path, cx)
4037    }
4038
4039    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4040        let worktree = self.worktree_for_entry(entry_id, cx)?;
4041        let worktree = worktree.read(cx);
4042        let worktree_id = worktree.id();
4043        let path = worktree.entry_for_id(entry_id)?.path.clone();
4044        Some(ProjectPath { worktree_id, path })
4045    }
4046
4047    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
4048        let workspace_root = self
4049            .worktree_for_id(project_path.worktree_id, cx)?
4050            .read(cx)
4051            .abs_path();
4052        let project_path = project_path.path.as_ref();
4053
4054        Some(if project_path == Path::new("") {
4055            workspace_root.to_path_buf()
4056        } else {
4057            workspace_root.join(project_path)
4058        })
4059    }
4060
4061    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4062    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4063    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4064    /// the first visible worktree that has an entry for that relative path.
4065    ///
4066    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4067    /// root name from paths.
4068    ///
4069    /// # Arguments
4070    ///
4071    /// * `path` - A full path that starts with a worktree root name, or alternatively a
4072    ///            relative path within a visible worktree.
4073    /// * `cx` - A reference to the `AppContext`.
4074    ///
4075    /// # Returns
4076    ///
4077    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4078    pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
4079        let worktree_store = self.worktree_store.read(cx);
4080
4081        for worktree in worktree_store.visible_worktrees(cx) {
4082            let worktree_root_name = worktree.read(cx).root_name();
4083            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4084                return Some(ProjectPath {
4085                    worktree_id: worktree.read(cx).id(),
4086                    path: relative_path.into(),
4087                });
4088            }
4089        }
4090
4091        for worktree in worktree_store.visible_worktrees(cx) {
4092            let worktree = worktree.read(cx);
4093            if let Some(entry) = worktree.entry_for_path(path) {
4094                return Some(ProjectPath {
4095                    worktree_id: worktree.id(),
4096                    path: entry.path.clone(),
4097                });
4098            }
4099        }
4100
4101        None
4102    }
4103
4104    pub fn get_workspace_root(
4105        &self,
4106        project_path: &ProjectPath,
4107        cx: &AppContext,
4108    ) -> Option<PathBuf> {
4109        Some(
4110            self.worktree_for_id(project_path.worktree_id, cx)?
4111                .read(cx)
4112                .abs_path()
4113                .to_path_buf(),
4114        )
4115    }
4116
4117    pub fn get_repo(
4118        &self,
4119        project_path: &ProjectPath,
4120        cx: &AppContext,
4121    ) -> Option<Arc<dyn GitRepository>> {
4122        self.worktree_for_id(project_path.worktree_id, cx)?
4123            .read(cx)
4124            .as_local()?
4125            .local_git_repo(&project_path.path)
4126    }
4127
4128    pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
4129        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
4130        let root_entry = worktree.root_git_entry()?;
4131        worktree.get_local_repo(&root_entry)?.repo().clone().into()
4132    }
4133
4134    pub fn blame_buffer(
4135        &self,
4136        buffer: &Model<Buffer>,
4137        version: Option<clock::Global>,
4138        cx: &AppContext,
4139    ) -> Task<Result<Blame>> {
4140        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
4141    }
4142
4143    // RPC message handlers
4144
4145    async fn handle_unshare_project(
4146        this: Model<Self>,
4147        _: TypedEnvelope<proto::UnshareProject>,
4148        mut cx: AsyncAppContext,
4149    ) -> Result<()> {
4150        this.update(&mut cx, |this, cx| {
4151            if this.is_local_or_ssh() {
4152                this.unshare(cx)?;
4153            } else {
4154                this.disconnected_from_host(cx);
4155            }
4156            Ok(())
4157        })?
4158    }
4159
4160    async fn handle_add_collaborator(
4161        this: Model<Self>,
4162        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4163        mut cx: AsyncAppContext,
4164    ) -> Result<()> {
4165        let collaborator = envelope
4166            .payload
4167            .collaborator
4168            .take()
4169            .ok_or_else(|| anyhow!("empty collaborator"))?;
4170
4171        let collaborator = Collaborator::from_proto(collaborator)?;
4172        this.update(&mut cx, |this, cx| {
4173            this.buffer_store.update(cx, |buffer_store, _| {
4174                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4175            });
4176            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4177            this.collaborators
4178                .insert(collaborator.peer_id, collaborator);
4179            cx.notify();
4180        })?;
4181
4182        Ok(())
4183    }
4184
4185    async fn handle_update_project_collaborator(
4186        this: Model<Self>,
4187        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4188        mut cx: AsyncAppContext,
4189    ) -> Result<()> {
4190        let old_peer_id = envelope
4191            .payload
4192            .old_peer_id
4193            .ok_or_else(|| anyhow!("missing old peer id"))?;
4194        let new_peer_id = envelope
4195            .payload
4196            .new_peer_id
4197            .ok_or_else(|| anyhow!("missing new peer id"))?;
4198        this.update(&mut cx, |this, cx| {
4199            let collaborator = this
4200                .collaborators
4201                .remove(&old_peer_id)
4202                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4203            let is_host = collaborator.replica_id == 0;
4204            this.collaborators.insert(new_peer_id, collaborator);
4205
4206            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4207            this.buffer_store.update(cx, |buffer_store, _| {
4208                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4209            });
4210
4211            if is_host {
4212                this.buffer_store
4213                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4214                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4215                    .unwrap();
4216                cx.emit(Event::HostReshared);
4217            }
4218
4219            cx.emit(Event::CollaboratorUpdated {
4220                old_peer_id,
4221                new_peer_id,
4222            });
4223            cx.notify();
4224            Ok(())
4225        })?
4226    }
4227
4228    async fn handle_remove_collaborator(
4229        this: Model<Self>,
4230        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4231        mut cx: AsyncAppContext,
4232    ) -> Result<()> {
4233        this.update(&mut cx, |this, cx| {
4234            let peer_id = envelope
4235                .payload
4236                .peer_id
4237                .ok_or_else(|| anyhow!("invalid peer id"))?;
4238            let replica_id = this
4239                .collaborators
4240                .remove(&peer_id)
4241                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4242                .replica_id;
4243            this.buffer_store.update(cx, |buffer_store, cx| {
4244                buffer_store.forget_shared_buffers_for(&peer_id);
4245                for buffer in buffer_store.buffers() {
4246                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4247                }
4248            });
4249
4250            cx.emit(Event::CollaboratorLeft(peer_id));
4251            cx.notify();
4252            Ok(())
4253        })?
4254    }
4255
4256    async fn handle_update_project(
4257        this: Model<Self>,
4258        envelope: TypedEnvelope<proto::UpdateProject>,
4259        mut cx: AsyncAppContext,
4260    ) -> Result<()> {
4261        this.update(&mut cx, |this, cx| {
4262            // Don't handle messages that were sent before the response to us joining the project
4263            if envelope.message_id > this.join_project_response_message_id {
4264                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4265            }
4266            Ok(())
4267        })?
4268    }
4269
4270    async fn handle_update_worktree(
4271        this: Model<Self>,
4272        envelope: TypedEnvelope<proto::UpdateWorktree>,
4273        mut cx: AsyncAppContext,
4274    ) -> Result<()> {
4275        this.update(&mut cx, |this, cx| {
4276            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4277            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4278                worktree.update(cx, |worktree, _| {
4279                    let worktree = worktree.as_remote_mut().unwrap();
4280                    worktree.update_from_remote(envelope.payload);
4281                });
4282            }
4283            Ok(())
4284        })?
4285    }
4286
4287    async fn handle_update_buffer(
4288        this: Model<Self>,
4289        envelope: TypedEnvelope<proto::UpdateBuffer>,
4290        cx: AsyncAppContext,
4291    ) -> Result<proto::Ack> {
4292        let buffer_store = this.read_with(&cx, |this, cx| {
4293            if let Some(ssh) = &this.ssh_session {
4294                let mut payload = envelope.payload.clone();
4295                payload.project_id = 0;
4296                cx.background_executor()
4297                    .spawn(ssh.request(payload))
4298                    .detach_and_log_err(cx);
4299            }
4300            this.buffer_store.clone()
4301        })?;
4302        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4303    }
4304
4305    fn retain_remotely_created_buffers(
4306        &mut self,
4307        cx: &mut ModelContext<Self>,
4308    ) -> RemotelyCreatedBufferGuard {
4309        {
4310            let mut remotely_created_buffers = self.remotely_created_buffers.lock();
4311            if remotely_created_buffers.retain_count == 0 {
4312                remotely_created_buffers.buffers = self.buffer_store.read(cx).buffers().collect();
4313            }
4314            remotely_created_buffers.retain_count += 1;
4315        }
4316        RemotelyCreatedBufferGuard {
4317            remote_buffers: Arc::downgrade(&self.remotely_created_buffers),
4318        }
4319    }
4320
4321    async fn handle_create_buffer_for_peer(
4322        this: Model<Self>,
4323        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4324        mut cx: AsyncAppContext,
4325    ) -> Result<()> {
4326        this.update(&mut cx, |this, cx| {
4327            this.buffer_store.update(cx, |buffer_store, cx| {
4328                buffer_store.handle_create_buffer_for_peer(
4329                    envelope,
4330                    this.replica_id(),
4331                    this.capability(),
4332                    cx,
4333                )
4334            })
4335        })?
4336    }
4337
4338    async fn handle_reload_buffers(
4339        this: Model<Self>,
4340        envelope: TypedEnvelope<proto::ReloadBuffers>,
4341        mut cx: AsyncAppContext,
4342    ) -> Result<proto::ReloadBuffersResponse> {
4343        let sender_id = envelope.original_sender_id()?;
4344        let reload = this.update(&mut cx, |this, cx| {
4345            let mut buffers = HashSet::default();
4346            for buffer_id in &envelope.payload.buffer_ids {
4347                let buffer_id = BufferId::new(*buffer_id)?;
4348                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
4349            }
4350            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
4351        })??;
4352
4353        let project_transaction = reload.await?;
4354        let project_transaction = this.update(&mut cx, |this, cx| {
4355            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4356        })?;
4357        Ok(proto::ReloadBuffersResponse {
4358            transaction: Some(project_transaction),
4359        })
4360    }
4361
4362    async fn handle_synchronize_buffers(
4363        this: Model<Self>,
4364        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4365        mut cx: AsyncAppContext,
4366    ) -> Result<proto::SynchronizeBuffersResponse> {
4367        let response = this.update(&mut cx, |this, cx| {
4368            let client = this.client.clone();
4369            this.buffer_store.update(cx, |this, cx| {
4370                this.handle_synchronize_buffers(envelope, cx, client)
4371            })
4372        })??;
4373
4374        Ok(response)
4375    }
4376
4377    async fn handle_format_buffers(
4378        this: Model<Self>,
4379        envelope: TypedEnvelope<proto::FormatBuffers>,
4380        mut cx: AsyncAppContext,
4381    ) -> Result<proto::FormatBuffersResponse> {
4382        let sender_id = envelope.original_sender_id()?;
4383        let format = this.update(&mut cx, |this, cx| {
4384            let mut buffers = HashSet::default();
4385            for buffer_id in &envelope.payload.buffer_ids {
4386                let buffer_id = BufferId::new(*buffer_id)?;
4387                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
4388            }
4389            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
4390            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
4391        })??;
4392
4393        let project_transaction = format.await?;
4394        let project_transaction = this.update(&mut cx, |this, cx| {
4395            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4396        })?;
4397        Ok(proto::FormatBuffersResponse {
4398            transaction: Some(project_transaction),
4399        })
4400    }
4401
4402    async fn handle_task_context_for_location(
4403        project: Model<Self>,
4404        envelope: TypedEnvelope<proto::TaskContextForLocation>,
4405        mut cx: AsyncAppContext,
4406    ) -> Result<proto::TaskContext> {
4407        let location = envelope
4408            .payload
4409            .location
4410            .context("no location given for task context handling")?;
4411        let location = cx
4412            .update(|cx| deserialize_location(&project, location, cx))?
4413            .await?;
4414        let context_task = project.update(&mut cx, |project, cx| {
4415            let captured_variables = {
4416                let mut variables = TaskVariables::default();
4417                for range in location
4418                    .buffer
4419                    .read(cx)
4420                    .snapshot()
4421                    .runnable_ranges(location.range.clone())
4422                {
4423                    for (capture_name, value) in range.extra_captures {
4424                        variables.insert(VariableName::Custom(capture_name.into()), value);
4425                    }
4426                }
4427                variables
4428            };
4429            project.task_context_for_location(captured_variables, location, cx)
4430        })?;
4431        let task_context = context_task.await.unwrap_or_default();
4432        Ok(proto::TaskContext {
4433            project_env: task_context.project_env.into_iter().collect(),
4434            cwd: task_context
4435                .cwd
4436                .map(|cwd| cwd.to_string_lossy().to_string()),
4437            task_variables: task_context
4438                .task_variables
4439                .into_iter()
4440                .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
4441                .collect(),
4442        })
4443    }
4444
4445    async fn handle_task_templates(
4446        project: Model<Self>,
4447        envelope: TypedEnvelope<proto::TaskTemplates>,
4448        mut cx: AsyncAppContext,
4449    ) -> Result<proto::TaskTemplatesResponse> {
4450        let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
4451        let location = match envelope.payload.location {
4452            Some(location) => Some(
4453                cx.update(|cx| deserialize_location(&project, location, cx))?
4454                    .await
4455                    .context("task templates request location deserializing")?,
4456            ),
4457            None => None,
4458        };
4459
4460        let templates = project
4461            .update(&mut cx, |project, cx| {
4462                project.task_templates(worktree, location, cx)
4463            })?
4464            .await
4465            .context("receiving task templates")?
4466            .into_iter()
4467            .map(|(kind, template)| {
4468                let kind = Some(match kind {
4469                    TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
4470                        proto::task_source_kind::UserInput {},
4471                    ),
4472                    TaskSourceKind::Worktree {
4473                        id,
4474                        abs_path,
4475                        id_base,
4476                    } => {
4477                        proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
4478                            id: id.to_proto(),
4479                            abs_path: abs_path.to_string_lossy().to_string(),
4480                            id_base: id_base.to_string(),
4481                        })
4482                    }
4483                    TaskSourceKind::AbsPath { id_base, abs_path } => {
4484                        proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
4485                            abs_path: abs_path.to_string_lossy().to_string(),
4486                            id_base: id_base.to_string(),
4487                        })
4488                    }
4489                    TaskSourceKind::Language { name } => {
4490                        proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
4491                            name: name.to_string(),
4492                        })
4493                    }
4494                });
4495                let kind = Some(proto::TaskSourceKind { kind });
4496                let template = Some(proto::TaskTemplate {
4497                    label: template.label,
4498                    command: template.command,
4499                    args: template.args,
4500                    env: template.env.into_iter().collect(),
4501                    cwd: template.cwd,
4502                    use_new_terminal: template.use_new_terminal,
4503                    allow_concurrent_runs: template.allow_concurrent_runs,
4504                    reveal: match template.reveal {
4505                        RevealStrategy::Always => proto::RevealStrategy::RevealAlways as i32,
4506                        RevealStrategy::Never => proto::RevealStrategy::RevealNever as i32,
4507                    },
4508                    hide: match template.hide {
4509                        HideStrategy::Always => proto::HideStrategy::HideAlways as i32,
4510                        HideStrategy::Never => proto::HideStrategy::HideNever as i32,
4511                        HideStrategy::OnSuccess => proto::HideStrategy::HideOnSuccess as i32,
4512                    },
4513                    shell: Some(proto::Shell {
4514                        shell_type: Some(match template.shell {
4515                            Shell::System => proto::shell::ShellType::System(proto::System {}),
4516                            Shell::Program(program) => proto::shell::ShellType::Program(program),
4517                            Shell::WithArguments { program, args } => {
4518                                proto::shell::ShellType::WithArguments(
4519                                    proto::shell::WithArguments { program, args },
4520                                )
4521                            }
4522                        }),
4523                    }),
4524                    tags: template.tags,
4525                });
4526                proto::TemplatePair { kind, template }
4527            })
4528            .collect();
4529
4530        Ok(proto::TaskTemplatesResponse { templates })
4531    }
4532
4533    async fn handle_search_project(
4534        this: Model<Self>,
4535        envelope: TypedEnvelope<proto::SearchProject>,
4536        mut cx: AsyncAppContext,
4537    ) -> Result<proto::SearchProjectResponse> {
4538        let peer_id = envelope.original_sender_id()?;
4539        let query = SearchQuery::from_proto_v1(envelope.payload)?;
4540        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
4541
4542        cx.spawn(move |mut cx| async move {
4543            let mut locations = Vec::new();
4544            let mut limit_reached = false;
4545            while let Some(result) = result.next().await {
4546                match result {
4547                    SearchResult::Buffer { buffer, ranges } => {
4548                        for range in ranges {
4549                            let start = serialize_anchor(&range.start);
4550                            let end = serialize_anchor(&range.end);
4551                            let buffer_id = this.update(&mut cx, |this, cx| {
4552                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
4553                            })?;
4554                            locations.push(proto::Location {
4555                                buffer_id,
4556                                start: Some(start),
4557                                end: Some(end),
4558                            });
4559                        }
4560                    }
4561                    SearchResult::LimitReached => limit_reached = true,
4562                }
4563            }
4564            Ok(proto::SearchProjectResponse {
4565                locations,
4566                limit_reached,
4567                // will restart
4568            })
4569        })
4570        .await
4571    }
4572
4573    async fn handle_search_candidate_buffers(
4574        this: Model<Self>,
4575        envelope: TypedEnvelope<proto::FindSearchCandidates>,
4576        mut cx: AsyncAppContext,
4577    ) -> Result<proto::FindSearchCandidatesResponse> {
4578        let peer_id = envelope.original_sender_id()?;
4579        let message = envelope.payload;
4580        let query = SearchQuery::from_proto(
4581            message
4582                .query
4583                .ok_or_else(|| anyhow!("missing query field"))?,
4584        )?;
4585        let mut results = this.update(&mut cx, |this, cx| {
4586            this.search_for_candidate_buffers(&query, message.limit as _, cx)
4587        })?;
4588
4589        let mut response = proto::FindSearchCandidatesResponse {
4590            buffer_ids: Vec::new(),
4591        };
4592
4593        while let Some(buffer) = results.next().await {
4594            this.update(&mut cx, |this, cx| {
4595                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4596                response.buffer_ids.push(buffer_id.to_proto());
4597            })?;
4598        }
4599
4600        Ok(response)
4601    }
4602
4603    async fn handle_open_buffer_by_id(
4604        this: Model<Self>,
4605        envelope: TypedEnvelope<proto::OpenBufferById>,
4606        mut cx: AsyncAppContext,
4607    ) -> Result<proto::OpenBufferResponse> {
4608        let peer_id = envelope.original_sender_id()?;
4609        let buffer_id = BufferId::new(envelope.payload.id)?;
4610        let buffer = this
4611            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4612            .await?;
4613        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4614    }
4615
4616    async fn handle_open_buffer_by_path(
4617        this: Model<Self>,
4618        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4619        mut cx: AsyncAppContext,
4620    ) -> Result<proto::OpenBufferResponse> {
4621        let peer_id = envelope.original_sender_id()?;
4622        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4623        let open_buffer = this.update(&mut cx, |this, cx| {
4624            this.open_buffer(
4625                ProjectPath {
4626                    worktree_id,
4627                    path: PathBuf::from(envelope.payload.path).into(),
4628                },
4629                cx,
4630            )
4631        })?;
4632
4633        let buffer = open_buffer.await?;
4634        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4635    }
4636
4637    async fn handle_open_new_buffer(
4638        this: Model<Self>,
4639        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4640        mut cx: AsyncAppContext,
4641    ) -> Result<proto::OpenBufferResponse> {
4642        let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
4643        let peer_id = envelope.original_sender_id()?;
4644
4645        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4646    }
4647
4648    fn respond_to_open_buffer_request(
4649        this: Model<Self>,
4650        buffer: Model<Buffer>,
4651        peer_id: proto::PeerId,
4652        cx: &mut AsyncAppContext,
4653    ) -> Result<proto::OpenBufferResponse> {
4654        this.update(cx, |this, cx| {
4655            let is_private = buffer
4656                .read(cx)
4657                .file()
4658                .map(|f| f.is_private())
4659                .unwrap_or_default();
4660            if is_private {
4661                Err(anyhow!(ErrorCode::UnsharedItem))
4662            } else {
4663                Ok(proto::OpenBufferResponse {
4664                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4665                })
4666            }
4667        })?
4668    }
4669
4670    fn serialize_project_transaction_for_peer(
4671        &mut self,
4672        project_transaction: ProjectTransaction,
4673        peer_id: proto::PeerId,
4674        cx: &mut AppContext,
4675    ) -> proto::ProjectTransaction {
4676        self.buffer_store.update(cx, |buffer_store, cx| {
4677            buffer_store.serialize_project_transaction_for_peer(project_transaction, peer_id, cx)
4678        })
4679    }
4680
4681    fn create_buffer_for_peer(
4682        &mut self,
4683        buffer: &Model<Buffer>,
4684        peer_id: proto::PeerId,
4685        cx: &mut AppContext,
4686    ) -> BufferId {
4687        self.buffer_store
4688            .update(cx, |buffer_store, cx| {
4689                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4690            })
4691            .detach_and_log_err(cx);
4692        buffer.read(cx).remote_id()
4693    }
4694
4695    fn wait_for_remote_buffer(
4696        &mut self,
4697        id: BufferId,
4698        cx: &mut ModelContext<Self>,
4699    ) -> Task<Result<Model<Buffer>>> {
4700        self.buffer_store.update(cx, |buffer_store, cx| {
4701            buffer_store.wait_for_remote_buffer(id, cx)
4702        })
4703    }
4704
4705    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
4706        let project_id = match self.client_state {
4707            ProjectClientState::Remote {
4708                sharing_has_stopped,
4709                remote_id,
4710                ..
4711            } => {
4712                if sharing_has_stopped {
4713                    return Task::ready(Err(anyhow!(
4714                        "can't synchronize remote buffers on a readonly project"
4715                    )));
4716                } else {
4717                    remote_id
4718                }
4719            }
4720            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4721                return Task::ready(Err(anyhow!(
4722                    "can't synchronize remote buffers on a local project"
4723                )))
4724            }
4725        };
4726
4727        let client = self.client.clone();
4728        cx.spawn(move |this, mut cx| async move {
4729            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4730                this.buffer_store.read(cx).buffer_version_info(cx)
4731            })?;
4732            let response = client
4733                .request(proto::SynchronizeBuffers {
4734                    project_id,
4735                    buffers,
4736                })
4737                .await?;
4738
4739            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4740                response
4741                    .buffers
4742                    .into_iter()
4743                    .map(|buffer| {
4744                        let client = client.clone();
4745                        let buffer_id = match BufferId::new(buffer.id) {
4746                            Ok(id) => id,
4747                            Err(e) => {
4748                                return Task::ready(Err(e));
4749                            }
4750                        };
4751                        let remote_version = language::proto::deserialize_version(&buffer.version);
4752                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4753                            let operations =
4754                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4755                            cx.background_executor().spawn(async move {
4756                                let operations = operations.await;
4757                                for chunk in split_operations(operations) {
4758                                    client
4759                                        .request(proto::UpdateBuffer {
4760                                            project_id,
4761                                            buffer_id: buffer_id.into(),
4762                                            operations: chunk,
4763                                        })
4764                                        .await?;
4765                                }
4766                                anyhow::Ok(())
4767                            })
4768                        } else {
4769                            Task::ready(Ok(()))
4770                        }
4771                    })
4772                    .collect::<Vec<_>>()
4773            })?;
4774
4775            // Any incomplete buffers have open requests waiting. Request that the host sends
4776            // creates these buffers for us again to unblock any waiting futures.
4777            for id in incomplete_buffer_ids {
4778                cx.background_executor()
4779                    .spawn(client.request(proto::OpenBufferById {
4780                        project_id,
4781                        id: id.into(),
4782                    }))
4783                    .detach();
4784            }
4785
4786            futures::future::join_all(send_updates_for_buffers)
4787                .await
4788                .into_iter()
4789                .collect()
4790        })
4791    }
4792
4793    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
4794        self.worktrees(cx)
4795            .map(|worktree| {
4796                let worktree = worktree.read(cx);
4797                proto::WorktreeMetadata {
4798                    id: worktree.id().to_proto(),
4799                    root_name: worktree.root_name().into(),
4800                    visible: worktree.is_visible(),
4801                    abs_path: worktree.abs_path().to_string_lossy().into(),
4802                }
4803            })
4804            .collect()
4805    }
4806
4807    fn set_worktrees_from_proto(
4808        &mut self,
4809        worktrees: Vec<proto::WorktreeMetadata>,
4810        cx: &mut ModelContext<Project>,
4811    ) -> Result<()> {
4812        self.metadata_changed(cx);
4813        self.worktree_store.update(cx, |worktree_store, cx| {
4814            worktree_store.set_worktrees_from_proto(
4815                worktrees,
4816                self.replica_id(),
4817                self.remote_id().ok_or_else(|| anyhow!("invalid project"))?,
4818                self.client.clone().into(),
4819                cx,
4820            )
4821        })
4822    }
4823
4824    fn set_collaborators_from_proto(
4825        &mut self,
4826        messages: Vec<proto::Collaborator>,
4827        cx: &mut ModelContext<Self>,
4828    ) -> Result<()> {
4829        let mut collaborators = HashMap::default();
4830        for message in messages {
4831            let collaborator = Collaborator::from_proto(message)?;
4832            collaborators.insert(collaborator.peer_id, collaborator);
4833        }
4834        for old_peer_id in self.collaborators.keys() {
4835            if !collaborators.contains_key(old_peer_id) {
4836                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4837            }
4838        }
4839        self.collaborators = collaborators;
4840        Ok(())
4841    }
4842
4843    pub fn language_servers<'a>(
4844        &'a self,
4845        cx: &'a AppContext,
4846    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
4847        self.lsp_store.read(cx).language_servers()
4848    }
4849
4850    pub fn supplementary_language_servers<'a>(
4851        &'a self,
4852        cx: &'a AppContext,
4853    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4854        self.lsp_store.read(cx).supplementary_language_servers()
4855    }
4856
4857    pub fn language_server_adapter_for_id(
4858        &self,
4859        id: LanguageServerId,
4860        cx: &AppContext,
4861    ) -> Option<Arc<CachedLspAdapter>> {
4862        self.lsp_store.read(cx).language_server_adapter_for_id(id)
4863    }
4864
4865    pub fn language_server_for_id(
4866        &self,
4867        id: LanguageServerId,
4868        cx: &AppContext,
4869    ) -> Option<Arc<LanguageServer>> {
4870        self.lsp_store.read(cx).language_server_for_id(id)
4871    }
4872
4873    pub fn language_servers_for_buffer<'a>(
4874        &'a self,
4875        buffer: &'a Buffer,
4876        cx: &'a AppContext,
4877    ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4878        self.lsp_store
4879            .read(cx)
4880            .language_servers_for_buffer(buffer, cx)
4881    }
4882
4883    pub fn language_server_for_buffer<'a>(
4884        &'a self,
4885        buffer: &'a Buffer,
4886        server_id: LanguageServerId,
4887        cx: &'a AppContext,
4888    ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4889        self.lsp_store
4890            .read(cx)
4891            .language_server_for_buffer(buffer, server_id, cx)
4892    }
4893
4894    pub fn task_context_for_location(
4895        &self,
4896        captured_variables: TaskVariables,
4897        location: Location,
4898        cx: &mut ModelContext<'_, Project>,
4899    ) -> Task<Option<TaskContext>> {
4900        if self.is_local_or_ssh() {
4901            let (worktree_id, worktree_abs_path) = if let Some(worktree) = self.task_worktree(cx) {
4902                (
4903                    Some(worktree.read(cx).id()),
4904                    Some(worktree.read(cx).abs_path()),
4905                )
4906            } else {
4907                (None, None)
4908            };
4909
4910            cx.spawn(|project, mut cx| async move {
4911                let mut task_variables = cx
4912                    .update(|cx| {
4913                        combine_task_variables(
4914                            captured_variables,
4915                            location,
4916                            BasicContextProvider::new(project.upgrade()?),
4917                            cx,
4918                        )
4919                        .log_err()
4920                    })
4921                    .ok()
4922                    .flatten()?;
4923                // Remove all custom entries starting with _, as they're not intended for use by the end user.
4924                task_variables.sweep();
4925
4926                let project_env = project
4927                    .update(&mut cx, |project, cx| {
4928                        let worktree_abs_path = worktree_abs_path.clone();
4929                        project.environment.update(cx, |environment, cx| {
4930                            environment.get_environment(worktree_id, worktree_abs_path, cx)
4931                        })
4932                    })
4933                    .ok()?
4934                    .await;
4935
4936                Some(TaskContext {
4937                    project_env: project_env.unwrap_or_default(),
4938                    cwd: worktree_abs_path.map(|p| p.to_path_buf()),
4939                    task_variables,
4940                })
4941            })
4942        } else if let Some(project_id) = self
4943            .remote_id()
4944            .filter(|_| self.ssh_connection_string(cx).is_some())
4945        {
4946            let task_context = self.client().request(proto::TaskContextForLocation {
4947                project_id,
4948                location: Some(proto::Location {
4949                    buffer_id: location.buffer.read(cx).remote_id().into(),
4950                    start: Some(serialize_anchor(&location.range.start)),
4951                    end: Some(serialize_anchor(&location.range.end)),
4952                }),
4953            });
4954            cx.background_executor().spawn(async move {
4955                let task_context = task_context.await.log_err()?;
4956                Some(TaskContext {
4957                    project_env: task_context.project_env.into_iter().collect(),
4958                    cwd: task_context.cwd.map(PathBuf::from),
4959                    task_variables: task_context
4960                        .task_variables
4961                        .into_iter()
4962                        .filter_map(
4963                            |(variable_name, variable_value)| match variable_name.parse() {
4964                                Ok(variable_name) => Some((variable_name, variable_value)),
4965                                Err(()) => {
4966                                    log::error!("Unknown variable name: {variable_name}");
4967                                    None
4968                                }
4969                            },
4970                        )
4971                        .collect(),
4972                })
4973            })
4974        } else {
4975            Task::ready(None)
4976        }
4977    }
4978
4979    pub fn task_templates(
4980        &self,
4981        worktree: Option<WorktreeId>,
4982        location: Option<Location>,
4983        cx: &mut ModelContext<Self>,
4984    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
4985        if self.is_local_or_ssh() {
4986            let (file, language) = location
4987                .map(|location| {
4988                    let buffer = location.buffer.read(cx);
4989                    (
4990                        buffer.file().cloned(),
4991                        buffer.language_at(location.range.start),
4992                    )
4993                })
4994                .unwrap_or_default();
4995            Task::ready(Ok(self
4996                .task_inventory()
4997                .read(cx)
4998                .list_tasks(file, language, worktree, cx)))
4999        } else if let Some(project_id) = self
5000            .remote_id()
5001            .filter(|_| self.ssh_connection_string(cx).is_some())
5002        {
5003            let remote_templates =
5004                self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
5005            cx.background_executor().spawn(remote_templates)
5006        } else {
5007            Task::ready(Ok(Vec::new()))
5008        }
5009    }
5010
5011    pub fn query_remote_task_templates(
5012        &self,
5013        project_id: u64,
5014        worktree: Option<WorktreeId>,
5015        location: Option<&Location>,
5016        cx: &AppContext,
5017    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
5018        let client = self.client();
5019        let location = location.map(|location| serialize_location(location, cx));
5020        cx.spawn(|_| async move {
5021            let response = client
5022                .request(proto::TaskTemplates {
5023                    project_id,
5024                    worktree_id: worktree.map(|id| id.to_proto()),
5025                    location,
5026                })
5027                .await?;
5028
5029            Ok(response
5030                .templates
5031                .into_iter()
5032                .filter_map(|template_pair| {
5033                    let task_source_kind = match template_pair.kind?.kind? {
5034                        proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
5035                        proto::task_source_kind::Kind::Worktree(worktree) => {
5036                            TaskSourceKind::Worktree {
5037                                id: WorktreeId::from_proto(worktree.id),
5038                                abs_path: PathBuf::from(worktree.abs_path),
5039                                id_base: Cow::Owned(worktree.id_base),
5040                            }
5041                        }
5042                        proto::task_source_kind::Kind::AbsPath(abs_path) => {
5043                            TaskSourceKind::AbsPath {
5044                                id_base: Cow::Owned(abs_path.id_base),
5045                                abs_path: PathBuf::from(abs_path.abs_path),
5046                            }
5047                        }
5048                        proto::task_source_kind::Kind::Language(language) => {
5049                            TaskSourceKind::Language {
5050                                name: language.name.into(),
5051                            }
5052                        }
5053                    };
5054
5055                    let proto_template = template_pair.template?;
5056                    let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
5057                        .unwrap_or(proto::RevealStrategy::RevealAlways)
5058                    {
5059                        proto::RevealStrategy::RevealAlways => RevealStrategy::Always,
5060                        proto::RevealStrategy::RevealNever => RevealStrategy::Never,
5061                    };
5062                    let hide = match proto::HideStrategy::from_i32(proto_template.hide)
5063                        .unwrap_or(proto::HideStrategy::HideNever)
5064                    {
5065                        proto::HideStrategy::HideAlways => HideStrategy::Always,
5066                        proto::HideStrategy::HideNever => HideStrategy::Never,
5067                        proto::HideStrategy::HideOnSuccess => HideStrategy::OnSuccess,
5068                    };
5069                    let shell = match proto_template
5070                        .shell
5071                        .and_then(|shell| shell.shell_type)
5072                        .unwrap_or(proto::shell::ShellType::System(proto::System {}))
5073                    {
5074                        proto::shell::ShellType::System(_) => Shell::System,
5075                        proto::shell::ShellType::Program(program) => Shell::Program(program),
5076                        proto::shell::ShellType::WithArguments(with_arguments) => {
5077                            Shell::WithArguments {
5078                                program: with_arguments.program,
5079                                args: with_arguments.args,
5080                            }
5081                        }
5082                    };
5083                    let task_template = TaskTemplate {
5084                        label: proto_template.label,
5085                        command: proto_template.command,
5086                        args: proto_template.args,
5087                        env: proto_template.env.into_iter().collect(),
5088                        cwd: proto_template.cwd,
5089                        use_new_terminal: proto_template.use_new_terminal,
5090                        allow_concurrent_runs: proto_template.allow_concurrent_runs,
5091                        reveal,
5092                        hide,
5093                        shell,
5094                        tags: proto_template.tags,
5095                    };
5096                    Some((task_source_kind, task_template))
5097                })
5098                .collect())
5099        })
5100    }
5101
5102    fn task_worktree(&self, cx: &AppContext) -> Option<Model<Worktree>> {
5103        let available_worktrees = self
5104            .worktrees(cx)
5105            .filter(|worktree| {
5106                let worktree = worktree.read(cx);
5107                worktree.is_visible()
5108                    && worktree.is_local()
5109                    && worktree.root_entry().map_or(false, |e| e.is_dir())
5110            })
5111            .collect::<Vec<_>>();
5112
5113        match available_worktrees.len() {
5114            0 => None,
5115            1 => Some(available_worktrees[0].clone()),
5116            _ => self.active_entry().and_then(|entry_id| {
5117                available_worktrees.into_iter().find_map(|worktree| {
5118                    if worktree.read(cx).contains_entry(entry_id) {
5119                        Some(worktree)
5120                    } else {
5121                        None
5122                    }
5123                })
5124            }),
5125        }
5126    }
5127}
5128
5129fn combine_task_variables(
5130    mut captured_variables: TaskVariables,
5131    location: Location,
5132    baseline: BasicContextProvider,
5133    cx: &mut AppContext,
5134) -> anyhow::Result<TaskVariables> {
5135    let language_context_provider = location
5136        .buffer
5137        .read(cx)
5138        .language()
5139        .and_then(|language| language.context_provider());
5140    let baseline = baseline
5141        .build_context(&captured_variables, &location, cx)
5142        .context("building basic default context")?;
5143    captured_variables.extend(baseline);
5144    if let Some(provider) = language_context_provider {
5145        captured_variables.extend(
5146            provider
5147                .build_context(&captured_variables, &location, cx)
5148                .context("building provider context")?,
5149        );
5150    }
5151    Ok(captured_variables)
5152}
5153
5154fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
5155    code_actions
5156        .iter()
5157        .flat_map(|(kind, enabled)| {
5158            if *enabled {
5159                Some(kind.clone().into())
5160            } else {
5161                None
5162            }
5163        })
5164        .collect()
5165}
5166
5167pub struct PathMatchCandidateSet {
5168    pub snapshot: Snapshot,
5169    pub include_ignored: bool,
5170    pub include_root_name: bool,
5171    pub candidates: Candidates,
5172}
5173
5174pub enum Candidates {
5175    /// Only consider directories.
5176    Directories,
5177    /// Only consider files.
5178    Files,
5179    /// Consider directories and files.
5180    Entries,
5181}
5182
5183impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5184    type Candidates = PathMatchCandidateSetIter<'a>;
5185
5186    fn id(&self) -> usize {
5187        self.snapshot.id().to_usize()
5188    }
5189
5190    fn len(&self) -> usize {
5191        match self.candidates {
5192            Candidates::Files => {
5193                if self.include_ignored {
5194                    self.snapshot.file_count()
5195                } else {
5196                    self.snapshot.visible_file_count()
5197                }
5198            }
5199
5200            Candidates::Directories => {
5201                if self.include_ignored {
5202                    self.snapshot.dir_count()
5203                } else {
5204                    self.snapshot.visible_dir_count()
5205                }
5206            }
5207
5208            Candidates::Entries => {
5209                if self.include_ignored {
5210                    self.snapshot.entry_count()
5211                } else {
5212                    self.snapshot.visible_entry_count()
5213                }
5214            }
5215        }
5216    }
5217
5218    fn prefix(&self) -> Arc<str> {
5219        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5220            self.snapshot.root_name().into()
5221        } else if self.include_root_name {
5222            format!("{}/", self.snapshot.root_name()).into()
5223        } else {
5224            Arc::default()
5225        }
5226    }
5227
5228    fn candidates(&'a self, start: usize) -> Self::Candidates {
5229        PathMatchCandidateSetIter {
5230            traversal: match self.candidates {
5231                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5232                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5233                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5234            },
5235        }
5236    }
5237}
5238
5239pub struct PathMatchCandidateSetIter<'a> {
5240    traversal: Traversal<'a>,
5241}
5242
5243impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5244    type Item = fuzzy::PathMatchCandidate<'a>;
5245
5246    fn next(&mut self) -> Option<Self::Item> {
5247        self.traversal
5248            .next()
5249            .map(|entry| fuzzy::PathMatchCandidate {
5250                is_dir: entry.kind.is_dir(),
5251                path: &entry.path,
5252                char_bag: entry.char_bag,
5253            })
5254    }
5255}
5256
5257impl EventEmitter<Event> for Project {}
5258
5259impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
5260    fn into(self) -> SettingsLocation<'a> {
5261        SettingsLocation {
5262            worktree_id: self.worktree_id.to_usize(),
5263            path: self.path.as_ref(),
5264        }
5265    }
5266}
5267
5268impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5269    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5270        Self {
5271            worktree_id,
5272            path: path.as_ref().into(),
5273        }
5274    }
5275}
5276
5277pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5278    let mut path_components = path.components();
5279    let mut base_components = base.components();
5280    let mut components: Vec<Component> = Vec::new();
5281    loop {
5282        match (path_components.next(), base_components.next()) {
5283            (None, None) => break,
5284            (Some(a), None) => {
5285                components.push(a);
5286                components.extend(path_components.by_ref());
5287                break;
5288            }
5289            (None, _) => components.push(Component::ParentDir),
5290            (Some(a), Some(b)) if components.is_empty() && a == b => (),
5291            (Some(a), Some(Component::CurDir)) => components.push(a),
5292            (Some(a), Some(_)) => {
5293                components.push(Component::ParentDir);
5294                for _ in base_components {
5295                    components.push(Component::ParentDir);
5296                }
5297                components.push(a);
5298                components.extend(path_components.by_ref());
5299                break;
5300            }
5301        }
5302    }
5303    components.iter().map(|c| c.as_os_str()).collect()
5304}
5305
5306fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5307    let mut result = base.to_path_buf();
5308    for component in path.components() {
5309        match component {
5310            Component::ParentDir => {
5311                result.pop();
5312            }
5313            Component::CurDir => (),
5314            _ => result.push(component),
5315        }
5316    }
5317    result
5318}
5319
5320/// ResolvedPath is a path that has been resolved to either a ProjectPath
5321/// or an AbsPath and that *exists*.
5322#[derive(Debug, Clone)]
5323pub enum ResolvedPath {
5324    ProjectPath(ProjectPath),
5325    AbsPath(PathBuf),
5326}
5327
5328impl Item for Buffer {
5329    fn try_open(
5330        project: &Model<Project>,
5331        path: &ProjectPath,
5332        cx: &mut AppContext,
5333    ) -> Option<Task<Result<Model<Self>>>> {
5334        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5335    }
5336
5337    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
5338        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5339    }
5340
5341    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
5342        File::from_dyn(self.file()).map(|file| ProjectPath {
5343            worktree_id: file.worktree_id(cx),
5344            path: file.path().clone(),
5345        })
5346    }
5347}
5348
5349impl Completion {
5350    /// A key that can be used to sort completions when displaying
5351    /// them to the user.
5352    pub fn sort_key(&self) -> (usize, &str) {
5353        let kind_key = match self.lsp_completion.kind {
5354            Some(lsp::CompletionItemKind::KEYWORD) => 0,
5355            Some(lsp::CompletionItemKind::VARIABLE) => 1,
5356            _ => 2,
5357        };
5358        (kind_key, &self.label.text[self.label.filter_range.clone()])
5359    }
5360
5361    /// Whether this completion is a snippet.
5362    pub fn is_snippet(&self) -> bool {
5363        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5364    }
5365}
5366
5367#[derive(Debug)]
5368pub struct NoRepositoryError {}
5369
5370impl std::fmt::Display for NoRepositoryError {
5371    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5372        write!(f, "no git repository for worktree found")
5373    }
5374}
5375
5376impl std::error::Error for NoRepositoryError {}
5377
5378fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
5379    proto::Location {
5380        buffer_id: location.buffer.read(cx).remote_id().into(),
5381        start: Some(serialize_anchor(&location.range.start)),
5382        end: Some(serialize_anchor(&location.range.end)),
5383    }
5384}
5385
5386fn deserialize_location(
5387    project: &Model<Project>,
5388    location: proto::Location,
5389    cx: &mut AppContext,
5390) -> Task<Result<Location>> {
5391    let buffer_id = match BufferId::new(location.buffer_id) {
5392        Ok(id) => id,
5393        Err(e) => return Task::ready(Err(e)),
5394    };
5395    let buffer_task = project.update(cx, |project, cx| {
5396        project.wait_for_remote_buffer(buffer_id, cx)
5397    });
5398    cx.spawn(|_| async move {
5399        let buffer = buffer_task.await?;
5400        let start = location
5401            .start
5402            .and_then(deserialize_anchor)
5403            .context("missing task context location start")?;
5404        let end = location
5405            .end
5406            .and_then(deserialize_anchor)
5407            .context("missing task context location end")?;
5408        Ok(Location {
5409            buffer,
5410            range: start..end,
5411        })
5412    })
5413}
5414
5415pub fn sort_worktree_entries(entries: &mut Vec<Entry>) {
5416    entries.sort_by(|entry_a, entry_b| {
5417        compare_paths(
5418            (&entry_a.path, entry_a.is_file()),
5419            (&entry_b.path, entry_b.is_file()),
5420        )
5421    });
5422}