project.rs

   1pub mod buffer_store;
   2mod color_extractor;
   3pub mod connection_manager;
   4pub mod debounced_delay;
   5pub mod git;
   6pub mod image_store;
   7pub mod lsp_command;
   8pub mod lsp_ext_command;
   9pub mod lsp_store;
  10pub mod prettier_store;
  11pub mod project_settings;
  12pub mod search;
  13mod task_inventory;
  14pub mod task_store;
  15pub mod terminals;
  16pub mod toolchain_store;
  17pub mod worktree_store;
  18
  19#[cfg(test)]
  20mod project_tests;
  21
  22mod direnv;
  23mod environment;
  24pub use environment::EnvironmentErrorMessage;
  25use git::RepositoryHandle;
  26pub mod search_history;
  27mod yarn;
  28
  29use crate::git::GitState;
  30use anyhow::{anyhow, Context as _, Result};
  31use buffer_store::{BufferChangeSet, BufferStore, BufferStoreEvent};
  32use client::{
  33    proto, Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore,
  34};
  35use clock::ReplicaId;
  36use collections::{BTreeSet, HashMap, HashSet};
  37use debounced_delay::DebouncedDelay;
  38pub use environment::ProjectEnvironment;
  39use futures::{
  40    channel::mpsc::{self, UnboundedReceiver},
  41    future::try_join_all,
  42    StreamExt,
  43};
  44pub use image_store::{ImageItem, ImageStore};
  45use image_store::{ImageItemEvent, ImageStoreEvent};
  46
  47use ::git::{
  48    blame::Blame,
  49    repository::{Branch, GitRepository, RepoPath},
  50    status::FileStatus,
  51    COMMIT_MESSAGE,
  52};
  53use gpui::{
  54    AnyEntity, App, AppContext as _, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter,
  55    Hsla, SharedString, Task, WeakEntity, Window,
  56};
  57use itertools::Itertools;
  58use language::{
  59    language_settings::InlayHintKind, proto::split_operations, Buffer, BufferEvent,
  60    CachedLspAdapter, Capability, CodeLabel, CompletionDocumentation, File as _, Language,
  61    LanguageName, LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainList,
  62    Transaction, Unclipped,
  63};
  64use lsp::{
  65    CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, LanguageServer,
  66    LanguageServerId, LanguageServerName, MessageActionItem,
  67};
  68use lsp_command::*;
  69use lsp_store::LspFormatTarget;
  70use node_runtime::NodeRuntime;
  71use parking_lot::Mutex;
  72pub use prettier_store::PrettierStore;
  73use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
  74use remote::{SshConnectionOptions, SshRemoteClient};
  75use rpc::{
  76    proto::{LanguageServerPromptResponse, SSH_PROJECT_ID},
  77    AnyProtoClient, ErrorCode,
  78};
  79use search::{SearchInputKind, SearchQuery, SearchResult};
  80use search_history::SearchHistory;
  81use settings::{InvalidSettingsError, Settings, SettingsLocation, SettingsStore};
  82use smol::channel::Receiver;
  83use snippet::Snippet;
  84use snippet_provider::SnippetProvider;
  85use std::{
  86    borrow::Cow,
  87    ops::Range,
  88    path::{Component, Path, PathBuf},
  89    pin::pin,
  90    str,
  91    sync::Arc,
  92    time::Duration,
  93};
  94use task_store::TaskStore;
  95use terminals::Terminals;
  96use text::{Anchor, BufferId};
  97use toolchain_store::EmptyToolchainStore;
  98use util::{paths::compare_paths, ResultExt as _};
  99use worktree::{CreatedEntry, Snapshot, Traversal};
 100use worktree_store::{WorktreeStore, WorktreeStoreEvent};
 101
 102pub use fs::*;
 103pub use language::Location;
 104#[cfg(any(test, feature = "test-support"))]
 105pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
 106pub use task_inventory::{
 107    BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
 108};
 109pub use worktree::{
 110    Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, UpdatedEntriesSet,
 111    UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings, FS_WATCH_LATENCY,
 112};
 113
 114pub use buffer_store::ProjectTransaction;
 115pub use lsp_store::{
 116    DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
 117    LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
 118    SERVER_PROGRESS_THROTTLE_TIMEOUT,
 119};
 120pub use toolchain_store::ToolchainStore;
 121const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
 122const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 123const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 124
 125pub trait ProjectItem {
 126    fn try_open(
 127        project: &Entity<Project>,
 128        path: &ProjectPath,
 129        cx: &mut App,
 130    ) -> Option<Task<Result<Entity<Self>>>>
 131    where
 132        Self: Sized;
 133    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
 134    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 135    fn is_dirty(&self) -> bool;
 136}
 137
 138#[derive(Clone)]
 139pub enum OpenedBufferEvent {
 140    Disconnected,
 141    Ok(BufferId),
 142    Err(BufferId, Arc<anyhow::Error>),
 143}
 144
 145/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
 146/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
 147/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
 148///
 149/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
 150pub struct Project {
 151    active_entry: Option<ProjectEntryId>,
 152    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 153    languages: Arc<LanguageRegistry>,
 154    client: Arc<client::Client>,
 155    join_project_response_message_id: u32,
 156    task_store: Entity<TaskStore>,
 157    user_store: Entity<UserStore>,
 158    fs: Arc<dyn Fs>,
 159    ssh_client: Option<Entity<SshRemoteClient>>,
 160    client_state: ProjectClientState,
 161    git_state: Entity<GitState>,
 162    collaborators: HashMap<proto::PeerId, Collaborator>,
 163    client_subscriptions: Vec<client::Subscription>,
 164    worktree_store: Entity<WorktreeStore>,
 165    buffer_store: Entity<BufferStore>,
 166    image_store: Entity<ImageStore>,
 167    lsp_store: Entity<LspStore>,
 168    _subscriptions: Vec<gpui::Subscription>,
 169    buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
 170    git_diff_debouncer: DebouncedDelay<Self>,
 171    remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
 172    terminals: Terminals,
 173    node: Option<NodeRuntime>,
 174    search_history: SearchHistory,
 175    search_included_history: SearchHistory,
 176    search_excluded_history: SearchHistory,
 177    snippets: Entity<SnippetProvider>,
 178    environment: Entity<ProjectEnvironment>,
 179    settings_observer: Entity<SettingsObserver>,
 180    toolchain_store: Option<Entity<ToolchainStore>>,
 181}
 182
 183#[derive(Default)]
 184struct RemotelyCreatedModels {
 185    worktrees: Vec<Entity<Worktree>>,
 186    buffers: Vec<Entity<Buffer>>,
 187    retain_count: usize,
 188}
 189
 190struct RemotelyCreatedModelGuard {
 191    remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
 192}
 193
 194impl Drop for RemotelyCreatedModelGuard {
 195    fn drop(&mut self) {
 196        if let Some(remote_models) = self.remote_models.upgrade() {
 197            let mut remote_models = remote_models.lock();
 198            assert!(
 199                remote_models.retain_count > 0,
 200                "RemotelyCreatedModelGuard dropped too many times"
 201            );
 202            remote_models.retain_count -= 1;
 203            if remote_models.retain_count == 0 {
 204                remote_models.buffers.clear();
 205                remote_models.worktrees.clear();
 206            }
 207        }
 208    }
 209}
 210/// Message ordered with respect to buffer operations
 211#[derive(Debug)]
 212enum BufferOrderedMessage {
 213    Operation {
 214        buffer_id: BufferId,
 215        operation: proto::Operation,
 216    },
 217    LanguageServerUpdate {
 218        language_server_id: LanguageServerId,
 219        message: proto::update_language_server::Variant,
 220    },
 221    Resync,
 222}
 223
 224#[derive(Debug)]
 225enum ProjectClientState {
 226    /// Single-player mode.
 227    Local,
 228    /// Multi-player mode but still a local project.
 229    Shared { remote_id: u64 },
 230    /// Multi-player mode but working on a remote project.
 231    Remote {
 232        sharing_has_stopped: bool,
 233        capability: Capability,
 234        remote_id: u64,
 235        replica_id: ReplicaId,
 236    },
 237}
 238
 239#[derive(Clone, Debug, PartialEq)]
 240pub enum Event {
 241    LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
 242    LanguageServerRemoved(LanguageServerId),
 243    LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
 244    Toast {
 245        notification_id: SharedString,
 246        message: String,
 247    },
 248    HideToast {
 249        notification_id: SharedString,
 250    },
 251    LanguageServerPrompt(LanguageServerPromptRequest),
 252    LanguageNotFound(Entity<Buffer>),
 253    ActiveEntryChanged(Option<ProjectEntryId>),
 254    ActivateProjectPanel,
 255    WorktreeAdded(WorktreeId),
 256    WorktreeOrderChanged,
 257    WorktreeRemoved(WorktreeId),
 258    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 259    WorktreeUpdatedGitRepositories(WorktreeId),
 260    DiskBasedDiagnosticsStarted {
 261        language_server_id: LanguageServerId,
 262    },
 263    DiskBasedDiagnosticsFinished {
 264        language_server_id: LanguageServerId,
 265    },
 266    DiagnosticsUpdated {
 267        path: ProjectPath,
 268        language_server_id: LanguageServerId,
 269    },
 270    RemoteIdChanged(Option<u64>),
 271    DisconnectedFromHost,
 272    DisconnectedFromSshRemote,
 273    Closed,
 274    DeletedEntry(WorktreeId, ProjectEntryId),
 275    CollaboratorUpdated {
 276        old_peer_id: proto::PeerId,
 277        new_peer_id: proto::PeerId,
 278    },
 279    CollaboratorJoined(proto::PeerId),
 280    CollaboratorLeft(proto::PeerId),
 281    HostReshared,
 282    Reshared,
 283    Rejoined,
 284    RefreshInlayHints,
 285    RevealInProjectPanel(ProjectEntryId),
 286    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
 287    ExpandedAllForEntry(WorktreeId, ProjectEntryId),
 288}
 289
 290#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 291pub struct ProjectPath {
 292    pub worktree_id: WorktreeId,
 293    pub path: Arc<Path>,
 294}
 295
 296impl ProjectPath {
 297    pub fn from_proto(p: proto::ProjectPath) -> Self {
 298        Self {
 299            worktree_id: WorktreeId::from_proto(p.worktree_id),
 300            path: Arc::from(PathBuf::from(p.path)),
 301        }
 302    }
 303
 304    pub fn to_proto(&self) -> proto::ProjectPath {
 305        proto::ProjectPath {
 306            worktree_id: self.worktree_id.to_proto(),
 307            path: self.path.to_string_lossy().to_string(),
 308        }
 309    }
 310
 311    pub fn root_path(worktree_id: WorktreeId) -> Self {
 312        Self {
 313            worktree_id,
 314            path: Path::new("").into(),
 315        }
 316    }
 317}
 318
 319#[derive(Debug, Default)]
 320pub enum PrepareRenameResponse {
 321    Success(Range<Anchor>),
 322    OnlyUnpreparedRenameSupported,
 323    #[default]
 324    InvalidPosition,
 325}
 326
 327#[derive(Debug, Clone, PartialEq, Eq)]
 328pub struct InlayHint {
 329    pub position: language::Anchor,
 330    pub label: InlayHintLabel,
 331    pub kind: Option<InlayHintKind>,
 332    pub padding_left: bool,
 333    pub padding_right: bool,
 334    pub tooltip: Option<InlayHintTooltip>,
 335    pub resolve_state: ResolveState,
 336}
 337
 338/// The user's intent behind a given completion confirmation
 339#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
 340pub enum CompletionIntent {
 341    /// The user intends to 'commit' this result, if possible
 342    /// completion confirmations should run side effects
 343    Complete,
 344    /// The user intends to continue 'composing' this completion
 345    /// completion confirmations should not run side effects and
 346    /// let the user continue composing their action
 347    Compose,
 348}
 349
 350impl CompletionIntent {
 351    pub fn is_complete(&self) -> bool {
 352        self == &Self::Complete
 353    }
 354
 355    pub fn is_compose(&self) -> bool {
 356        self == &Self::Compose
 357    }
 358}
 359
 360/// A completion provided by a language server
 361#[derive(Clone)]
 362pub struct Completion {
 363    /// The range of the buffer that will be replaced.
 364    pub old_range: Range<Anchor>,
 365    /// The new text that will be inserted.
 366    pub new_text: String,
 367    /// A label for this completion that is shown in the menu.
 368    pub label: CodeLabel,
 369    /// The id of the language server that produced this completion.
 370    pub server_id: LanguageServerId,
 371    /// The documentation for this completion.
 372    pub documentation: Option<CompletionDocumentation>,
 373    /// The raw completion provided by the language server.
 374    pub lsp_completion: lsp::CompletionItem,
 375    /// Whether this completion has been resolved, to ensure it happens once per completion.
 376    pub resolved: bool,
 377    /// An optional callback to invoke when this completion is confirmed.
 378    /// Returns, whether new completions should be retriggered after the current one.
 379    /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
 380    /// if no confirmation is provided or `false` is returned, the completion will be committed.
 381    pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
 382}
 383
 384impl std::fmt::Debug for Completion {
 385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 386        f.debug_struct("Completion")
 387            .field("old_range", &self.old_range)
 388            .field("new_text", &self.new_text)
 389            .field("label", &self.label)
 390            .field("server_id", &self.server_id)
 391            .field("documentation", &self.documentation)
 392            .field("lsp_completion", &self.lsp_completion)
 393            .finish()
 394    }
 395}
 396
 397/// A completion provided by a language server
 398#[derive(Clone, Debug)]
 399pub(crate) struct CoreCompletion {
 400    old_range: Range<Anchor>,
 401    new_text: String,
 402    server_id: LanguageServerId,
 403    lsp_completion: lsp::CompletionItem,
 404    resolved: bool,
 405}
 406
 407/// A code action provided by a language server.
 408#[derive(Clone, Debug)]
 409pub struct CodeAction {
 410    /// The id of the language server that produced this code action.
 411    pub server_id: LanguageServerId,
 412    /// The range of the buffer where this code action is applicable.
 413    pub range: Range<Anchor>,
 414    /// The raw code action provided by the language server.
 415    pub lsp_action: lsp::CodeAction,
 416}
 417
 418#[derive(Debug, Clone, PartialEq, Eq)]
 419pub enum ResolveState {
 420    Resolved,
 421    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 422    Resolving,
 423}
 424
 425impl InlayHint {
 426    pub fn text(&self) -> String {
 427        match &self.label {
 428            InlayHintLabel::String(s) => s.to_owned(),
 429            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 430        }
 431    }
 432}
 433
 434#[derive(Debug, Clone, PartialEq, Eq)]
 435pub enum InlayHintLabel {
 436    String(String),
 437    LabelParts(Vec<InlayHintLabelPart>),
 438}
 439
 440#[derive(Debug, Clone, PartialEq, Eq)]
 441pub struct InlayHintLabelPart {
 442    pub value: String,
 443    pub tooltip: Option<InlayHintLabelPartTooltip>,
 444    pub location: Option<(LanguageServerId, lsp::Location)>,
 445}
 446
 447#[derive(Debug, Clone, PartialEq, Eq)]
 448pub enum InlayHintTooltip {
 449    String(String),
 450    MarkupContent(MarkupContent),
 451}
 452
 453#[derive(Debug, Clone, PartialEq, Eq)]
 454pub enum InlayHintLabelPartTooltip {
 455    String(String),
 456    MarkupContent(MarkupContent),
 457}
 458
 459#[derive(Debug, Clone, PartialEq, Eq)]
 460pub struct MarkupContent {
 461    pub kind: HoverBlockKind,
 462    pub value: String,
 463}
 464
 465#[derive(Debug, Clone)]
 466pub struct LocationLink {
 467    pub origin: Option<Location>,
 468    pub target: Location,
 469}
 470
 471#[derive(Debug)]
 472pub struct DocumentHighlight {
 473    pub range: Range<language::Anchor>,
 474    pub kind: DocumentHighlightKind,
 475}
 476
 477#[derive(Clone, Debug)]
 478pub struct Symbol {
 479    pub language_server_name: LanguageServerName,
 480    pub source_worktree_id: WorktreeId,
 481    pub path: ProjectPath,
 482    pub label: CodeLabel,
 483    pub name: String,
 484    pub kind: lsp::SymbolKind,
 485    pub range: Range<Unclipped<PointUtf16>>,
 486    pub signature: [u8; 32],
 487}
 488
 489#[derive(Clone, Debug, PartialEq)]
 490pub struct HoverBlock {
 491    pub text: String,
 492    pub kind: HoverBlockKind,
 493}
 494
 495#[derive(Clone, Debug, PartialEq, Eq)]
 496pub enum HoverBlockKind {
 497    PlainText,
 498    Markdown,
 499    Code { language: String },
 500}
 501
 502#[derive(Debug, Clone)]
 503pub struct Hover {
 504    pub contents: Vec<HoverBlock>,
 505    pub range: Option<Range<language::Anchor>>,
 506    pub language: Option<Arc<Language>>,
 507}
 508
 509impl Hover {
 510    pub fn is_empty(&self) -> bool {
 511        self.contents.iter().all(|block| block.text.is_empty())
 512    }
 513}
 514
 515enum EntitySubscription {
 516    Project(PendingEntitySubscription<Project>),
 517    BufferStore(PendingEntitySubscription<BufferStore>),
 518    WorktreeStore(PendingEntitySubscription<WorktreeStore>),
 519    LspStore(PendingEntitySubscription<LspStore>),
 520    SettingsObserver(PendingEntitySubscription<SettingsObserver>),
 521}
 522
 523#[derive(Clone)]
 524pub enum DirectoryLister {
 525    Project(Entity<Project>),
 526    Local(Arc<dyn Fs>),
 527}
 528
 529impl DirectoryLister {
 530    pub fn is_local(&self, cx: &App) -> bool {
 531        match self {
 532            DirectoryLister::Local(_) => true,
 533            DirectoryLister::Project(project) => project.read(cx).is_local(),
 534        }
 535    }
 536
 537    pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
 538        if self.is_local(cx) {
 539            shellexpand::tilde(path)
 540        } else {
 541            Cow::from(path)
 542        }
 543    }
 544
 545    pub fn default_query(&self, cx: &mut App) -> String {
 546        if let DirectoryLister::Project(project) = self {
 547            if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
 548                return worktree.read(cx).abs_path().to_string_lossy().to_string();
 549            }
 550        };
 551        "~/".to_string()
 552    }
 553
 554    pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<PathBuf>>> {
 555        match self {
 556            DirectoryLister::Project(project) => {
 557                project.update(cx, |project, cx| project.list_directory(path, cx))
 558            }
 559            DirectoryLister::Local(fs) => {
 560                let fs = fs.clone();
 561                cx.background_executor().spawn(async move {
 562                    let mut results = vec![];
 563                    let expanded = shellexpand::tilde(&path);
 564                    let query = Path::new(expanded.as_ref());
 565                    let mut response = fs.read_dir(query).await?;
 566                    while let Some(path) = response.next().await {
 567                        if let Some(file_name) = path?.file_name() {
 568                            results.push(PathBuf::from(file_name.to_os_string()));
 569                        }
 570                    }
 571                    Ok(results)
 572                })
 573            }
 574        }
 575    }
 576}
 577
 578#[cfg(any(test, feature = "test-support"))]
 579pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
 580    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
 581    trigger_character: None,
 582};
 583
 584impl Project {
 585    pub fn init_settings(cx: &mut App) {
 586        WorktreeSettings::register(cx);
 587        ProjectSettings::register(cx);
 588    }
 589
 590    pub fn init(client: &Arc<Client>, cx: &mut App) {
 591        connection_manager::init(client.clone(), cx);
 592        Self::init_settings(cx);
 593
 594        let client: AnyProtoClient = client.clone().into();
 595        client.add_model_message_handler(Self::handle_add_collaborator);
 596        client.add_model_message_handler(Self::handle_update_project_collaborator);
 597        client.add_model_message_handler(Self::handle_remove_collaborator);
 598        client.add_model_message_handler(Self::handle_update_project);
 599        client.add_model_message_handler(Self::handle_unshare_project);
 600        client.add_model_request_handler(Self::handle_update_buffer);
 601        client.add_model_message_handler(Self::handle_update_worktree);
 602        client.add_model_request_handler(Self::handle_synchronize_buffers);
 603
 604        client.add_model_request_handler(Self::handle_search_candidate_buffers);
 605        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 606        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 607        client.add_model_request_handler(Self::handle_open_new_buffer);
 608        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 609
 610        client.add_model_request_handler(Self::handle_stage);
 611        client.add_model_request_handler(Self::handle_unstage);
 612        client.add_model_request_handler(Self::handle_commit);
 613        client.add_model_request_handler(Self::handle_open_commit_message_buffer);
 614
 615        WorktreeStore::init(&client);
 616        BufferStore::init(&client);
 617        LspStore::init(&client);
 618        SettingsObserver::init(&client);
 619        TaskStore::init(Some(&client));
 620        ToolchainStore::init(&client);
 621    }
 622
 623    pub fn local(
 624        client: Arc<Client>,
 625        node: NodeRuntime,
 626        user_store: Entity<UserStore>,
 627        languages: Arc<LanguageRegistry>,
 628        fs: Arc<dyn Fs>,
 629        env: Option<HashMap<String, String>>,
 630        cx: &mut App,
 631    ) -> Entity<Self> {
 632        cx.new(|cx: &mut Context<Self>| {
 633            let (tx, rx) = mpsc::unbounded();
 634            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 635                .detach();
 636            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
 637            let worktree_store = cx.new(|_| WorktreeStore::local(false, fs.clone()));
 638            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 639                .detach();
 640
 641            let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
 642            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 643                .detach();
 644
 645            let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
 646            cx.subscribe(&image_store, Self::on_image_store_event)
 647                .detach();
 648
 649            let prettier_store = cx.new(|cx| {
 650                PrettierStore::new(
 651                    node.clone(),
 652                    fs.clone(),
 653                    languages.clone(),
 654                    worktree_store.clone(),
 655                    cx,
 656                )
 657            });
 658
 659            let environment = ProjectEnvironment::new(&worktree_store, env, cx);
 660            let toolchain_store = cx.new(|cx| {
 661                ToolchainStore::local(
 662                    languages.clone(),
 663                    worktree_store.clone(),
 664                    environment.clone(),
 665                    cx,
 666                )
 667            });
 668            let task_store = cx.new(|cx| {
 669                TaskStore::local(
 670                    fs.clone(),
 671                    buffer_store.downgrade(),
 672                    worktree_store.clone(),
 673                    toolchain_store.read(cx).as_language_toolchain_store(),
 674                    environment.clone(),
 675                    cx,
 676                )
 677            });
 678
 679            let settings_observer = cx.new(|cx| {
 680                SettingsObserver::new_local(
 681                    fs.clone(),
 682                    worktree_store.clone(),
 683                    task_store.clone(),
 684                    cx,
 685                )
 686            });
 687            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
 688                .detach();
 689
 690            let lsp_store = cx.new(|cx| {
 691                LspStore::new_local(
 692                    buffer_store.clone(),
 693                    worktree_store.clone(),
 694                    prettier_store.clone(),
 695                    toolchain_store.clone(),
 696                    environment.clone(),
 697                    languages.clone(),
 698                    client.http_client(),
 699                    fs.clone(),
 700                    cx,
 701                )
 702            });
 703
 704            let git_state = cx.new(|cx| GitState::new(&worktree_store, None, None, cx));
 705
 706            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 707
 708            Self {
 709                buffer_ordered_messages_tx: tx,
 710                collaborators: Default::default(),
 711                worktree_store,
 712                buffer_store,
 713                image_store,
 714                lsp_store,
 715                join_project_response_message_id: 0,
 716                client_state: ProjectClientState::Local,
 717                git_state,
 718                client_subscriptions: Vec::new(),
 719                _subscriptions: vec![cx.on_release(Self::release)],
 720                active_entry: None,
 721                snippets,
 722                languages,
 723                client,
 724                task_store,
 725                user_store,
 726                settings_observer,
 727                fs,
 728                ssh_client: None,
 729                buffers_needing_diff: Default::default(),
 730                git_diff_debouncer: DebouncedDelay::new(),
 731                terminals: Terminals {
 732                    local_handles: Vec::new(),
 733                },
 734                node: Some(node),
 735                search_history: Self::new_search_history(),
 736                environment,
 737                remotely_created_models: Default::default(),
 738
 739                search_included_history: Self::new_search_history(),
 740                search_excluded_history: Self::new_search_history(),
 741
 742                toolchain_store: Some(toolchain_store),
 743            }
 744        })
 745    }
 746
 747    pub fn ssh(
 748        ssh: Entity<SshRemoteClient>,
 749        client: Arc<Client>,
 750        node: NodeRuntime,
 751        user_store: Entity<UserStore>,
 752        languages: Arc<LanguageRegistry>,
 753        fs: Arc<dyn Fs>,
 754        cx: &mut App,
 755    ) -> Entity<Self> {
 756        cx.new(|cx: &mut Context<Self>| {
 757            let (tx, rx) = mpsc::unbounded();
 758            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 759                .detach();
 760            let global_snippets_dir = paths::config_dir().join("snippets");
 761            let snippets =
 762                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
 763
 764            let ssh_proto = ssh.read(cx).proto_client();
 765            let worktree_store =
 766                cx.new(|_| WorktreeStore::remote(false, ssh_proto.clone(), SSH_PROJECT_ID));
 767            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 768                .detach();
 769
 770            let buffer_store = cx.new(|cx| {
 771                BufferStore::remote(
 772                    worktree_store.clone(),
 773                    ssh.read(cx).proto_client(),
 774                    SSH_PROJECT_ID,
 775                    cx,
 776                )
 777            });
 778            let image_store = cx.new(|cx| {
 779                ImageStore::remote(
 780                    worktree_store.clone(),
 781                    ssh.read(cx).proto_client(),
 782                    SSH_PROJECT_ID,
 783                    cx,
 784                )
 785            });
 786            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 787                .detach();
 788            let toolchain_store = cx
 789                .new(|cx| ToolchainStore::remote(SSH_PROJECT_ID, ssh.read(cx).proto_client(), cx));
 790            let task_store = cx.new(|cx| {
 791                TaskStore::remote(
 792                    fs.clone(),
 793                    buffer_store.downgrade(),
 794                    worktree_store.clone(),
 795                    toolchain_store.read(cx).as_language_toolchain_store(),
 796                    ssh.read(cx).proto_client(),
 797                    SSH_PROJECT_ID,
 798                    cx,
 799                )
 800            });
 801
 802            let settings_observer = cx.new(|cx| {
 803                SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
 804            });
 805            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
 806                .detach();
 807
 808            let environment = ProjectEnvironment::new(&worktree_store, None, cx);
 809
 810            let lsp_store = cx.new(|cx| {
 811                LspStore::new_remote(
 812                    buffer_store.clone(),
 813                    worktree_store.clone(),
 814                    Some(toolchain_store.clone()),
 815                    languages.clone(),
 816                    ssh_proto.clone(),
 817                    SSH_PROJECT_ID,
 818                    fs.clone(),
 819                    cx,
 820                )
 821            });
 822            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 823
 824            let git_state = cx.new(|cx| {
 825                GitState::new(
 826                    &worktree_store,
 827                    Some(ssh_proto.clone()),
 828                    Some(ProjectId(SSH_PROJECT_ID)),
 829                    cx,
 830                )
 831            });
 832
 833            cx.subscribe(&ssh, Self::on_ssh_event).detach();
 834            cx.observe(&ssh, |_, _, cx| cx.notify()).detach();
 835
 836            let this = Self {
 837                buffer_ordered_messages_tx: tx,
 838                collaborators: Default::default(),
 839                worktree_store,
 840                buffer_store,
 841                image_store,
 842                lsp_store,
 843                join_project_response_message_id: 0,
 844                client_state: ProjectClientState::Local,
 845                git_state,
 846                client_subscriptions: Vec::new(),
 847                _subscriptions: vec![
 848                    cx.on_release(Self::release),
 849                    cx.on_app_quit(|this, cx| {
 850                        let shutdown = this.ssh_client.take().and_then(|client| {
 851                            client
 852                                .read(cx)
 853                                .shutdown_processes(Some(proto::ShutdownRemoteServer {}))
 854                        });
 855
 856                        cx.background_executor().spawn(async move {
 857                            if let Some(shutdown) = shutdown {
 858                                shutdown.await;
 859                            }
 860                        })
 861                    }),
 862                ],
 863                active_entry: None,
 864                snippets,
 865                languages,
 866                client,
 867                task_store,
 868                user_store,
 869                settings_observer,
 870                fs,
 871                ssh_client: Some(ssh.clone()),
 872                buffers_needing_diff: Default::default(),
 873                git_diff_debouncer: DebouncedDelay::new(),
 874                terminals: Terminals {
 875                    local_handles: Vec::new(),
 876                },
 877                node: Some(node),
 878                search_history: Self::new_search_history(),
 879                environment,
 880                remotely_created_models: Default::default(),
 881
 882                search_included_history: Self::new_search_history(),
 883                search_excluded_history: Self::new_search_history(),
 884
 885                toolchain_store: Some(toolchain_store),
 886            };
 887
 888            // ssh -> local machine handlers
 889            let ssh = ssh.read(cx);
 890            ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.entity());
 891            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
 892            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
 893            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
 894            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
 895
 896            ssh_proto.add_model_message_handler(Self::handle_create_buffer_for_peer);
 897            ssh_proto.add_model_message_handler(Self::handle_update_worktree);
 898            ssh_proto.add_model_message_handler(Self::handle_update_project);
 899            ssh_proto.add_model_message_handler(Self::handle_toast);
 900            ssh_proto.add_model_request_handler(Self::handle_language_server_prompt_request);
 901            ssh_proto.add_model_message_handler(Self::handle_hide_toast);
 902            ssh_proto.add_model_request_handler(Self::handle_update_buffer_from_ssh);
 903            BufferStore::init(&ssh_proto);
 904            LspStore::init(&ssh_proto);
 905            SettingsObserver::init(&ssh_proto);
 906            TaskStore::init(Some(&ssh_proto));
 907            ToolchainStore::init(&ssh_proto);
 908
 909            this
 910        })
 911    }
 912
 913    pub async fn remote(
 914        remote_id: u64,
 915        client: Arc<Client>,
 916        user_store: Entity<UserStore>,
 917        languages: Arc<LanguageRegistry>,
 918        fs: Arc<dyn Fs>,
 919        cx: AsyncApp,
 920    ) -> Result<Entity<Self>> {
 921        let project =
 922            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
 923        cx.update(|cx| {
 924            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
 925                manager.maintain_project_connection(&project, cx)
 926            })
 927        })?;
 928        Ok(project)
 929    }
 930
 931    pub async fn in_room(
 932        remote_id: u64,
 933        client: Arc<Client>,
 934        user_store: Entity<UserStore>,
 935        languages: Arc<LanguageRegistry>,
 936        fs: Arc<dyn Fs>,
 937        cx: AsyncApp,
 938    ) -> Result<Entity<Self>> {
 939        client.authenticate_and_connect(true, &cx).await?;
 940
 941        let subscriptions = [
 942            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
 943            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
 944            EntitySubscription::WorktreeStore(
 945                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
 946            ),
 947            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
 948            EntitySubscription::SettingsObserver(
 949                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
 950            ),
 951        ];
 952        let response = client
 953            .request_envelope(proto::JoinProject {
 954                project_id: remote_id,
 955            })
 956            .await?;
 957        Self::from_join_project_response(
 958            response,
 959            subscriptions,
 960            client,
 961            false,
 962            user_store,
 963            languages,
 964            fs,
 965            cx,
 966        )
 967        .await
 968    }
 969
 970    #[allow(clippy::too_many_arguments)]
 971    async fn from_join_project_response(
 972        response: TypedEnvelope<proto::JoinProjectResponse>,
 973        subscriptions: [EntitySubscription; 5],
 974        client: Arc<Client>,
 975        run_tasks: bool,
 976        user_store: Entity<UserStore>,
 977        languages: Arc<LanguageRegistry>,
 978        fs: Arc<dyn Fs>,
 979        mut cx: AsyncApp,
 980    ) -> Result<Entity<Self>> {
 981        let remote_id = response.payload.project_id;
 982        let role = response.payload.role();
 983
 984        let worktree_store = cx.new(|_| {
 985            WorktreeStore::remote(true, client.clone().into(), response.payload.project_id)
 986        })?;
 987        let buffer_store = cx.new(|cx| {
 988            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
 989        })?;
 990        let image_store = cx.new(|cx| {
 991            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
 992        })?;
 993
 994        let lsp_store = cx.new(|cx| {
 995            let mut lsp_store = LspStore::new_remote(
 996                buffer_store.clone(),
 997                worktree_store.clone(),
 998                None,
 999                languages.clone(),
1000                client.clone().into(),
1001                remote_id,
1002                fs.clone(),
1003                cx,
1004            );
1005            lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
1006            lsp_store
1007        })?;
1008
1009        let task_store = cx.new(|cx| {
1010            if run_tasks {
1011                TaskStore::remote(
1012                    fs.clone(),
1013                    buffer_store.downgrade(),
1014                    worktree_store.clone(),
1015                    Arc::new(EmptyToolchainStore),
1016                    client.clone().into(),
1017                    remote_id,
1018                    cx,
1019                )
1020            } else {
1021                TaskStore::Noop
1022            }
1023        })?;
1024
1025        let settings_observer = cx.new(|cx| {
1026            SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
1027        })?;
1028
1029        let git_state = cx.new(|cx| {
1030            GitState::new(
1031                &worktree_store,
1032                Some(client.clone().into()),
1033                Some(ProjectId(remote_id)),
1034                cx,
1035            )
1036        })?;
1037
1038        let this = cx.new(|cx| {
1039            let replica_id = response.payload.replica_id as ReplicaId;
1040
1041            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1042
1043            let mut worktrees = Vec::new();
1044            for worktree in response.payload.worktrees {
1045                let worktree =
1046                    Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
1047                worktrees.push(worktree);
1048            }
1049
1050            let (tx, rx) = mpsc::unbounded();
1051            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
1052                .detach();
1053
1054            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1055                .detach();
1056
1057            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1058                .detach();
1059            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1060            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1061                .detach();
1062
1063            let mut this = Self {
1064                buffer_ordered_messages_tx: tx,
1065                buffer_store: buffer_store.clone(),
1066                image_store,
1067                worktree_store: worktree_store.clone(),
1068                lsp_store: lsp_store.clone(),
1069                active_entry: None,
1070                collaborators: Default::default(),
1071                join_project_response_message_id: response.message_id,
1072                languages,
1073                user_store: user_store.clone(),
1074                task_store,
1075                snippets,
1076                fs,
1077                ssh_client: None,
1078                settings_observer: settings_observer.clone(),
1079                client_subscriptions: Default::default(),
1080                _subscriptions: vec![cx.on_release(Self::release)],
1081                client: client.clone(),
1082                client_state: ProjectClientState::Remote {
1083                    sharing_has_stopped: false,
1084                    capability: Capability::ReadWrite,
1085                    remote_id,
1086                    replica_id,
1087                },
1088                git_state,
1089                buffers_needing_diff: Default::default(),
1090                git_diff_debouncer: DebouncedDelay::new(),
1091                terminals: Terminals {
1092                    local_handles: Vec::new(),
1093                },
1094                node: None,
1095                search_history: Self::new_search_history(),
1096                search_included_history: Self::new_search_history(),
1097                search_excluded_history: Self::new_search_history(),
1098                environment: ProjectEnvironment::new(&worktree_store, None, cx),
1099                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1100                toolchain_store: None,
1101            };
1102            this.set_role(role, cx);
1103            for worktree in worktrees {
1104                this.add_worktree(&worktree, cx);
1105            }
1106            this
1107        })?;
1108
1109        let subscriptions = subscriptions
1110            .into_iter()
1111            .map(|s| match s {
1112                EntitySubscription::BufferStore(subscription) => {
1113                    subscription.set_model(&buffer_store, &mut cx)
1114                }
1115                EntitySubscription::WorktreeStore(subscription) => {
1116                    subscription.set_model(&worktree_store, &mut cx)
1117                }
1118                EntitySubscription::SettingsObserver(subscription) => {
1119                    subscription.set_model(&settings_observer, &mut cx)
1120                }
1121                EntitySubscription::Project(subscription) => subscription.set_model(&this, &mut cx),
1122                EntitySubscription::LspStore(subscription) => {
1123                    subscription.set_model(&lsp_store, &mut cx)
1124                }
1125            })
1126            .collect::<Vec<_>>();
1127
1128        let user_ids = response
1129            .payload
1130            .collaborators
1131            .iter()
1132            .map(|peer| peer.user_id)
1133            .collect();
1134        user_store
1135            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1136            .await?;
1137
1138        this.update(&mut cx, |this, cx| {
1139            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1140            this.client_subscriptions.extend(subscriptions);
1141            anyhow::Ok(())
1142        })??;
1143
1144        Ok(this)
1145    }
1146
1147    fn new_search_history() -> SearchHistory {
1148        SearchHistory::new(
1149            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1150            search_history::QueryInsertionBehavior::AlwaysInsert,
1151        )
1152    }
1153
1154    fn release(&mut self, cx: &mut App) {
1155        if let Some(client) = self.ssh_client.take() {
1156            let shutdown = client
1157                .read(cx)
1158                .shutdown_processes(Some(proto::ShutdownRemoteServer {}));
1159
1160            cx.background_executor()
1161                .spawn(async move {
1162                    if let Some(shutdown) = shutdown {
1163                        shutdown.await;
1164                    }
1165                })
1166                .detach()
1167        }
1168
1169        match &self.client_state {
1170            ProjectClientState::Local => {}
1171            ProjectClientState::Shared { .. } => {
1172                let _ = self.unshare_internal(cx);
1173            }
1174            ProjectClientState::Remote { remote_id, .. } => {
1175                let _ = self.client.send(proto::LeaveProject {
1176                    project_id: *remote_id,
1177                });
1178                self.disconnected_from_host_internal(cx);
1179            }
1180        }
1181    }
1182
1183    #[cfg(any(test, feature = "test-support"))]
1184    pub async fn example(
1185        root_paths: impl IntoIterator<Item = &Path>,
1186        cx: &mut AsyncApp,
1187    ) -> Entity<Project> {
1188        use clock::FakeSystemClock;
1189
1190        let fs = Arc::new(RealFs::default());
1191        let languages = LanguageRegistry::test(cx.background_executor().clone());
1192        let clock = Arc::new(FakeSystemClock::new());
1193        let http_client = http_client::FakeHttpClient::with_404_response();
1194        let client = cx
1195            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1196            .unwrap();
1197        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1198        let project = cx
1199            .update(|cx| {
1200                Project::local(
1201                    client,
1202                    node_runtime::NodeRuntime::unavailable(),
1203                    user_store,
1204                    Arc::new(languages),
1205                    fs,
1206                    None,
1207                    cx,
1208                )
1209            })
1210            .unwrap();
1211        for path in root_paths {
1212            let (tree, _) = project
1213                .update(cx, |project, cx| {
1214                    project.find_or_create_worktree(path, true, cx)
1215                })
1216                .unwrap()
1217                .await
1218                .unwrap();
1219            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1220                .unwrap()
1221                .await;
1222        }
1223        project
1224    }
1225
1226    #[cfg(any(test, feature = "test-support"))]
1227    pub async fn test(
1228        fs: Arc<dyn Fs>,
1229        root_paths: impl IntoIterator<Item = &Path>,
1230        cx: &mut gpui::TestAppContext,
1231    ) -> Entity<Project> {
1232        use clock::FakeSystemClock;
1233
1234        let languages = LanguageRegistry::test(cx.executor());
1235        let clock = Arc::new(FakeSystemClock::new());
1236        let http_client = http_client::FakeHttpClient::with_404_response();
1237        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1238        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1239        let project = cx.update(|cx| {
1240            Project::local(
1241                client,
1242                node_runtime::NodeRuntime::unavailable(),
1243                user_store,
1244                Arc::new(languages),
1245                fs,
1246                None,
1247                cx,
1248            )
1249        });
1250        for path in root_paths {
1251            let (tree, _) = project
1252                .update(cx, |project, cx| {
1253                    project.find_or_create_worktree(path, true, cx)
1254                })
1255                .await
1256                .unwrap();
1257
1258            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1259                .await;
1260        }
1261        project
1262    }
1263
1264    pub fn lsp_store(&self) -> Entity<LspStore> {
1265        self.lsp_store.clone()
1266    }
1267
1268    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1269        self.worktree_store.clone()
1270    }
1271
1272    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1273        self.buffer_store.read(cx).get(remote_id)
1274    }
1275
1276    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1277        &self.languages
1278    }
1279
1280    pub fn client(&self) -> Arc<Client> {
1281        self.client.clone()
1282    }
1283
1284    pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1285        self.ssh_client.clone()
1286    }
1287
1288    pub fn user_store(&self) -> Entity<UserStore> {
1289        self.user_store.clone()
1290    }
1291
1292    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1293        self.node.as_ref()
1294    }
1295
1296    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1297        self.buffer_store.read(cx).buffers().collect()
1298    }
1299
1300    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1301        &self.environment
1302    }
1303
1304    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1305        self.environment.read(cx).get_cli_environment()
1306    }
1307
1308    pub fn shell_environment_errors<'a>(
1309        &'a self,
1310        cx: &'a App,
1311    ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1312        self.environment.read(cx).environment_errors()
1313    }
1314
1315    pub fn remove_environment_error(&mut self, cx: &mut Context<Self>, worktree_id: WorktreeId) {
1316        self.environment.update(cx, |environment, _| {
1317            environment.remove_environment_error(worktree_id);
1318        });
1319    }
1320
1321    #[cfg(any(test, feature = "test-support"))]
1322    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1323        self.buffer_store
1324            .read(cx)
1325            .get_by_path(&path.into(), cx)
1326            .is_some()
1327    }
1328
1329    pub fn fs(&self) -> &Arc<dyn Fs> {
1330        &self.fs
1331    }
1332
1333    pub fn remote_id(&self) -> Option<u64> {
1334        match self.client_state {
1335            ProjectClientState::Local => None,
1336            ProjectClientState::Shared { remote_id, .. }
1337            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1338        }
1339    }
1340
1341    pub fn supports_terminal(&self, _cx: &App) -> bool {
1342        if self.is_local() {
1343            return true;
1344        }
1345        if self.is_via_ssh() {
1346            return true;
1347        }
1348
1349        return false;
1350    }
1351
1352    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1353        if let Some(ssh_state) = &self.ssh_client {
1354            return Some(ssh_state.read(cx).connection_string().into());
1355        }
1356
1357        return None;
1358    }
1359
1360    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1361        self.ssh_client
1362            .as_ref()
1363            .map(|ssh| ssh.read(cx).connection_state())
1364    }
1365
1366    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1367        self.ssh_client
1368            .as_ref()
1369            .map(|ssh| ssh.read(cx).connection_options())
1370    }
1371
1372    pub fn replica_id(&self) -> ReplicaId {
1373        match self.client_state {
1374            ProjectClientState::Remote { replica_id, .. } => replica_id,
1375            _ => {
1376                if self.ssh_client.is_some() {
1377                    1
1378                } else {
1379                    0
1380                }
1381            }
1382        }
1383    }
1384
1385    pub fn task_store(&self) -> &Entity<TaskStore> {
1386        &self.task_store
1387    }
1388
1389    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1390        &self.snippets
1391    }
1392
1393    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1394        match kind {
1395            SearchInputKind::Query => &self.search_history,
1396            SearchInputKind::Include => &self.search_included_history,
1397            SearchInputKind::Exclude => &self.search_excluded_history,
1398        }
1399    }
1400
1401    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1402        match kind {
1403            SearchInputKind::Query => &mut self.search_history,
1404            SearchInputKind::Include => &mut self.search_included_history,
1405            SearchInputKind::Exclude => &mut self.search_excluded_history,
1406        }
1407    }
1408
1409    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1410        &self.collaborators
1411    }
1412
1413    pub fn host(&self) -> Option<&Collaborator> {
1414        self.collaborators.values().find(|c| c.is_host)
1415    }
1416
1417    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1418        self.worktree_store.update(cx, |store, _| {
1419            store.set_worktrees_reordered(worktrees_reordered);
1420        });
1421    }
1422
1423    /// Collect all worktrees, including ones that don't appear in the project panel
1424    pub fn worktrees<'a>(
1425        &self,
1426        cx: &'a App,
1427    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1428        self.worktree_store.read(cx).worktrees()
1429    }
1430
1431    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1432    pub fn visible_worktrees<'a>(
1433        &'a self,
1434        cx: &'a App,
1435    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1436        self.worktree_store.read(cx).visible_worktrees(cx)
1437    }
1438
1439    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1440        self.visible_worktrees(cx)
1441            .map(|tree| tree.read(cx).root_name())
1442    }
1443
1444    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1445        self.worktree_store.read(cx).worktree_for_id(id, cx)
1446    }
1447
1448    pub fn worktree_for_entry(
1449        &self,
1450        entry_id: ProjectEntryId,
1451        cx: &App,
1452    ) -> Option<Entity<Worktree>> {
1453        self.worktree_store
1454            .read(cx)
1455            .worktree_for_entry(entry_id, cx)
1456    }
1457
1458    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1459        self.worktree_for_entry(entry_id, cx)
1460            .map(|worktree| worktree.read(cx).id())
1461    }
1462
1463    /// Checks if the entry is the root of a worktree.
1464    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1465        self.worktree_for_entry(entry_id, cx)
1466            .map(|worktree| {
1467                worktree
1468                    .read(cx)
1469                    .root_entry()
1470                    .is_some_and(|e| e.id == entry_id)
1471            })
1472            .unwrap_or(false)
1473    }
1474
1475    pub fn project_path_git_status(
1476        &self,
1477        project_path: &ProjectPath,
1478        cx: &App,
1479    ) -> Option<FileStatus> {
1480        self.worktree_for_id(project_path.worktree_id, cx)
1481            .and_then(|worktree| worktree.read(cx).status_for_file(&project_path.path))
1482    }
1483
1484    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &App) -> Option<bool> {
1485        paths
1486            .iter()
1487            .map(|path| self.visibility_for_path(path, cx))
1488            .max()
1489            .flatten()
1490    }
1491
1492    pub fn visibility_for_path(&self, path: &Path, cx: &App) -> Option<bool> {
1493        self.worktrees(cx)
1494            .filter_map(|worktree| {
1495                let worktree = worktree.read(cx);
1496                worktree
1497                    .as_local()?
1498                    .contains_abs_path(path)
1499                    .then(|| worktree.is_visible())
1500            })
1501            .max()
1502    }
1503
1504    pub fn create_entry(
1505        &mut self,
1506        project_path: impl Into<ProjectPath>,
1507        is_directory: bool,
1508        cx: &mut Context<Self>,
1509    ) -> Task<Result<CreatedEntry>> {
1510        let project_path = project_path.into();
1511        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1512            return Task::ready(Err(anyhow!(format!(
1513                "No worktree for path {project_path:?}"
1514            ))));
1515        };
1516        worktree.update(cx, |worktree, cx| {
1517            worktree.create_entry(project_path.path, is_directory, cx)
1518        })
1519    }
1520
1521    pub fn copy_entry(
1522        &mut self,
1523        entry_id: ProjectEntryId,
1524        relative_worktree_source_path: Option<PathBuf>,
1525        new_path: impl Into<Arc<Path>>,
1526        cx: &mut Context<Self>,
1527    ) -> Task<Result<Option<Entry>>> {
1528        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1529            return Task::ready(Ok(None));
1530        };
1531        worktree.update(cx, |worktree, cx| {
1532            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1533        })
1534    }
1535
1536    pub fn rename_entry(
1537        &mut self,
1538        entry_id: ProjectEntryId,
1539        new_path: impl Into<Arc<Path>>,
1540        cx: &mut Context<Self>,
1541    ) -> Task<Result<CreatedEntry>> {
1542        let worktree_store = self.worktree_store.read(cx);
1543        let new_path = new_path.into();
1544        let Some((worktree, old_path, is_dir)) = worktree_store
1545            .worktree_and_entry_for_id(entry_id, cx)
1546            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1547        else {
1548            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1549        };
1550
1551        let worktree_id = worktree.read(cx).id();
1552
1553        let lsp_store = self.lsp_store().downgrade();
1554        cx.spawn(|_, mut cx| async move {
1555            let (old_abs_path, new_abs_path) = {
1556                let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
1557                (root_path.join(&old_path), root_path.join(&new_path))
1558            };
1559            LspStore::will_rename_entry(
1560                lsp_store.clone(),
1561                worktree_id,
1562                &old_abs_path,
1563                &new_abs_path,
1564                is_dir,
1565                cx.clone(),
1566            )
1567            .await;
1568
1569            let entry = worktree
1570                .update(&mut cx, |worktree, cx| {
1571                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1572                })?
1573                .await?;
1574
1575            lsp_store
1576                .update(&mut cx, |this, _| {
1577                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1578                })
1579                .ok();
1580            Ok(entry)
1581        })
1582    }
1583
1584    pub fn delete_entry(
1585        &mut self,
1586        entry_id: ProjectEntryId,
1587        trash: bool,
1588        cx: &mut Context<Self>,
1589    ) -> Option<Task<Result<()>>> {
1590        let worktree = self.worktree_for_entry(entry_id, cx)?;
1591        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1592        worktree.update(cx, |worktree, cx| {
1593            worktree.delete_entry(entry_id, trash, cx)
1594        })
1595    }
1596
1597    pub fn expand_entry(
1598        &mut self,
1599        worktree_id: WorktreeId,
1600        entry_id: ProjectEntryId,
1601        cx: &mut Context<Self>,
1602    ) -> Option<Task<Result<()>>> {
1603        let worktree = self.worktree_for_id(worktree_id, cx)?;
1604        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1605    }
1606
1607    pub fn expand_all_for_entry(
1608        &mut self,
1609        worktree_id: WorktreeId,
1610        entry_id: ProjectEntryId,
1611        cx: &mut Context<Self>,
1612    ) -> Option<Task<Result<()>>> {
1613        let worktree = self.worktree_for_id(worktree_id, cx)?;
1614        let task = worktree.update(cx, |worktree, cx| {
1615            worktree.expand_all_for_entry(entry_id, cx)
1616        });
1617        Some(cx.spawn(|this, mut cx| async move {
1618            task.ok_or_else(|| anyhow!("no task"))?.await?;
1619            this.update(&mut cx, |_, cx| {
1620                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
1621            })?;
1622            Ok(())
1623        }))
1624    }
1625
1626    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
1627        if !matches!(self.client_state, ProjectClientState::Local) {
1628            return Err(anyhow!("project was already shared"));
1629        }
1630
1631        self.client_subscriptions.extend([
1632            self.client
1633                .subscribe_to_entity(project_id)?
1634                .set_model(&cx.entity(), &mut cx.to_async()),
1635            self.client
1636                .subscribe_to_entity(project_id)?
1637                .set_model(&self.worktree_store, &mut cx.to_async()),
1638            self.client
1639                .subscribe_to_entity(project_id)?
1640                .set_model(&self.buffer_store, &mut cx.to_async()),
1641            self.client
1642                .subscribe_to_entity(project_id)?
1643                .set_model(&self.lsp_store, &mut cx.to_async()),
1644            self.client
1645                .subscribe_to_entity(project_id)?
1646                .set_model(&self.settings_observer, &mut cx.to_async()),
1647        ]);
1648
1649        self.buffer_store.update(cx, |buffer_store, cx| {
1650            buffer_store.shared(project_id, self.client.clone().into(), cx)
1651        });
1652        self.worktree_store.update(cx, |worktree_store, cx| {
1653            worktree_store.shared(project_id, self.client.clone().into(), cx);
1654        });
1655        self.lsp_store.update(cx, |lsp_store, cx| {
1656            lsp_store.shared(project_id, self.client.clone().into(), cx)
1657        });
1658        self.task_store.update(cx, |task_store, cx| {
1659            task_store.shared(project_id, self.client.clone().into(), cx);
1660        });
1661        self.settings_observer.update(cx, |settings_observer, cx| {
1662            settings_observer.shared(project_id, self.client.clone().into(), cx)
1663        });
1664
1665        self.client_state = ProjectClientState::Shared {
1666            remote_id: project_id,
1667        };
1668
1669        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1670        cx.notify();
1671        Ok(())
1672    }
1673
1674    pub fn reshared(
1675        &mut self,
1676        message: proto::ResharedProject,
1677        cx: &mut Context<Self>,
1678    ) -> Result<()> {
1679        self.buffer_store
1680            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1681        self.set_collaborators_from_proto(message.collaborators, cx)?;
1682
1683        self.worktree_store.update(cx, |worktree_store, cx| {
1684            worktree_store.send_project_updates(cx);
1685        });
1686        cx.notify();
1687        cx.emit(Event::Reshared);
1688        Ok(())
1689    }
1690
1691    pub fn rejoined(
1692        &mut self,
1693        message: proto::RejoinedProject,
1694        message_id: u32,
1695        cx: &mut Context<Self>,
1696    ) -> Result<()> {
1697        cx.update_global::<SettingsStore, _>(|store, cx| {
1698            self.worktree_store.update(cx, |worktree_store, cx| {
1699                for worktree in worktree_store.worktrees() {
1700                    store
1701                        .clear_local_settings(worktree.read(cx).id(), cx)
1702                        .log_err();
1703                }
1704            });
1705        });
1706
1707        self.join_project_response_message_id = message_id;
1708        self.set_worktrees_from_proto(message.worktrees, cx)?;
1709        self.set_collaborators_from_proto(message.collaborators, cx)?;
1710        self.lsp_store.update(cx, |lsp_store, _| {
1711            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1712        });
1713        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1714            .unwrap();
1715        cx.emit(Event::Rejoined);
1716        cx.notify();
1717        Ok(())
1718    }
1719
1720    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
1721        self.unshare_internal(cx)?;
1722        cx.notify();
1723        Ok(())
1724    }
1725
1726    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
1727        if self.is_via_collab() {
1728            return Err(anyhow!("attempted to unshare a remote project"));
1729        }
1730
1731        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1732            self.client_state = ProjectClientState::Local;
1733            self.collaborators.clear();
1734            self.client_subscriptions.clear();
1735            self.worktree_store.update(cx, |store, cx| {
1736                store.unshared(cx);
1737            });
1738            self.buffer_store.update(cx, |buffer_store, cx| {
1739                buffer_store.forget_shared_buffers();
1740                buffer_store.unshared(cx)
1741            });
1742            self.task_store.update(cx, |task_store, cx| {
1743                task_store.unshared(cx);
1744            });
1745            self.settings_observer.update(cx, |settings_observer, cx| {
1746                settings_observer.unshared(cx);
1747            });
1748
1749            self.client
1750                .send(proto::UnshareProject {
1751                    project_id: remote_id,
1752                })
1753                .ok();
1754            Ok(())
1755        } else {
1756            Err(anyhow!("attempted to unshare an unshared project"))
1757        }
1758    }
1759
1760    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
1761        if self.is_disconnected(cx) {
1762            return;
1763        }
1764        self.disconnected_from_host_internal(cx);
1765        cx.emit(Event::DisconnectedFromHost);
1766        cx.notify();
1767    }
1768
1769    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
1770        let new_capability =
1771            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1772                Capability::ReadWrite
1773            } else {
1774                Capability::ReadOnly
1775            };
1776        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1777            if *capability == new_capability {
1778                return;
1779            }
1780
1781            *capability = new_capability;
1782            for buffer in self.opened_buffers(cx) {
1783                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1784            }
1785        }
1786    }
1787
1788    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
1789        if let ProjectClientState::Remote {
1790            sharing_has_stopped,
1791            ..
1792        } = &mut self.client_state
1793        {
1794            *sharing_has_stopped = true;
1795            self.collaborators.clear();
1796            self.worktree_store.update(cx, |store, cx| {
1797                store.disconnected_from_host(cx);
1798            });
1799            self.buffer_store.update(cx, |buffer_store, cx| {
1800                buffer_store.disconnected_from_host(cx)
1801            });
1802            self.lsp_store
1803                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1804        }
1805    }
1806
1807    pub fn close(&mut self, cx: &mut Context<Self>) {
1808        cx.emit(Event::Closed);
1809    }
1810
1811    pub fn is_disconnected(&self, cx: &App) -> bool {
1812        match &self.client_state {
1813            ProjectClientState::Remote {
1814                sharing_has_stopped,
1815                ..
1816            } => *sharing_has_stopped,
1817            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1818            _ => false,
1819        }
1820    }
1821
1822    fn ssh_is_disconnected(&self, cx: &App) -> bool {
1823        self.ssh_client
1824            .as_ref()
1825            .map(|ssh| ssh.read(cx).is_disconnected())
1826            .unwrap_or(false)
1827    }
1828
1829    pub fn capability(&self) -> Capability {
1830        match &self.client_state {
1831            ProjectClientState::Remote { capability, .. } => *capability,
1832            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1833        }
1834    }
1835
1836    pub fn is_read_only(&self, cx: &App) -> bool {
1837        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1838    }
1839
1840    pub fn is_local(&self) -> bool {
1841        match &self.client_state {
1842            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1843                self.ssh_client.is_none()
1844            }
1845            ProjectClientState::Remote { .. } => false,
1846        }
1847    }
1848
1849    pub fn is_via_ssh(&self) -> bool {
1850        match &self.client_state {
1851            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1852                self.ssh_client.is_some()
1853            }
1854            ProjectClientState::Remote { .. } => false,
1855        }
1856    }
1857
1858    pub fn is_via_collab(&self) -> bool {
1859        match &self.client_state {
1860            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1861            ProjectClientState::Remote { .. } => true,
1862        }
1863    }
1864
1865    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
1866        self.buffer_store
1867            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1868    }
1869
1870    pub fn create_local_buffer(
1871        &mut self,
1872        text: &str,
1873        language: Option<Arc<Language>>,
1874        cx: &mut Context<Self>,
1875    ) -> Entity<Buffer> {
1876        if self.is_via_collab() || self.is_via_ssh() {
1877            panic!("called create_local_buffer on a remote project")
1878        }
1879        self.buffer_store.update(cx, |buffer_store, cx| {
1880            buffer_store.create_local_buffer(text, language, cx)
1881        })
1882    }
1883
1884    pub fn open_path(
1885        &mut self,
1886        path: ProjectPath,
1887        cx: &mut Context<Self>,
1888    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
1889        let task = self.open_buffer(path.clone(), cx);
1890        cx.spawn(move |_, cx| async move {
1891            let buffer = task.await?;
1892            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1893                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1894            })?;
1895
1896            let buffer: &AnyEntity = &buffer;
1897            Ok((project_entry_id, buffer.clone()))
1898        })
1899    }
1900
1901    pub fn open_local_buffer(
1902        &mut self,
1903        abs_path: impl AsRef<Path>,
1904        cx: &mut Context<Self>,
1905    ) -> Task<Result<Entity<Buffer>>> {
1906        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1907            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1908        } else {
1909            Task::ready(Err(anyhow!("no such path")))
1910        }
1911    }
1912
1913    #[cfg(any(test, feature = "test-support"))]
1914    pub fn open_local_buffer_with_lsp(
1915        &mut self,
1916        abs_path: impl AsRef<Path>,
1917        cx: &mut Context<Self>,
1918    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1919        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1920            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
1921        } else {
1922            Task::ready(Err(anyhow!("no such path")))
1923        }
1924    }
1925
1926    pub fn open_buffer(
1927        &mut self,
1928        path: impl Into<ProjectPath>,
1929        cx: &mut Context<Self>,
1930    ) -> Task<Result<Entity<Buffer>>> {
1931        if self.is_disconnected(cx) {
1932            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1933        }
1934
1935        self.buffer_store.update(cx, |buffer_store, cx| {
1936            buffer_store.open_buffer(path.into(), cx)
1937        })
1938    }
1939
1940    #[cfg(any(test, feature = "test-support"))]
1941    pub fn open_buffer_with_lsp(
1942        &mut self,
1943        path: impl Into<ProjectPath>,
1944        cx: &mut Context<Self>,
1945    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1946        let buffer = self.open_buffer(path, cx);
1947        let lsp_store = self.lsp_store().clone();
1948        cx.spawn(|_, mut cx| async move {
1949            let buffer = buffer.await?;
1950            let handle = lsp_store.update(&mut cx, |lsp_store, cx| {
1951                lsp_store.register_buffer_with_language_servers(&buffer, cx)
1952            })?;
1953            Ok((buffer, handle))
1954        })
1955    }
1956
1957    pub fn open_unstaged_changes(
1958        &mut self,
1959        buffer: Entity<Buffer>,
1960        cx: &mut Context<Self>,
1961    ) -> Task<Result<Entity<BufferChangeSet>>> {
1962        if self.is_disconnected(cx) {
1963            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1964        }
1965
1966        self.buffer_store.update(cx, |buffer_store, cx| {
1967            buffer_store.open_unstaged_changes(buffer, cx)
1968        })
1969    }
1970
1971    pub fn open_buffer_by_id(
1972        &mut self,
1973        id: BufferId,
1974        cx: &mut Context<Self>,
1975    ) -> Task<Result<Entity<Buffer>>> {
1976        if let Some(buffer) = self.buffer_for_id(id, cx) {
1977            Task::ready(Ok(buffer))
1978        } else if self.is_local() || self.is_via_ssh() {
1979            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1980        } else if let Some(project_id) = self.remote_id() {
1981            let request = self.client.request(proto::OpenBufferById {
1982                project_id,
1983                id: id.into(),
1984            });
1985            cx.spawn(move |this, mut cx| async move {
1986                let buffer_id = BufferId::new(request.await?.buffer_id)?;
1987                this.update(&mut cx, |this, cx| {
1988                    this.wait_for_remote_buffer(buffer_id, cx)
1989                })?
1990                .await
1991            })
1992        } else {
1993            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1994        }
1995    }
1996
1997    pub fn save_buffers(
1998        &self,
1999        buffers: HashSet<Entity<Buffer>>,
2000        cx: &mut Context<Self>,
2001    ) -> Task<Result<()>> {
2002        cx.spawn(move |this, mut cx| async move {
2003            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2004                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
2005                    .ok()
2006            });
2007            try_join_all(save_tasks).await?;
2008            Ok(())
2009        })
2010    }
2011
2012    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2013        self.buffer_store
2014            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2015    }
2016
2017    pub fn save_buffer_as(
2018        &mut self,
2019        buffer: Entity<Buffer>,
2020        path: ProjectPath,
2021        cx: &mut Context<Self>,
2022    ) -> Task<Result<()>> {
2023        self.buffer_store.update(cx, |buffer_store, cx| {
2024            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2025        })
2026    }
2027
2028    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2029        self.buffer_store.read(cx).get_by_path(path, cx)
2030    }
2031
2032    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2033        {
2034            let mut remotely_created_models = self.remotely_created_models.lock();
2035            if remotely_created_models.retain_count > 0 {
2036                remotely_created_models.buffers.push(buffer.clone())
2037            }
2038        }
2039
2040        self.request_buffer_diff_recalculation(buffer, cx);
2041
2042        cx.subscribe(buffer, |this, buffer, event, cx| {
2043            this.on_buffer_event(buffer, event, cx);
2044        })
2045        .detach();
2046
2047        Ok(())
2048    }
2049
2050    pub fn open_image(
2051        &mut self,
2052        path: impl Into<ProjectPath>,
2053        cx: &mut Context<Self>,
2054    ) -> Task<Result<Entity<ImageItem>>> {
2055        if self.is_disconnected(cx) {
2056            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2057        }
2058
2059        self.image_store.update(cx, |image_store, cx| {
2060            image_store.open_image(path.into(), cx)
2061        })
2062    }
2063
2064    async fn send_buffer_ordered_messages(
2065        this: WeakEntity<Self>,
2066        rx: UnboundedReceiver<BufferOrderedMessage>,
2067        mut cx: AsyncApp,
2068    ) -> Result<()> {
2069        const MAX_BATCH_SIZE: usize = 128;
2070
2071        let mut operations_by_buffer_id = HashMap::default();
2072        async fn flush_operations(
2073            this: &WeakEntity<Project>,
2074            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2075            needs_resync_with_host: &mut bool,
2076            is_local: bool,
2077            cx: &mut AsyncApp,
2078        ) -> Result<()> {
2079            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2080                let request = this.update(cx, |this, _| {
2081                    let project_id = this.remote_id()?;
2082                    Some(this.client.request(proto::UpdateBuffer {
2083                        buffer_id: buffer_id.into(),
2084                        project_id,
2085                        operations,
2086                    }))
2087                })?;
2088                if let Some(request) = request {
2089                    if request.await.is_err() && !is_local {
2090                        *needs_resync_with_host = true;
2091                        break;
2092                    }
2093                }
2094            }
2095            Ok(())
2096        }
2097
2098        let mut needs_resync_with_host = false;
2099        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2100
2101        while let Some(changes) = changes.next().await {
2102            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2103
2104            for change in changes {
2105                match change {
2106                    BufferOrderedMessage::Operation {
2107                        buffer_id,
2108                        operation,
2109                    } => {
2110                        if needs_resync_with_host {
2111                            continue;
2112                        }
2113
2114                        operations_by_buffer_id
2115                            .entry(buffer_id)
2116                            .or_insert(Vec::new())
2117                            .push(operation);
2118                    }
2119
2120                    BufferOrderedMessage::Resync => {
2121                        operations_by_buffer_id.clear();
2122                        if this
2123                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2124                            .await
2125                            .is_ok()
2126                        {
2127                            needs_resync_with_host = false;
2128                        }
2129                    }
2130
2131                    BufferOrderedMessage::LanguageServerUpdate {
2132                        language_server_id,
2133                        message,
2134                    } => {
2135                        flush_operations(
2136                            &this,
2137                            &mut operations_by_buffer_id,
2138                            &mut needs_resync_with_host,
2139                            is_local,
2140                            &mut cx,
2141                        )
2142                        .await?;
2143
2144                        this.update(&mut cx, |this, _| {
2145                            if let Some(project_id) = this.remote_id() {
2146                                this.client
2147                                    .send(proto::UpdateLanguageServer {
2148                                        project_id,
2149                                        language_server_id: language_server_id.0 as u64,
2150                                        variant: Some(message),
2151                                    })
2152                                    .log_err();
2153                            }
2154                        })?;
2155                    }
2156                }
2157            }
2158
2159            flush_operations(
2160                &this,
2161                &mut operations_by_buffer_id,
2162                &mut needs_resync_with_host,
2163                is_local,
2164                &mut cx,
2165            )
2166            .await?;
2167        }
2168
2169        Ok(())
2170    }
2171
2172    fn on_buffer_store_event(
2173        &mut self,
2174        _: Entity<BufferStore>,
2175        event: &BufferStoreEvent,
2176        cx: &mut Context<Self>,
2177    ) {
2178        match event {
2179            BufferStoreEvent::BufferAdded(buffer) => {
2180                self.register_buffer(buffer, cx).log_err();
2181            }
2182            BufferStoreEvent::BufferChangedFilePath { .. } => {}
2183            BufferStoreEvent::BufferDropped(buffer_id) => {
2184                if let Some(ref ssh_client) = self.ssh_client {
2185                    ssh_client
2186                        .read(cx)
2187                        .proto_client()
2188                        .send(proto::CloseBuffer {
2189                            project_id: 0,
2190                            buffer_id: buffer_id.to_proto(),
2191                        })
2192                        .log_err();
2193                }
2194            }
2195        }
2196    }
2197
2198    fn on_image_store_event(
2199        &mut self,
2200        _: Entity<ImageStore>,
2201        event: &ImageStoreEvent,
2202        cx: &mut Context<Self>,
2203    ) {
2204        match event {
2205            ImageStoreEvent::ImageAdded(image) => {
2206                cx.subscribe(image, |this, image, event, cx| {
2207                    this.on_image_event(image, event, cx);
2208                })
2209                .detach();
2210            }
2211        }
2212    }
2213
2214    fn on_lsp_store_event(
2215        &mut self,
2216        _: Entity<LspStore>,
2217        event: &LspStoreEvent,
2218        cx: &mut Context<Self>,
2219    ) {
2220        match event {
2221            LspStoreEvent::DiagnosticsUpdated {
2222                language_server_id,
2223                path,
2224            } => cx.emit(Event::DiagnosticsUpdated {
2225                path: path.clone(),
2226                language_server_id: *language_server_id,
2227            }),
2228            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2229                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2230            ),
2231            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2232                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2233            }
2234            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2235                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2236            ),
2237            LspStoreEvent::LanguageDetected {
2238                buffer,
2239                new_language,
2240            } => {
2241                let Some(_) = new_language else {
2242                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2243                    return;
2244                };
2245            }
2246            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2247            LspStoreEvent::LanguageServerPrompt(prompt) => {
2248                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2249            }
2250            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2251                cx.emit(Event::DiskBasedDiagnosticsStarted {
2252                    language_server_id: *language_server_id,
2253                });
2254            }
2255            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2256                cx.emit(Event::DiskBasedDiagnosticsFinished {
2257                    language_server_id: *language_server_id,
2258                });
2259            }
2260            LspStoreEvent::LanguageServerUpdate {
2261                language_server_id,
2262                message,
2263            } => {
2264                if self.is_local() {
2265                    self.enqueue_buffer_ordered_message(
2266                        BufferOrderedMessage::LanguageServerUpdate {
2267                            language_server_id: *language_server_id,
2268                            message: message.clone(),
2269                        },
2270                    )
2271                    .ok();
2272                }
2273            }
2274            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2275                notification_id: "lsp".into(),
2276                message: message.clone(),
2277            }),
2278            LspStoreEvent::SnippetEdit {
2279                buffer_id,
2280                edits,
2281                most_recent_edit,
2282            } => {
2283                if most_recent_edit.replica_id == self.replica_id() {
2284                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2285                }
2286            }
2287        }
2288    }
2289
2290    fn on_ssh_event(
2291        &mut self,
2292        _: Entity<SshRemoteClient>,
2293        event: &remote::SshRemoteEvent,
2294        cx: &mut Context<Self>,
2295    ) {
2296        match event {
2297            remote::SshRemoteEvent::Disconnected => {
2298                // if self.is_via_ssh() {
2299                // self.collaborators.clear();
2300                self.worktree_store.update(cx, |store, cx| {
2301                    store.disconnected_from_host(cx);
2302                });
2303                self.buffer_store.update(cx, |buffer_store, cx| {
2304                    buffer_store.disconnected_from_host(cx)
2305                });
2306                self.lsp_store.update(cx, |lsp_store, _cx| {
2307                    lsp_store.disconnected_from_ssh_remote()
2308                });
2309                cx.emit(Event::DisconnectedFromSshRemote);
2310            }
2311        }
2312    }
2313
2314    fn on_settings_observer_event(
2315        &mut self,
2316        _: Entity<SettingsObserver>,
2317        event: &SettingsObserverEvent,
2318        cx: &mut Context<Self>,
2319    ) {
2320        match event {
2321            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2322                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2323                    let message =
2324                        format!("Failed to set local settings in {:?}:\n{}", path, message);
2325                    cx.emit(Event::Toast {
2326                        notification_id: "local-settings".into(),
2327                        message,
2328                    });
2329                }
2330                Ok(_) => cx.emit(Event::HideToast {
2331                    notification_id: "local-settings".into(),
2332                }),
2333                Err(_) => {}
2334            },
2335        }
2336    }
2337
2338    fn on_worktree_store_event(
2339        &mut self,
2340        _: Entity<WorktreeStore>,
2341        event: &WorktreeStoreEvent,
2342        cx: &mut Context<Self>,
2343    ) {
2344        match event {
2345            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2346                self.on_worktree_added(worktree, cx);
2347                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2348            }
2349            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2350                cx.emit(Event::WorktreeRemoved(*id));
2351            }
2352            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2353                self.on_worktree_released(*id, cx);
2354            }
2355            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2356            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2357            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2358                self.client()
2359                    .telemetry()
2360                    .report_discovered_project_events(*worktree_id, changes);
2361                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2362            }
2363            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id) => {
2364                cx.emit(Event::WorktreeUpdatedGitRepositories(*worktree_id))
2365            }
2366            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2367                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2368            }
2369        }
2370    }
2371
2372    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
2373        {
2374            let mut remotely_created_models = self.remotely_created_models.lock();
2375            if remotely_created_models.retain_count > 0 {
2376                remotely_created_models.worktrees.push(worktree.clone())
2377            }
2378        }
2379        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2380        cx.notify();
2381    }
2382
2383    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2384        if let Some(ssh) = &self.ssh_client {
2385            ssh.read(cx)
2386                .proto_client()
2387                .send(proto::RemoveWorktree {
2388                    worktree_id: id_to_remove.to_proto(),
2389                })
2390                .log_err();
2391        }
2392
2393        cx.notify();
2394    }
2395
2396    fn on_buffer_event(
2397        &mut self,
2398        buffer: Entity<Buffer>,
2399        event: &BufferEvent,
2400        cx: &mut Context<Self>,
2401    ) -> Option<()> {
2402        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2403            self.request_buffer_diff_recalculation(&buffer, cx);
2404        }
2405
2406        let buffer_id = buffer.read(cx).remote_id();
2407        match event {
2408            BufferEvent::ReloadNeeded => {
2409                if !self.is_via_collab() {
2410                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2411                        .detach_and_log_err(cx);
2412                }
2413            }
2414            BufferEvent::Operation {
2415                operation,
2416                is_local: true,
2417            } => {
2418                let operation = language::proto::serialize_operation(operation);
2419
2420                if let Some(ssh) = &self.ssh_client {
2421                    ssh.read(cx)
2422                        .proto_client()
2423                        .send(proto::UpdateBuffer {
2424                            project_id: 0,
2425                            buffer_id: buffer_id.to_proto(),
2426                            operations: vec![operation.clone()],
2427                        })
2428                        .ok();
2429                }
2430
2431                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2432                    buffer_id,
2433                    operation,
2434                })
2435                .ok();
2436            }
2437
2438            _ => {}
2439        }
2440
2441        None
2442    }
2443
2444    fn on_image_event(
2445        &mut self,
2446        image: Entity<ImageItem>,
2447        event: &ImageItemEvent,
2448        cx: &mut Context<Self>,
2449    ) -> Option<()> {
2450        match event {
2451            ImageItemEvent::ReloadNeeded => {
2452                if !self.is_via_collab() {
2453                    self.reload_images([image.clone()].into_iter().collect(), cx)
2454                        .detach_and_log_err(cx);
2455                }
2456            }
2457            _ => {}
2458        }
2459
2460        None
2461    }
2462
2463    fn request_buffer_diff_recalculation(
2464        &mut self,
2465        buffer: &Entity<Buffer>,
2466        cx: &mut Context<Self>,
2467    ) {
2468        self.buffers_needing_diff.insert(buffer.downgrade());
2469        let first_insertion = self.buffers_needing_diff.len() == 1;
2470
2471        let settings = ProjectSettings::get_global(cx);
2472        let delay = if let Some(delay) = settings.git.gutter_debounce {
2473            delay
2474        } else {
2475            if first_insertion {
2476                let this = cx.weak_entity();
2477                cx.defer(move |cx| {
2478                    if let Some(this) = this.upgrade() {
2479                        this.update(cx, |this, cx| {
2480                            this.recalculate_buffer_diffs(cx).detach();
2481                        });
2482                    }
2483                });
2484            }
2485            return;
2486        };
2487
2488        const MIN_DELAY: u64 = 50;
2489        let delay = delay.max(MIN_DELAY);
2490        let duration = Duration::from_millis(delay);
2491
2492        self.git_diff_debouncer
2493            .fire_new(duration, cx, move |this, cx| {
2494                this.recalculate_buffer_diffs(cx)
2495            });
2496    }
2497
2498    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2499        cx.spawn(move |this, mut cx| async move {
2500            loop {
2501                let task = this
2502                    .update(&mut cx, |this, cx| {
2503                        let buffers = this
2504                            .buffers_needing_diff
2505                            .drain()
2506                            .filter_map(|buffer| buffer.upgrade())
2507                            .collect::<Vec<_>>();
2508                        if buffers.is_empty() {
2509                            None
2510                        } else {
2511                            Some(this.buffer_store.update(cx, |buffer_store, cx| {
2512                                buffer_store.recalculate_buffer_diffs(buffers, cx)
2513                            }))
2514                        }
2515                    })
2516                    .ok()
2517                    .flatten();
2518
2519                if let Some(task) = task {
2520                    task.await;
2521                } else {
2522                    break;
2523                }
2524            }
2525        })
2526    }
2527
2528    pub fn set_language_for_buffer(
2529        &mut self,
2530        buffer: &Entity<Buffer>,
2531        new_language: Arc<Language>,
2532        cx: &mut Context<Self>,
2533    ) {
2534        self.lsp_store.update(cx, |lsp_store, cx| {
2535            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2536        })
2537    }
2538
2539    pub fn restart_language_servers_for_buffers(
2540        &mut self,
2541        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2542        cx: &mut Context<Self>,
2543    ) {
2544        self.lsp_store.update(cx, |lsp_store, cx| {
2545            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2546        })
2547    }
2548
2549    pub fn cancel_language_server_work_for_buffers(
2550        &mut self,
2551        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2552        cx: &mut Context<Self>,
2553    ) {
2554        self.lsp_store.update(cx, |lsp_store, cx| {
2555            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2556        })
2557    }
2558
2559    pub fn cancel_language_server_work(
2560        &mut self,
2561        server_id: LanguageServerId,
2562        token_to_cancel: Option<String>,
2563        cx: &mut Context<Self>,
2564    ) {
2565        self.lsp_store.update(cx, |lsp_store, cx| {
2566            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2567        })
2568    }
2569
2570    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2571        self.buffer_ordered_messages_tx
2572            .unbounded_send(message)
2573            .map_err(|e| anyhow!(e))
2574    }
2575
2576    pub fn available_toolchains(
2577        &self,
2578        worktree_id: WorktreeId,
2579        language_name: LanguageName,
2580        cx: &App,
2581    ) -> Task<Option<ToolchainList>> {
2582        if let Some(toolchain_store) = self.toolchain_store.clone() {
2583            cx.spawn(|cx| async move {
2584                cx.update(|cx| {
2585                    toolchain_store
2586                        .read(cx)
2587                        .list_toolchains(worktree_id, language_name, cx)
2588                })
2589                .ok()?
2590                .await
2591            })
2592        } else {
2593            Task::ready(None)
2594        }
2595    }
2596
2597    pub async fn toolchain_term(
2598        languages: Arc<LanguageRegistry>,
2599        language_name: LanguageName,
2600    ) -> Option<SharedString> {
2601        languages
2602            .language_for_name(language_name.as_ref())
2603            .await
2604            .ok()?
2605            .toolchain_lister()
2606            .map(|lister| lister.term())
2607    }
2608
2609    pub fn activate_toolchain(
2610        &self,
2611        worktree_id: WorktreeId,
2612        toolchain: Toolchain,
2613        cx: &mut App,
2614    ) -> Task<Option<()>> {
2615        let Some(toolchain_store) = self.toolchain_store.clone() else {
2616            return Task::ready(None);
2617        };
2618        toolchain_store.update(cx, |this, cx| {
2619            this.activate_toolchain(worktree_id, toolchain, cx)
2620        })
2621    }
2622    pub fn active_toolchain(
2623        &self,
2624        worktree_id: WorktreeId,
2625        language_name: LanguageName,
2626        cx: &App,
2627    ) -> Task<Option<Toolchain>> {
2628        let Some(toolchain_store) = self.toolchain_store.clone() else {
2629            return Task::ready(None);
2630        };
2631        toolchain_store
2632            .read(cx)
2633            .active_toolchain(worktree_id, language_name, cx)
2634    }
2635    pub fn language_server_statuses<'a>(
2636        &'a self,
2637        cx: &'a App,
2638    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2639        self.lsp_store.read(cx).language_server_statuses()
2640    }
2641
2642    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
2643        self.lsp_store.read(cx).last_formatting_failure()
2644    }
2645
2646    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
2647        self.lsp_store
2648            .update(cx, |store, _| store.reset_last_formatting_failure());
2649    }
2650
2651    pub fn reload_buffers(
2652        &self,
2653        buffers: HashSet<Entity<Buffer>>,
2654        push_to_history: bool,
2655        cx: &mut Context<Self>,
2656    ) -> Task<Result<ProjectTransaction>> {
2657        self.buffer_store.update(cx, |buffer_store, cx| {
2658            buffer_store.reload_buffers(buffers, push_to_history, cx)
2659        })
2660    }
2661
2662    pub fn reload_images(
2663        &self,
2664        images: HashSet<Entity<ImageItem>>,
2665        cx: &mut Context<Self>,
2666    ) -> Task<Result<()>> {
2667        self.image_store
2668            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
2669    }
2670
2671    pub fn format(
2672        &mut self,
2673        buffers: HashSet<Entity<Buffer>>,
2674        target: LspFormatTarget,
2675        push_to_history: bool,
2676        trigger: lsp_store::FormatTrigger,
2677        cx: &mut Context<Project>,
2678    ) -> Task<anyhow::Result<ProjectTransaction>> {
2679        self.lsp_store.update(cx, |lsp_store, cx| {
2680            lsp_store.format(buffers, target, push_to_history, trigger, cx)
2681        })
2682    }
2683
2684    #[inline(never)]
2685    fn definition_impl(
2686        &mut self,
2687        buffer: &Entity<Buffer>,
2688        position: PointUtf16,
2689        cx: &mut Context<Self>,
2690    ) -> Task<Result<Vec<LocationLink>>> {
2691        self.request_lsp(
2692            buffer.clone(),
2693            LanguageServerToQuery::Primary,
2694            GetDefinition { position },
2695            cx,
2696        )
2697    }
2698    pub fn definition<T: ToPointUtf16>(
2699        &mut self,
2700        buffer: &Entity<Buffer>,
2701        position: T,
2702        cx: &mut Context<Self>,
2703    ) -> Task<Result<Vec<LocationLink>>> {
2704        let position = position.to_point_utf16(buffer.read(cx));
2705        self.definition_impl(buffer, position, cx)
2706    }
2707
2708    fn declaration_impl(
2709        &mut self,
2710        buffer: &Entity<Buffer>,
2711        position: PointUtf16,
2712        cx: &mut Context<Self>,
2713    ) -> Task<Result<Vec<LocationLink>>> {
2714        self.request_lsp(
2715            buffer.clone(),
2716            LanguageServerToQuery::Primary,
2717            GetDeclaration { position },
2718            cx,
2719        )
2720    }
2721
2722    pub fn declaration<T: ToPointUtf16>(
2723        &mut self,
2724        buffer: &Entity<Buffer>,
2725        position: T,
2726        cx: &mut Context<Self>,
2727    ) -> Task<Result<Vec<LocationLink>>> {
2728        let position = position.to_point_utf16(buffer.read(cx));
2729        self.declaration_impl(buffer, position, cx)
2730    }
2731
2732    fn type_definition_impl(
2733        &mut self,
2734        buffer: &Entity<Buffer>,
2735        position: PointUtf16,
2736        cx: &mut Context<Self>,
2737    ) -> Task<Result<Vec<LocationLink>>> {
2738        self.request_lsp(
2739            buffer.clone(),
2740            LanguageServerToQuery::Primary,
2741            GetTypeDefinition { position },
2742            cx,
2743        )
2744    }
2745
2746    pub fn type_definition<T: ToPointUtf16>(
2747        &mut self,
2748        buffer: &Entity<Buffer>,
2749        position: T,
2750        cx: &mut Context<Self>,
2751    ) -> Task<Result<Vec<LocationLink>>> {
2752        let position = position.to_point_utf16(buffer.read(cx));
2753        self.type_definition_impl(buffer, position, cx)
2754    }
2755
2756    pub fn implementation<T: ToPointUtf16>(
2757        &mut self,
2758        buffer: &Entity<Buffer>,
2759        position: T,
2760        cx: &mut Context<Self>,
2761    ) -> Task<Result<Vec<LocationLink>>> {
2762        let position = position.to_point_utf16(buffer.read(cx));
2763        self.request_lsp(
2764            buffer.clone(),
2765            LanguageServerToQuery::Primary,
2766            GetImplementation { position },
2767            cx,
2768        )
2769    }
2770
2771    pub fn references<T: ToPointUtf16>(
2772        &mut self,
2773        buffer: &Entity<Buffer>,
2774        position: T,
2775        cx: &mut Context<Self>,
2776    ) -> Task<Result<Vec<Location>>> {
2777        let position = position.to_point_utf16(buffer.read(cx));
2778        self.request_lsp(
2779            buffer.clone(),
2780            LanguageServerToQuery::Primary,
2781            GetReferences { position },
2782            cx,
2783        )
2784    }
2785
2786    fn document_highlights_impl(
2787        &mut self,
2788        buffer: &Entity<Buffer>,
2789        position: PointUtf16,
2790        cx: &mut Context<Self>,
2791    ) -> Task<Result<Vec<DocumentHighlight>>> {
2792        self.request_lsp(
2793            buffer.clone(),
2794            LanguageServerToQuery::Primary,
2795            GetDocumentHighlights { position },
2796            cx,
2797        )
2798    }
2799
2800    pub fn document_highlights<T: ToPointUtf16>(
2801        &mut self,
2802        buffer: &Entity<Buffer>,
2803        position: T,
2804        cx: &mut Context<Self>,
2805    ) -> Task<Result<Vec<DocumentHighlight>>> {
2806        let position = position.to_point_utf16(buffer.read(cx));
2807        self.document_highlights_impl(buffer, position, cx)
2808    }
2809
2810    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
2811        self.lsp_store
2812            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2813    }
2814
2815    pub fn open_buffer_for_symbol(
2816        &mut self,
2817        symbol: &Symbol,
2818        cx: &mut Context<Self>,
2819    ) -> Task<Result<Entity<Buffer>>> {
2820        self.lsp_store.update(cx, |lsp_store, cx| {
2821            lsp_store.open_buffer_for_symbol(symbol, cx)
2822        })
2823    }
2824
2825    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2826        let guard = self.retain_remotely_created_models(cx);
2827        let Some(ssh_client) = self.ssh_client.as_ref() else {
2828            return Task::ready(Err(anyhow!("not an ssh project")));
2829        };
2830
2831        let proto_client = ssh_client.read(cx).proto_client();
2832
2833        cx.spawn(|this, mut cx| async move {
2834            let buffer = proto_client
2835                .request(proto::OpenServerSettings {
2836                    project_id: SSH_PROJECT_ID,
2837                })
2838                .await?;
2839
2840            let buffer = this
2841                .update(&mut cx, |this, cx| {
2842                    anyhow::Ok(this.wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx))
2843                })??
2844                .await;
2845
2846            drop(guard);
2847            buffer
2848        })
2849    }
2850
2851    pub fn open_local_buffer_via_lsp(
2852        &mut self,
2853        abs_path: lsp::Url,
2854        language_server_id: LanguageServerId,
2855        language_server_name: LanguageServerName,
2856        cx: &mut Context<Self>,
2857    ) -> Task<Result<Entity<Buffer>>> {
2858        self.lsp_store.update(cx, |lsp_store, cx| {
2859            lsp_store.open_local_buffer_via_lsp(
2860                abs_path,
2861                language_server_id,
2862                language_server_name,
2863                cx,
2864            )
2865        })
2866    }
2867
2868    pub fn signature_help<T: ToPointUtf16>(
2869        &self,
2870        buffer: &Entity<Buffer>,
2871        position: T,
2872        cx: &mut Context<Self>,
2873    ) -> Task<Vec<SignatureHelp>> {
2874        self.lsp_store.update(cx, |lsp_store, cx| {
2875            lsp_store.signature_help(buffer, position, cx)
2876        })
2877    }
2878
2879    pub fn hover<T: ToPointUtf16>(
2880        &self,
2881        buffer: &Entity<Buffer>,
2882        position: T,
2883        cx: &mut Context<Self>,
2884    ) -> Task<Vec<Hover>> {
2885        let position = position.to_point_utf16(buffer.read(cx));
2886        self.lsp_store
2887            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2888    }
2889
2890    pub fn linked_edit(
2891        &self,
2892        buffer: &Entity<Buffer>,
2893        position: Anchor,
2894        cx: &mut Context<Self>,
2895    ) -> Task<Result<Vec<Range<Anchor>>>> {
2896        self.lsp_store.update(cx, |lsp_store, cx| {
2897            lsp_store.linked_edit(buffer, position, cx)
2898        })
2899    }
2900
2901    pub fn completions<T: ToOffset + ToPointUtf16>(
2902        &self,
2903        buffer: &Entity<Buffer>,
2904        position: T,
2905        context: CompletionContext,
2906        cx: &mut Context<Self>,
2907    ) -> Task<Result<Vec<Completion>>> {
2908        let position = position.to_point_utf16(buffer.read(cx));
2909        self.lsp_store.update(cx, |lsp_store, cx| {
2910            lsp_store.completions(buffer, position, context, cx)
2911        })
2912    }
2913
2914    pub fn code_actions<T: Clone + ToOffset>(
2915        &mut self,
2916        buffer_handle: &Entity<Buffer>,
2917        range: Range<T>,
2918        kinds: Option<Vec<CodeActionKind>>,
2919        cx: &mut Context<Self>,
2920    ) -> Task<Result<Vec<CodeAction>>> {
2921        let buffer = buffer_handle.read(cx);
2922        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2923        self.lsp_store.update(cx, |lsp_store, cx| {
2924            lsp_store.code_actions(buffer_handle, range, kinds, cx)
2925        })
2926    }
2927
2928    pub fn apply_code_action(
2929        &self,
2930        buffer_handle: Entity<Buffer>,
2931        action: CodeAction,
2932        push_to_history: bool,
2933        cx: &mut Context<Self>,
2934    ) -> Task<Result<ProjectTransaction>> {
2935        self.lsp_store.update(cx, |lsp_store, cx| {
2936            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2937        })
2938    }
2939
2940    fn prepare_rename_impl(
2941        &mut self,
2942        buffer: Entity<Buffer>,
2943        position: PointUtf16,
2944        cx: &mut Context<Self>,
2945    ) -> Task<Result<PrepareRenameResponse>> {
2946        self.request_lsp(
2947            buffer,
2948            LanguageServerToQuery::Primary,
2949            PrepareRename { position },
2950            cx,
2951        )
2952    }
2953    pub fn prepare_rename<T: ToPointUtf16>(
2954        &mut self,
2955        buffer: Entity<Buffer>,
2956        position: T,
2957        cx: &mut Context<Self>,
2958    ) -> Task<Result<PrepareRenameResponse>> {
2959        let position = position.to_point_utf16(buffer.read(cx));
2960        self.prepare_rename_impl(buffer, position, cx)
2961    }
2962
2963    pub fn perform_rename<T: ToPointUtf16>(
2964        &mut self,
2965        buffer: Entity<Buffer>,
2966        position: T,
2967        new_name: String,
2968        cx: &mut Context<Self>,
2969    ) -> Task<Result<ProjectTransaction>> {
2970        let push_to_history = true;
2971        let position = position.to_point_utf16(buffer.read(cx));
2972        self.request_lsp(
2973            buffer,
2974            LanguageServerToQuery::Primary,
2975            PerformRename {
2976                position,
2977                new_name,
2978                push_to_history,
2979            },
2980            cx,
2981        )
2982    }
2983
2984    pub fn on_type_format<T: ToPointUtf16>(
2985        &mut self,
2986        buffer: Entity<Buffer>,
2987        position: T,
2988        trigger: String,
2989        push_to_history: bool,
2990        cx: &mut Context<Self>,
2991    ) -> Task<Result<Option<Transaction>>> {
2992        self.lsp_store.update(cx, |lsp_store, cx| {
2993            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
2994        })
2995    }
2996
2997    pub fn inlay_hints<T: ToOffset>(
2998        &mut self,
2999        buffer_handle: Entity<Buffer>,
3000        range: Range<T>,
3001        cx: &mut Context<Self>,
3002    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3003        let buffer = buffer_handle.read(cx);
3004        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3005        self.lsp_store.update(cx, |lsp_store, cx| {
3006            lsp_store.inlay_hints(buffer_handle, range, cx)
3007        })
3008    }
3009
3010    pub fn resolve_inlay_hint(
3011        &self,
3012        hint: InlayHint,
3013        buffer_handle: Entity<Buffer>,
3014        server_id: LanguageServerId,
3015        cx: &mut Context<Self>,
3016    ) -> Task<anyhow::Result<InlayHint>> {
3017        self.lsp_store.update(cx, |lsp_store, cx| {
3018            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3019        })
3020    }
3021
3022    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3023        let (result_tx, result_rx) = smol::channel::unbounded();
3024
3025        let matching_buffers_rx = if query.is_opened_only() {
3026            self.sort_search_candidates(&query, cx)
3027        } else {
3028            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3029        };
3030
3031        cx.spawn(|_, cx| async move {
3032            let mut range_count = 0;
3033            let mut buffer_count = 0;
3034            let mut limit_reached = false;
3035            let query = Arc::new(query);
3036            let mut chunks = matching_buffers_rx.ready_chunks(64);
3037
3038            // Now that we know what paths match the query, we will load at most
3039            // 64 buffers at a time to avoid overwhelming the main thread. For each
3040            // opened buffer, we will spawn a background task that retrieves all the
3041            // ranges in the buffer matched by the query.
3042            let mut chunks = pin!(chunks);
3043            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3044                let mut chunk_results = Vec::new();
3045                for buffer in matching_buffer_chunk {
3046                    let buffer = buffer.clone();
3047                    let query = query.clone();
3048                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3049                    chunk_results.push(cx.background_executor().spawn(async move {
3050                        let ranges = query
3051                            .search(&snapshot, None)
3052                            .await
3053                            .iter()
3054                            .map(|range| {
3055                                snapshot.anchor_before(range.start)
3056                                    ..snapshot.anchor_after(range.end)
3057                            })
3058                            .collect::<Vec<_>>();
3059                        anyhow::Ok((buffer, ranges))
3060                    }));
3061                }
3062
3063                let chunk_results = futures::future::join_all(chunk_results).await;
3064                for result in chunk_results {
3065                    if let Some((buffer, ranges)) = result.log_err() {
3066                        range_count += ranges.len();
3067                        buffer_count += 1;
3068                        result_tx
3069                            .send(SearchResult::Buffer { buffer, ranges })
3070                            .await?;
3071                        if buffer_count > MAX_SEARCH_RESULT_FILES
3072                            || range_count > MAX_SEARCH_RESULT_RANGES
3073                        {
3074                            limit_reached = true;
3075                            break 'outer;
3076                        }
3077                    }
3078                }
3079            }
3080
3081            if limit_reached {
3082                result_tx.send(SearchResult::LimitReached).await?;
3083            }
3084
3085            anyhow::Ok(())
3086        })
3087        .detach();
3088
3089        result_rx
3090    }
3091
3092    fn find_search_candidate_buffers(
3093        &mut self,
3094        query: &SearchQuery,
3095        limit: usize,
3096        cx: &mut Context<Project>,
3097    ) -> Receiver<Entity<Buffer>> {
3098        if self.is_local() {
3099            let fs = self.fs.clone();
3100            self.buffer_store.update(cx, |buffer_store, cx| {
3101                buffer_store.find_search_candidates(query, limit, fs, cx)
3102            })
3103        } else {
3104            self.find_search_candidates_remote(query, limit, cx)
3105        }
3106    }
3107
3108    fn sort_search_candidates(
3109        &mut self,
3110        search_query: &SearchQuery,
3111        cx: &mut Context<Project>,
3112    ) -> Receiver<Entity<Buffer>> {
3113        let worktree_store = self.worktree_store.read(cx);
3114        let mut buffers = search_query
3115            .buffers()
3116            .into_iter()
3117            .flatten()
3118            .filter(|buffer| {
3119                let b = buffer.read(cx);
3120                if let Some(file) = b.file() {
3121                    if !search_query.file_matches(file.path()) {
3122                        return false;
3123                    }
3124                    if let Some(entry) = b
3125                        .entry_id(cx)
3126                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3127                    {
3128                        if entry.is_ignored && !search_query.include_ignored() {
3129                            return false;
3130                        }
3131                    }
3132                }
3133                true
3134            })
3135            .collect::<Vec<_>>();
3136        let (tx, rx) = smol::channel::unbounded();
3137        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3138            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3139            (None, Some(_)) => std::cmp::Ordering::Less,
3140            (Some(_), None) => std::cmp::Ordering::Greater,
3141            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3142        });
3143        for buffer in buffers {
3144            tx.send_blocking(buffer.clone()).unwrap()
3145        }
3146
3147        rx
3148    }
3149
3150    fn find_search_candidates_remote(
3151        &mut self,
3152        query: &SearchQuery,
3153        limit: usize,
3154        cx: &mut Context<Project>,
3155    ) -> Receiver<Entity<Buffer>> {
3156        let (tx, rx) = smol::channel::unbounded();
3157
3158        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3159            (ssh_client.read(cx).proto_client(), 0)
3160        } else if let Some(remote_id) = self.remote_id() {
3161            (self.client.clone().into(), remote_id)
3162        } else {
3163            return rx;
3164        };
3165
3166        let request = client.request(proto::FindSearchCandidates {
3167            project_id: remote_id,
3168            query: Some(query.to_proto()),
3169            limit: limit as _,
3170        });
3171        let guard = self.retain_remotely_created_models(cx);
3172
3173        cx.spawn(move |this, mut cx| async move {
3174            let response = request.await?;
3175            for buffer_id in response.buffer_ids {
3176                let buffer_id = BufferId::new(buffer_id)?;
3177                let buffer = this
3178                    .update(&mut cx, |this, cx| {
3179                        this.wait_for_remote_buffer(buffer_id, cx)
3180                    })?
3181                    .await?;
3182                let _ = tx.send(buffer).await;
3183            }
3184
3185            drop(guard);
3186            anyhow::Ok(())
3187        })
3188        .detach_and_log_err(cx);
3189        rx
3190    }
3191
3192    pub fn request_lsp<R: LspCommand>(
3193        &mut self,
3194        buffer_handle: Entity<Buffer>,
3195        server: LanguageServerToQuery,
3196        request: R,
3197        cx: &mut Context<Self>,
3198    ) -> Task<Result<R::Response>>
3199    where
3200        <R::LspRequest as lsp::request::Request>::Result: Send,
3201        <R::LspRequest as lsp::request::Request>::Params: Send,
3202    {
3203        let guard = self.retain_remotely_created_models(cx);
3204        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3205            lsp_store.request_lsp(buffer_handle, server, request, cx)
3206        });
3207        cx.spawn(|_, _| async move {
3208            let result = task.await;
3209            drop(guard);
3210            result
3211        })
3212    }
3213
3214    /// Move a worktree to a new position in the worktree order.
3215    ///
3216    /// The worktree will moved to the opposite side of the destination worktree.
3217    ///
3218    /// # Example
3219    ///
3220    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3221    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3222    ///
3223    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3224    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3225    ///
3226    /// # Errors
3227    ///
3228    /// An error will be returned if the worktree or destination worktree are not found.
3229    pub fn move_worktree(
3230        &mut self,
3231        source: WorktreeId,
3232        destination: WorktreeId,
3233        cx: &mut Context<'_, Self>,
3234    ) -> Result<()> {
3235        self.worktree_store.update(cx, |worktree_store, cx| {
3236            worktree_store.move_worktree(source, destination, cx)
3237        })
3238    }
3239
3240    pub fn find_or_create_worktree(
3241        &mut self,
3242        abs_path: impl AsRef<Path>,
3243        visible: bool,
3244        cx: &mut Context<Self>,
3245    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3246        self.worktree_store.update(cx, |worktree_store, cx| {
3247            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3248        })
3249    }
3250
3251    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3252        self.worktree_store.read_with(cx, |worktree_store, cx| {
3253            worktree_store.find_worktree(abs_path, cx)
3254        })
3255    }
3256
3257    pub fn is_shared(&self) -> bool {
3258        match &self.client_state {
3259            ProjectClientState::Shared { .. } => true,
3260            ProjectClientState::Local => false,
3261            ProjectClientState::Remote { .. } => true,
3262        }
3263    }
3264
3265    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3266    pub fn resolve_path_in_buffer(
3267        &self,
3268        path: &str,
3269        buffer: &Entity<Buffer>,
3270        cx: &mut Context<Self>,
3271    ) -> Task<Option<ResolvedPath>> {
3272        let path_buf = PathBuf::from(path);
3273        if path_buf.is_absolute() || path.starts_with("~") {
3274            self.resolve_abs_path(path, cx)
3275        } else {
3276            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3277        }
3278    }
3279
3280    pub fn resolve_abs_file_path(
3281        &self,
3282        path: &str,
3283        cx: &mut Context<Self>,
3284    ) -> Task<Option<ResolvedPath>> {
3285        let resolve_task = self.resolve_abs_path(path, cx);
3286        cx.background_executor().spawn(async move {
3287            let resolved_path = resolve_task.await;
3288            resolved_path.filter(|path| path.is_file())
3289        })
3290    }
3291
3292    pub fn resolve_abs_path(
3293        &self,
3294        path: &str,
3295        cx: &mut Context<Self>,
3296    ) -> Task<Option<ResolvedPath>> {
3297        if self.is_local() {
3298            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3299            let fs = self.fs.clone();
3300            cx.background_executor().spawn(async move {
3301                let path = expanded.as_path();
3302                let metadata = fs.metadata(path).await.ok().flatten();
3303
3304                metadata.map(|metadata| ResolvedPath::AbsPath {
3305                    path: expanded,
3306                    is_dir: metadata.is_dir,
3307                })
3308            })
3309        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3310            let request = ssh_client
3311                .read(cx)
3312                .proto_client()
3313                .request(proto::GetPathMetadata {
3314                    project_id: SSH_PROJECT_ID,
3315                    path: path.to_string(),
3316                });
3317            cx.background_executor().spawn(async move {
3318                let response = request.await.log_err()?;
3319                if response.exists {
3320                    Some(ResolvedPath::AbsPath {
3321                        path: PathBuf::from(response.path),
3322                        is_dir: response.is_dir,
3323                    })
3324                } else {
3325                    None
3326                }
3327            })
3328        } else {
3329            return Task::ready(None);
3330        }
3331    }
3332
3333    fn resolve_path_in_worktrees(
3334        &self,
3335        path: PathBuf,
3336        buffer: &Entity<Buffer>,
3337        cx: &mut Context<Self>,
3338    ) -> Task<Option<ResolvedPath>> {
3339        let mut candidates = vec![path.clone()];
3340
3341        if let Some(file) = buffer.read(cx).file() {
3342            if let Some(dir) = file.path().parent() {
3343                let joined = dir.to_path_buf().join(path);
3344                candidates.push(joined);
3345            }
3346        }
3347
3348        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3349        cx.spawn(|_, mut cx| async move {
3350            for worktree in worktrees {
3351                for candidate in candidates.iter() {
3352                    let path = worktree
3353                        .update(&mut cx, |worktree, _| {
3354                            let root_entry_path = &worktree.root_entry()?.path;
3355
3356                            let resolved = resolve_path(root_entry_path, candidate);
3357
3358                            let stripped =
3359                                resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3360
3361                            worktree.entry_for_path(stripped).map(|entry| {
3362                                let project_path = ProjectPath {
3363                                    worktree_id: worktree.id(),
3364                                    path: entry.path.clone(),
3365                                };
3366                                ResolvedPath::ProjectPath {
3367                                    project_path,
3368                                    is_dir: entry.is_dir(),
3369                                }
3370                            })
3371                        })
3372                        .ok()?;
3373
3374                    if path.is_some() {
3375                        return path;
3376                    }
3377                }
3378            }
3379            None
3380        })
3381    }
3382
3383    pub fn list_directory(
3384        &self,
3385        query: String,
3386        cx: &mut Context<Self>,
3387    ) -> Task<Result<Vec<PathBuf>>> {
3388        if self.is_local() {
3389            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3390        } else if let Some(session) = self.ssh_client.as_ref() {
3391            let request = proto::ListRemoteDirectory {
3392                dev_server_id: SSH_PROJECT_ID,
3393                path: query,
3394            };
3395
3396            let response = session.read(cx).proto_client().request(request);
3397            cx.background_executor().spawn(async move {
3398                let response = response.await?;
3399                Ok(response.entries.into_iter().map(PathBuf::from).collect())
3400            })
3401        } else {
3402            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3403        }
3404    }
3405
3406    pub fn create_worktree(
3407        &mut self,
3408        abs_path: impl AsRef<Path>,
3409        visible: bool,
3410        cx: &mut Context<Self>,
3411    ) -> Task<Result<Entity<Worktree>>> {
3412        self.worktree_store.update(cx, |worktree_store, cx| {
3413            worktree_store.create_worktree(abs_path, visible, cx)
3414        })
3415    }
3416
3417    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3418        self.worktree_store.update(cx, |worktree_store, cx| {
3419            worktree_store.remove_worktree(id_to_remove, cx);
3420        });
3421    }
3422
3423    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3424        self.worktree_store.update(cx, |worktree_store, cx| {
3425            worktree_store.add(worktree, cx);
3426        });
3427    }
3428
3429    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3430        let new_active_entry = entry.and_then(|project_path| {
3431            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3432            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3433            Some(entry.id)
3434        });
3435        if new_active_entry != self.active_entry {
3436            self.active_entry = new_active_entry;
3437            self.lsp_store.update(cx, |lsp_store, _| {
3438                lsp_store.set_active_entry(new_active_entry);
3439            });
3440            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3441        }
3442    }
3443
3444    pub fn language_servers_running_disk_based_diagnostics<'a>(
3445        &'a self,
3446        cx: &'a App,
3447    ) -> impl Iterator<Item = LanguageServerId> + 'a {
3448        self.lsp_store
3449            .read(cx)
3450            .language_servers_running_disk_based_diagnostics()
3451    }
3452
3453    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3454        self.lsp_store
3455            .read(cx)
3456            .diagnostic_summary(include_ignored, cx)
3457    }
3458
3459    pub fn diagnostic_summaries<'a>(
3460        &'a self,
3461        include_ignored: bool,
3462        cx: &'a App,
3463    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3464        self.lsp_store
3465            .read(cx)
3466            .diagnostic_summaries(include_ignored, cx)
3467    }
3468
3469    pub fn active_entry(&self) -> Option<ProjectEntryId> {
3470        self.active_entry
3471    }
3472
3473    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
3474        self.worktree_store.read(cx).entry_for_path(path, cx)
3475    }
3476
3477    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
3478        let worktree = self.worktree_for_entry(entry_id, cx)?;
3479        let worktree = worktree.read(cx);
3480        let worktree_id = worktree.id();
3481        let path = worktree.entry_for_id(entry_id)?.path.clone();
3482        Some(ProjectPath { worktree_id, path })
3483    }
3484
3485    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3486        self.worktree_for_id(project_path.worktree_id, cx)?
3487            .read(cx)
3488            .absolutize(&project_path.path)
3489            .ok()
3490    }
3491
3492    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3493    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3494    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3495    /// the first visible worktree that has an entry for that relative path.
3496    ///
3497    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3498    /// root name from paths.
3499    ///
3500    /// # Arguments
3501    ///
3502    /// * `path` - A full path that starts with a worktree root name, or alternatively a
3503    ///            relative path within a visible worktree.
3504    /// * `cx` - A reference to the `AppContext`.
3505    ///
3506    /// # Returns
3507    ///
3508    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3509    pub fn find_project_path(&self, path: &Path, cx: &App) -> Option<ProjectPath> {
3510        let worktree_store = self.worktree_store.read(cx);
3511
3512        for worktree in worktree_store.visible_worktrees(cx) {
3513            let worktree_root_name = worktree.read(cx).root_name();
3514            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3515                return Some(ProjectPath {
3516                    worktree_id: worktree.read(cx).id(),
3517                    path: relative_path.into(),
3518                });
3519            }
3520        }
3521
3522        for worktree in worktree_store.visible_worktrees(cx) {
3523            let worktree = worktree.read(cx);
3524            if let Some(entry) = worktree.entry_for_path(path) {
3525                return Some(ProjectPath {
3526                    worktree_id: worktree.id(),
3527                    path: entry.path.clone(),
3528                });
3529            }
3530        }
3531
3532        None
3533    }
3534
3535    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3536        Some(
3537            self.worktree_for_id(project_path.worktree_id, cx)?
3538                .read(cx)
3539                .abs_path()
3540                .to_path_buf(),
3541        )
3542    }
3543
3544    pub fn get_first_worktree_root_repo(&self, cx: &App) -> Option<Arc<dyn GitRepository>> {
3545        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3546        let root_entry = worktree.root_git_entry()?;
3547        worktree.get_local_repo(&root_entry)?.repo().clone().into()
3548    }
3549
3550    pub fn branches(&self, project_path: ProjectPath, cx: &App) -> Task<Result<Vec<Branch>>> {
3551        self.worktree_store().read(cx).branches(project_path, cx)
3552    }
3553
3554    pub fn update_or_create_branch(
3555        &self,
3556        repository: ProjectPath,
3557        new_branch: String,
3558        cx: &App,
3559    ) -> Task<Result<()>> {
3560        self.worktree_store()
3561            .read(cx)
3562            .update_or_create_branch(repository, new_branch, cx)
3563    }
3564
3565    pub fn blame_buffer(
3566        &self,
3567        buffer: &Entity<Buffer>,
3568        version: Option<clock::Global>,
3569        cx: &App,
3570    ) -> Task<Result<Option<Blame>>> {
3571        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3572    }
3573
3574    pub fn get_permalink_to_line(
3575        &self,
3576        buffer: &Entity<Buffer>,
3577        selection: Range<u32>,
3578        cx: &App,
3579    ) -> Task<Result<url::Url>> {
3580        self.buffer_store
3581            .read(cx)
3582            .get_permalink_to_line(buffer, selection, cx)
3583    }
3584
3585    // RPC message handlers
3586
3587    async fn handle_unshare_project(
3588        this: Entity<Self>,
3589        _: TypedEnvelope<proto::UnshareProject>,
3590        mut cx: AsyncApp,
3591    ) -> Result<()> {
3592        this.update(&mut cx, |this, cx| {
3593            if this.is_local() || this.is_via_ssh() {
3594                this.unshare(cx)?;
3595            } else {
3596                this.disconnected_from_host(cx);
3597            }
3598            Ok(())
3599        })?
3600    }
3601
3602    async fn handle_add_collaborator(
3603        this: Entity<Self>,
3604        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3605        mut cx: AsyncApp,
3606    ) -> Result<()> {
3607        let collaborator = envelope
3608            .payload
3609            .collaborator
3610            .take()
3611            .ok_or_else(|| anyhow!("empty collaborator"))?;
3612
3613        let collaborator = Collaborator::from_proto(collaborator)?;
3614        this.update(&mut cx, |this, cx| {
3615            this.buffer_store.update(cx, |buffer_store, _| {
3616                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3617            });
3618            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3619            this.collaborators
3620                .insert(collaborator.peer_id, collaborator);
3621            cx.notify();
3622        })?;
3623
3624        Ok(())
3625    }
3626
3627    async fn handle_update_project_collaborator(
3628        this: Entity<Self>,
3629        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3630        mut cx: AsyncApp,
3631    ) -> Result<()> {
3632        let old_peer_id = envelope
3633            .payload
3634            .old_peer_id
3635            .ok_or_else(|| anyhow!("missing old peer id"))?;
3636        let new_peer_id = envelope
3637            .payload
3638            .new_peer_id
3639            .ok_or_else(|| anyhow!("missing new peer id"))?;
3640        this.update(&mut cx, |this, cx| {
3641            let collaborator = this
3642                .collaborators
3643                .remove(&old_peer_id)
3644                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3645            let is_host = collaborator.is_host;
3646            this.collaborators.insert(new_peer_id, collaborator);
3647
3648            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3649            this.buffer_store.update(cx, |buffer_store, _| {
3650                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3651            });
3652
3653            if is_host {
3654                this.buffer_store
3655                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3656                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3657                    .unwrap();
3658                cx.emit(Event::HostReshared);
3659            }
3660
3661            cx.emit(Event::CollaboratorUpdated {
3662                old_peer_id,
3663                new_peer_id,
3664            });
3665            cx.notify();
3666            Ok(())
3667        })?
3668    }
3669
3670    async fn handle_remove_collaborator(
3671        this: Entity<Self>,
3672        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3673        mut cx: AsyncApp,
3674    ) -> Result<()> {
3675        this.update(&mut cx, |this, cx| {
3676            let peer_id = envelope
3677                .payload
3678                .peer_id
3679                .ok_or_else(|| anyhow!("invalid peer id"))?;
3680            let replica_id = this
3681                .collaborators
3682                .remove(&peer_id)
3683                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3684                .replica_id;
3685            this.buffer_store.update(cx, |buffer_store, cx| {
3686                buffer_store.forget_shared_buffers_for(&peer_id);
3687                for buffer in buffer_store.buffers() {
3688                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3689                }
3690            });
3691
3692            cx.emit(Event::CollaboratorLeft(peer_id));
3693            cx.notify();
3694            Ok(())
3695        })?
3696    }
3697
3698    async fn handle_update_project(
3699        this: Entity<Self>,
3700        envelope: TypedEnvelope<proto::UpdateProject>,
3701        mut cx: AsyncApp,
3702    ) -> Result<()> {
3703        this.update(&mut cx, |this, cx| {
3704            // Don't handle messages that were sent before the response to us joining the project
3705            if envelope.message_id > this.join_project_response_message_id {
3706                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3707            }
3708            Ok(())
3709        })?
3710    }
3711
3712    async fn handle_toast(
3713        this: Entity<Self>,
3714        envelope: TypedEnvelope<proto::Toast>,
3715        mut cx: AsyncApp,
3716    ) -> Result<()> {
3717        this.update(&mut cx, |_, cx| {
3718            cx.emit(Event::Toast {
3719                notification_id: envelope.payload.notification_id.into(),
3720                message: envelope.payload.message,
3721            });
3722            Ok(())
3723        })?
3724    }
3725
3726    async fn handle_language_server_prompt_request(
3727        this: Entity<Self>,
3728        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3729        mut cx: AsyncApp,
3730    ) -> Result<proto::LanguageServerPromptResponse> {
3731        let (tx, mut rx) = smol::channel::bounded(1);
3732        let actions: Vec<_> = envelope
3733            .payload
3734            .actions
3735            .into_iter()
3736            .map(|action| MessageActionItem {
3737                title: action,
3738                properties: Default::default(),
3739            })
3740            .collect();
3741        this.update(&mut cx, |_, cx| {
3742            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3743                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3744                message: envelope.payload.message,
3745                actions: actions.clone(),
3746                lsp_name: envelope.payload.lsp_name,
3747                response_channel: tx,
3748            }));
3749
3750            anyhow::Ok(())
3751        })??;
3752
3753        // We drop `this` to avoid holding a reference in this future for too
3754        // long.
3755        // If we keep the reference, we might not drop the `Project` early
3756        // enough when closing a window and it will only get releases on the
3757        // next `flush_effects()` call.
3758        drop(this);
3759
3760        let mut rx = pin!(rx);
3761        let answer = rx.next().await;
3762
3763        Ok(LanguageServerPromptResponse {
3764            action_response: answer.and_then(|answer| {
3765                actions
3766                    .iter()
3767                    .position(|action| *action == answer)
3768                    .map(|index| index as u64)
3769            }),
3770        })
3771    }
3772
3773    async fn handle_hide_toast(
3774        this: Entity<Self>,
3775        envelope: TypedEnvelope<proto::HideToast>,
3776        mut cx: AsyncApp,
3777    ) -> Result<()> {
3778        this.update(&mut cx, |_, cx| {
3779            cx.emit(Event::HideToast {
3780                notification_id: envelope.payload.notification_id.into(),
3781            });
3782            Ok(())
3783        })?
3784    }
3785
3786    // Collab sends UpdateWorktree protos as messages
3787    async fn handle_update_worktree(
3788        this: Entity<Self>,
3789        envelope: TypedEnvelope<proto::UpdateWorktree>,
3790        mut cx: AsyncApp,
3791    ) -> Result<()> {
3792        this.update(&mut cx, |this, cx| {
3793            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3794            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3795                worktree.update(cx, |worktree, _| {
3796                    let worktree = worktree.as_remote_mut().unwrap();
3797                    worktree.update_from_remote(envelope.payload);
3798                });
3799            }
3800            Ok(())
3801        })?
3802    }
3803
3804    async fn handle_update_buffer_from_ssh(
3805        this: Entity<Self>,
3806        envelope: TypedEnvelope<proto::UpdateBuffer>,
3807        cx: AsyncApp,
3808    ) -> Result<proto::Ack> {
3809        let buffer_store = this.read_with(&cx, |this, cx| {
3810            if let Some(remote_id) = this.remote_id() {
3811                let mut payload = envelope.payload.clone();
3812                payload.project_id = remote_id;
3813                cx.background_executor()
3814                    .spawn(this.client.request(payload))
3815                    .detach_and_log_err(cx);
3816            }
3817            this.buffer_store.clone()
3818        })?;
3819        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3820    }
3821
3822    async fn handle_update_buffer(
3823        this: Entity<Self>,
3824        envelope: TypedEnvelope<proto::UpdateBuffer>,
3825        cx: AsyncApp,
3826    ) -> Result<proto::Ack> {
3827        let buffer_store = this.read_with(&cx, |this, cx| {
3828            if let Some(ssh) = &this.ssh_client {
3829                let mut payload = envelope.payload.clone();
3830                payload.project_id = SSH_PROJECT_ID;
3831                cx.background_executor()
3832                    .spawn(ssh.read(cx).proto_client().request(payload))
3833                    .detach_and_log_err(cx);
3834            }
3835            this.buffer_store.clone()
3836        })?;
3837        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3838    }
3839
3840    fn retain_remotely_created_models(
3841        &mut self,
3842        cx: &mut Context<Self>,
3843    ) -> RemotelyCreatedModelGuard {
3844        {
3845            let mut remotely_create_models = self.remotely_created_models.lock();
3846            if remotely_create_models.retain_count == 0 {
3847                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3848                remotely_create_models.worktrees =
3849                    self.worktree_store.read(cx).worktrees().collect();
3850            }
3851            remotely_create_models.retain_count += 1;
3852        }
3853        RemotelyCreatedModelGuard {
3854            remote_models: Arc::downgrade(&self.remotely_created_models),
3855        }
3856    }
3857
3858    async fn handle_create_buffer_for_peer(
3859        this: Entity<Self>,
3860        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3861        mut cx: AsyncApp,
3862    ) -> Result<()> {
3863        this.update(&mut cx, |this, cx| {
3864            this.buffer_store.update(cx, |buffer_store, cx| {
3865                buffer_store.handle_create_buffer_for_peer(
3866                    envelope,
3867                    this.replica_id(),
3868                    this.capability(),
3869                    cx,
3870                )
3871            })
3872        })?
3873    }
3874
3875    async fn handle_synchronize_buffers(
3876        this: Entity<Self>,
3877        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3878        mut cx: AsyncApp,
3879    ) -> Result<proto::SynchronizeBuffersResponse> {
3880        let response = this.update(&mut cx, |this, cx| {
3881            let client = this.client.clone();
3882            this.buffer_store.update(cx, |this, cx| {
3883                this.handle_synchronize_buffers(envelope, cx, client)
3884            })
3885        })??;
3886
3887        Ok(response)
3888    }
3889
3890    async fn handle_search_candidate_buffers(
3891        this: Entity<Self>,
3892        envelope: TypedEnvelope<proto::FindSearchCandidates>,
3893        mut cx: AsyncApp,
3894    ) -> Result<proto::FindSearchCandidatesResponse> {
3895        let peer_id = envelope.original_sender_id()?;
3896        let message = envelope.payload;
3897        let query = SearchQuery::from_proto(
3898            message
3899                .query
3900                .ok_or_else(|| anyhow!("missing query field"))?,
3901        )?;
3902        let results = this.update(&mut cx, |this, cx| {
3903            this.find_search_candidate_buffers(&query, message.limit as _, cx)
3904        })?;
3905
3906        let mut response = proto::FindSearchCandidatesResponse {
3907            buffer_ids: Vec::new(),
3908        };
3909
3910        while let Ok(buffer) = results.recv().await {
3911            this.update(&mut cx, |this, cx| {
3912                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3913                response.buffer_ids.push(buffer_id.to_proto());
3914            })?;
3915        }
3916
3917        Ok(response)
3918    }
3919
3920    async fn handle_open_buffer_by_id(
3921        this: Entity<Self>,
3922        envelope: TypedEnvelope<proto::OpenBufferById>,
3923        mut cx: AsyncApp,
3924    ) -> Result<proto::OpenBufferResponse> {
3925        let peer_id = envelope.original_sender_id()?;
3926        let buffer_id = BufferId::new(envelope.payload.id)?;
3927        let buffer = this
3928            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3929            .await?;
3930        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3931    }
3932
3933    async fn handle_open_buffer_by_path(
3934        this: Entity<Self>,
3935        envelope: TypedEnvelope<proto::OpenBufferByPath>,
3936        mut cx: AsyncApp,
3937    ) -> Result<proto::OpenBufferResponse> {
3938        let peer_id = envelope.original_sender_id()?;
3939        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3940        let open_buffer = this.update(&mut cx, |this, cx| {
3941            this.open_buffer(
3942                ProjectPath {
3943                    worktree_id,
3944                    path: PathBuf::from(envelope.payload.path).into(),
3945                },
3946                cx,
3947            )
3948        })?;
3949
3950        let buffer = open_buffer.await?;
3951        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3952    }
3953
3954    async fn handle_open_new_buffer(
3955        this: Entity<Self>,
3956        envelope: TypedEnvelope<proto::OpenNewBuffer>,
3957        mut cx: AsyncApp,
3958    ) -> Result<proto::OpenBufferResponse> {
3959        let buffer = this
3960            .update(&mut cx, |this, cx| this.create_buffer(cx))?
3961            .await?;
3962        let peer_id = envelope.original_sender_id()?;
3963
3964        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3965    }
3966
3967    async fn handle_stage(
3968        this: Entity<Self>,
3969        envelope: TypedEnvelope<proto::Stage>,
3970        mut cx: AsyncApp,
3971    ) -> Result<proto::Ack> {
3972        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3973        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
3974        let repository_handle =
3975            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
3976
3977        let entries = envelope
3978            .payload
3979            .paths
3980            .into_iter()
3981            .map(PathBuf::from)
3982            .map(RepoPath::new)
3983            .collect();
3984        let (err_sender, mut err_receiver) = mpsc::channel(1);
3985        repository_handle
3986            .stage_entries(entries, err_sender)
3987            .context("staging entries")?;
3988        if let Some(error) = err_receiver.next().await {
3989            Err(error.context("error during staging"))
3990        } else {
3991            Ok(proto::Ack {})
3992        }
3993    }
3994
3995    async fn handle_unstage(
3996        this: Entity<Self>,
3997        envelope: TypedEnvelope<proto::Unstage>,
3998        mut cx: AsyncApp,
3999    ) -> Result<proto::Ack> {
4000        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4001        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4002        let repository_handle =
4003            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4004
4005        let entries = envelope
4006            .payload
4007            .paths
4008            .into_iter()
4009            .map(PathBuf::from)
4010            .map(RepoPath::new)
4011            .collect();
4012        let (err_sender, mut err_receiver) = mpsc::channel(1);
4013        repository_handle
4014            .unstage_entries(entries, err_sender)
4015            .context("unstaging entries")?;
4016        if let Some(error) = err_receiver.next().await {
4017            Err(error.context("error during unstaging"))
4018        } else {
4019            Ok(proto::Ack {})
4020        }
4021    }
4022
4023    async fn handle_commit(
4024        this: Entity<Self>,
4025        envelope: TypedEnvelope<proto::Commit>,
4026        mut cx: AsyncApp,
4027    ) -> Result<proto::Ack> {
4028        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4029        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4030        let repository_handle =
4031            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4032
4033        let name = envelope.payload.name.map(SharedString::from);
4034        let email = envelope.payload.email.map(SharedString::from);
4035        let (err_sender, mut err_receiver) = mpsc::channel(1);
4036        cx.update(|cx| {
4037            repository_handle
4038                .commit(name.zip(email), err_sender, cx)
4039                .context("unstaging entries")
4040        })??;
4041        if let Some(error) = err_receiver.next().await {
4042            Err(error.context("error during unstaging"))
4043        } else {
4044            Ok(proto::Ack {})
4045        }
4046    }
4047
4048    async fn handle_open_commit_message_buffer(
4049        this: Entity<Self>,
4050        envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
4051        mut cx: AsyncApp,
4052    ) -> Result<proto::OpenBufferResponse> {
4053        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4054        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4055        let repository_handle =
4056            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4057        let git_repository = match &repository_handle.git_repo {
4058            git::GitRepo::Local(git_repository) => git_repository.clone(),
4059            git::GitRepo::Remote { .. } => {
4060                anyhow::bail!("Cannot handle open commit message buffer for remote git repo")
4061            }
4062        };
4063        let commit_message_file = git_repository.dot_git_dir().join(*COMMIT_MESSAGE);
4064        let fs = this.update(&mut cx, |project, _| project.fs().clone())?;
4065        fs.create_file(
4066            &commit_message_file,
4067            CreateOptions {
4068                overwrite: false,
4069                ignore_if_exists: true,
4070            },
4071        )
4072        .await
4073        .with_context(|| format!("creating commit message file {commit_message_file:?}"))?;
4074
4075        let (worktree, relative_path) = this
4076            .update(&mut cx, |headless_project, cx| {
4077                headless_project
4078                    .worktree_store
4079                    .update(cx, |worktree_store, cx| {
4080                        worktree_store.find_or_create_worktree(&commit_message_file, false, cx)
4081                    })
4082            })?
4083            .await
4084            .with_context(|| {
4085                format!("deriving worktree for commit message file {commit_message_file:?}")
4086            })?;
4087
4088        let buffer = this
4089            .update(&mut cx, |headless_project, cx| {
4090                headless_project
4091                    .buffer_store
4092                    .update(cx, |buffer_store, cx| {
4093                        buffer_store.open_buffer(
4094                            ProjectPath {
4095                                worktree_id: worktree.read(cx).id(),
4096                                path: Arc::from(relative_path),
4097                            },
4098                            cx,
4099                        )
4100                    })
4101            })
4102            .with_context(|| {
4103                format!("opening buffer for commit message file {commit_message_file:?}")
4104            })?
4105            .await?;
4106        let peer_id = envelope.original_sender_id()?;
4107        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4108    }
4109
4110    fn repository_for_request(
4111        this: &Entity<Self>,
4112        worktree_id: WorktreeId,
4113        work_directory_id: ProjectEntryId,
4114        cx: &mut AsyncApp,
4115    ) -> Result<RepositoryHandle> {
4116        this.update(cx, |project, cx| {
4117            let repository_handle = project
4118                .git_state()
4119                .read(cx)
4120                .all_repositories()
4121                .into_iter()
4122                .find(|repository_handle| {
4123                    repository_handle.worktree_id == worktree_id
4124                        && repository_handle.repository_entry.work_directory_id()
4125                            == work_directory_id
4126                })
4127                .context("missing repository handle")?;
4128            anyhow::Ok(repository_handle)
4129        })?
4130    }
4131
4132    fn respond_to_open_buffer_request(
4133        this: Entity<Self>,
4134        buffer: Entity<Buffer>,
4135        peer_id: proto::PeerId,
4136        cx: &mut AsyncApp,
4137    ) -> Result<proto::OpenBufferResponse> {
4138        this.update(cx, |this, cx| {
4139            let is_private = buffer
4140                .read(cx)
4141                .file()
4142                .map(|f| f.is_private())
4143                .unwrap_or_default();
4144            if is_private {
4145                Err(anyhow!(ErrorCode::UnsharedItem))
4146            } else {
4147                Ok(proto::OpenBufferResponse {
4148                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4149                })
4150            }
4151        })?
4152    }
4153
4154    fn create_buffer_for_peer(
4155        &mut self,
4156        buffer: &Entity<Buffer>,
4157        peer_id: proto::PeerId,
4158        cx: &mut App,
4159    ) -> BufferId {
4160        self.buffer_store
4161            .update(cx, |buffer_store, cx| {
4162                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4163            })
4164            .detach_and_log_err(cx);
4165        buffer.read(cx).remote_id()
4166    }
4167
4168    pub fn wait_for_remote_buffer(
4169        &mut self,
4170        id: BufferId,
4171        cx: &mut Context<Self>,
4172    ) -> Task<Result<Entity<Buffer>>> {
4173        self.buffer_store.update(cx, |buffer_store, cx| {
4174            buffer_store.wait_for_remote_buffer(id, cx)
4175        })
4176    }
4177
4178    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4179        let project_id = match self.client_state {
4180            ProjectClientState::Remote {
4181                sharing_has_stopped,
4182                remote_id,
4183                ..
4184            } => {
4185                if sharing_has_stopped {
4186                    return Task::ready(Err(anyhow!(
4187                        "can't synchronize remote buffers on a readonly project"
4188                    )));
4189                } else {
4190                    remote_id
4191                }
4192            }
4193            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4194                return Task::ready(Err(anyhow!(
4195                    "can't synchronize remote buffers on a local project"
4196                )))
4197            }
4198        };
4199
4200        let client = self.client.clone();
4201        cx.spawn(move |this, mut cx| async move {
4202            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4203                this.buffer_store.read(cx).buffer_version_info(cx)
4204            })?;
4205            let response = client
4206                .request(proto::SynchronizeBuffers {
4207                    project_id,
4208                    buffers,
4209                })
4210                .await?;
4211
4212            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4213                response
4214                    .buffers
4215                    .into_iter()
4216                    .map(|buffer| {
4217                        let client = client.clone();
4218                        let buffer_id = match BufferId::new(buffer.id) {
4219                            Ok(id) => id,
4220                            Err(e) => {
4221                                return Task::ready(Err(e));
4222                            }
4223                        };
4224                        let remote_version = language::proto::deserialize_version(&buffer.version);
4225                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4226                            let operations =
4227                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4228                            cx.background_executor().spawn(async move {
4229                                let operations = operations.await;
4230                                for chunk in split_operations(operations) {
4231                                    client
4232                                        .request(proto::UpdateBuffer {
4233                                            project_id,
4234                                            buffer_id: buffer_id.into(),
4235                                            operations: chunk,
4236                                        })
4237                                        .await?;
4238                                }
4239                                anyhow::Ok(())
4240                            })
4241                        } else {
4242                            Task::ready(Ok(()))
4243                        }
4244                    })
4245                    .collect::<Vec<_>>()
4246            })?;
4247
4248            // Any incomplete buffers have open requests waiting. Request that the host sends
4249            // creates these buffers for us again to unblock any waiting futures.
4250            for id in incomplete_buffer_ids {
4251                cx.background_executor()
4252                    .spawn(client.request(proto::OpenBufferById {
4253                        project_id,
4254                        id: id.into(),
4255                    }))
4256                    .detach();
4257            }
4258
4259            futures::future::join_all(send_updates_for_buffers)
4260                .await
4261                .into_iter()
4262                .collect()
4263        })
4264    }
4265
4266    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4267        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4268    }
4269
4270    /// Iterator of all open buffers that have unsaved changes
4271    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4272        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4273            let buf = buf.read(cx);
4274            if buf.is_dirty() {
4275                buf.project_path(cx)
4276            } else {
4277                None
4278            }
4279        })
4280    }
4281
4282    fn set_worktrees_from_proto(
4283        &mut self,
4284        worktrees: Vec<proto::WorktreeMetadata>,
4285        cx: &mut Context<Project>,
4286    ) -> Result<()> {
4287        cx.notify();
4288        self.worktree_store.update(cx, |worktree_store, cx| {
4289            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4290        })
4291    }
4292
4293    fn set_collaborators_from_proto(
4294        &mut self,
4295        messages: Vec<proto::Collaborator>,
4296        cx: &mut Context<Self>,
4297    ) -> Result<()> {
4298        let mut collaborators = HashMap::default();
4299        for message in messages {
4300            let collaborator = Collaborator::from_proto(message)?;
4301            collaborators.insert(collaborator.peer_id, collaborator);
4302        }
4303        for old_peer_id in self.collaborators.keys() {
4304            if !collaborators.contains_key(old_peer_id) {
4305                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4306            }
4307        }
4308        self.collaborators = collaborators;
4309        Ok(())
4310    }
4311
4312    pub fn supplementary_language_servers<'a>(
4313        &'a self,
4314        cx: &'a App,
4315    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4316        self.lsp_store.read(cx).supplementary_language_servers()
4317    }
4318
4319    pub fn language_servers_for_local_buffer<'a>(
4320        &'a self,
4321        buffer: &'a Buffer,
4322        cx: &'a App,
4323    ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4324        self.lsp_store
4325            .read(cx)
4326            .language_servers_for_local_buffer(buffer, cx)
4327    }
4328
4329    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4330        &self.buffer_store
4331    }
4332
4333    pub fn git_state(&self) -> &Entity<GitState> {
4334        &self.git_state
4335    }
4336
4337    pub fn active_repository(&self, cx: &App) -> Option<RepositoryHandle> {
4338        self.git_state.read(cx).active_repository()
4339    }
4340
4341    pub fn all_repositories(&self, cx: &App) -> Vec<RepositoryHandle> {
4342        self.git_state.read(cx).all_repositories()
4343    }
4344}
4345
4346fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4347    code_actions
4348        .iter()
4349        .flat_map(|(kind, enabled)| {
4350            if *enabled {
4351                Some(kind.clone().into())
4352            } else {
4353                None
4354            }
4355        })
4356        .collect()
4357}
4358
4359pub struct PathMatchCandidateSet {
4360    pub snapshot: Snapshot,
4361    pub include_ignored: bool,
4362    pub include_root_name: bool,
4363    pub candidates: Candidates,
4364}
4365
4366pub enum Candidates {
4367    /// Only consider directories.
4368    Directories,
4369    /// Only consider files.
4370    Files,
4371    /// Consider directories and files.
4372    Entries,
4373}
4374
4375impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4376    type Candidates = PathMatchCandidateSetIter<'a>;
4377
4378    fn id(&self) -> usize {
4379        self.snapshot.id().to_usize()
4380    }
4381
4382    fn len(&self) -> usize {
4383        match self.candidates {
4384            Candidates::Files => {
4385                if self.include_ignored {
4386                    self.snapshot.file_count()
4387                } else {
4388                    self.snapshot.visible_file_count()
4389                }
4390            }
4391
4392            Candidates::Directories => {
4393                if self.include_ignored {
4394                    self.snapshot.dir_count()
4395                } else {
4396                    self.snapshot.visible_dir_count()
4397                }
4398            }
4399
4400            Candidates::Entries => {
4401                if self.include_ignored {
4402                    self.snapshot.entry_count()
4403                } else {
4404                    self.snapshot.visible_entry_count()
4405                }
4406            }
4407        }
4408    }
4409
4410    fn prefix(&self) -> Arc<str> {
4411        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4412            self.snapshot.root_name().into()
4413        } else if self.include_root_name {
4414            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4415        } else {
4416            Arc::default()
4417        }
4418    }
4419
4420    fn candidates(&'a self, start: usize) -> Self::Candidates {
4421        PathMatchCandidateSetIter {
4422            traversal: match self.candidates {
4423                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4424                Candidates::Files => self.snapshot.files(self.include_ignored, start),
4425                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4426            },
4427        }
4428    }
4429}
4430
4431pub struct PathMatchCandidateSetIter<'a> {
4432    traversal: Traversal<'a>,
4433}
4434
4435impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4436    type Item = fuzzy::PathMatchCandidate<'a>;
4437
4438    fn next(&mut self) -> Option<Self::Item> {
4439        self.traversal
4440            .next()
4441            .map(|entry| fuzzy::PathMatchCandidate {
4442                is_dir: entry.kind.is_dir(),
4443                path: &entry.path,
4444                char_bag: entry.char_bag,
4445            })
4446    }
4447}
4448
4449impl EventEmitter<Event> for Project {}
4450
4451impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4452    fn from(val: &'a ProjectPath) -> Self {
4453        SettingsLocation {
4454            worktree_id: val.worktree_id,
4455            path: val.path.as_ref(),
4456        }
4457    }
4458}
4459
4460impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4461    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4462        Self {
4463            worktree_id,
4464            path: path.as_ref().into(),
4465        }
4466    }
4467}
4468
4469pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4470    let mut path_components = path.components();
4471    let mut base_components = base.components();
4472    let mut components: Vec<Component> = Vec::new();
4473    loop {
4474        match (path_components.next(), base_components.next()) {
4475            (None, None) => break,
4476            (Some(a), None) => {
4477                components.push(a);
4478                components.extend(path_components.by_ref());
4479                break;
4480            }
4481            (None, _) => components.push(Component::ParentDir),
4482            (Some(a), Some(b)) if components.is_empty() && a == b => (),
4483            (Some(a), Some(Component::CurDir)) => components.push(a),
4484            (Some(a), Some(_)) => {
4485                components.push(Component::ParentDir);
4486                for _ in base_components {
4487                    components.push(Component::ParentDir);
4488                }
4489                components.push(a);
4490                components.extend(path_components.by_ref());
4491                break;
4492            }
4493        }
4494    }
4495    components.iter().map(|c| c.as_os_str()).collect()
4496}
4497
4498fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4499    let mut result = base.to_path_buf();
4500    for component in path.components() {
4501        match component {
4502            Component::ParentDir => {
4503                result.pop();
4504            }
4505            Component::CurDir => (),
4506            _ => result.push(component),
4507        }
4508    }
4509    result
4510}
4511
4512/// ResolvedPath is a path that has been resolved to either a ProjectPath
4513/// or an AbsPath and that *exists*.
4514#[derive(Debug, Clone)]
4515pub enum ResolvedPath {
4516    ProjectPath {
4517        project_path: ProjectPath,
4518        is_dir: bool,
4519    },
4520    AbsPath {
4521        path: PathBuf,
4522        is_dir: bool,
4523    },
4524}
4525
4526impl ResolvedPath {
4527    pub fn abs_path(&self) -> Option<&Path> {
4528        match self {
4529            Self::AbsPath { path, .. } => Some(path.as_path()),
4530            _ => None,
4531        }
4532    }
4533
4534    pub fn project_path(&self) -> Option<&ProjectPath> {
4535        match self {
4536            Self::ProjectPath { project_path, .. } => Some(&project_path),
4537            _ => None,
4538        }
4539    }
4540
4541    pub fn is_file(&self) -> bool {
4542        !self.is_dir()
4543    }
4544
4545    pub fn is_dir(&self) -> bool {
4546        match self {
4547            Self::ProjectPath { is_dir, .. } => *is_dir,
4548            Self::AbsPath { is_dir, .. } => *is_dir,
4549        }
4550    }
4551}
4552
4553impl ProjectItem for Buffer {
4554    fn try_open(
4555        project: &Entity<Project>,
4556        path: &ProjectPath,
4557        cx: &mut App,
4558    ) -> Option<Task<Result<Entity<Self>>>> {
4559        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4560    }
4561
4562    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4563        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4564    }
4565
4566    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4567        File::from_dyn(self.file()).map(|file| ProjectPath {
4568            worktree_id: file.worktree_id(cx),
4569            path: file.path().clone(),
4570        })
4571    }
4572
4573    fn is_dirty(&self) -> bool {
4574        self.is_dirty()
4575    }
4576}
4577
4578impl Completion {
4579    /// A key that can be used to sort completions when displaying
4580    /// them to the user.
4581    pub fn sort_key(&self) -> (usize, &str) {
4582        let kind_key = match self.lsp_completion.kind {
4583            Some(lsp::CompletionItemKind::KEYWORD) => 0,
4584            Some(lsp::CompletionItemKind::VARIABLE) => 1,
4585            _ => 2,
4586        };
4587        (kind_key, &self.label.text[self.label.filter_range.clone()])
4588    }
4589
4590    /// Whether this completion is a snippet.
4591    pub fn is_snippet(&self) -> bool {
4592        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4593    }
4594
4595    /// Returns the corresponding color for this completion.
4596    ///
4597    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4598    pub fn color(&self) -> Option<Hsla> {
4599        match self.lsp_completion.kind {
4600            Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4601            _ => None,
4602        }
4603    }
4604}
4605
4606pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
4607    entries.sort_by(|entry_a, entry_b| {
4608        let entry_a = entry_a.as_ref();
4609        let entry_b = entry_b.as_ref();
4610        compare_paths(
4611            (&entry_a.path, entry_a.is_file()),
4612            (&entry_b.path, entry_b.is_file()),
4613        )
4614    });
4615}
4616
4617fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4618    match level {
4619        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4620        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4621        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4622    }
4623}