project.rs

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