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