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