project.rs

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