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