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