project.rs

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