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