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