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