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(), false, cx)
1937        })
1938    }
1939
1940    pub fn open_buffer_without_contents(
1941        &mut self,
1942        path: impl Into<ProjectPath>,
1943        cx: &mut Context<Self>,
1944    ) -> Task<Result<Entity<Buffer>>> {
1945        if self.is_disconnected(cx) {
1946            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1947        }
1948
1949        self.buffer_store.update(cx, |buffer_store, cx| {
1950            buffer_store.open_buffer(path.into(), true, cx)
1951        })
1952    }
1953
1954    #[cfg(any(test, feature = "test-support"))]
1955    pub fn open_buffer_with_lsp(
1956        &mut self,
1957        path: impl Into<ProjectPath>,
1958        cx: &mut Context<Self>,
1959    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1960        let buffer = self.open_buffer(path, cx);
1961        let lsp_store = self.lsp_store().clone();
1962        cx.spawn(|_, mut cx| async move {
1963            let buffer = buffer.await?;
1964            let handle = lsp_store.update(&mut cx, |lsp_store, cx| {
1965                lsp_store.register_buffer_with_language_servers(&buffer, cx)
1966            })?;
1967            Ok((buffer, handle))
1968        })
1969    }
1970
1971    pub fn open_unstaged_changes(
1972        &mut self,
1973        buffer: Entity<Buffer>,
1974        cx: &mut Context<Self>,
1975    ) -> Task<Result<Entity<BufferChangeSet>>> {
1976        if self.is_disconnected(cx) {
1977            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1978        }
1979
1980        self.buffer_store.update(cx, |buffer_store, cx| {
1981            buffer_store.open_unstaged_changes(buffer, cx)
1982        })
1983    }
1984
1985    pub fn open_buffer_by_id(
1986        &mut self,
1987        id: BufferId,
1988        cx: &mut Context<Self>,
1989    ) -> Task<Result<Entity<Buffer>>> {
1990        if let Some(buffer) = self.buffer_for_id(id, cx) {
1991            Task::ready(Ok(buffer))
1992        } else if self.is_local() || self.is_via_ssh() {
1993            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1994        } else if let Some(project_id) = self.remote_id() {
1995            let request = self.client.request(proto::OpenBufferById {
1996                project_id,
1997                id: id.into(),
1998            });
1999            cx.spawn(move |this, mut cx| async move {
2000                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2001                this.update(&mut cx, |this, cx| {
2002                    this.wait_for_remote_buffer(buffer_id, cx)
2003                })?
2004                .await
2005            })
2006        } else {
2007            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2008        }
2009    }
2010
2011    pub fn save_buffers(
2012        &self,
2013        buffers: HashSet<Entity<Buffer>>,
2014        cx: &mut Context<Self>,
2015    ) -> Task<Result<()>> {
2016        cx.spawn(move |this, mut cx| async move {
2017            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2018                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
2019                    .ok()
2020            });
2021            try_join_all(save_tasks).await?;
2022            Ok(())
2023        })
2024    }
2025
2026    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2027        self.buffer_store
2028            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2029    }
2030
2031    pub fn save_buffer_as(
2032        &mut self,
2033        buffer: Entity<Buffer>,
2034        path: ProjectPath,
2035        cx: &mut Context<Self>,
2036    ) -> Task<Result<()>> {
2037        self.buffer_store.update(cx, |buffer_store, cx| {
2038            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2039        })
2040    }
2041
2042    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2043        self.buffer_store.read(cx).get_by_path(path, cx)
2044    }
2045
2046    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2047        {
2048            let mut remotely_created_models = self.remotely_created_models.lock();
2049            if remotely_created_models.retain_count > 0 {
2050                remotely_created_models.buffers.push(buffer.clone())
2051            }
2052        }
2053
2054        self.request_buffer_diff_recalculation(buffer, cx);
2055
2056        cx.subscribe(buffer, |this, buffer, event, cx| {
2057            this.on_buffer_event(buffer, event, cx);
2058        })
2059        .detach();
2060
2061        Ok(())
2062    }
2063
2064    pub fn open_image(
2065        &mut self,
2066        path: impl Into<ProjectPath>,
2067        cx: &mut Context<Self>,
2068    ) -> Task<Result<Entity<ImageItem>>> {
2069        if self.is_disconnected(cx) {
2070            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2071        }
2072
2073        self.image_store.update(cx, |image_store, cx| {
2074            image_store.open_image(path.into(), cx)
2075        })
2076    }
2077
2078    async fn send_buffer_ordered_messages(
2079        this: WeakEntity<Self>,
2080        rx: UnboundedReceiver<BufferOrderedMessage>,
2081        mut cx: AsyncApp,
2082    ) -> Result<()> {
2083        const MAX_BATCH_SIZE: usize = 128;
2084
2085        let mut operations_by_buffer_id = HashMap::default();
2086        async fn flush_operations(
2087            this: &WeakEntity<Project>,
2088            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2089            needs_resync_with_host: &mut bool,
2090            is_local: bool,
2091            cx: &mut AsyncApp,
2092        ) -> Result<()> {
2093            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2094                let request = this.update(cx, |this, _| {
2095                    let project_id = this.remote_id()?;
2096                    Some(this.client.request(proto::UpdateBuffer {
2097                        buffer_id: buffer_id.into(),
2098                        project_id,
2099                        operations,
2100                    }))
2101                })?;
2102                if let Some(request) = request {
2103                    if request.await.is_err() && !is_local {
2104                        *needs_resync_with_host = true;
2105                        break;
2106                    }
2107                }
2108            }
2109            Ok(())
2110        }
2111
2112        let mut needs_resync_with_host = false;
2113        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2114
2115        while let Some(changes) = changes.next().await {
2116            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2117
2118            for change in changes {
2119                match change {
2120                    BufferOrderedMessage::Operation {
2121                        buffer_id,
2122                        operation,
2123                    } => {
2124                        if needs_resync_with_host {
2125                            continue;
2126                        }
2127
2128                        operations_by_buffer_id
2129                            .entry(buffer_id)
2130                            .or_insert(Vec::new())
2131                            .push(operation);
2132                    }
2133
2134                    BufferOrderedMessage::Resync => {
2135                        operations_by_buffer_id.clear();
2136                        if this
2137                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2138                            .await
2139                            .is_ok()
2140                        {
2141                            needs_resync_with_host = false;
2142                        }
2143                    }
2144
2145                    BufferOrderedMessage::LanguageServerUpdate {
2146                        language_server_id,
2147                        message,
2148                    } => {
2149                        flush_operations(
2150                            &this,
2151                            &mut operations_by_buffer_id,
2152                            &mut needs_resync_with_host,
2153                            is_local,
2154                            &mut cx,
2155                        )
2156                        .await?;
2157
2158                        this.update(&mut cx, |this, _| {
2159                            if let Some(project_id) = this.remote_id() {
2160                                this.client
2161                                    .send(proto::UpdateLanguageServer {
2162                                        project_id,
2163                                        language_server_id: language_server_id.0 as u64,
2164                                        variant: Some(message),
2165                                    })
2166                                    .log_err();
2167                            }
2168                        })?;
2169                    }
2170                }
2171            }
2172
2173            flush_operations(
2174                &this,
2175                &mut operations_by_buffer_id,
2176                &mut needs_resync_with_host,
2177                is_local,
2178                &mut cx,
2179            )
2180            .await?;
2181        }
2182
2183        Ok(())
2184    }
2185
2186    fn on_buffer_store_event(
2187        &mut self,
2188        _: Entity<BufferStore>,
2189        event: &BufferStoreEvent,
2190        cx: &mut Context<Self>,
2191    ) {
2192        match event {
2193            BufferStoreEvent::BufferAdded(buffer) => {
2194                self.register_buffer(buffer, cx).log_err();
2195            }
2196            BufferStoreEvent::BufferChangedFilePath { .. } => {}
2197            BufferStoreEvent::BufferDropped(buffer_id) => {
2198                if let Some(ref ssh_client) = self.ssh_client {
2199                    ssh_client
2200                        .read(cx)
2201                        .proto_client()
2202                        .send(proto::CloseBuffer {
2203                            project_id: 0,
2204                            buffer_id: buffer_id.to_proto(),
2205                        })
2206                        .log_err();
2207                }
2208            }
2209        }
2210    }
2211
2212    fn on_image_store_event(
2213        &mut self,
2214        _: Entity<ImageStore>,
2215        event: &ImageStoreEvent,
2216        cx: &mut Context<Self>,
2217    ) {
2218        match event {
2219            ImageStoreEvent::ImageAdded(image) => {
2220                cx.subscribe(image, |this, image, event, cx| {
2221                    this.on_image_event(image, event, cx);
2222                })
2223                .detach();
2224            }
2225        }
2226    }
2227
2228    fn on_lsp_store_event(
2229        &mut self,
2230        _: Entity<LspStore>,
2231        event: &LspStoreEvent,
2232        cx: &mut Context<Self>,
2233    ) {
2234        match event {
2235            LspStoreEvent::DiagnosticsUpdated {
2236                language_server_id,
2237                path,
2238            } => cx.emit(Event::DiagnosticsUpdated {
2239                path: path.clone(),
2240                language_server_id: *language_server_id,
2241            }),
2242            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2243                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2244            ),
2245            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2246                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2247            }
2248            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2249                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2250            ),
2251            LspStoreEvent::LanguageDetected {
2252                buffer,
2253                new_language,
2254            } => {
2255                let Some(_) = new_language else {
2256                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2257                    return;
2258                };
2259            }
2260            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2261            LspStoreEvent::LanguageServerPrompt(prompt) => {
2262                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2263            }
2264            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2265                cx.emit(Event::DiskBasedDiagnosticsStarted {
2266                    language_server_id: *language_server_id,
2267                });
2268            }
2269            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2270                cx.emit(Event::DiskBasedDiagnosticsFinished {
2271                    language_server_id: *language_server_id,
2272                });
2273            }
2274            LspStoreEvent::LanguageServerUpdate {
2275                language_server_id,
2276                message,
2277            } => {
2278                if self.is_local() {
2279                    self.enqueue_buffer_ordered_message(
2280                        BufferOrderedMessage::LanguageServerUpdate {
2281                            language_server_id: *language_server_id,
2282                            message: message.clone(),
2283                        },
2284                    )
2285                    .ok();
2286                }
2287            }
2288            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2289                notification_id: "lsp".into(),
2290                message: message.clone(),
2291            }),
2292            LspStoreEvent::SnippetEdit {
2293                buffer_id,
2294                edits,
2295                most_recent_edit,
2296            } => {
2297                if most_recent_edit.replica_id == self.replica_id() {
2298                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2299                }
2300            }
2301        }
2302    }
2303
2304    fn on_ssh_event(
2305        &mut self,
2306        _: Entity<SshRemoteClient>,
2307        event: &remote::SshRemoteEvent,
2308        cx: &mut Context<Self>,
2309    ) {
2310        match event {
2311            remote::SshRemoteEvent::Disconnected => {
2312                // if self.is_via_ssh() {
2313                // self.collaborators.clear();
2314                self.worktree_store.update(cx, |store, cx| {
2315                    store.disconnected_from_host(cx);
2316                });
2317                self.buffer_store.update(cx, |buffer_store, cx| {
2318                    buffer_store.disconnected_from_host(cx)
2319                });
2320                self.lsp_store.update(cx, |lsp_store, _cx| {
2321                    lsp_store.disconnected_from_ssh_remote()
2322                });
2323                cx.emit(Event::DisconnectedFromSshRemote);
2324            }
2325        }
2326    }
2327
2328    fn on_settings_observer_event(
2329        &mut self,
2330        _: Entity<SettingsObserver>,
2331        event: &SettingsObserverEvent,
2332        cx: &mut Context<Self>,
2333    ) {
2334        match event {
2335            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2336                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2337                    let message =
2338                        format!("Failed to set local settings in {:?}:\n{}", path, message);
2339                    cx.emit(Event::Toast {
2340                        notification_id: "local-settings".into(),
2341                        message,
2342                    });
2343                }
2344                Ok(_) => cx.emit(Event::HideToast {
2345                    notification_id: "local-settings".into(),
2346                }),
2347                Err(_) => {}
2348            },
2349        }
2350    }
2351
2352    fn on_worktree_store_event(
2353        &mut self,
2354        _: Entity<WorktreeStore>,
2355        event: &WorktreeStoreEvent,
2356        cx: &mut Context<Self>,
2357    ) {
2358        match event {
2359            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2360                self.on_worktree_added(worktree, cx);
2361                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2362            }
2363            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2364                cx.emit(Event::WorktreeRemoved(*id));
2365            }
2366            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2367                self.on_worktree_released(*id, cx);
2368            }
2369            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2370            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2371            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2372                self.client()
2373                    .telemetry()
2374                    .report_discovered_project_events(*worktree_id, changes);
2375                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2376            }
2377            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id) => {
2378                cx.emit(Event::WorktreeUpdatedGitRepositories(*worktree_id))
2379            }
2380            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2381                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2382            }
2383        }
2384    }
2385
2386    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
2387        {
2388            let mut remotely_created_models = self.remotely_created_models.lock();
2389            if remotely_created_models.retain_count > 0 {
2390                remotely_created_models.worktrees.push(worktree.clone())
2391            }
2392        }
2393        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2394        cx.notify();
2395    }
2396
2397    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2398        if let Some(ssh) = &self.ssh_client {
2399            ssh.read(cx)
2400                .proto_client()
2401                .send(proto::RemoveWorktree {
2402                    worktree_id: id_to_remove.to_proto(),
2403                })
2404                .log_err();
2405        }
2406
2407        cx.notify();
2408    }
2409
2410    fn on_buffer_event(
2411        &mut self,
2412        buffer: Entity<Buffer>,
2413        event: &BufferEvent,
2414        cx: &mut Context<Self>,
2415    ) -> Option<()> {
2416        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2417            self.request_buffer_diff_recalculation(&buffer, cx);
2418        }
2419
2420        let buffer_id = buffer.read(cx).remote_id();
2421        match event {
2422            BufferEvent::ReloadNeeded => {
2423                if !self.is_via_collab() {
2424                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2425                        .detach_and_log_err(cx);
2426                }
2427            }
2428            BufferEvent::Operation {
2429                operation,
2430                is_local: true,
2431            } => {
2432                let operation = language::proto::serialize_operation(operation);
2433
2434                if let Some(ssh) = &self.ssh_client {
2435                    ssh.read(cx)
2436                        .proto_client()
2437                        .send(proto::UpdateBuffer {
2438                            project_id: 0,
2439                            buffer_id: buffer_id.to_proto(),
2440                            operations: vec![operation.clone()],
2441                        })
2442                        .ok();
2443                }
2444
2445                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2446                    buffer_id,
2447                    operation,
2448                })
2449                .ok();
2450            }
2451
2452            _ => {}
2453        }
2454
2455        None
2456    }
2457
2458    fn on_image_event(
2459        &mut self,
2460        image: Entity<ImageItem>,
2461        event: &ImageItemEvent,
2462        cx: &mut Context<Self>,
2463    ) -> Option<()> {
2464        match event {
2465            ImageItemEvent::ReloadNeeded => {
2466                if !self.is_via_collab() {
2467                    self.reload_images([image.clone()].into_iter().collect(), cx)
2468                        .detach_and_log_err(cx);
2469                }
2470            }
2471            _ => {}
2472        }
2473
2474        None
2475    }
2476
2477    fn request_buffer_diff_recalculation(
2478        &mut self,
2479        buffer: &Entity<Buffer>,
2480        cx: &mut Context<Self>,
2481    ) {
2482        self.buffers_needing_diff.insert(buffer.downgrade());
2483        let first_insertion = self.buffers_needing_diff.len() == 1;
2484
2485        let settings = ProjectSettings::get_global(cx);
2486        let delay = if let Some(delay) = settings.git.gutter_debounce {
2487            delay
2488        } else {
2489            if first_insertion {
2490                let this = cx.weak_entity();
2491                cx.defer(move |cx| {
2492                    if let Some(this) = this.upgrade() {
2493                        this.update(cx, |this, cx| {
2494                            this.recalculate_buffer_diffs(cx).detach();
2495                        });
2496                    }
2497                });
2498            }
2499            return;
2500        };
2501
2502        const MIN_DELAY: u64 = 50;
2503        let delay = delay.max(MIN_DELAY);
2504        let duration = Duration::from_millis(delay);
2505
2506        self.git_diff_debouncer
2507            .fire_new(duration, cx, move |this, cx| {
2508                this.recalculate_buffer_diffs(cx)
2509            });
2510    }
2511
2512    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2513        cx.spawn(move |this, mut cx| async move {
2514            loop {
2515                let task = this
2516                    .update(&mut cx, |this, cx| {
2517                        let buffers = this
2518                            .buffers_needing_diff
2519                            .drain()
2520                            .filter_map(|buffer| buffer.upgrade())
2521                            .collect::<Vec<_>>();
2522                        if buffers.is_empty() {
2523                            None
2524                        } else {
2525                            Some(this.buffer_store.update(cx, |buffer_store, cx| {
2526                                buffer_store.recalculate_buffer_diffs(buffers, cx)
2527                            }))
2528                        }
2529                    })
2530                    .ok()
2531                    .flatten();
2532
2533                if let Some(task) = task {
2534                    task.await;
2535                } else {
2536                    break;
2537                }
2538            }
2539        })
2540    }
2541
2542    pub fn set_language_for_buffer(
2543        &mut self,
2544        buffer: &Entity<Buffer>,
2545        new_language: Arc<Language>,
2546        cx: &mut Context<Self>,
2547    ) {
2548        self.lsp_store.update(cx, |lsp_store, cx| {
2549            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2550        })
2551    }
2552
2553    pub fn restart_language_servers_for_buffers(
2554        &mut self,
2555        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2556        cx: &mut Context<Self>,
2557    ) {
2558        self.lsp_store.update(cx, |lsp_store, cx| {
2559            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2560        })
2561    }
2562
2563    pub fn cancel_language_server_work_for_buffers(
2564        &mut self,
2565        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2566        cx: &mut Context<Self>,
2567    ) {
2568        self.lsp_store.update(cx, |lsp_store, cx| {
2569            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2570        })
2571    }
2572
2573    pub fn cancel_language_server_work(
2574        &mut self,
2575        server_id: LanguageServerId,
2576        token_to_cancel: Option<String>,
2577        cx: &mut Context<Self>,
2578    ) {
2579        self.lsp_store.update(cx, |lsp_store, cx| {
2580            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2581        })
2582    }
2583
2584    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2585        self.buffer_ordered_messages_tx
2586            .unbounded_send(message)
2587            .map_err(|e| anyhow!(e))
2588    }
2589
2590    pub fn available_toolchains(
2591        &self,
2592        worktree_id: WorktreeId,
2593        language_name: LanguageName,
2594        cx: &App,
2595    ) -> Task<Option<ToolchainList>> {
2596        if let Some(toolchain_store) = self.toolchain_store.clone() {
2597            cx.spawn(|cx| async move {
2598                cx.update(|cx| {
2599                    toolchain_store
2600                        .read(cx)
2601                        .list_toolchains(worktree_id, language_name, cx)
2602                })
2603                .ok()?
2604                .await
2605            })
2606        } else {
2607            Task::ready(None)
2608        }
2609    }
2610
2611    pub async fn toolchain_term(
2612        languages: Arc<LanguageRegistry>,
2613        language_name: LanguageName,
2614    ) -> Option<SharedString> {
2615        languages
2616            .language_for_name(language_name.as_ref())
2617            .await
2618            .ok()?
2619            .toolchain_lister()
2620            .map(|lister| lister.term())
2621    }
2622
2623    pub fn activate_toolchain(
2624        &self,
2625        worktree_id: WorktreeId,
2626        toolchain: Toolchain,
2627        cx: &mut App,
2628    ) -> Task<Option<()>> {
2629        let Some(toolchain_store) = self.toolchain_store.clone() else {
2630            return Task::ready(None);
2631        };
2632        toolchain_store.update(cx, |this, cx| {
2633            this.activate_toolchain(worktree_id, toolchain, cx)
2634        })
2635    }
2636    pub fn active_toolchain(
2637        &self,
2638        worktree_id: WorktreeId,
2639        language_name: LanguageName,
2640        cx: &App,
2641    ) -> Task<Option<Toolchain>> {
2642        let Some(toolchain_store) = self.toolchain_store.clone() else {
2643            return Task::ready(None);
2644        };
2645        toolchain_store
2646            .read(cx)
2647            .active_toolchain(worktree_id, language_name, cx)
2648    }
2649    pub fn language_server_statuses<'a>(
2650        &'a self,
2651        cx: &'a App,
2652    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2653        self.lsp_store.read(cx).language_server_statuses()
2654    }
2655
2656    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
2657        self.lsp_store.read(cx).last_formatting_failure()
2658    }
2659
2660    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
2661        self.lsp_store
2662            .update(cx, |store, _| store.reset_last_formatting_failure());
2663    }
2664
2665    pub fn reload_buffers(
2666        &self,
2667        buffers: HashSet<Entity<Buffer>>,
2668        push_to_history: bool,
2669        cx: &mut Context<Self>,
2670    ) -> Task<Result<ProjectTransaction>> {
2671        self.buffer_store.update(cx, |buffer_store, cx| {
2672            buffer_store.reload_buffers(buffers, push_to_history, cx)
2673        })
2674    }
2675
2676    pub fn reload_images(
2677        &self,
2678        images: HashSet<Entity<ImageItem>>,
2679        cx: &mut Context<Self>,
2680    ) -> Task<Result<()>> {
2681        self.image_store
2682            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
2683    }
2684
2685    pub fn format(
2686        &mut self,
2687        buffers: HashSet<Entity<Buffer>>,
2688        target: LspFormatTarget,
2689        push_to_history: bool,
2690        trigger: lsp_store::FormatTrigger,
2691        cx: &mut Context<Project>,
2692    ) -> Task<anyhow::Result<ProjectTransaction>> {
2693        self.lsp_store.update(cx, |lsp_store, cx| {
2694            lsp_store.format(buffers, target, push_to_history, trigger, cx)
2695        })
2696    }
2697
2698    #[inline(never)]
2699    fn definition_impl(
2700        &mut self,
2701        buffer: &Entity<Buffer>,
2702        position: PointUtf16,
2703        cx: &mut Context<Self>,
2704    ) -> Task<Result<Vec<LocationLink>>> {
2705        self.request_lsp(
2706            buffer.clone(),
2707            LanguageServerToQuery::Primary,
2708            GetDefinition { position },
2709            cx,
2710        )
2711    }
2712    pub fn definition<T: ToPointUtf16>(
2713        &mut self,
2714        buffer: &Entity<Buffer>,
2715        position: T,
2716        cx: &mut Context<Self>,
2717    ) -> Task<Result<Vec<LocationLink>>> {
2718        let position = position.to_point_utf16(buffer.read(cx));
2719        self.definition_impl(buffer, position, cx)
2720    }
2721
2722    fn declaration_impl(
2723        &mut self,
2724        buffer: &Entity<Buffer>,
2725        position: PointUtf16,
2726        cx: &mut Context<Self>,
2727    ) -> Task<Result<Vec<LocationLink>>> {
2728        self.request_lsp(
2729            buffer.clone(),
2730            LanguageServerToQuery::Primary,
2731            GetDeclaration { position },
2732            cx,
2733        )
2734    }
2735
2736    pub fn declaration<T: ToPointUtf16>(
2737        &mut self,
2738        buffer: &Entity<Buffer>,
2739        position: T,
2740        cx: &mut Context<Self>,
2741    ) -> Task<Result<Vec<LocationLink>>> {
2742        let position = position.to_point_utf16(buffer.read(cx));
2743        self.declaration_impl(buffer, position, cx)
2744    }
2745
2746    fn type_definition_impl(
2747        &mut self,
2748        buffer: &Entity<Buffer>,
2749        position: PointUtf16,
2750        cx: &mut Context<Self>,
2751    ) -> Task<Result<Vec<LocationLink>>> {
2752        self.request_lsp(
2753            buffer.clone(),
2754            LanguageServerToQuery::Primary,
2755            GetTypeDefinition { position },
2756            cx,
2757        )
2758    }
2759
2760    pub fn type_definition<T: ToPointUtf16>(
2761        &mut self,
2762        buffer: &Entity<Buffer>,
2763        position: T,
2764        cx: &mut Context<Self>,
2765    ) -> Task<Result<Vec<LocationLink>>> {
2766        let position = position.to_point_utf16(buffer.read(cx));
2767        self.type_definition_impl(buffer, position, cx)
2768    }
2769
2770    pub fn implementation<T: ToPointUtf16>(
2771        &mut self,
2772        buffer: &Entity<Buffer>,
2773        position: T,
2774        cx: &mut Context<Self>,
2775    ) -> Task<Result<Vec<LocationLink>>> {
2776        let position = position.to_point_utf16(buffer.read(cx));
2777        self.request_lsp(
2778            buffer.clone(),
2779            LanguageServerToQuery::Primary,
2780            GetImplementation { position },
2781            cx,
2782        )
2783    }
2784
2785    pub fn references<T: ToPointUtf16>(
2786        &mut self,
2787        buffer: &Entity<Buffer>,
2788        position: T,
2789        cx: &mut Context<Self>,
2790    ) -> Task<Result<Vec<Location>>> {
2791        let position = position.to_point_utf16(buffer.read(cx));
2792        self.request_lsp(
2793            buffer.clone(),
2794            LanguageServerToQuery::Primary,
2795            GetReferences { position },
2796            cx,
2797        )
2798    }
2799
2800    fn document_highlights_impl(
2801        &mut self,
2802        buffer: &Entity<Buffer>,
2803        position: PointUtf16,
2804        cx: &mut Context<Self>,
2805    ) -> Task<Result<Vec<DocumentHighlight>>> {
2806        self.request_lsp(
2807            buffer.clone(),
2808            LanguageServerToQuery::Primary,
2809            GetDocumentHighlights { position },
2810            cx,
2811        )
2812    }
2813
2814    pub fn document_highlights<T: ToPointUtf16>(
2815        &mut self,
2816        buffer: &Entity<Buffer>,
2817        position: T,
2818        cx: &mut Context<Self>,
2819    ) -> Task<Result<Vec<DocumentHighlight>>> {
2820        let position = position.to_point_utf16(buffer.read(cx));
2821        self.document_highlights_impl(buffer, position, cx)
2822    }
2823
2824    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
2825        self.lsp_store
2826            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2827    }
2828
2829    pub fn open_buffer_for_symbol(
2830        &mut self,
2831        symbol: &Symbol,
2832        cx: &mut Context<Self>,
2833    ) -> Task<Result<Entity<Buffer>>> {
2834        self.lsp_store.update(cx, |lsp_store, cx| {
2835            lsp_store.open_buffer_for_symbol(symbol, cx)
2836        })
2837    }
2838
2839    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2840        let guard = self.retain_remotely_created_models(cx);
2841        let Some(ssh_client) = self.ssh_client.as_ref() else {
2842            return Task::ready(Err(anyhow!("not an ssh project")));
2843        };
2844
2845        let proto_client = ssh_client.read(cx).proto_client();
2846
2847        cx.spawn(|this, mut cx| async move {
2848            let buffer = proto_client
2849                .request(proto::OpenServerSettings {
2850                    project_id: SSH_PROJECT_ID,
2851                })
2852                .await?;
2853
2854            let buffer = this
2855                .update(&mut cx, |this, cx| {
2856                    anyhow::Ok(this.wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx))
2857                })??
2858                .await;
2859
2860            drop(guard);
2861            buffer
2862        })
2863    }
2864
2865    pub fn open_local_buffer_via_lsp(
2866        &mut self,
2867        abs_path: lsp::Url,
2868        language_server_id: LanguageServerId,
2869        language_server_name: LanguageServerName,
2870        cx: &mut Context<Self>,
2871    ) -> Task<Result<Entity<Buffer>>> {
2872        self.lsp_store.update(cx, |lsp_store, cx| {
2873            lsp_store.open_local_buffer_via_lsp(
2874                abs_path,
2875                language_server_id,
2876                language_server_name,
2877                cx,
2878            )
2879        })
2880    }
2881
2882    pub fn signature_help<T: ToPointUtf16>(
2883        &self,
2884        buffer: &Entity<Buffer>,
2885        position: T,
2886        cx: &mut Context<Self>,
2887    ) -> Task<Vec<SignatureHelp>> {
2888        self.lsp_store.update(cx, |lsp_store, cx| {
2889            lsp_store.signature_help(buffer, position, cx)
2890        })
2891    }
2892
2893    pub fn hover<T: ToPointUtf16>(
2894        &self,
2895        buffer: &Entity<Buffer>,
2896        position: T,
2897        cx: &mut Context<Self>,
2898    ) -> Task<Vec<Hover>> {
2899        let position = position.to_point_utf16(buffer.read(cx));
2900        self.lsp_store
2901            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2902    }
2903
2904    pub fn linked_edit(
2905        &self,
2906        buffer: &Entity<Buffer>,
2907        position: Anchor,
2908        cx: &mut Context<Self>,
2909    ) -> Task<Result<Vec<Range<Anchor>>>> {
2910        self.lsp_store.update(cx, |lsp_store, cx| {
2911            lsp_store.linked_edit(buffer, position, cx)
2912        })
2913    }
2914
2915    pub fn completions<T: ToOffset + ToPointUtf16>(
2916        &self,
2917        buffer: &Entity<Buffer>,
2918        position: T,
2919        context: CompletionContext,
2920        cx: &mut Context<Self>,
2921    ) -> Task<Result<Vec<Completion>>> {
2922        let position = position.to_point_utf16(buffer.read(cx));
2923        self.lsp_store.update(cx, |lsp_store, cx| {
2924            lsp_store.completions(buffer, position, context, cx)
2925        })
2926    }
2927
2928    pub fn code_actions<T: Clone + ToOffset>(
2929        &mut self,
2930        buffer_handle: &Entity<Buffer>,
2931        range: Range<T>,
2932        kinds: Option<Vec<CodeActionKind>>,
2933        cx: &mut Context<Self>,
2934    ) -> Task<Result<Vec<CodeAction>>> {
2935        let buffer = buffer_handle.read(cx);
2936        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2937        self.lsp_store.update(cx, |lsp_store, cx| {
2938            lsp_store.code_actions(buffer_handle, range, kinds, cx)
2939        })
2940    }
2941
2942    pub fn apply_code_action(
2943        &self,
2944        buffer_handle: Entity<Buffer>,
2945        action: CodeAction,
2946        push_to_history: bool,
2947        cx: &mut Context<Self>,
2948    ) -> Task<Result<ProjectTransaction>> {
2949        self.lsp_store.update(cx, |lsp_store, cx| {
2950            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2951        })
2952    }
2953
2954    fn prepare_rename_impl(
2955        &mut self,
2956        buffer: Entity<Buffer>,
2957        position: PointUtf16,
2958        cx: &mut Context<Self>,
2959    ) -> Task<Result<PrepareRenameResponse>> {
2960        self.request_lsp(
2961            buffer,
2962            LanguageServerToQuery::Primary,
2963            PrepareRename { position },
2964            cx,
2965        )
2966    }
2967    pub fn prepare_rename<T: ToPointUtf16>(
2968        &mut self,
2969        buffer: Entity<Buffer>,
2970        position: T,
2971        cx: &mut Context<Self>,
2972    ) -> Task<Result<PrepareRenameResponse>> {
2973        let position = position.to_point_utf16(buffer.read(cx));
2974        self.prepare_rename_impl(buffer, position, cx)
2975    }
2976
2977    pub fn perform_rename<T: ToPointUtf16>(
2978        &mut self,
2979        buffer: Entity<Buffer>,
2980        position: T,
2981        new_name: String,
2982        cx: &mut Context<Self>,
2983    ) -> Task<Result<ProjectTransaction>> {
2984        let push_to_history = true;
2985        let position = position.to_point_utf16(buffer.read(cx));
2986        self.request_lsp(
2987            buffer,
2988            LanguageServerToQuery::Primary,
2989            PerformRename {
2990                position,
2991                new_name,
2992                push_to_history,
2993            },
2994            cx,
2995        )
2996    }
2997
2998    pub fn on_type_format<T: ToPointUtf16>(
2999        &mut self,
3000        buffer: Entity<Buffer>,
3001        position: T,
3002        trigger: String,
3003        push_to_history: bool,
3004        cx: &mut Context<Self>,
3005    ) -> Task<Result<Option<Transaction>>> {
3006        self.lsp_store.update(cx, |lsp_store, cx| {
3007            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3008        })
3009    }
3010
3011    pub fn inlay_hints<T: ToOffset>(
3012        &mut self,
3013        buffer_handle: Entity<Buffer>,
3014        range: Range<T>,
3015        cx: &mut Context<Self>,
3016    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3017        let buffer = buffer_handle.read(cx);
3018        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3019        self.lsp_store.update(cx, |lsp_store, cx| {
3020            lsp_store.inlay_hints(buffer_handle, range, cx)
3021        })
3022    }
3023
3024    pub fn resolve_inlay_hint(
3025        &self,
3026        hint: InlayHint,
3027        buffer_handle: Entity<Buffer>,
3028        server_id: LanguageServerId,
3029        cx: &mut Context<Self>,
3030    ) -> Task<anyhow::Result<InlayHint>> {
3031        self.lsp_store.update(cx, |lsp_store, cx| {
3032            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3033        })
3034    }
3035
3036    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3037        let (result_tx, result_rx) = smol::channel::unbounded();
3038
3039        let matching_buffers_rx = if query.is_opened_only() {
3040            self.sort_search_candidates(&query, cx)
3041        } else {
3042            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3043        };
3044
3045        cx.spawn(|_, cx| async move {
3046            let mut range_count = 0;
3047            let mut buffer_count = 0;
3048            let mut limit_reached = false;
3049            let query = Arc::new(query);
3050            let mut chunks = matching_buffers_rx.ready_chunks(64);
3051
3052            // Now that we know what paths match the query, we will load at most
3053            // 64 buffers at a time to avoid overwhelming the main thread. For each
3054            // opened buffer, we will spawn a background task that retrieves all the
3055            // ranges in the buffer matched by the query.
3056            let mut chunks = pin!(chunks);
3057            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3058                let mut chunk_results = Vec::new();
3059                for buffer in matching_buffer_chunk {
3060                    let buffer = buffer.clone();
3061                    let query = query.clone();
3062                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3063                    chunk_results.push(cx.background_executor().spawn(async move {
3064                        let ranges = query
3065                            .search(&snapshot, None)
3066                            .await
3067                            .iter()
3068                            .map(|range| {
3069                                snapshot.anchor_before(range.start)
3070                                    ..snapshot.anchor_after(range.end)
3071                            })
3072                            .collect::<Vec<_>>();
3073                        anyhow::Ok((buffer, ranges))
3074                    }));
3075                }
3076
3077                let chunk_results = futures::future::join_all(chunk_results).await;
3078                for result in chunk_results {
3079                    if let Some((buffer, ranges)) = result.log_err() {
3080                        range_count += ranges.len();
3081                        buffer_count += 1;
3082                        result_tx
3083                            .send(SearchResult::Buffer { buffer, ranges })
3084                            .await?;
3085                        if buffer_count > MAX_SEARCH_RESULT_FILES
3086                            || range_count > MAX_SEARCH_RESULT_RANGES
3087                        {
3088                            limit_reached = true;
3089                            break 'outer;
3090                        }
3091                    }
3092                }
3093            }
3094
3095            if limit_reached {
3096                result_tx.send(SearchResult::LimitReached).await?;
3097            }
3098
3099            anyhow::Ok(())
3100        })
3101        .detach();
3102
3103        result_rx
3104    }
3105
3106    fn find_search_candidate_buffers(
3107        &mut self,
3108        query: &SearchQuery,
3109        limit: usize,
3110        cx: &mut Context<Project>,
3111    ) -> Receiver<Entity<Buffer>> {
3112        if self.is_local() {
3113            let fs = self.fs.clone();
3114            self.buffer_store.update(cx, |buffer_store, cx| {
3115                buffer_store.find_search_candidates(query, limit, fs, cx)
3116            })
3117        } else {
3118            self.find_search_candidates_remote(query, limit, cx)
3119        }
3120    }
3121
3122    fn sort_search_candidates(
3123        &mut self,
3124        search_query: &SearchQuery,
3125        cx: &mut Context<Project>,
3126    ) -> Receiver<Entity<Buffer>> {
3127        let worktree_store = self.worktree_store.read(cx);
3128        let mut buffers = search_query
3129            .buffers()
3130            .into_iter()
3131            .flatten()
3132            .filter(|buffer| {
3133                let b = buffer.read(cx);
3134                if let Some(file) = b.file() {
3135                    if !search_query.file_matches(file.path()) {
3136                        return false;
3137                    }
3138                    if let Some(entry) = b
3139                        .entry_id(cx)
3140                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3141                    {
3142                        if entry.is_ignored && !search_query.include_ignored() {
3143                            return false;
3144                        }
3145                    }
3146                }
3147                true
3148            })
3149            .collect::<Vec<_>>();
3150        let (tx, rx) = smol::channel::unbounded();
3151        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3152            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3153            (None, Some(_)) => std::cmp::Ordering::Less,
3154            (Some(_), None) => std::cmp::Ordering::Greater,
3155            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3156        });
3157        for buffer in buffers {
3158            tx.send_blocking(buffer.clone()).unwrap()
3159        }
3160
3161        rx
3162    }
3163
3164    fn find_search_candidates_remote(
3165        &mut self,
3166        query: &SearchQuery,
3167        limit: usize,
3168        cx: &mut Context<Project>,
3169    ) -> Receiver<Entity<Buffer>> {
3170        let (tx, rx) = smol::channel::unbounded();
3171
3172        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3173            (ssh_client.read(cx).proto_client(), 0)
3174        } else if let Some(remote_id) = self.remote_id() {
3175            (self.client.clone().into(), remote_id)
3176        } else {
3177            return rx;
3178        };
3179
3180        let request = client.request(proto::FindSearchCandidates {
3181            project_id: remote_id,
3182            query: Some(query.to_proto()),
3183            limit: limit as _,
3184        });
3185        let guard = self.retain_remotely_created_models(cx);
3186
3187        cx.spawn(move |this, mut cx| async move {
3188            let response = request.await?;
3189            for buffer_id in response.buffer_ids {
3190                let buffer_id = BufferId::new(buffer_id)?;
3191                let buffer = this
3192                    .update(&mut cx, |this, cx| {
3193                        this.wait_for_remote_buffer(buffer_id, cx)
3194                    })?
3195                    .await?;
3196                let _ = tx.send(buffer).await;
3197            }
3198
3199            drop(guard);
3200            anyhow::Ok(())
3201        })
3202        .detach_and_log_err(cx);
3203        rx
3204    }
3205
3206    pub fn request_lsp<R: LspCommand>(
3207        &mut self,
3208        buffer_handle: Entity<Buffer>,
3209        server: LanguageServerToQuery,
3210        request: R,
3211        cx: &mut Context<Self>,
3212    ) -> Task<Result<R::Response>>
3213    where
3214        <R::LspRequest as lsp::request::Request>::Result: Send,
3215        <R::LspRequest as lsp::request::Request>::Params: Send,
3216    {
3217        let guard = self.retain_remotely_created_models(cx);
3218        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3219            lsp_store.request_lsp(buffer_handle, server, request, cx)
3220        });
3221        cx.spawn(|_, _| async move {
3222            let result = task.await;
3223            drop(guard);
3224            result
3225        })
3226    }
3227
3228    /// Move a worktree to a new position in the worktree order.
3229    ///
3230    /// The worktree will moved to the opposite side of the destination worktree.
3231    ///
3232    /// # Example
3233    ///
3234    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3235    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3236    ///
3237    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3238    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3239    ///
3240    /// # Errors
3241    ///
3242    /// An error will be returned if the worktree or destination worktree are not found.
3243    pub fn move_worktree(
3244        &mut self,
3245        source: WorktreeId,
3246        destination: WorktreeId,
3247        cx: &mut Context<'_, Self>,
3248    ) -> Result<()> {
3249        self.worktree_store.update(cx, |worktree_store, cx| {
3250            worktree_store.move_worktree(source, destination, cx)
3251        })
3252    }
3253
3254    pub fn find_or_create_worktree(
3255        &mut self,
3256        abs_path: impl AsRef<Path>,
3257        visible: bool,
3258        cx: &mut Context<Self>,
3259    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3260        self.worktree_store.update(cx, |worktree_store, cx| {
3261            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3262        })
3263    }
3264
3265    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3266        self.worktree_store.read_with(cx, |worktree_store, cx| {
3267            worktree_store.find_worktree(abs_path, cx)
3268        })
3269    }
3270
3271    pub fn is_shared(&self) -> bool {
3272        match &self.client_state {
3273            ProjectClientState::Shared { .. } => true,
3274            ProjectClientState::Local => false,
3275            ProjectClientState::Remote { .. } => true,
3276        }
3277    }
3278
3279    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3280    pub fn resolve_path_in_buffer(
3281        &self,
3282        path: &str,
3283        buffer: &Entity<Buffer>,
3284        cx: &mut Context<Self>,
3285    ) -> Task<Option<ResolvedPath>> {
3286        let path_buf = PathBuf::from(path);
3287        if path_buf.is_absolute() || path.starts_with("~") {
3288            self.resolve_abs_path(path, cx)
3289        } else {
3290            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3291        }
3292    }
3293
3294    pub fn resolve_abs_file_path(
3295        &self,
3296        path: &str,
3297        cx: &mut Context<Self>,
3298    ) -> Task<Option<ResolvedPath>> {
3299        let resolve_task = self.resolve_abs_path(path, cx);
3300        cx.background_executor().spawn(async move {
3301            let resolved_path = resolve_task.await;
3302            resolved_path.filter(|path| path.is_file())
3303        })
3304    }
3305
3306    pub fn resolve_abs_path(
3307        &self,
3308        path: &str,
3309        cx: &mut Context<Self>,
3310    ) -> Task<Option<ResolvedPath>> {
3311        if self.is_local() {
3312            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3313            let fs = self.fs.clone();
3314            cx.background_executor().spawn(async move {
3315                let path = expanded.as_path();
3316                let metadata = fs.metadata(path).await.ok().flatten();
3317
3318                metadata.map(|metadata| ResolvedPath::AbsPath {
3319                    path: expanded,
3320                    is_dir: metadata.is_dir,
3321                })
3322            })
3323        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3324            let request = ssh_client
3325                .read(cx)
3326                .proto_client()
3327                .request(proto::GetPathMetadata {
3328                    project_id: SSH_PROJECT_ID,
3329                    path: path.to_string(),
3330                });
3331            cx.background_executor().spawn(async move {
3332                let response = request.await.log_err()?;
3333                if response.exists {
3334                    Some(ResolvedPath::AbsPath {
3335                        path: PathBuf::from(response.path),
3336                        is_dir: response.is_dir,
3337                    })
3338                } else {
3339                    None
3340                }
3341            })
3342        } else {
3343            return Task::ready(None);
3344        }
3345    }
3346
3347    fn resolve_path_in_worktrees(
3348        &self,
3349        path: PathBuf,
3350        buffer: &Entity<Buffer>,
3351        cx: &mut Context<Self>,
3352    ) -> Task<Option<ResolvedPath>> {
3353        let mut candidates = vec![path.clone()];
3354
3355        if let Some(file) = buffer.read(cx).file() {
3356            if let Some(dir) = file.path().parent() {
3357                let joined = dir.to_path_buf().join(path);
3358                candidates.push(joined);
3359            }
3360        }
3361
3362        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3363        cx.spawn(|_, mut cx| async move {
3364            for worktree in worktrees {
3365                for candidate in candidates.iter() {
3366                    let path = worktree
3367                        .update(&mut cx, |worktree, _| {
3368                            let root_entry_path = &worktree.root_entry()?.path;
3369
3370                            let resolved = resolve_path(root_entry_path, candidate);
3371
3372                            let stripped =
3373                                resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3374
3375                            worktree.entry_for_path(stripped).map(|entry| {
3376                                let project_path = ProjectPath {
3377                                    worktree_id: worktree.id(),
3378                                    path: entry.path.clone(),
3379                                };
3380                                ResolvedPath::ProjectPath {
3381                                    project_path,
3382                                    is_dir: entry.is_dir(),
3383                                }
3384                            })
3385                        })
3386                        .ok()?;
3387
3388                    if path.is_some() {
3389                        return path;
3390                    }
3391                }
3392            }
3393            None
3394        })
3395    }
3396
3397    pub fn list_directory(
3398        &self,
3399        query: String,
3400        cx: &mut Context<Self>,
3401    ) -> Task<Result<Vec<PathBuf>>> {
3402        if self.is_local() {
3403            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3404        } else if let Some(session) = self.ssh_client.as_ref() {
3405            let request = proto::ListRemoteDirectory {
3406                dev_server_id: SSH_PROJECT_ID,
3407                path: query,
3408            };
3409
3410            let response = session.read(cx).proto_client().request(request);
3411            cx.background_executor().spawn(async move {
3412                let response = response.await?;
3413                Ok(response.entries.into_iter().map(PathBuf::from).collect())
3414            })
3415        } else {
3416            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3417        }
3418    }
3419
3420    pub fn create_worktree(
3421        &mut self,
3422        abs_path: impl AsRef<Path>,
3423        visible: bool,
3424        cx: &mut Context<Self>,
3425    ) -> Task<Result<Entity<Worktree>>> {
3426        self.worktree_store.update(cx, |worktree_store, cx| {
3427            worktree_store.create_worktree(abs_path, visible, cx)
3428        })
3429    }
3430
3431    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3432        self.worktree_store.update(cx, |worktree_store, cx| {
3433            worktree_store.remove_worktree(id_to_remove, cx);
3434        });
3435    }
3436
3437    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3438        self.worktree_store.update(cx, |worktree_store, cx| {
3439            worktree_store.add(worktree, cx);
3440        });
3441    }
3442
3443    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3444        let new_active_entry = entry.and_then(|project_path| {
3445            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3446            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3447            Some(entry.id)
3448        });
3449        if new_active_entry != self.active_entry {
3450            self.active_entry = new_active_entry;
3451            self.lsp_store.update(cx, |lsp_store, _| {
3452                lsp_store.set_active_entry(new_active_entry);
3453            });
3454            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3455        }
3456    }
3457
3458    pub fn language_servers_running_disk_based_diagnostics<'a>(
3459        &'a self,
3460        cx: &'a App,
3461    ) -> impl Iterator<Item = LanguageServerId> + 'a {
3462        self.lsp_store
3463            .read(cx)
3464            .language_servers_running_disk_based_diagnostics()
3465    }
3466
3467    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3468        self.lsp_store
3469            .read(cx)
3470            .diagnostic_summary(include_ignored, cx)
3471    }
3472
3473    pub fn diagnostic_summaries<'a>(
3474        &'a self,
3475        include_ignored: bool,
3476        cx: &'a App,
3477    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3478        self.lsp_store
3479            .read(cx)
3480            .diagnostic_summaries(include_ignored, cx)
3481    }
3482
3483    pub fn active_entry(&self) -> Option<ProjectEntryId> {
3484        self.active_entry
3485    }
3486
3487    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
3488        self.worktree_store.read(cx).entry_for_path(path, cx)
3489    }
3490
3491    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
3492        let worktree = self.worktree_for_entry(entry_id, cx)?;
3493        let worktree = worktree.read(cx);
3494        let worktree_id = worktree.id();
3495        let path = worktree.entry_for_id(entry_id)?.path.clone();
3496        Some(ProjectPath { worktree_id, path })
3497    }
3498
3499    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3500        self.worktree_for_id(project_path.worktree_id, cx)?
3501            .read(cx)
3502            .absolutize(&project_path.path)
3503            .ok()
3504    }
3505
3506    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3507    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3508    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3509    /// the first visible worktree that has an entry for that relative path.
3510    ///
3511    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3512    /// root name from paths.
3513    ///
3514    /// # Arguments
3515    ///
3516    /// * `path` - A full path that starts with a worktree root name, or alternatively a
3517    ///            relative path within a visible worktree.
3518    /// * `cx` - A reference to the `AppContext`.
3519    ///
3520    /// # Returns
3521    ///
3522    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3523    pub fn find_project_path(&self, path: &Path, cx: &App) -> Option<ProjectPath> {
3524        let worktree_store = self.worktree_store.read(cx);
3525
3526        for worktree in worktree_store.visible_worktrees(cx) {
3527            let worktree_root_name = worktree.read(cx).root_name();
3528            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3529                return Some(ProjectPath {
3530                    worktree_id: worktree.read(cx).id(),
3531                    path: relative_path.into(),
3532                });
3533            }
3534        }
3535
3536        for worktree in worktree_store.visible_worktrees(cx) {
3537            let worktree = worktree.read(cx);
3538            if let Some(entry) = worktree.entry_for_path(path) {
3539                return Some(ProjectPath {
3540                    worktree_id: worktree.id(),
3541                    path: entry.path.clone(),
3542                });
3543            }
3544        }
3545
3546        None
3547    }
3548
3549    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3550        Some(
3551            self.worktree_for_id(project_path.worktree_id, cx)?
3552                .read(cx)
3553                .abs_path()
3554                .to_path_buf(),
3555        )
3556    }
3557
3558    pub fn get_first_worktree_root_repo(&self, cx: &App) -> Option<Arc<dyn GitRepository>> {
3559        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3560        let root_entry = worktree.root_git_entry()?;
3561        worktree.get_local_repo(&root_entry)?.repo().clone().into()
3562    }
3563
3564    pub fn branches(&self, project_path: ProjectPath, cx: &App) -> Task<Result<Vec<Branch>>> {
3565        self.worktree_store().read(cx).branches(project_path, cx)
3566    }
3567
3568    pub fn update_or_create_branch(
3569        &self,
3570        repository: ProjectPath,
3571        new_branch: String,
3572        cx: &App,
3573    ) -> Task<Result<()>> {
3574        self.worktree_store()
3575            .read(cx)
3576            .update_or_create_branch(repository, new_branch, cx)
3577    }
3578
3579    pub fn blame_buffer(
3580        &self,
3581        buffer: &Entity<Buffer>,
3582        version: Option<clock::Global>,
3583        cx: &App,
3584    ) -> Task<Result<Option<Blame>>> {
3585        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3586    }
3587
3588    pub fn get_permalink_to_line(
3589        &self,
3590        buffer: &Entity<Buffer>,
3591        selection: Range<u32>,
3592        cx: &App,
3593    ) -> Task<Result<url::Url>> {
3594        self.buffer_store
3595            .read(cx)
3596            .get_permalink_to_line(buffer, selection, cx)
3597    }
3598
3599    // RPC message handlers
3600
3601    async fn handle_unshare_project(
3602        this: Entity<Self>,
3603        _: TypedEnvelope<proto::UnshareProject>,
3604        mut cx: AsyncApp,
3605    ) -> Result<()> {
3606        this.update(&mut cx, |this, cx| {
3607            if this.is_local() || this.is_via_ssh() {
3608                this.unshare(cx)?;
3609            } else {
3610                this.disconnected_from_host(cx);
3611            }
3612            Ok(())
3613        })?
3614    }
3615
3616    async fn handle_add_collaborator(
3617        this: Entity<Self>,
3618        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3619        mut cx: AsyncApp,
3620    ) -> Result<()> {
3621        let collaborator = envelope
3622            .payload
3623            .collaborator
3624            .take()
3625            .ok_or_else(|| anyhow!("empty collaborator"))?;
3626
3627        let collaborator = Collaborator::from_proto(collaborator)?;
3628        this.update(&mut cx, |this, cx| {
3629            this.buffer_store.update(cx, |buffer_store, _| {
3630                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3631            });
3632            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3633            this.collaborators
3634                .insert(collaborator.peer_id, collaborator);
3635            cx.notify();
3636        })?;
3637
3638        Ok(())
3639    }
3640
3641    async fn handle_update_project_collaborator(
3642        this: Entity<Self>,
3643        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3644        mut cx: AsyncApp,
3645    ) -> Result<()> {
3646        let old_peer_id = envelope
3647            .payload
3648            .old_peer_id
3649            .ok_or_else(|| anyhow!("missing old peer id"))?;
3650        let new_peer_id = envelope
3651            .payload
3652            .new_peer_id
3653            .ok_or_else(|| anyhow!("missing new peer id"))?;
3654        this.update(&mut cx, |this, cx| {
3655            let collaborator = this
3656                .collaborators
3657                .remove(&old_peer_id)
3658                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3659            let is_host = collaborator.is_host;
3660            this.collaborators.insert(new_peer_id, collaborator);
3661
3662            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3663            this.buffer_store.update(cx, |buffer_store, _| {
3664                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3665            });
3666
3667            if is_host {
3668                this.buffer_store
3669                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3670                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3671                    .unwrap();
3672                cx.emit(Event::HostReshared);
3673            }
3674
3675            cx.emit(Event::CollaboratorUpdated {
3676                old_peer_id,
3677                new_peer_id,
3678            });
3679            cx.notify();
3680            Ok(())
3681        })?
3682    }
3683
3684    async fn handle_remove_collaborator(
3685        this: Entity<Self>,
3686        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3687        mut cx: AsyncApp,
3688    ) -> Result<()> {
3689        this.update(&mut cx, |this, cx| {
3690            let peer_id = envelope
3691                .payload
3692                .peer_id
3693                .ok_or_else(|| anyhow!("invalid peer id"))?;
3694            let replica_id = this
3695                .collaborators
3696                .remove(&peer_id)
3697                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3698                .replica_id;
3699            this.buffer_store.update(cx, |buffer_store, cx| {
3700                buffer_store.forget_shared_buffers_for(&peer_id);
3701                for buffer in buffer_store.buffers() {
3702                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3703                }
3704            });
3705
3706            cx.emit(Event::CollaboratorLeft(peer_id));
3707            cx.notify();
3708            Ok(())
3709        })?
3710    }
3711
3712    async fn handle_update_project(
3713        this: Entity<Self>,
3714        envelope: TypedEnvelope<proto::UpdateProject>,
3715        mut cx: AsyncApp,
3716    ) -> Result<()> {
3717        this.update(&mut cx, |this, cx| {
3718            // Don't handle messages that were sent before the response to us joining the project
3719            if envelope.message_id > this.join_project_response_message_id {
3720                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3721            }
3722            Ok(())
3723        })?
3724    }
3725
3726    async fn handle_toast(
3727        this: Entity<Self>,
3728        envelope: TypedEnvelope<proto::Toast>,
3729        mut cx: AsyncApp,
3730    ) -> Result<()> {
3731        this.update(&mut cx, |_, cx| {
3732            cx.emit(Event::Toast {
3733                notification_id: envelope.payload.notification_id.into(),
3734                message: envelope.payload.message,
3735            });
3736            Ok(())
3737        })?
3738    }
3739
3740    async fn handle_language_server_prompt_request(
3741        this: Entity<Self>,
3742        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3743        mut cx: AsyncApp,
3744    ) -> Result<proto::LanguageServerPromptResponse> {
3745        let (tx, mut rx) = smol::channel::bounded(1);
3746        let actions: Vec<_> = envelope
3747            .payload
3748            .actions
3749            .into_iter()
3750            .map(|action| MessageActionItem {
3751                title: action,
3752                properties: Default::default(),
3753            })
3754            .collect();
3755        this.update(&mut cx, |_, cx| {
3756            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3757                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3758                message: envelope.payload.message,
3759                actions: actions.clone(),
3760                lsp_name: envelope.payload.lsp_name,
3761                response_channel: tx,
3762            }));
3763
3764            anyhow::Ok(())
3765        })??;
3766
3767        // We drop `this` to avoid holding a reference in this future for too
3768        // long.
3769        // If we keep the reference, we might not drop the `Project` early
3770        // enough when closing a window and it will only get releases on the
3771        // next `flush_effects()` call.
3772        drop(this);
3773
3774        let mut rx = pin!(rx);
3775        let answer = rx.next().await;
3776
3777        Ok(LanguageServerPromptResponse {
3778            action_response: answer.and_then(|answer| {
3779                actions
3780                    .iter()
3781                    .position(|action| *action == answer)
3782                    .map(|index| index as u64)
3783            }),
3784        })
3785    }
3786
3787    async fn handle_hide_toast(
3788        this: Entity<Self>,
3789        envelope: TypedEnvelope<proto::HideToast>,
3790        mut cx: AsyncApp,
3791    ) -> Result<()> {
3792        this.update(&mut cx, |_, cx| {
3793            cx.emit(Event::HideToast {
3794                notification_id: envelope.payload.notification_id.into(),
3795            });
3796            Ok(())
3797        })?
3798    }
3799
3800    // Collab sends UpdateWorktree protos as messages
3801    async fn handle_update_worktree(
3802        this: Entity<Self>,
3803        envelope: TypedEnvelope<proto::UpdateWorktree>,
3804        mut cx: AsyncApp,
3805    ) -> Result<()> {
3806        this.update(&mut cx, |this, cx| {
3807            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3808            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3809                worktree.update(cx, |worktree, _| {
3810                    let worktree = worktree.as_remote_mut().unwrap();
3811                    worktree.update_from_remote(envelope.payload);
3812                });
3813            }
3814            Ok(())
3815        })?
3816    }
3817
3818    async fn handle_update_buffer_from_ssh(
3819        this: Entity<Self>,
3820        envelope: TypedEnvelope<proto::UpdateBuffer>,
3821        cx: AsyncApp,
3822    ) -> Result<proto::Ack> {
3823        let buffer_store = this.read_with(&cx, |this, cx| {
3824            if let Some(remote_id) = this.remote_id() {
3825                let mut payload = envelope.payload.clone();
3826                payload.project_id = remote_id;
3827                cx.background_executor()
3828                    .spawn(this.client.request(payload))
3829                    .detach_and_log_err(cx);
3830            }
3831            this.buffer_store.clone()
3832        })?;
3833        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3834    }
3835
3836    async fn handle_update_buffer(
3837        this: Entity<Self>,
3838        envelope: TypedEnvelope<proto::UpdateBuffer>,
3839        cx: AsyncApp,
3840    ) -> Result<proto::Ack> {
3841        let buffer_store = this.read_with(&cx, |this, cx| {
3842            if let Some(ssh) = &this.ssh_client {
3843                let mut payload = envelope.payload.clone();
3844                payload.project_id = SSH_PROJECT_ID;
3845                cx.background_executor()
3846                    .spawn(ssh.read(cx).proto_client().request(payload))
3847                    .detach_and_log_err(cx);
3848            }
3849            this.buffer_store.clone()
3850        })?;
3851        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3852    }
3853
3854    fn retain_remotely_created_models(
3855        &mut self,
3856        cx: &mut Context<Self>,
3857    ) -> RemotelyCreatedModelGuard {
3858        {
3859            let mut remotely_create_models = self.remotely_created_models.lock();
3860            if remotely_create_models.retain_count == 0 {
3861                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3862                remotely_create_models.worktrees =
3863                    self.worktree_store.read(cx).worktrees().collect();
3864            }
3865            remotely_create_models.retain_count += 1;
3866        }
3867        RemotelyCreatedModelGuard {
3868            remote_models: Arc::downgrade(&self.remotely_created_models),
3869        }
3870    }
3871
3872    async fn handle_create_buffer_for_peer(
3873        this: Entity<Self>,
3874        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3875        mut cx: AsyncApp,
3876    ) -> Result<()> {
3877        this.update(&mut cx, |this, cx| {
3878            this.buffer_store.update(cx, |buffer_store, cx| {
3879                buffer_store.handle_create_buffer_for_peer(
3880                    envelope,
3881                    this.replica_id(),
3882                    this.capability(),
3883                    cx,
3884                )
3885            })
3886        })?
3887    }
3888
3889    async fn handle_synchronize_buffers(
3890        this: Entity<Self>,
3891        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3892        mut cx: AsyncApp,
3893    ) -> Result<proto::SynchronizeBuffersResponse> {
3894        let response = this.update(&mut cx, |this, cx| {
3895            let client = this.client.clone();
3896            this.buffer_store.update(cx, |this, cx| {
3897                this.handle_synchronize_buffers(envelope, cx, client)
3898            })
3899        })??;
3900
3901        Ok(response)
3902    }
3903
3904    async fn handle_search_candidate_buffers(
3905        this: Entity<Self>,
3906        envelope: TypedEnvelope<proto::FindSearchCandidates>,
3907        mut cx: AsyncApp,
3908    ) -> Result<proto::FindSearchCandidatesResponse> {
3909        let peer_id = envelope.original_sender_id()?;
3910        let message = envelope.payload;
3911        let query = SearchQuery::from_proto(
3912            message
3913                .query
3914                .ok_or_else(|| anyhow!("missing query field"))?,
3915        )?;
3916        let results = this.update(&mut cx, |this, cx| {
3917            this.find_search_candidate_buffers(&query, message.limit as _, cx)
3918        })?;
3919
3920        let mut response = proto::FindSearchCandidatesResponse {
3921            buffer_ids: Vec::new(),
3922        };
3923
3924        while let Ok(buffer) = results.recv().await {
3925            this.update(&mut cx, |this, cx| {
3926                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3927                response.buffer_ids.push(buffer_id.to_proto());
3928            })?;
3929        }
3930
3931        Ok(response)
3932    }
3933
3934    async fn handle_open_buffer_by_id(
3935        this: Entity<Self>,
3936        envelope: TypedEnvelope<proto::OpenBufferById>,
3937        mut cx: AsyncApp,
3938    ) -> Result<proto::OpenBufferResponse> {
3939        let peer_id = envelope.original_sender_id()?;
3940        let buffer_id = BufferId::new(envelope.payload.id)?;
3941        let buffer = this
3942            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3943            .await?;
3944        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3945    }
3946
3947    async fn handle_open_buffer_by_path(
3948        this: Entity<Self>,
3949        envelope: TypedEnvelope<proto::OpenBufferByPath>,
3950        mut cx: AsyncApp,
3951    ) -> Result<proto::OpenBufferResponse> {
3952        let peer_id = envelope.original_sender_id()?;
3953        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3954        let skip_file_contents = envelope.payload.skip_file_contents;
3955        let open_buffer = this.update(&mut cx, |this, cx| {
3956            if skip_file_contents {
3957                this.open_buffer_without_contents(
3958                    ProjectPath {
3959                        worktree_id,
3960                        path: PathBuf::from(envelope.payload.path).into(),
3961                    },
3962                    cx,
3963                )
3964            } else {
3965                this.open_buffer(
3966                    ProjectPath {
3967                        worktree_id,
3968                        path: PathBuf::from(envelope.payload.path).into(),
3969                    },
3970                    cx,
3971                )
3972            }
3973        })?;
3974
3975        let buffer = open_buffer.await?;
3976        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3977    }
3978
3979    async fn handle_open_new_buffer(
3980        this: Entity<Self>,
3981        envelope: TypedEnvelope<proto::OpenNewBuffer>,
3982        mut cx: AsyncApp,
3983    ) -> Result<proto::OpenBufferResponse> {
3984        let buffer = this
3985            .update(&mut cx, |this, cx| this.create_buffer(cx))?
3986            .await?;
3987        let peer_id = envelope.original_sender_id()?;
3988
3989        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3990    }
3991
3992    async fn handle_stage(
3993        this: Entity<Self>,
3994        envelope: TypedEnvelope<proto::Stage>,
3995        mut cx: AsyncApp,
3996    ) -> Result<proto::Ack> {
3997        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3998        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
3999        let repository_handle =
4000            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4001
4002        let entries = envelope
4003            .payload
4004            .paths
4005            .into_iter()
4006            .map(PathBuf::from)
4007            .map(RepoPath::new)
4008            .collect();
4009
4010        repository_handle.stage_entries(entries).await?;
4011        Ok(proto::Ack {})
4012    }
4013
4014    async fn handle_unstage(
4015        this: Entity<Self>,
4016        envelope: TypedEnvelope<proto::Unstage>,
4017        mut cx: AsyncApp,
4018    ) -> Result<proto::Ack> {
4019        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4020        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4021        let repository_handle =
4022            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4023
4024        let entries = envelope
4025            .payload
4026            .paths
4027            .into_iter()
4028            .map(PathBuf::from)
4029            .map(RepoPath::new)
4030            .collect();
4031
4032        repository_handle.unstage_entries(entries).await?;
4033        Ok(proto::Ack {})
4034    }
4035
4036    async fn handle_commit(
4037        this: Entity<Self>,
4038        envelope: TypedEnvelope<proto::Commit>,
4039        mut cx: AsyncApp,
4040    ) -> Result<proto::Ack> {
4041        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4042        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4043        let repository_handle =
4044            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4045
4046        let name = envelope.payload.name.map(SharedString::from);
4047        let email = envelope.payload.email.map(SharedString::from);
4048        repository_handle.commit(name.zip(email)).await?;
4049        Ok(proto::Ack {})
4050    }
4051
4052    async fn handle_open_commit_message_buffer(
4053        this: Entity<Self>,
4054        envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
4055        mut cx: AsyncApp,
4056    ) -> Result<proto::OpenBufferResponse> {
4057        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4058        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4059        let repository_handle =
4060            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4061        let git_repository = match &repository_handle.git_repo {
4062            git::GitRepo::Local(git_repository) => git_repository.clone(),
4063            git::GitRepo::Remote { .. } => {
4064                anyhow::bail!("Cannot handle open commit message buffer for remote git repo")
4065            }
4066        };
4067        let commit_message_file = git_repository.dot_git_dir().join(*COMMIT_MESSAGE);
4068        let fs = this.update(&mut cx, |project, _| project.fs().clone())?;
4069        fs.create_file(
4070            &commit_message_file,
4071            CreateOptions {
4072                overwrite: false,
4073                ignore_if_exists: true,
4074            },
4075        )
4076        .await
4077        .with_context(|| format!("creating commit message file {commit_message_file:?}"))?;
4078
4079        let (worktree, relative_path) = this
4080            .update(&mut cx, |project, cx| {
4081                project.worktree_store.update(cx, |worktree_store, cx| {
4082                    worktree_store.find_or_create_worktree(&commit_message_file, false, cx)
4083                })
4084            })?
4085            .await
4086            .with_context(|| {
4087                format!("deriving worktree for commit message file {commit_message_file:?}")
4088            })?;
4089
4090        let buffer = this
4091            .update(&mut cx, |project, cx| {
4092                project.buffer_store.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                        true,
4099                        cx,
4100                    )
4101                })
4102            })
4103            .with_context(|| {
4104                format!("opening buffer for commit message file {commit_message_file:?}")
4105            })?
4106            .await?;
4107        let peer_id = envelope.original_sender_id()?;
4108        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4109    }
4110
4111    fn repository_for_request(
4112        this: &Entity<Self>,
4113        worktree_id: WorktreeId,
4114        work_directory_id: ProjectEntryId,
4115        cx: &mut AsyncApp,
4116    ) -> Result<RepositoryHandle> {
4117        this.update(cx, |project, cx| {
4118            let repository_handle = project
4119                .git_state()
4120                .read(cx)
4121                .all_repositories()
4122                .into_iter()
4123                .find(|repository_handle| {
4124                    repository_handle.worktree_id == worktree_id
4125                        && repository_handle.repository_entry.work_directory_id()
4126                            == work_directory_id
4127                })
4128                .context("missing repository handle")?;
4129            anyhow::Ok(repository_handle)
4130        })?
4131    }
4132
4133    fn respond_to_open_buffer_request(
4134        this: Entity<Self>,
4135        buffer: Entity<Buffer>,
4136        peer_id: proto::PeerId,
4137        cx: &mut AsyncApp,
4138    ) -> Result<proto::OpenBufferResponse> {
4139        this.update(cx, |this, cx| {
4140            let is_private = buffer
4141                .read(cx)
4142                .file()
4143                .map(|f| f.is_private())
4144                .unwrap_or_default();
4145            if is_private {
4146                Err(anyhow!(ErrorCode::UnsharedItem))
4147            } else {
4148                Ok(proto::OpenBufferResponse {
4149                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4150                })
4151            }
4152        })?
4153    }
4154
4155    fn create_buffer_for_peer(
4156        &mut self,
4157        buffer: &Entity<Buffer>,
4158        peer_id: proto::PeerId,
4159        cx: &mut App,
4160    ) -> BufferId {
4161        self.buffer_store
4162            .update(cx, |buffer_store, cx| {
4163                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4164            })
4165            .detach_and_log_err(cx);
4166        buffer.read(cx).remote_id()
4167    }
4168
4169    pub fn wait_for_remote_buffer(
4170        &mut self,
4171        id: BufferId,
4172        cx: &mut Context<Self>,
4173    ) -> Task<Result<Entity<Buffer>>> {
4174        self.buffer_store.update(cx, |buffer_store, cx| {
4175            buffer_store.wait_for_remote_buffer(id, cx)
4176        })
4177    }
4178
4179    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4180        let project_id = match self.client_state {
4181            ProjectClientState::Remote {
4182                sharing_has_stopped,
4183                remote_id,
4184                ..
4185            } => {
4186                if sharing_has_stopped {
4187                    return Task::ready(Err(anyhow!(
4188                        "can't synchronize remote buffers on a readonly project"
4189                    )));
4190                } else {
4191                    remote_id
4192                }
4193            }
4194            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4195                return Task::ready(Err(anyhow!(
4196                    "can't synchronize remote buffers on a local project"
4197                )))
4198            }
4199        };
4200
4201        let client = self.client.clone();
4202        cx.spawn(move |this, mut cx| async move {
4203            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4204                this.buffer_store.read(cx).buffer_version_info(cx)
4205            })?;
4206            let response = client
4207                .request(proto::SynchronizeBuffers {
4208                    project_id,
4209                    buffers,
4210                })
4211                .await?;
4212
4213            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4214                response
4215                    .buffers
4216                    .into_iter()
4217                    .map(|buffer| {
4218                        let client = client.clone();
4219                        let buffer_id = match BufferId::new(buffer.id) {
4220                            Ok(id) => id,
4221                            Err(e) => {
4222                                return Task::ready(Err(e));
4223                            }
4224                        };
4225                        let remote_version = language::proto::deserialize_version(&buffer.version);
4226                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4227                            let operations =
4228                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4229                            cx.background_executor().spawn(async move {
4230                                let operations = operations.await;
4231                                for chunk in split_operations(operations) {
4232                                    client
4233                                        .request(proto::UpdateBuffer {
4234                                            project_id,
4235                                            buffer_id: buffer_id.into(),
4236                                            operations: chunk,
4237                                        })
4238                                        .await?;
4239                                }
4240                                anyhow::Ok(())
4241                            })
4242                        } else {
4243                            Task::ready(Ok(()))
4244                        }
4245                    })
4246                    .collect::<Vec<_>>()
4247            })?;
4248
4249            // Any incomplete buffers have open requests waiting. Request that the host sends
4250            // creates these buffers for us again to unblock any waiting futures.
4251            for id in incomplete_buffer_ids {
4252                cx.background_executor()
4253                    .spawn(client.request(proto::OpenBufferById {
4254                        project_id,
4255                        id: id.into(),
4256                    }))
4257                    .detach();
4258            }
4259
4260            futures::future::join_all(send_updates_for_buffers)
4261                .await
4262                .into_iter()
4263                .collect()
4264        })
4265    }
4266
4267    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4268        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4269    }
4270
4271    /// Iterator of all open buffers that have unsaved changes
4272    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4273        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4274            let buf = buf.read(cx);
4275            if buf.is_dirty() {
4276                buf.project_path(cx)
4277            } else {
4278                None
4279            }
4280        })
4281    }
4282
4283    fn set_worktrees_from_proto(
4284        &mut self,
4285        worktrees: Vec<proto::WorktreeMetadata>,
4286        cx: &mut Context<Project>,
4287    ) -> Result<()> {
4288        cx.notify();
4289        self.worktree_store.update(cx, |worktree_store, cx| {
4290            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4291        })
4292    }
4293
4294    fn set_collaborators_from_proto(
4295        &mut self,
4296        messages: Vec<proto::Collaborator>,
4297        cx: &mut Context<Self>,
4298    ) -> Result<()> {
4299        let mut collaborators = HashMap::default();
4300        for message in messages {
4301            let collaborator = Collaborator::from_proto(message)?;
4302            collaborators.insert(collaborator.peer_id, collaborator);
4303        }
4304        for old_peer_id in self.collaborators.keys() {
4305            if !collaborators.contains_key(old_peer_id) {
4306                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4307            }
4308        }
4309        self.collaborators = collaborators;
4310        Ok(())
4311    }
4312
4313    pub fn supplementary_language_servers<'a>(
4314        &'a self,
4315        cx: &'a App,
4316    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4317        self.lsp_store.read(cx).supplementary_language_servers()
4318    }
4319
4320    pub fn language_servers_for_local_buffer<'a>(
4321        &'a self,
4322        buffer: &'a Buffer,
4323        cx: &'a App,
4324    ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4325        self.lsp_store
4326            .read(cx)
4327            .language_servers_for_local_buffer(buffer, cx)
4328    }
4329
4330    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4331        &self.buffer_store
4332    }
4333
4334    pub fn git_state(&self) -> &Entity<GitState> {
4335        &self.git_state
4336    }
4337
4338    pub fn active_repository(&self, cx: &App) -> Option<RepositoryHandle> {
4339        self.git_state.read(cx).active_repository()
4340    }
4341
4342    pub fn all_repositories(&self, cx: &App) -> Vec<RepositoryHandle> {
4343        self.git_state.read(cx).all_repositories()
4344    }
4345}
4346
4347fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4348    code_actions
4349        .iter()
4350        .flat_map(|(kind, enabled)| {
4351            if *enabled {
4352                Some(kind.clone().into())
4353            } else {
4354                None
4355            }
4356        })
4357        .collect()
4358}
4359
4360pub struct PathMatchCandidateSet {
4361    pub snapshot: Snapshot,
4362    pub include_ignored: bool,
4363    pub include_root_name: bool,
4364    pub candidates: Candidates,
4365}
4366
4367pub enum Candidates {
4368    /// Only consider directories.
4369    Directories,
4370    /// Only consider files.
4371    Files,
4372    /// Consider directories and files.
4373    Entries,
4374}
4375
4376impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4377    type Candidates = PathMatchCandidateSetIter<'a>;
4378
4379    fn id(&self) -> usize {
4380        self.snapshot.id().to_usize()
4381    }
4382
4383    fn len(&self) -> usize {
4384        match self.candidates {
4385            Candidates::Files => {
4386                if self.include_ignored {
4387                    self.snapshot.file_count()
4388                } else {
4389                    self.snapshot.visible_file_count()
4390                }
4391            }
4392
4393            Candidates::Directories => {
4394                if self.include_ignored {
4395                    self.snapshot.dir_count()
4396                } else {
4397                    self.snapshot.visible_dir_count()
4398                }
4399            }
4400
4401            Candidates::Entries => {
4402                if self.include_ignored {
4403                    self.snapshot.entry_count()
4404                } else {
4405                    self.snapshot.visible_entry_count()
4406                }
4407            }
4408        }
4409    }
4410
4411    fn prefix(&self) -> Arc<str> {
4412        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4413            self.snapshot.root_name().into()
4414        } else if self.include_root_name {
4415            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4416        } else {
4417            Arc::default()
4418        }
4419    }
4420
4421    fn candidates(&'a self, start: usize) -> Self::Candidates {
4422        PathMatchCandidateSetIter {
4423            traversal: match self.candidates {
4424                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4425                Candidates::Files => self.snapshot.files(self.include_ignored, start),
4426                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4427            },
4428        }
4429    }
4430}
4431
4432pub struct PathMatchCandidateSetIter<'a> {
4433    traversal: Traversal<'a>,
4434}
4435
4436impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4437    type Item = fuzzy::PathMatchCandidate<'a>;
4438
4439    fn next(&mut self) -> Option<Self::Item> {
4440        self.traversal
4441            .next()
4442            .map(|entry| fuzzy::PathMatchCandidate {
4443                is_dir: entry.kind.is_dir(),
4444                path: &entry.path,
4445                char_bag: entry.char_bag,
4446            })
4447    }
4448}
4449
4450impl EventEmitter<Event> for Project {}
4451
4452impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4453    fn from(val: &'a ProjectPath) -> Self {
4454        SettingsLocation {
4455            worktree_id: val.worktree_id,
4456            path: val.path.as_ref(),
4457        }
4458    }
4459}
4460
4461impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4462    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4463        Self {
4464            worktree_id,
4465            path: path.as_ref().into(),
4466        }
4467    }
4468}
4469
4470pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4471    let mut path_components = path.components();
4472    let mut base_components = base.components();
4473    let mut components: Vec<Component> = Vec::new();
4474    loop {
4475        match (path_components.next(), base_components.next()) {
4476            (None, None) => break,
4477            (Some(a), None) => {
4478                components.push(a);
4479                components.extend(path_components.by_ref());
4480                break;
4481            }
4482            (None, _) => components.push(Component::ParentDir),
4483            (Some(a), Some(b)) if components.is_empty() && a == b => (),
4484            (Some(a), Some(Component::CurDir)) => components.push(a),
4485            (Some(a), Some(_)) => {
4486                components.push(Component::ParentDir);
4487                for _ in base_components {
4488                    components.push(Component::ParentDir);
4489                }
4490                components.push(a);
4491                components.extend(path_components.by_ref());
4492                break;
4493            }
4494        }
4495    }
4496    components.iter().map(|c| c.as_os_str()).collect()
4497}
4498
4499fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4500    let mut result = base.to_path_buf();
4501    for component in path.components() {
4502        match component {
4503            Component::ParentDir => {
4504                result.pop();
4505            }
4506            Component::CurDir => (),
4507            _ => result.push(component),
4508        }
4509    }
4510    result
4511}
4512
4513/// ResolvedPath is a path that has been resolved to either a ProjectPath
4514/// or an AbsPath and that *exists*.
4515#[derive(Debug, Clone)]
4516pub enum ResolvedPath {
4517    ProjectPath {
4518        project_path: ProjectPath,
4519        is_dir: bool,
4520    },
4521    AbsPath {
4522        path: PathBuf,
4523        is_dir: bool,
4524    },
4525}
4526
4527impl ResolvedPath {
4528    pub fn abs_path(&self) -> Option<&Path> {
4529        match self {
4530            Self::AbsPath { path, .. } => Some(path.as_path()),
4531            _ => None,
4532        }
4533    }
4534
4535    pub fn project_path(&self) -> Option<&ProjectPath> {
4536        match self {
4537            Self::ProjectPath { project_path, .. } => Some(&project_path),
4538            _ => None,
4539        }
4540    }
4541
4542    pub fn is_file(&self) -> bool {
4543        !self.is_dir()
4544    }
4545
4546    pub fn is_dir(&self) -> bool {
4547        match self {
4548            Self::ProjectPath { is_dir, .. } => *is_dir,
4549            Self::AbsPath { is_dir, .. } => *is_dir,
4550        }
4551    }
4552}
4553
4554impl ProjectItem for Buffer {
4555    fn try_open(
4556        project: &Entity<Project>,
4557        path: &ProjectPath,
4558        cx: &mut App,
4559    ) -> Option<Task<Result<Entity<Self>>>> {
4560        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4561    }
4562
4563    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4564        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4565    }
4566
4567    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4568        File::from_dyn(self.file()).map(|file| ProjectPath {
4569            worktree_id: file.worktree_id(cx),
4570            path: file.path().clone(),
4571        })
4572    }
4573
4574    fn is_dirty(&self) -> bool {
4575        self.is_dirty()
4576    }
4577}
4578
4579impl Completion {
4580    /// A key that can be used to sort completions when displaying
4581    /// them to the user.
4582    pub fn sort_key(&self) -> (usize, &str) {
4583        let kind_key = match self.lsp_completion.kind {
4584            Some(lsp::CompletionItemKind::KEYWORD) => 0,
4585            Some(lsp::CompletionItemKind::VARIABLE) => 1,
4586            _ => 2,
4587        };
4588        (kind_key, &self.label.text[self.label.filter_range.clone()])
4589    }
4590
4591    /// Whether this completion is a snippet.
4592    pub fn is_snippet(&self) -> bool {
4593        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4594    }
4595
4596    /// Returns the corresponding color for this completion.
4597    ///
4598    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4599    pub fn color(&self) -> Option<Hsla> {
4600        match self.lsp_completion.kind {
4601            Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4602            _ => None,
4603        }
4604    }
4605}
4606
4607pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
4608    entries.sort_by(|entry_a, entry_b| {
4609        let entry_a = entry_a.as_ref();
4610        let entry_b = entry_b.as_ref();
4611        compare_paths(
4612            (&entry_a.path, entry_a.is_file()),
4613            (&entry_b.path, entry_b.is_file()),
4614        )
4615    });
4616}
4617
4618fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4619    match level {
4620        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4621        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4622        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4623    }
4624}