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