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;
  24use diff::BufferDiff;
  25pub use environment::EnvironmentErrorMessage;
  26use git::Repository;
  27pub mod search_history;
  28mod yarn;
  29
  30use crate::git::GitState;
  31use anyhow::{anyhow, Context as _, Result};
  32use buffer_store::{BufferStore, BufferStoreEvent};
  33use client::{
  34    proto, Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore,
  35};
  36use clock::ReplicaId;
  37use collections::{BTreeSet, HashMap, HashSet};
  38use debounced_delay::DebouncedDelay;
  39pub use environment::ProjectEnvironment;
  40use futures::{
  41    channel::mpsc::{self, UnboundedReceiver},
  42    future::try_join_all,
  43    StreamExt,
  44};
  45pub use image_store::{ImageItem, ImageStore};
  46use image_store::{ImageItemEvent, ImageStoreEvent};
  47
  48use ::git::{
  49    blame::Blame,
  50    repository::{Branch, GitRepository, RepoPath},
  51    status::FileStatus,
  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_entity_message_handler(Self::handle_add_collaborator);
 596        client.add_entity_message_handler(Self::handle_update_project_collaborator);
 597        client.add_entity_message_handler(Self::handle_remove_collaborator);
 598        client.add_entity_message_handler(Self::handle_update_project);
 599        client.add_entity_message_handler(Self::handle_unshare_project);
 600        client.add_entity_request_handler(Self::handle_update_buffer);
 601        client.add_entity_message_handler(Self::handle_update_worktree);
 602        client.add_entity_request_handler(Self::handle_synchronize_buffers);
 603
 604        client.add_entity_request_handler(Self::handle_search_candidate_buffers);
 605        client.add_entity_request_handler(Self::handle_open_buffer_by_id);
 606        client.add_entity_request_handler(Self::handle_open_buffer_by_path);
 607        client.add_entity_request_handler(Self::handle_open_new_buffer);
 608        client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
 609
 610        client.add_entity_request_handler(Self::handle_stage);
 611        client.add_entity_request_handler(Self::handle_unstage);
 612        client.add_entity_request_handler(Self::handle_commit);
 613        client.add_entity_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_entity_message_handler(Self::handle_create_buffer_for_peer);
 897            ssh_proto.add_entity_message_handler(Self::handle_update_worktree);
 898            ssh_proto.add_entity_message_handler(Self::handle_update_project);
 899            ssh_proto.add_entity_message_handler(Self::handle_toast);
 900            ssh_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
 901            ssh_proto.add_entity_message_handler(Self::handle_hide_toast);
 902            ssh_proto.add_entity_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_entity(&buffer_store, &mut cx)
1114                }
1115                EntitySubscription::WorktreeStore(subscription) => {
1116                    subscription.set_entity(&worktree_store, &mut cx)
1117                }
1118                EntitySubscription::SettingsObserver(subscription) => {
1119                    subscription.set_entity(&settings_observer, &mut cx)
1120                }
1121                EntitySubscription::Project(subscription) => {
1122                    subscription.set_entity(&this, &mut cx)
1123                }
1124                EntitySubscription::LspStore(subscription) => {
1125                    subscription.set_entity(&lsp_store, &mut cx)
1126                }
1127            })
1128            .collect::<Vec<_>>();
1129
1130        let user_ids = response
1131            .payload
1132            .collaborators
1133            .iter()
1134            .map(|peer| peer.user_id)
1135            .collect();
1136        user_store
1137            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1138            .await?;
1139
1140        this.update(&mut cx, |this, cx| {
1141            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1142            this.client_subscriptions.extend(subscriptions);
1143            anyhow::Ok(())
1144        })??;
1145
1146        Ok(this)
1147    }
1148
1149    fn new_search_history() -> SearchHistory {
1150        SearchHistory::new(
1151            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1152            search_history::QueryInsertionBehavior::AlwaysInsert,
1153        )
1154    }
1155
1156    fn release(&mut self, cx: &mut App) {
1157        if let Some(client) = self.ssh_client.take() {
1158            let shutdown = client
1159                .read(cx)
1160                .shutdown_processes(Some(proto::ShutdownRemoteServer {}));
1161
1162            cx.background_executor()
1163                .spawn(async move {
1164                    if let Some(shutdown) = shutdown {
1165                        shutdown.await;
1166                    }
1167                })
1168                .detach()
1169        }
1170
1171        match &self.client_state {
1172            ProjectClientState::Local => {}
1173            ProjectClientState::Shared { .. } => {
1174                let _ = self.unshare_internal(cx);
1175            }
1176            ProjectClientState::Remote { remote_id, .. } => {
1177                let _ = self.client.send(proto::LeaveProject {
1178                    project_id: *remote_id,
1179                });
1180                self.disconnected_from_host_internal(cx);
1181            }
1182        }
1183    }
1184
1185    #[cfg(any(test, feature = "test-support"))]
1186    pub async fn example(
1187        root_paths: impl IntoIterator<Item = &Path>,
1188        cx: &mut AsyncApp,
1189    ) -> Entity<Project> {
1190        use clock::FakeSystemClock;
1191
1192        let fs = Arc::new(RealFs::default());
1193        let languages = LanguageRegistry::test(cx.background_executor().clone());
1194        let clock = Arc::new(FakeSystemClock::new());
1195        let http_client = http_client::FakeHttpClient::with_404_response();
1196        let client = cx
1197            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1198            .unwrap();
1199        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1200        let project = cx
1201            .update(|cx| {
1202                Project::local(
1203                    client,
1204                    node_runtime::NodeRuntime::unavailable(),
1205                    user_store,
1206                    Arc::new(languages),
1207                    fs,
1208                    None,
1209                    cx,
1210                )
1211            })
1212            .unwrap();
1213        for path in root_paths {
1214            let (tree, _) = project
1215                .update(cx, |project, cx| {
1216                    project.find_or_create_worktree(path, true, cx)
1217                })
1218                .unwrap()
1219                .await
1220                .unwrap();
1221            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1222                .unwrap()
1223                .await;
1224        }
1225        project
1226    }
1227
1228    #[cfg(any(test, feature = "test-support"))]
1229    pub async fn test(
1230        fs: Arc<dyn Fs>,
1231        root_paths: impl IntoIterator<Item = &Path>,
1232        cx: &mut gpui::TestAppContext,
1233    ) -> Entity<Project> {
1234        use clock::FakeSystemClock;
1235
1236        let languages = LanguageRegistry::test(cx.executor());
1237        let clock = Arc::new(FakeSystemClock::new());
1238        let http_client = http_client::FakeHttpClient::with_404_response();
1239        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1240        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1241        let project = cx.update(|cx| {
1242            Project::local(
1243                client,
1244                node_runtime::NodeRuntime::unavailable(),
1245                user_store,
1246                Arc::new(languages),
1247                fs,
1248                None,
1249                cx,
1250            )
1251        });
1252        for path in root_paths {
1253            let (tree, _) = project
1254                .update(cx, |project, cx| {
1255                    project.find_or_create_worktree(path, true, cx)
1256                })
1257                .await
1258                .unwrap();
1259
1260            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1261                .await;
1262        }
1263        project
1264    }
1265
1266    pub fn lsp_store(&self) -> Entity<LspStore> {
1267        self.lsp_store.clone()
1268    }
1269
1270    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1271        self.worktree_store.clone()
1272    }
1273
1274    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1275        self.buffer_store.read(cx).get(remote_id)
1276    }
1277
1278    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1279        &self.languages
1280    }
1281
1282    pub fn client(&self) -> Arc<Client> {
1283        self.client.clone()
1284    }
1285
1286    pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1287        self.ssh_client.clone()
1288    }
1289
1290    pub fn user_store(&self) -> Entity<UserStore> {
1291        self.user_store.clone()
1292    }
1293
1294    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1295        self.node.as_ref()
1296    }
1297
1298    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1299        self.buffer_store.read(cx).buffers().collect()
1300    }
1301
1302    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1303        &self.environment
1304    }
1305
1306    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1307        self.environment.read(cx).get_cli_environment()
1308    }
1309
1310    pub fn shell_environment_errors<'a>(
1311        &'a self,
1312        cx: &'a App,
1313    ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1314        self.environment.read(cx).environment_errors()
1315    }
1316
1317    pub fn remove_environment_error(&mut self, cx: &mut Context<Self>, worktree_id: WorktreeId) {
1318        self.environment.update(cx, |environment, _| {
1319            environment.remove_environment_error(worktree_id);
1320        });
1321    }
1322
1323    #[cfg(any(test, feature = "test-support"))]
1324    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1325        self.buffer_store
1326            .read(cx)
1327            .get_by_path(&path.into(), cx)
1328            .is_some()
1329    }
1330
1331    pub fn fs(&self) -> &Arc<dyn Fs> {
1332        &self.fs
1333    }
1334
1335    pub fn remote_id(&self) -> Option<u64> {
1336        match self.client_state {
1337            ProjectClientState::Local => None,
1338            ProjectClientState::Shared { remote_id, .. }
1339            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1340        }
1341    }
1342
1343    pub fn supports_terminal(&self, _cx: &App) -> bool {
1344        if self.is_local() {
1345            return true;
1346        }
1347        if self.is_via_ssh() {
1348            return true;
1349        }
1350
1351        return false;
1352    }
1353
1354    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1355        if let Some(ssh_state) = &self.ssh_client {
1356            return Some(ssh_state.read(cx).connection_string().into());
1357        }
1358
1359        return None;
1360    }
1361
1362    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1363        self.ssh_client
1364            .as_ref()
1365            .map(|ssh| ssh.read(cx).connection_state())
1366    }
1367
1368    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1369        self.ssh_client
1370            .as_ref()
1371            .map(|ssh| ssh.read(cx).connection_options())
1372    }
1373
1374    pub fn replica_id(&self) -> ReplicaId {
1375        match self.client_state {
1376            ProjectClientState::Remote { replica_id, .. } => replica_id,
1377            _ => {
1378                if self.ssh_client.is_some() {
1379                    1
1380                } else {
1381                    0
1382                }
1383            }
1384        }
1385    }
1386
1387    pub fn task_store(&self) -> &Entity<TaskStore> {
1388        &self.task_store
1389    }
1390
1391    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1392        &self.snippets
1393    }
1394
1395    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1396        match kind {
1397            SearchInputKind::Query => &self.search_history,
1398            SearchInputKind::Include => &self.search_included_history,
1399            SearchInputKind::Exclude => &self.search_excluded_history,
1400        }
1401    }
1402
1403    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1404        match kind {
1405            SearchInputKind::Query => &mut self.search_history,
1406            SearchInputKind::Include => &mut self.search_included_history,
1407            SearchInputKind::Exclude => &mut self.search_excluded_history,
1408        }
1409    }
1410
1411    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1412        &self.collaborators
1413    }
1414
1415    pub fn host(&self) -> Option<&Collaborator> {
1416        self.collaborators.values().find(|c| c.is_host)
1417    }
1418
1419    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1420        self.worktree_store.update(cx, |store, _| {
1421            store.set_worktrees_reordered(worktrees_reordered);
1422        });
1423    }
1424
1425    /// Collect all worktrees, including ones that don't appear in the project panel
1426    pub fn worktrees<'a>(
1427        &self,
1428        cx: &'a App,
1429    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1430        self.worktree_store.read(cx).worktrees()
1431    }
1432
1433    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1434    pub fn visible_worktrees<'a>(
1435        &'a self,
1436        cx: &'a App,
1437    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1438        self.worktree_store.read(cx).visible_worktrees(cx)
1439    }
1440
1441    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1442        self.visible_worktrees(cx)
1443            .map(|tree| tree.read(cx).root_name())
1444    }
1445
1446    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1447        self.worktree_store.read(cx).worktree_for_id(id, cx)
1448    }
1449
1450    pub fn worktree_for_entry(
1451        &self,
1452        entry_id: ProjectEntryId,
1453        cx: &App,
1454    ) -> Option<Entity<Worktree>> {
1455        self.worktree_store
1456            .read(cx)
1457            .worktree_for_entry(entry_id, cx)
1458    }
1459
1460    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1461        self.worktree_for_entry(entry_id, cx)
1462            .map(|worktree| worktree.read(cx).id())
1463    }
1464
1465    /// Checks if the entry is the root of a worktree.
1466    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1467        self.worktree_for_entry(entry_id, cx)
1468            .map(|worktree| {
1469                worktree
1470                    .read(cx)
1471                    .root_entry()
1472                    .is_some_and(|e| e.id == entry_id)
1473            })
1474            .unwrap_or(false)
1475    }
1476
1477    pub fn project_path_git_status(
1478        &self,
1479        project_path: &ProjectPath,
1480        cx: &App,
1481    ) -> Option<FileStatus> {
1482        self.worktree_for_id(project_path.worktree_id, cx)
1483            .and_then(|worktree| worktree.read(cx).status_for_file(&project_path.path))
1484    }
1485
1486    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &App) -> Option<bool> {
1487        paths
1488            .iter()
1489            .map(|path| self.visibility_for_path(path, cx))
1490            .max()
1491            .flatten()
1492    }
1493
1494    pub fn visibility_for_path(&self, path: &Path, cx: &App) -> Option<bool> {
1495        self.worktrees(cx)
1496            .filter_map(|worktree| {
1497                let worktree = worktree.read(cx);
1498                worktree
1499                    .as_local()?
1500                    .contains_abs_path(path)
1501                    .then(|| worktree.is_visible())
1502            })
1503            .max()
1504    }
1505
1506    pub fn create_entry(
1507        &mut self,
1508        project_path: impl Into<ProjectPath>,
1509        is_directory: bool,
1510        cx: &mut Context<Self>,
1511    ) -> Task<Result<CreatedEntry>> {
1512        let project_path = project_path.into();
1513        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1514            return Task::ready(Err(anyhow!(format!(
1515                "No worktree for path {project_path:?}"
1516            ))));
1517        };
1518        worktree.update(cx, |worktree, cx| {
1519            worktree.create_entry(project_path.path, is_directory, cx)
1520        })
1521    }
1522
1523    pub fn copy_entry(
1524        &mut self,
1525        entry_id: ProjectEntryId,
1526        relative_worktree_source_path: Option<PathBuf>,
1527        new_path: impl Into<Arc<Path>>,
1528        cx: &mut Context<Self>,
1529    ) -> Task<Result<Option<Entry>>> {
1530        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1531            return Task::ready(Ok(None));
1532        };
1533        worktree.update(cx, |worktree, cx| {
1534            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1535        })
1536    }
1537
1538    pub fn rename_entry(
1539        &mut self,
1540        entry_id: ProjectEntryId,
1541        new_path: impl Into<Arc<Path>>,
1542        cx: &mut Context<Self>,
1543    ) -> Task<Result<CreatedEntry>> {
1544        let worktree_store = self.worktree_store.read(cx);
1545        let new_path = new_path.into();
1546        let Some((worktree, old_path, is_dir)) = worktree_store
1547            .worktree_and_entry_for_id(entry_id, cx)
1548            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1549        else {
1550            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1551        };
1552
1553        let worktree_id = worktree.read(cx).id();
1554
1555        let lsp_store = self.lsp_store().downgrade();
1556        cx.spawn(|_, mut cx| async move {
1557            let (old_abs_path, new_abs_path) = {
1558                let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
1559                (root_path.join(&old_path), root_path.join(&new_path))
1560            };
1561            LspStore::will_rename_entry(
1562                lsp_store.clone(),
1563                worktree_id,
1564                &old_abs_path,
1565                &new_abs_path,
1566                is_dir,
1567                cx.clone(),
1568            )
1569            .await;
1570
1571            let entry = worktree
1572                .update(&mut cx, |worktree, cx| {
1573                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1574                })?
1575                .await?;
1576
1577            lsp_store
1578                .update(&mut cx, |this, _| {
1579                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1580                })
1581                .ok();
1582            Ok(entry)
1583        })
1584    }
1585
1586    pub fn delete_entry(
1587        &mut self,
1588        entry_id: ProjectEntryId,
1589        trash: bool,
1590        cx: &mut Context<Self>,
1591    ) -> Option<Task<Result<()>>> {
1592        let worktree = self.worktree_for_entry(entry_id, cx)?;
1593        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1594        worktree.update(cx, |worktree, cx| {
1595            worktree.delete_entry(entry_id, trash, cx)
1596        })
1597    }
1598
1599    pub fn expand_entry(
1600        &mut self,
1601        worktree_id: WorktreeId,
1602        entry_id: ProjectEntryId,
1603        cx: &mut Context<Self>,
1604    ) -> Option<Task<Result<()>>> {
1605        let worktree = self.worktree_for_id(worktree_id, cx)?;
1606        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1607    }
1608
1609    pub fn expand_all_for_entry(
1610        &mut self,
1611        worktree_id: WorktreeId,
1612        entry_id: ProjectEntryId,
1613        cx: &mut Context<Self>,
1614    ) -> Option<Task<Result<()>>> {
1615        let worktree = self.worktree_for_id(worktree_id, cx)?;
1616        let task = worktree.update(cx, |worktree, cx| {
1617            worktree.expand_all_for_entry(entry_id, cx)
1618        });
1619        Some(cx.spawn(|this, mut cx| async move {
1620            task.ok_or_else(|| anyhow!("no task"))?.await?;
1621            this.update(&mut cx, |_, cx| {
1622                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
1623            })?;
1624            Ok(())
1625        }))
1626    }
1627
1628    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
1629        if !matches!(self.client_state, ProjectClientState::Local) {
1630            return Err(anyhow!("project was already shared"));
1631        }
1632
1633        self.client_subscriptions.extend([
1634            self.client
1635                .subscribe_to_entity(project_id)?
1636                .set_entity(&cx.entity(), &mut cx.to_async()),
1637            self.client
1638                .subscribe_to_entity(project_id)?
1639                .set_entity(&self.worktree_store, &mut cx.to_async()),
1640            self.client
1641                .subscribe_to_entity(project_id)?
1642                .set_entity(&self.buffer_store, &mut cx.to_async()),
1643            self.client
1644                .subscribe_to_entity(project_id)?
1645                .set_entity(&self.lsp_store, &mut cx.to_async()),
1646            self.client
1647                .subscribe_to_entity(project_id)?
1648                .set_entity(&self.settings_observer, &mut cx.to_async()),
1649        ]);
1650
1651        self.buffer_store.update(cx, |buffer_store, cx| {
1652            buffer_store.shared(project_id, self.client.clone().into(), cx)
1653        });
1654        self.worktree_store.update(cx, |worktree_store, cx| {
1655            worktree_store.shared(project_id, self.client.clone().into(), cx);
1656        });
1657        self.lsp_store.update(cx, |lsp_store, cx| {
1658            lsp_store.shared(project_id, self.client.clone().into(), cx)
1659        });
1660        self.task_store.update(cx, |task_store, cx| {
1661            task_store.shared(project_id, self.client.clone().into(), cx);
1662        });
1663        self.settings_observer.update(cx, |settings_observer, cx| {
1664            settings_observer.shared(project_id, self.client.clone().into(), cx)
1665        });
1666
1667        self.client_state = ProjectClientState::Shared {
1668            remote_id: project_id,
1669        };
1670
1671        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1672        cx.notify();
1673        Ok(())
1674    }
1675
1676    pub fn reshared(
1677        &mut self,
1678        message: proto::ResharedProject,
1679        cx: &mut Context<Self>,
1680    ) -> Result<()> {
1681        self.buffer_store
1682            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1683        self.set_collaborators_from_proto(message.collaborators, cx)?;
1684
1685        self.worktree_store.update(cx, |worktree_store, cx| {
1686            worktree_store.send_project_updates(cx);
1687        });
1688        cx.notify();
1689        cx.emit(Event::Reshared);
1690        Ok(())
1691    }
1692
1693    pub fn rejoined(
1694        &mut self,
1695        message: proto::RejoinedProject,
1696        message_id: u32,
1697        cx: &mut Context<Self>,
1698    ) -> Result<()> {
1699        cx.update_global::<SettingsStore, _>(|store, cx| {
1700            self.worktree_store.update(cx, |worktree_store, cx| {
1701                for worktree in worktree_store.worktrees() {
1702                    store
1703                        .clear_local_settings(worktree.read(cx).id(), cx)
1704                        .log_err();
1705                }
1706            });
1707        });
1708
1709        self.join_project_response_message_id = message_id;
1710        self.set_worktrees_from_proto(message.worktrees, cx)?;
1711        self.set_collaborators_from_proto(message.collaborators, cx)?;
1712        self.lsp_store.update(cx, |lsp_store, _| {
1713            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1714        });
1715        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1716            .unwrap();
1717        cx.emit(Event::Rejoined);
1718        cx.notify();
1719        Ok(())
1720    }
1721
1722    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
1723        self.unshare_internal(cx)?;
1724        cx.notify();
1725        Ok(())
1726    }
1727
1728    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
1729        if self.is_via_collab() {
1730            return Err(anyhow!("attempted to unshare a remote project"));
1731        }
1732
1733        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1734            self.client_state = ProjectClientState::Local;
1735            self.collaborators.clear();
1736            self.client_subscriptions.clear();
1737            self.worktree_store.update(cx, |store, cx| {
1738                store.unshared(cx);
1739            });
1740            self.buffer_store.update(cx, |buffer_store, cx| {
1741                buffer_store.forget_shared_buffers();
1742                buffer_store.unshared(cx)
1743            });
1744            self.task_store.update(cx, |task_store, cx| {
1745                task_store.unshared(cx);
1746            });
1747            self.settings_observer.update(cx, |settings_observer, cx| {
1748                settings_observer.unshared(cx);
1749            });
1750
1751            self.client
1752                .send(proto::UnshareProject {
1753                    project_id: remote_id,
1754                })
1755                .ok();
1756            Ok(())
1757        } else {
1758            Err(anyhow!("attempted to unshare an unshared project"))
1759        }
1760    }
1761
1762    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
1763        if self.is_disconnected(cx) {
1764            return;
1765        }
1766        self.disconnected_from_host_internal(cx);
1767        cx.emit(Event::DisconnectedFromHost);
1768        cx.notify();
1769    }
1770
1771    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
1772        let new_capability =
1773            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1774                Capability::ReadWrite
1775            } else {
1776                Capability::ReadOnly
1777            };
1778        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1779            if *capability == new_capability {
1780                return;
1781            }
1782
1783            *capability = new_capability;
1784            for buffer in self.opened_buffers(cx) {
1785                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1786            }
1787        }
1788    }
1789
1790    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
1791        if let ProjectClientState::Remote {
1792            sharing_has_stopped,
1793            ..
1794        } = &mut self.client_state
1795        {
1796            *sharing_has_stopped = true;
1797            self.collaborators.clear();
1798            self.worktree_store.update(cx, |store, cx| {
1799                store.disconnected_from_host(cx);
1800            });
1801            self.buffer_store.update(cx, |buffer_store, cx| {
1802                buffer_store.disconnected_from_host(cx)
1803            });
1804            self.lsp_store
1805                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1806        }
1807    }
1808
1809    pub fn close(&mut self, cx: &mut Context<Self>) {
1810        cx.emit(Event::Closed);
1811    }
1812
1813    pub fn is_disconnected(&self, cx: &App) -> bool {
1814        match &self.client_state {
1815            ProjectClientState::Remote {
1816                sharing_has_stopped,
1817                ..
1818            } => *sharing_has_stopped,
1819            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1820            _ => false,
1821        }
1822    }
1823
1824    fn ssh_is_disconnected(&self, cx: &App) -> bool {
1825        self.ssh_client
1826            .as_ref()
1827            .map(|ssh| ssh.read(cx).is_disconnected())
1828            .unwrap_or(false)
1829    }
1830
1831    pub fn capability(&self) -> Capability {
1832        match &self.client_state {
1833            ProjectClientState::Remote { capability, .. } => *capability,
1834            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1835        }
1836    }
1837
1838    pub fn is_read_only(&self, cx: &App) -> bool {
1839        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1840    }
1841
1842    pub fn is_local(&self) -> bool {
1843        match &self.client_state {
1844            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1845                self.ssh_client.is_none()
1846            }
1847            ProjectClientState::Remote { .. } => false,
1848        }
1849    }
1850
1851    pub fn is_via_ssh(&self) -> bool {
1852        match &self.client_state {
1853            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1854                self.ssh_client.is_some()
1855            }
1856            ProjectClientState::Remote { .. } => false,
1857        }
1858    }
1859
1860    pub fn is_via_collab(&self) -> bool {
1861        match &self.client_state {
1862            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1863            ProjectClientState::Remote { .. } => true,
1864        }
1865    }
1866
1867    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
1868        self.buffer_store
1869            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1870    }
1871
1872    pub fn create_local_buffer(
1873        &mut self,
1874        text: &str,
1875        language: Option<Arc<Language>>,
1876        cx: &mut Context<Self>,
1877    ) -> Entity<Buffer> {
1878        if self.is_via_collab() || self.is_via_ssh() {
1879            panic!("called create_local_buffer on a remote project")
1880        }
1881        self.buffer_store.update(cx, |buffer_store, cx| {
1882            buffer_store.create_local_buffer(text, language, cx)
1883        })
1884    }
1885
1886    pub fn open_path(
1887        &mut self,
1888        path: ProjectPath,
1889        cx: &mut Context<Self>,
1890    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
1891        let task = self.open_buffer(path.clone(), cx);
1892        cx.spawn(move |_, cx| async move {
1893            let buffer = task.await?;
1894            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1895                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1896            })?;
1897
1898            let buffer: &AnyEntity = &buffer;
1899            Ok((project_entry_id, buffer.clone()))
1900        })
1901    }
1902
1903    pub fn open_local_buffer(
1904        &mut self,
1905        abs_path: impl AsRef<Path>,
1906        cx: &mut Context<Self>,
1907    ) -> Task<Result<Entity<Buffer>>> {
1908        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1909            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1910        } else {
1911            Task::ready(Err(anyhow!("no such path")))
1912        }
1913    }
1914
1915    #[cfg(any(test, feature = "test-support"))]
1916    pub fn open_local_buffer_with_lsp(
1917        &mut self,
1918        abs_path: impl AsRef<Path>,
1919        cx: &mut Context<Self>,
1920    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1921        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1922            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
1923        } else {
1924            Task::ready(Err(anyhow!("no such path")))
1925        }
1926    }
1927
1928    pub fn open_buffer(
1929        &mut self,
1930        path: impl Into<ProjectPath>,
1931        cx: &mut Context<Self>,
1932    ) -> Task<Result<Entity<Buffer>>> {
1933        if self.is_disconnected(cx) {
1934            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1935        }
1936
1937        self.buffer_store.update(cx, |buffer_store, cx| {
1938            buffer_store.open_buffer(path.into(), cx)
1939        })
1940    }
1941
1942    #[cfg(any(test, feature = "test-support"))]
1943    pub fn open_buffer_with_lsp(
1944        &mut self,
1945        path: impl Into<ProjectPath>,
1946        cx: &mut Context<Self>,
1947    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1948        let buffer = self.open_buffer(path, cx);
1949        let lsp_store = self.lsp_store().clone();
1950        cx.spawn(|_, mut cx| async move {
1951            let buffer = buffer.await?;
1952            let handle = lsp_store.update(&mut cx, |lsp_store, cx| {
1953                lsp_store.register_buffer_with_language_servers(&buffer, cx)
1954            })?;
1955            Ok((buffer, handle))
1956        })
1957    }
1958
1959    pub fn open_unstaged_diff(
1960        &mut self,
1961        buffer: Entity<Buffer>,
1962        cx: &mut Context<Self>,
1963    ) -> Task<Result<Entity<BufferDiff>>> {
1964        if self.is_disconnected(cx) {
1965            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1966        }
1967
1968        self.buffer_store.update(cx, |buffer_store, cx| {
1969            buffer_store.open_unstaged_diff(buffer, cx)
1970        })
1971    }
1972
1973    pub fn open_uncommitted_diff(
1974        &mut self,
1975        buffer: Entity<Buffer>,
1976        cx: &mut Context<Self>,
1977    ) -> Task<Result<Entity<BufferDiff>>> {
1978        if self.is_disconnected(cx) {
1979            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1980        }
1981
1982        self.buffer_store.update(cx, |buffer_store, cx| {
1983            buffer_store.open_uncommitted_diff(buffer, cx)
1984        })
1985    }
1986
1987    pub fn open_buffer_by_id(
1988        &mut self,
1989        id: BufferId,
1990        cx: &mut Context<Self>,
1991    ) -> Task<Result<Entity<Buffer>>> {
1992        if let Some(buffer) = self.buffer_for_id(id, cx) {
1993            Task::ready(Ok(buffer))
1994        } else if self.is_local() || self.is_via_ssh() {
1995            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1996        } else if let Some(project_id) = self.remote_id() {
1997            let request = self.client.request(proto::OpenBufferById {
1998                project_id,
1999                id: id.into(),
2000            });
2001            cx.spawn(move |project, mut cx| async move {
2002                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2003                project
2004                    .update(&mut cx, |project, cx| {
2005                        project.buffer_store.update(cx, |buffer_store, cx| {
2006                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2007                        })
2008                    })?
2009                    .await
2010            })
2011        } else {
2012            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2013        }
2014    }
2015
2016    pub fn save_buffers(
2017        &self,
2018        buffers: HashSet<Entity<Buffer>>,
2019        cx: &mut Context<Self>,
2020    ) -> Task<Result<()>> {
2021        cx.spawn(move |this, mut cx| async move {
2022            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2023                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
2024                    .ok()
2025            });
2026            try_join_all(save_tasks).await?;
2027            Ok(())
2028        })
2029    }
2030
2031    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2032        self.buffer_store
2033            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2034    }
2035
2036    pub fn save_buffer_as(
2037        &mut self,
2038        buffer: Entity<Buffer>,
2039        path: ProjectPath,
2040        cx: &mut Context<Self>,
2041    ) -> Task<Result<()>> {
2042        self.buffer_store.update(cx, |buffer_store, cx| {
2043            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2044        })
2045    }
2046
2047    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2048        self.buffer_store.read(cx).get_by_path(path, cx)
2049    }
2050
2051    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2052        {
2053            let mut remotely_created_models = self.remotely_created_models.lock();
2054            if remotely_created_models.retain_count > 0 {
2055                remotely_created_models.buffers.push(buffer.clone())
2056            }
2057        }
2058
2059        self.request_buffer_diff_recalculation(buffer, cx);
2060
2061        cx.subscribe(buffer, |this, buffer, event, cx| {
2062            this.on_buffer_event(buffer, event, cx);
2063        })
2064        .detach();
2065
2066        Ok(())
2067    }
2068
2069    pub fn open_image(
2070        &mut self,
2071        path: impl Into<ProjectPath>,
2072        cx: &mut Context<Self>,
2073    ) -> Task<Result<Entity<ImageItem>>> {
2074        if self.is_disconnected(cx) {
2075            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2076        }
2077
2078        self.image_store.update(cx, |image_store, cx| {
2079            image_store.open_image(path.into(), cx)
2080        })
2081    }
2082
2083    async fn send_buffer_ordered_messages(
2084        this: WeakEntity<Self>,
2085        rx: UnboundedReceiver<BufferOrderedMessage>,
2086        mut cx: AsyncApp,
2087    ) -> Result<()> {
2088        const MAX_BATCH_SIZE: usize = 128;
2089
2090        let mut operations_by_buffer_id = HashMap::default();
2091        async fn flush_operations(
2092            this: &WeakEntity<Project>,
2093            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2094            needs_resync_with_host: &mut bool,
2095            is_local: bool,
2096            cx: &mut AsyncApp,
2097        ) -> Result<()> {
2098            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2099                let request = this.update(cx, |this, _| {
2100                    let project_id = this.remote_id()?;
2101                    Some(this.client.request(proto::UpdateBuffer {
2102                        buffer_id: buffer_id.into(),
2103                        project_id,
2104                        operations,
2105                    }))
2106                })?;
2107                if let Some(request) = request {
2108                    if request.await.is_err() && !is_local {
2109                        *needs_resync_with_host = true;
2110                        break;
2111                    }
2112                }
2113            }
2114            Ok(())
2115        }
2116
2117        let mut needs_resync_with_host = false;
2118        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2119
2120        while let Some(changes) = changes.next().await {
2121            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2122
2123            for change in changes {
2124                match change {
2125                    BufferOrderedMessage::Operation {
2126                        buffer_id,
2127                        operation,
2128                    } => {
2129                        if needs_resync_with_host {
2130                            continue;
2131                        }
2132
2133                        operations_by_buffer_id
2134                            .entry(buffer_id)
2135                            .or_insert(Vec::new())
2136                            .push(operation);
2137                    }
2138
2139                    BufferOrderedMessage::Resync => {
2140                        operations_by_buffer_id.clear();
2141                        if this
2142                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2143                            .await
2144                            .is_ok()
2145                        {
2146                            needs_resync_with_host = false;
2147                        }
2148                    }
2149
2150                    BufferOrderedMessage::LanguageServerUpdate {
2151                        language_server_id,
2152                        message,
2153                    } => {
2154                        flush_operations(
2155                            &this,
2156                            &mut operations_by_buffer_id,
2157                            &mut needs_resync_with_host,
2158                            is_local,
2159                            &mut cx,
2160                        )
2161                        .await?;
2162
2163                        this.update(&mut cx, |this, _| {
2164                            if let Some(project_id) = this.remote_id() {
2165                                this.client
2166                                    .send(proto::UpdateLanguageServer {
2167                                        project_id,
2168                                        language_server_id: language_server_id.0 as u64,
2169                                        variant: Some(message),
2170                                    })
2171                                    .log_err();
2172                            }
2173                        })?;
2174                    }
2175                }
2176            }
2177
2178            flush_operations(
2179                &this,
2180                &mut operations_by_buffer_id,
2181                &mut needs_resync_with_host,
2182                is_local,
2183                &mut cx,
2184            )
2185            .await?;
2186        }
2187
2188        Ok(())
2189    }
2190
2191    fn on_buffer_store_event(
2192        &mut self,
2193        _: Entity<BufferStore>,
2194        event: &BufferStoreEvent,
2195        cx: &mut Context<Self>,
2196    ) {
2197        match event {
2198            BufferStoreEvent::BufferAdded(buffer) => {
2199                self.register_buffer(buffer, cx).log_err();
2200            }
2201            BufferStoreEvent::BufferChangedFilePath { .. } => {}
2202            BufferStoreEvent::BufferDropped(buffer_id) => {
2203                if let Some(ref ssh_client) = self.ssh_client {
2204                    ssh_client
2205                        .read(cx)
2206                        .proto_client()
2207                        .send(proto::CloseBuffer {
2208                            project_id: 0,
2209                            buffer_id: buffer_id.to_proto(),
2210                        })
2211                        .log_err();
2212                }
2213            }
2214        }
2215    }
2216
2217    fn on_image_store_event(
2218        &mut self,
2219        _: Entity<ImageStore>,
2220        event: &ImageStoreEvent,
2221        cx: &mut Context<Self>,
2222    ) {
2223        match event {
2224            ImageStoreEvent::ImageAdded(image) => {
2225                cx.subscribe(image, |this, image, event, cx| {
2226                    this.on_image_event(image, event, cx);
2227                })
2228                .detach();
2229            }
2230        }
2231    }
2232
2233    fn on_lsp_store_event(
2234        &mut self,
2235        _: Entity<LspStore>,
2236        event: &LspStoreEvent,
2237        cx: &mut Context<Self>,
2238    ) {
2239        match event {
2240            LspStoreEvent::DiagnosticsUpdated {
2241                language_server_id,
2242                path,
2243            } => cx.emit(Event::DiagnosticsUpdated {
2244                path: path.clone(),
2245                language_server_id: *language_server_id,
2246            }),
2247            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2248                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2249            ),
2250            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2251                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2252            }
2253            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2254                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2255            ),
2256            LspStoreEvent::LanguageDetected {
2257                buffer,
2258                new_language,
2259            } => {
2260                let Some(_) = new_language else {
2261                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2262                    return;
2263                };
2264            }
2265            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2266            LspStoreEvent::LanguageServerPrompt(prompt) => {
2267                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2268            }
2269            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2270                cx.emit(Event::DiskBasedDiagnosticsStarted {
2271                    language_server_id: *language_server_id,
2272                });
2273            }
2274            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2275                cx.emit(Event::DiskBasedDiagnosticsFinished {
2276                    language_server_id: *language_server_id,
2277                });
2278            }
2279            LspStoreEvent::LanguageServerUpdate {
2280                language_server_id,
2281                message,
2282            } => {
2283                if self.is_local() {
2284                    self.enqueue_buffer_ordered_message(
2285                        BufferOrderedMessage::LanguageServerUpdate {
2286                            language_server_id: *language_server_id,
2287                            message: message.clone(),
2288                        },
2289                    )
2290                    .ok();
2291                }
2292            }
2293            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2294                notification_id: "lsp".into(),
2295                message: message.clone(),
2296            }),
2297            LspStoreEvent::SnippetEdit {
2298                buffer_id,
2299                edits,
2300                most_recent_edit,
2301            } => {
2302                if most_recent_edit.replica_id == self.replica_id() {
2303                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2304                }
2305            }
2306        }
2307    }
2308
2309    fn on_ssh_event(
2310        &mut self,
2311        _: Entity<SshRemoteClient>,
2312        event: &remote::SshRemoteEvent,
2313        cx: &mut Context<Self>,
2314    ) {
2315        match event {
2316            remote::SshRemoteEvent::Disconnected => {
2317                // if self.is_via_ssh() {
2318                // self.collaborators.clear();
2319                self.worktree_store.update(cx, |store, cx| {
2320                    store.disconnected_from_host(cx);
2321                });
2322                self.buffer_store.update(cx, |buffer_store, cx| {
2323                    buffer_store.disconnected_from_host(cx)
2324                });
2325                self.lsp_store.update(cx, |lsp_store, _cx| {
2326                    lsp_store.disconnected_from_ssh_remote()
2327                });
2328                cx.emit(Event::DisconnectedFromSshRemote);
2329            }
2330        }
2331    }
2332
2333    fn on_settings_observer_event(
2334        &mut self,
2335        _: Entity<SettingsObserver>,
2336        event: &SettingsObserverEvent,
2337        cx: &mut Context<Self>,
2338    ) {
2339        match event {
2340            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2341                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2342                    let message =
2343                        format!("Failed to set local settings in {:?}:\n{}", path, message);
2344                    cx.emit(Event::Toast {
2345                        notification_id: "local-settings".into(),
2346                        message,
2347                    });
2348                }
2349                Ok(_) => cx.emit(Event::HideToast {
2350                    notification_id: "local-settings".into(),
2351                }),
2352                Err(_) => {}
2353            },
2354        }
2355    }
2356
2357    fn on_worktree_store_event(
2358        &mut self,
2359        _: Entity<WorktreeStore>,
2360        event: &WorktreeStoreEvent,
2361        cx: &mut Context<Self>,
2362    ) {
2363        match event {
2364            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2365                self.on_worktree_added(worktree, cx);
2366                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2367            }
2368            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2369                cx.emit(Event::WorktreeRemoved(*id));
2370            }
2371            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2372                self.on_worktree_released(*id, cx);
2373            }
2374            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2375            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2376            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2377                self.client()
2378                    .telemetry()
2379                    .report_discovered_project_events(*worktree_id, changes);
2380                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2381            }
2382            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id) => {
2383                cx.emit(Event::WorktreeUpdatedGitRepositories(*worktree_id))
2384            }
2385            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2386                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2387            }
2388        }
2389    }
2390
2391    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
2392        {
2393            let mut remotely_created_models = self.remotely_created_models.lock();
2394            if remotely_created_models.retain_count > 0 {
2395                remotely_created_models.worktrees.push(worktree.clone())
2396            }
2397        }
2398        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2399        cx.notify();
2400    }
2401
2402    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2403        if let Some(ssh) = &self.ssh_client {
2404            ssh.read(cx)
2405                .proto_client()
2406                .send(proto::RemoveWorktree {
2407                    worktree_id: id_to_remove.to_proto(),
2408                })
2409                .log_err();
2410        }
2411
2412        cx.notify();
2413    }
2414
2415    fn on_buffer_event(
2416        &mut self,
2417        buffer: Entity<Buffer>,
2418        event: &BufferEvent,
2419        cx: &mut Context<Self>,
2420    ) -> Option<()> {
2421        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2422            self.request_buffer_diff_recalculation(&buffer, cx);
2423        }
2424
2425        let buffer_id = buffer.read(cx).remote_id();
2426        match event {
2427            BufferEvent::ReloadNeeded => {
2428                if !self.is_via_collab() {
2429                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2430                        .detach_and_log_err(cx);
2431                }
2432            }
2433            BufferEvent::Operation {
2434                operation,
2435                is_local: true,
2436            } => {
2437                let operation = language::proto::serialize_operation(operation);
2438
2439                if let Some(ssh) = &self.ssh_client {
2440                    ssh.read(cx)
2441                        .proto_client()
2442                        .send(proto::UpdateBuffer {
2443                            project_id: 0,
2444                            buffer_id: buffer_id.to_proto(),
2445                            operations: vec![operation.clone()],
2446                        })
2447                        .ok();
2448                }
2449
2450                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2451                    buffer_id,
2452                    operation,
2453                })
2454                .ok();
2455            }
2456
2457            _ => {}
2458        }
2459
2460        None
2461    }
2462
2463    fn on_image_event(
2464        &mut self,
2465        image: Entity<ImageItem>,
2466        event: &ImageItemEvent,
2467        cx: &mut Context<Self>,
2468    ) -> Option<()> {
2469        match event {
2470            ImageItemEvent::ReloadNeeded => {
2471                if !self.is_via_collab() {
2472                    self.reload_images([image.clone()].into_iter().collect(), cx)
2473                        .detach_and_log_err(cx);
2474                }
2475            }
2476            _ => {}
2477        }
2478
2479        None
2480    }
2481
2482    fn request_buffer_diff_recalculation(
2483        &mut self,
2484        buffer: &Entity<Buffer>,
2485        cx: &mut Context<Self>,
2486    ) {
2487        self.buffers_needing_diff.insert(buffer.downgrade());
2488        let first_insertion = self.buffers_needing_diff.len() == 1;
2489
2490        let settings = ProjectSettings::get_global(cx);
2491        let delay = if let Some(delay) = settings.git.gutter_debounce {
2492            delay
2493        } else {
2494            if first_insertion {
2495                let this = cx.weak_entity();
2496                cx.defer(move |cx| {
2497                    if let Some(this) = this.upgrade() {
2498                        this.update(cx, |this, cx| {
2499                            this.recalculate_buffer_diffs(cx).detach();
2500                        });
2501                    }
2502                });
2503            }
2504            return;
2505        };
2506
2507        const MIN_DELAY: u64 = 50;
2508        let delay = delay.max(MIN_DELAY);
2509        let duration = Duration::from_millis(delay);
2510
2511        self.git_diff_debouncer
2512            .fire_new(duration, cx, move |this, cx| {
2513                this.recalculate_buffer_diffs(cx)
2514            });
2515    }
2516
2517    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2518        cx.spawn(move |this, mut cx| async move {
2519            loop {
2520                let task = this
2521                    .update(&mut cx, |this, cx| {
2522                        let buffers = this
2523                            .buffers_needing_diff
2524                            .drain()
2525                            .filter_map(|buffer| buffer.upgrade())
2526                            .collect::<Vec<_>>();
2527                        if buffers.is_empty() {
2528                            None
2529                        } else {
2530                            Some(this.buffer_store.update(cx, |buffer_store, cx| {
2531                                buffer_store.recalculate_buffer_diffs(buffers, cx)
2532                            }))
2533                        }
2534                    })
2535                    .ok()
2536                    .flatten();
2537
2538                if let Some(task) = task {
2539                    task.await;
2540                } else {
2541                    break;
2542                }
2543            }
2544        })
2545    }
2546
2547    pub fn set_language_for_buffer(
2548        &mut self,
2549        buffer: &Entity<Buffer>,
2550        new_language: Arc<Language>,
2551        cx: &mut Context<Self>,
2552    ) {
2553        self.lsp_store.update(cx, |lsp_store, cx| {
2554            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2555        })
2556    }
2557
2558    pub fn restart_language_servers_for_buffers(
2559        &mut self,
2560        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2561        cx: &mut Context<Self>,
2562    ) {
2563        self.lsp_store.update(cx, |lsp_store, cx| {
2564            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2565        })
2566    }
2567
2568    pub fn cancel_language_server_work_for_buffers(
2569        &mut self,
2570        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2571        cx: &mut Context<Self>,
2572    ) {
2573        self.lsp_store.update(cx, |lsp_store, cx| {
2574            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2575        })
2576    }
2577
2578    pub fn cancel_language_server_work(
2579        &mut self,
2580        server_id: LanguageServerId,
2581        token_to_cancel: Option<String>,
2582        cx: &mut Context<Self>,
2583    ) {
2584        self.lsp_store.update(cx, |lsp_store, cx| {
2585            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2586        })
2587    }
2588
2589    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2590        self.buffer_ordered_messages_tx
2591            .unbounded_send(message)
2592            .map_err(|e| anyhow!(e))
2593    }
2594
2595    pub fn available_toolchains(
2596        &self,
2597        worktree_id: WorktreeId,
2598        language_name: LanguageName,
2599        cx: &App,
2600    ) -> Task<Option<ToolchainList>> {
2601        if let Some(toolchain_store) = self.toolchain_store.clone() {
2602            cx.spawn(|cx| async move {
2603                cx.update(|cx| {
2604                    toolchain_store
2605                        .read(cx)
2606                        .list_toolchains(worktree_id, language_name, cx)
2607                })
2608                .ok()?
2609                .await
2610            })
2611        } else {
2612            Task::ready(None)
2613        }
2614    }
2615
2616    pub async fn toolchain_term(
2617        languages: Arc<LanguageRegistry>,
2618        language_name: LanguageName,
2619    ) -> Option<SharedString> {
2620        languages
2621            .language_for_name(language_name.as_ref())
2622            .await
2623            .ok()?
2624            .toolchain_lister()
2625            .map(|lister| lister.term())
2626    }
2627
2628    pub fn activate_toolchain(
2629        &self,
2630        worktree_id: WorktreeId,
2631        toolchain: Toolchain,
2632        cx: &mut App,
2633    ) -> Task<Option<()>> {
2634        let Some(toolchain_store) = self.toolchain_store.clone() else {
2635            return Task::ready(None);
2636        };
2637        toolchain_store.update(cx, |this, cx| {
2638            this.activate_toolchain(worktree_id, toolchain, cx)
2639        })
2640    }
2641    pub fn active_toolchain(
2642        &self,
2643        worktree_id: WorktreeId,
2644        language_name: LanguageName,
2645        cx: &App,
2646    ) -> Task<Option<Toolchain>> {
2647        let Some(toolchain_store) = self.toolchain_store.clone() else {
2648            return Task::ready(None);
2649        };
2650        toolchain_store
2651            .read(cx)
2652            .active_toolchain(worktree_id, language_name, cx)
2653    }
2654    pub fn language_server_statuses<'a>(
2655        &'a self,
2656        cx: &'a App,
2657    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2658        self.lsp_store.read(cx).language_server_statuses()
2659    }
2660
2661    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
2662        self.lsp_store.read(cx).last_formatting_failure()
2663    }
2664
2665    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
2666        self.lsp_store
2667            .update(cx, |store, _| store.reset_last_formatting_failure());
2668    }
2669
2670    pub fn reload_buffers(
2671        &self,
2672        buffers: HashSet<Entity<Buffer>>,
2673        push_to_history: bool,
2674        cx: &mut Context<Self>,
2675    ) -> Task<Result<ProjectTransaction>> {
2676        self.buffer_store.update(cx, |buffer_store, cx| {
2677            buffer_store.reload_buffers(buffers, push_to_history, cx)
2678        })
2679    }
2680
2681    pub fn reload_images(
2682        &self,
2683        images: HashSet<Entity<ImageItem>>,
2684        cx: &mut Context<Self>,
2685    ) -> Task<Result<()>> {
2686        self.image_store
2687            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
2688    }
2689
2690    pub fn format(
2691        &mut self,
2692        buffers: HashSet<Entity<Buffer>>,
2693        target: LspFormatTarget,
2694        push_to_history: bool,
2695        trigger: lsp_store::FormatTrigger,
2696        cx: &mut Context<Project>,
2697    ) -> Task<anyhow::Result<ProjectTransaction>> {
2698        self.lsp_store.update(cx, |lsp_store, cx| {
2699            lsp_store.format(buffers, target, push_to_history, trigger, cx)
2700        })
2701    }
2702
2703    #[inline(never)]
2704    fn definition_impl(
2705        &mut self,
2706        buffer: &Entity<Buffer>,
2707        position: PointUtf16,
2708        cx: &mut Context<Self>,
2709    ) -> Task<Result<Vec<LocationLink>>> {
2710        self.request_lsp(
2711            buffer.clone(),
2712            LanguageServerToQuery::Primary,
2713            GetDefinition { position },
2714            cx,
2715        )
2716    }
2717    pub fn definition<T: ToPointUtf16>(
2718        &mut self,
2719        buffer: &Entity<Buffer>,
2720        position: T,
2721        cx: &mut Context<Self>,
2722    ) -> Task<Result<Vec<LocationLink>>> {
2723        let position = position.to_point_utf16(buffer.read(cx));
2724        self.definition_impl(buffer, position, cx)
2725    }
2726
2727    fn declaration_impl(
2728        &mut self,
2729        buffer: &Entity<Buffer>,
2730        position: PointUtf16,
2731        cx: &mut Context<Self>,
2732    ) -> Task<Result<Vec<LocationLink>>> {
2733        self.request_lsp(
2734            buffer.clone(),
2735            LanguageServerToQuery::Primary,
2736            GetDeclaration { position },
2737            cx,
2738        )
2739    }
2740
2741    pub fn declaration<T: ToPointUtf16>(
2742        &mut self,
2743        buffer: &Entity<Buffer>,
2744        position: T,
2745        cx: &mut Context<Self>,
2746    ) -> Task<Result<Vec<LocationLink>>> {
2747        let position = position.to_point_utf16(buffer.read(cx));
2748        self.declaration_impl(buffer, position, cx)
2749    }
2750
2751    fn type_definition_impl(
2752        &mut self,
2753        buffer: &Entity<Buffer>,
2754        position: PointUtf16,
2755        cx: &mut Context<Self>,
2756    ) -> Task<Result<Vec<LocationLink>>> {
2757        self.request_lsp(
2758            buffer.clone(),
2759            LanguageServerToQuery::Primary,
2760            GetTypeDefinition { position },
2761            cx,
2762        )
2763    }
2764
2765    pub fn type_definition<T: ToPointUtf16>(
2766        &mut self,
2767        buffer: &Entity<Buffer>,
2768        position: T,
2769        cx: &mut Context<Self>,
2770    ) -> Task<Result<Vec<LocationLink>>> {
2771        let position = position.to_point_utf16(buffer.read(cx));
2772        self.type_definition_impl(buffer, position, cx)
2773    }
2774
2775    pub fn implementation<T: ToPointUtf16>(
2776        &mut self,
2777        buffer: &Entity<Buffer>,
2778        position: T,
2779        cx: &mut Context<Self>,
2780    ) -> Task<Result<Vec<LocationLink>>> {
2781        let position = position.to_point_utf16(buffer.read(cx));
2782        self.request_lsp(
2783            buffer.clone(),
2784            LanguageServerToQuery::Primary,
2785            GetImplementation { position },
2786            cx,
2787        )
2788    }
2789
2790    pub fn references<T: ToPointUtf16>(
2791        &mut self,
2792        buffer: &Entity<Buffer>,
2793        position: T,
2794        cx: &mut Context<Self>,
2795    ) -> Task<Result<Vec<Location>>> {
2796        let position = position.to_point_utf16(buffer.read(cx));
2797        self.request_lsp(
2798            buffer.clone(),
2799            LanguageServerToQuery::Primary,
2800            GetReferences { position },
2801            cx,
2802        )
2803    }
2804
2805    fn document_highlights_impl(
2806        &mut self,
2807        buffer: &Entity<Buffer>,
2808        position: PointUtf16,
2809        cx: &mut Context<Self>,
2810    ) -> Task<Result<Vec<DocumentHighlight>>> {
2811        self.request_lsp(
2812            buffer.clone(),
2813            LanguageServerToQuery::Primary,
2814            GetDocumentHighlights { position },
2815            cx,
2816        )
2817    }
2818
2819    pub fn document_highlights<T: ToPointUtf16>(
2820        &mut self,
2821        buffer: &Entity<Buffer>,
2822        position: T,
2823        cx: &mut Context<Self>,
2824    ) -> Task<Result<Vec<DocumentHighlight>>> {
2825        let position = position.to_point_utf16(buffer.read(cx));
2826        self.document_highlights_impl(buffer, position, cx)
2827    }
2828
2829    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
2830        self.lsp_store
2831            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2832    }
2833
2834    pub fn open_buffer_for_symbol(
2835        &mut self,
2836        symbol: &Symbol,
2837        cx: &mut Context<Self>,
2838    ) -> Task<Result<Entity<Buffer>>> {
2839        self.lsp_store.update(cx, |lsp_store, cx| {
2840            lsp_store.open_buffer_for_symbol(symbol, cx)
2841        })
2842    }
2843
2844    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2845        let guard = self.retain_remotely_created_models(cx);
2846        let Some(ssh_client) = self.ssh_client.as_ref() else {
2847            return Task::ready(Err(anyhow!("not an ssh project")));
2848        };
2849
2850        let proto_client = ssh_client.read(cx).proto_client();
2851
2852        cx.spawn(|project, mut cx| async move {
2853            let buffer = proto_client
2854                .request(proto::OpenServerSettings {
2855                    project_id: SSH_PROJECT_ID,
2856                })
2857                .await?;
2858
2859            let buffer = project
2860                .update(&mut cx, |project, cx| {
2861                    project.buffer_store.update(cx, |buffer_store, cx| {
2862                        anyhow::Ok(
2863                            buffer_store
2864                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
2865                        )
2866                    })
2867                })??
2868                .await;
2869
2870            drop(guard);
2871            buffer
2872        })
2873    }
2874
2875    pub fn open_local_buffer_via_lsp(
2876        &mut self,
2877        abs_path: lsp::Url,
2878        language_server_id: LanguageServerId,
2879        language_server_name: LanguageServerName,
2880        cx: &mut Context<Self>,
2881    ) -> Task<Result<Entity<Buffer>>> {
2882        self.lsp_store.update(cx, |lsp_store, cx| {
2883            lsp_store.open_local_buffer_via_lsp(
2884                abs_path,
2885                language_server_id,
2886                language_server_name,
2887                cx,
2888            )
2889        })
2890    }
2891
2892    pub fn signature_help<T: ToPointUtf16>(
2893        &self,
2894        buffer: &Entity<Buffer>,
2895        position: T,
2896        cx: &mut Context<Self>,
2897    ) -> Task<Vec<SignatureHelp>> {
2898        self.lsp_store.update(cx, |lsp_store, cx| {
2899            lsp_store.signature_help(buffer, position, cx)
2900        })
2901    }
2902
2903    pub fn hover<T: ToPointUtf16>(
2904        &self,
2905        buffer: &Entity<Buffer>,
2906        position: T,
2907        cx: &mut Context<Self>,
2908    ) -> Task<Vec<Hover>> {
2909        let position = position.to_point_utf16(buffer.read(cx));
2910        self.lsp_store
2911            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2912    }
2913
2914    pub fn linked_edit(
2915        &self,
2916        buffer: &Entity<Buffer>,
2917        position: Anchor,
2918        cx: &mut Context<Self>,
2919    ) -> Task<Result<Vec<Range<Anchor>>>> {
2920        self.lsp_store.update(cx, |lsp_store, cx| {
2921            lsp_store.linked_edit(buffer, position, cx)
2922        })
2923    }
2924
2925    pub fn completions<T: ToOffset + ToPointUtf16>(
2926        &self,
2927        buffer: &Entity<Buffer>,
2928        position: T,
2929        context: CompletionContext,
2930        cx: &mut Context<Self>,
2931    ) -> Task<Result<Vec<Completion>>> {
2932        let position = position.to_point_utf16(buffer.read(cx));
2933        self.lsp_store.update(cx, |lsp_store, cx| {
2934            lsp_store.completions(buffer, position, context, cx)
2935        })
2936    }
2937
2938    pub fn code_actions<T: Clone + ToOffset>(
2939        &mut self,
2940        buffer_handle: &Entity<Buffer>,
2941        range: Range<T>,
2942        kinds: Option<Vec<CodeActionKind>>,
2943        cx: &mut Context<Self>,
2944    ) -> Task<Result<Vec<CodeAction>>> {
2945        let buffer = buffer_handle.read(cx);
2946        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2947        self.lsp_store.update(cx, |lsp_store, cx| {
2948            lsp_store.code_actions(buffer_handle, range, kinds, cx)
2949        })
2950    }
2951
2952    pub fn apply_code_action(
2953        &self,
2954        buffer_handle: Entity<Buffer>,
2955        action: CodeAction,
2956        push_to_history: bool,
2957        cx: &mut Context<Self>,
2958    ) -> Task<Result<ProjectTransaction>> {
2959        self.lsp_store.update(cx, |lsp_store, cx| {
2960            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2961        })
2962    }
2963
2964    fn prepare_rename_impl(
2965        &mut self,
2966        buffer: Entity<Buffer>,
2967        position: PointUtf16,
2968        cx: &mut Context<Self>,
2969    ) -> Task<Result<PrepareRenameResponse>> {
2970        self.request_lsp(
2971            buffer,
2972            LanguageServerToQuery::Primary,
2973            PrepareRename { position },
2974            cx,
2975        )
2976    }
2977    pub fn prepare_rename<T: ToPointUtf16>(
2978        &mut self,
2979        buffer: Entity<Buffer>,
2980        position: T,
2981        cx: &mut Context<Self>,
2982    ) -> Task<Result<PrepareRenameResponse>> {
2983        let position = position.to_point_utf16(buffer.read(cx));
2984        self.prepare_rename_impl(buffer, position, cx)
2985    }
2986
2987    pub fn perform_rename<T: ToPointUtf16>(
2988        &mut self,
2989        buffer: Entity<Buffer>,
2990        position: T,
2991        new_name: String,
2992        cx: &mut Context<Self>,
2993    ) -> Task<Result<ProjectTransaction>> {
2994        let push_to_history = true;
2995        let position = position.to_point_utf16(buffer.read(cx));
2996        self.request_lsp(
2997            buffer,
2998            LanguageServerToQuery::Primary,
2999            PerformRename {
3000                position,
3001                new_name,
3002                push_to_history,
3003            },
3004            cx,
3005        )
3006    }
3007
3008    pub fn on_type_format<T: ToPointUtf16>(
3009        &mut self,
3010        buffer: Entity<Buffer>,
3011        position: T,
3012        trigger: String,
3013        push_to_history: bool,
3014        cx: &mut Context<Self>,
3015    ) -> Task<Result<Option<Transaction>>> {
3016        self.lsp_store.update(cx, |lsp_store, cx| {
3017            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3018        })
3019    }
3020
3021    pub fn inlay_hints<T: ToOffset>(
3022        &mut self,
3023        buffer_handle: Entity<Buffer>,
3024        range: Range<T>,
3025        cx: &mut Context<Self>,
3026    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3027        let buffer = buffer_handle.read(cx);
3028        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3029        self.lsp_store.update(cx, |lsp_store, cx| {
3030            lsp_store.inlay_hints(buffer_handle, range, cx)
3031        })
3032    }
3033
3034    pub fn resolve_inlay_hint(
3035        &self,
3036        hint: InlayHint,
3037        buffer_handle: Entity<Buffer>,
3038        server_id: LanguageServerId,
3039        cx: &mut Context<Self>,
3040    ) -> Task<anyhow::Result<InlayHint>> {
3041        self.lsp_store.update(cx, |lsp_store, cx| {
3042            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3043        })
3044    }
3045
3046    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3047        let (result_tx, result_rx) = smol::channel::unbounded();
3048
3049        let matching_buffers_rx = if query.is_opened_only() {
3050            self.sort_search_candidates(&query, cx)
3051        } else {
3052            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3053        };
3054
3055        cx.spawn(|_, cx| async move {
3056            let mut range_count = 0;
3057            let mut buffer_count = 0;
3058            let mut limit_reached = false;
3059            let query = Arc::new(query);
3060            let mut chunks = matching_buffers_rx.ready_chunks(64);
3061
3062            // Now that we know what paths match the query, we will load at most
3063            // 64 buffers at a time to avoid overwhelming the main thread. For each
3064            // opened buffer, we will spawn a background task that retrieves all the
3065            // ranges in the buffer matched by the query.
3066            let mut chunks = pin!(chunks);
3067            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3068                let mut chunk_results = Vec::new();
3069                for buffer in matching_buffer_chunk {
3070                    let buffer = buffer.clone();
3071                    let query = query.clone();
3072                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3073                    chunk_results.push(cx.background_executor().spawn(async move {
3074                        let ranges = query
3075                            .search(&snapshot, None)
3076                            .await
3077                            .iter()
3078                            .map(|range| {
3079                                snapshot.anchor_before(range.start)
3080                                    ..snapshot.anchor_after(range.end)
3081                            })
3082                            .collect::<Vec<_>>();
3083                        anyhow::Ok((buffer, ranges))
3084                    }));
3085                }
3086
3087                let chunk_results = futures::future::join_all(chunk_results).await;
3088                for result in chunk_results {
3089                    if let Some((buffer, ranges)) = result.log_err() {
3090                        range_count += ranges.len();
3091                        buffer_count += 1;
3092                        result_tx
3093                            .send(SearchResult::Buffer { buffer, ranges })
3094                            .await?;
3095                        if buffer_count > MAX_SEARCH_RESULT_FILES
3096                            || range_count > MAX_SEARCH_RESULT_RANGES
3097                        {
3098                            limit_reached = true;
3099                            break 'outer;
3100                        }
3101                    }
3102                }
3103            }
3104
3105            if limit_reached {
3106                result_tx.send(SearchResult::LimitReached).await?;
3107            }
3108
3109            anyhow::Ok(())
3110        })
3111        .detach();
3112
3113        result_rx
3114    }
3115
3116    fn find_search_candidate_buffers(
3117        &mut self,
3118        query: &SearchQuery,
3119        limit: usize,
3120        cx: &mut Context<Project>,
3121    ) -> Receiver<Entity<Buffer>> {
3122        if self.is_local() {
3123            let fs = self.fs.clone();
3124            self.buffer_store.update(cx, |buffer_store, cx| {
3125                buffer_store.find_search_candidates(query, limit, fs, cx)
3126            })
3127        } else {
3128            self.find_search_candidates_remote(query, limit, cx)
3129        }
3130    }
3131
3132    fn sort_search_candidates(
3133        &mut self,
3134        search_query: &SearchQuery,
3135        cx: &mut Context<Project>,
3136    ) -> Receiver<Entity<Buffer>> {
3137        let worktree_store = self.worktree_store.read(cx);
3138        let mut buffers = search_query
3139            .buffers()
3140            .into_iter()
3141            .flatten()
3142            .filter(|buffer| {
3143                let b = buffer.read(cx);
3144                if let Some(file) = b.file() {
3145                    if !search_query.file_matches(file.path()) {
3146                        return false;
3147                    }
3148                    if let Some(entry) = b
3149                        .entry_id(cx)
3150                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3151                    {
3152                        if entry.is_ignored && !search_query.include_ignored() {
3153                            return false;
3154                        }
3155                    }
3156                }
3157                true
3158            })
3159            .collect::<Vec<_>>();
3160        let (tx, rx) = smol::channel::unbounded();
3161        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3162            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3163            (None, Some(_)) => std::cmp::Ordering::Less,
3164            (Some(_), None) => std::cmp::Ordering::Greater,
3165            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3166        });
3167        for buffer in buffers {
3168            tx.send_blocking(buffer.clone()).unwrap()
3169        }
3170
3171        rx
3172    }
3173
3174    fn find_search_candidates_remote(
3175        &mut self,
3176        query: &SearchQuery,
3177        limit: usize,
3178        cx: &mut Context<Project>,
3179    ) -> Receiver<Entity<Buffer>> {
3180        let (tx, rx) = smol::channel::unbounded();
3181
3182        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3183            (ssh_client.read(cx).proto_client(), 0)
3184        } else if let Some(remote_id) = self.remote_id() {
3185            (self.client.clone().into(), remote_id)
3186        } else {
3187            return rx;
3188        };
3189
3190        let request = client.request(proto::FindSearchCandidates {
3191            project_id: remote_id,
3192            query: Some(query.to_proto()),
3193            limit: limit as _,
3194        });
3195        let guard = self.retain_remotely_created_models(cx);
3196
3197        cx.spawn(move |project, mut cx| async move {
3198            let response = request.await?;
3199            for buffer_id in response.buffer_ids {
3200                let buffer_id = BufferId::new(buffer_id)?;
3201                let buffer = project
3202                    .update(&mut cx, |project, cx| {
3203                        project.buffer_store.update(cx, |buffer_store, cx| {
3204                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3205                        })
3206                    })?
3207                    .await?;
3208                let _ = tx.send(buffer).await;
3209            }
3210
3211            drop(guard);
3212            anyhow::Ok(())
3213        })
3214        .detach_and_log_err(cx);
3215        rx
3216    }
3217
3218    pub fn request_lsp<R: LspCommand>(
3219        &mut self,
3220        buffer_handle: Entity<Buffer>,
3221        server: LanguageServerToQuery,
3222        request: R,
3223        cx: &mut Context<Self>,
3224    ) -> Task<Result<R::Response>>
3225    where
3226        <R::LspRequest as lsp::request::Request>::Result: Send,
3227        <R::LspRequest as lsp::request::Request>::Params: Send,
3228    {
3229        let guard = self.retain_remotely_created_models(cx);
3230        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3231            lsp_store.request_lsp(buffer_handle, server, request, cx)
3232        });
3233        cx.spawn(|_, _| async move {
3234            let result = task.await;
3235            drop(guard);
3236            result
3237        })
3238    }
3239
3240    /// Move a worktree to a new position in the worktree order.
3241    ///
3242    /// The worktree will moved to the opposite side of the destination worktree.
3243    ///
3244    /// # Example
3245    ///
3246    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3247    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3248    ///
3249    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3250    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3251    ///
3252    /// # Errors
3253    ///
3254    /// An error will be returned if the worktree or destination worktree are not found.
3255    pub fn move_worktree(
3256        &mut self,
3257        source: WorktreeId,
3258        destination: WorktreeId,
3259        cx: &mut Context<'_, Self>,
3260    ) -> Result<()> {
3261        self.worktree_store.update(cx, |worktree_store, cx| {
3262            worktree_store.move_worktree(source, destination, cx)
3263        })
3264    }
3265
3266    pub fn find_or_create_worktree(
3267        &mut self,
3268        abs_path: impl AsRef<Path>,
3269        visible: bool,
3270        cx: &mut Context<Self>,
3271    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3272        self.worktree_store.update(cx, |worktree_store, cx| {
3273            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3274        })
3275    }
3276
3277    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3278        self.worktree_store.read_with(cx, |worktree_store, cx| {
3279            worktree_store.find_worktree(abs_path, cx)
3280        })
3281    }
3282
3283    pub fn is_shared(&self) -> bool {
3284        match &self.client_state {
3285            ProjectClientState::Shared { .. } => true,
3286            ProjectClientState::Local => false,
3287            ProjectClientState::Remote { .. } => true,
3288        }
3289    }
3290
3291    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3292    pub fn resolve_path_in_buffer(
3293        &self,
3294        path: &str,
3295        buffer: &Entity<Buffer>,
3296        cx: &mut Context<Self>,
3297    ) -> Task<Option<ResolvedPath>> {
3298        let path_buf = PathBuf::from(path);
3299        if path_buf.is_absolute() || path.starts_with("~") {
3300            self.resolve_abs_path(path, cx)
3301        } else {
3302            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3303        }
3304    }
3305
3306    pub fn resolve_abs_file_path(
3307        &self,
3308        path: &str,
3309        cx: &mut Context<Self>,
3310    ) -> Task<Option<ResolvedPath>> {
3311        let resolve_task = self.resolve_abs_path(path, cx);
3312        cx.background_executor().spawn(async move {
3313            let resolved_path = resolve_task.await;
3314            resolved_path.filter(|path| path.is_file())
3315        })
3316    }
3317
3318    pub fn resolve_abs_path(
3319        &self,
3320        path: &str,
3321        cx: &mut Context<Self>,
3322    ) -> Task<Option<ResolvedPath>> {
3323        if self.is_local() {
3324            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3325            let fs = self.fs.clone();
3326            cx.background_executor().spawn(async move {
3327                let path = expanded.as_path();
3328                let metadata = fs.metadata(path).await.ok().flatten();
3329
3330                metadata.map(|metadata| ResolvedPath::AbsPath {
3331                    path: expanded,
3332                    is_dir: metadata.is_dir,
3333                })
3334            })
3335        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3336            let request = ssh_client
3337                .read(cx)
3338                .proto_client()
3339                .request(proto::GetPathMetadata {
3340                    project_id: SSH_PROJECT_ID,
3341                    path: path.to_string(),
3342                });
3343            cx.background_executor().spawn(async move {
3344                let response = request.await.log_err()?;
3345                if response.exists {
3346                    Some(ResolvedPath::AbsPath {
3347                        path: PathBuf::from(response.path),
3348                        is_dir: response.is_dir,
3349                    })
3350                } else {
3351                    None
3352                }
3353            })
3354        } else {
3355            return Task::ready(None);
3356        }
3357    }
3358
3359    fn resolve_path_in_worktrees(
3360        &self,
3361        path: PathBuf,
3362        buffer: &Entity<Buffer>,
3363        cx: &mut Context<Self>,
3364    ) -> Task<Option<ResolvedPath>> {
3365        let mut candidates = vec![path.clone()];
3366
3367        if let Some(file) = buffer.read(cx).file() {
3368            if let Some(dir) = file.path().parent() {
3369                let joined = dir.to_path_buf().join(path);
3370                candidates.push(joined);
3371            }
3372        }
3373
3374        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3375        cx.spawn(|_, mut cx| async move {
3376            for worktree in worktrees {
3377                for candidate in candidates.iter() {
3378                    let path = worktree
3379                        .update(&mut cx, |worktree, _| {
3380                            let root_entry_path = &worktree.root_entry()?.path;
3381
3382                            let resolved = resolve_path(root_entry_path, candidate);
3383
3384                            let stripped =
3385                                resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3386
3387                            worktree.entry_for_path(stripped).map(|entry| {
3388                                let project_path = ProjectPath {
3389                                    worktree_id: worktree.id(),
3390                                    path: entry.path.clone(),
3391                                };
3392                                ResolvedPath::ProjectPath {
3393                                    project_path,
3394                                    is_dir: entry.is_dir(),
3395                                }
3396                            })
3397                        })
3398                        .ok()?;
3399
3400                    if path.is_some() {
3401                        return path;
3402                    }
3403                }
3404            }
3405            None
3406        })
3407    }
3408
3409    pub fn list_directory(
3410        &self,
3411        query: String,
3412        cx: &mut Context<Self>,
3413    ) -> Task<Result<Vec<PathBuf>>> {
3414        if self.is_local() {
3415            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3416        } else if let Some(session) = self.ssh_client.as_ref() {
3417            let request = proto::ListRemoteDirectory {
3418                dev_server_id: SSH_PROJECT_ID,
3419                path: query,
3420            };
3421
3422            let response = session.read(cx).proto_client().request(request);
3423            cx.background_executor().spawn(async move {
3424                let response = response.await?;
3425                Ok(response.entries.into_iter().map(PathBuf::from).collect())
3426            })
3427        } else {
3428            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3429        }
3430    }
3431
3432    pub fn create_worktree(
3433        &mut self,
3434        abs_path: impl AsRef<Path>,
3435        visible: bool,
3436        cx: &mut Context<Self>,
3437    ) -> Task<Result<Entity<Worktree>>> {
3438        self.worktree_store.update(cx, |worktree_store, cx| {
3439            worktree_store.create_worktree(abs_path, visible, cx)
3440        })
3441    }
3442
3443    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3444        self.worktree_store.update(cx, |worktree_store, cx| {
3445            worktree_store.remove_worktree(id_to_remove, cx);
3446        });
3447    }
3448
3449    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3450        self.worktree_store.update(cx, |worktree_store, cx| {
3451            worktree_store.add(worktree, cx);
3452        });
3453    }
3454
3455    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3456        let new_active_entry = entry.and_then(|project_path| {
3457            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3458            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3459            Some(entry.id)
3460        });
3461        if new_active_entry != self.active_entry {
3462            self.active_entry = new_active_entry;
3463            self.lsp_store.update(cx, |lsp_store, _| {
3464                lsp_store.set_active_entry(new_active_entry);
3465            });
3466            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3467        }
3468    }
3469
3470    pub fn language_servers_running_disk_based_diagnostics<'a>(
3471        &'a self,
3472        cx: &'a App,
3473    ) -> impl Iterator<Item = LanguageServerId> + 'a {
3474        self.lsp_store
3475            .read(cx)
3476            .language_servers_running_disk_based_diagnostics()
3477    }
3478
3479    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3480        self.lsp_store
3481            .read(cx)
3482            .diagnostic_summary(include_ignored, cx)
3483    }
3484
3485    pub fn diagnostic_summaries<'a>(
3486        &'a self,
3487        include_ignored: bool,
3488        cx: &'a App,
3489    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3490        self.lsp_store
3491            .read(cx)
3492            .diagnostic_summaries(include_ignored, cx)
3493    }
3494
3495    pub fn active_entry(&self) -> Option<ProjectEntryId> {
3496        self.active_entry
3497    }
3498
3499    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
3500        self.worktree_store.read(cx).entry_for_path(path, cx)
3501    }
3502
3503    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
3504        let worktree = self.worktree_for_entry(entry_id, cx)?;
3505        let worktree = worktree.read(cx);
3506        let worktree_id = worktree.id();
3507        let path = worktree.entry_for_id(entry_id)?.path.clone();
3508        Some(ProjectPath { worktree_id, path })
3509    }
3510
3511    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3512        self.worktree_for_id(project_path.worktree_id, cx)?
3513            .read(cx)
3514            .absolutize(&project_path.path)
3515            .ok()
3516    }
3517
3518    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3519    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3520    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3521    /// the first visible worktree that has an entry for that relative path.
3522    ///
3523    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3524    /// root name from paths.
3525    ///
3526    /// # Arguments
3527    ///
3528    /// * `path` - A full path that starts with a worktree root name, or alternatively a
3529    ///            relative path within a visible worktree.
3530    /// * `cx` - A reference to the `AppContext`.
3531    ///
3532    /// # Returns
3533    ///
3534    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3535    pub fn find_project_path(&self, path: &Path, cx: &App) -> Option<ProjectPath> {
3536        let worktree_store = self.worktree_store.read(cx);
3537
3538        for worktree in worktree_store.visible_worktrees(cx) {
3539            let worktree_root_name = worktree.read(cx).root_name();
3540            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3541                return Some(ProjectPath {
3542                    worktree_id: worktree.read(cx).id(),
3543                    path: relative_path.into(),
3544                });
3545            }
3546        }
3547
3548        for worktree in worktree_store.visible_worktrees(cx) {
3549            let worktree = worktree.read(cx);
3550            if let Some(entry) = worktree.entry_for_path(path) {
3551                return Some(ProjectPath {
3552                    worktree_id: worktree.id(),
3553                    path: entry.path.clone(),
3554                });
3555            }
3556        }
3557
3558        None
3559    }
3560
3561    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3562        Some(
3563            self.worktree_for_id(project_path.worktree_id, cx)?
3564                .read(cx)
3565                .abs_path()
3566                .to_path_buf(),
3567        )
3568    }
3569
3570    pub fn get_first_worktree_root_repo(&self, cx: &App) -> Option<Arc<dyn GitRepository>> {
3571        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3572        let root_entry = worktree.root_git_entry()?;
3573        worktree.get_local_repo(&root_entry)?.repo().clone().into()
3574    }
3575
3576    pub fn branches(&self, project_path: ProjectPath, cx: &App) -> Task<Result<Vec<Branch>>> {
3577        self.worktree_store().read(cx).branches(project_path, cx)
3578    }
3579
3580    pub fn update_or_create_branch(
3581        &self,
3582        repository: ProjectPath,
3583        new_branch: String,
3584        cx: &App,
3585    ) -> Task<Result<()>> {
3586        self.worktree_store()
3587            .read(cx)
3588            .update_or_create_branch(repository, new_branch, cx)
3589    }
3590
3591    pub fn blame_buffer(
3592        &self,
3593        buffer: &Entity<Buffer>,
3594        version: Option<clock::Global>,
3595        cx: &App,
3596    ) -> Task<Result<Option<Blame>>> {
3597        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3598    }
3599
3600    pub fn get_permalink_to_line(
3601        &self,
3602        buffer: &Entity<Buffer>,
3603        selection: Range<u32>,
3604        cx: &App,
3605    ) -> Task<Result<url::Url>> {
3606        self.buffer_store
3607            .read(cx)
3608            .get_permalink_to_line(buffer, selection, cx)
3609    }
3610
3611    // RPC message handlers
3612
3613    async fn handle_unshare_project(
3614        this: Entity<Self>,
3615        _: TypedEnvelope<proto::UnshareProject>,
3616        mut cx: AsyncApp,
3617    ) -> Result<()> {
3618        this.update(&mut cx, |this, cx| {
3619            if this.is_local() || this.is_via_ssh() {
3620                this.unshare(cx)?;
3621            } else {
3622                this.disconnected_from_host(cx);
3623            }
3624            Ok(())
3625        })?
3626    }
3627
3628    async fn handle_add_collaborator(
3629        this: Entity<Self>,
3630        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3631        mut cx: AsyncApp,
3632    ) -> Result<()> {
3633        let collaborator = envelope
3634            .payload
3635            .collaborator
3636            .take()
3637            .ok_or_else(|| anyhow!("empty collaborator"))?;
3638
3639        let collaborator = Collaborator::from_proto(collaborator)?;
3640        this.update(&mut cx, |this, cx| {
3641            this.buffer_store.update(cx, |buffer_store, _| {
3642                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3643            });
3644            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3645            this.collaborators
3646                .insert(collaborator.peer_id, collaborator);
3647            cx.notify();
3648        })?;
3649
3650        Ok(())
3651    }
3652
3653    async fn handle_update_project_collaborator(
3654        this: Entity<Self>,
3655        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3656        mut cx: AsyncApp,
3657    ) -> Result<()> {
3658        let old_peer_id = envelope
3659            .payload
3660            .old_peer_id
3661            .ok_or_else(|| anyhow!("missing old peer id"))?;
3662        let new_peer_id = envelope
3663            .payload
3664            .new_peer_id
3665            .ok_or_else(|| anyhow!("missing new peer id"))?;
3666        this.update(&mut cx, |this, cx| {
3667            let collaborator = this
3668                .collaborators
3669                .remove(&old_peer_id)
3670                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3671            let is_host = collaborator.is_host;
3672            this.collaborators.insert(new_peer_id, collaborator);
3673
3674            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3675            this.buffer_store.update(cx, |buffer_store, _| {
3676                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3677            });
3678
3679            if is_host {
3680                this.buffer_store
3681                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3682                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3683                    .unwrap();
3684                cx.emit(Event::HostReshared);
3685            }
3686
3687            cx.emit(Event::CollaboratorUpdated {
3688                old_peer_id,
3689                new_peer_id,
3690            });
3691            cx.notify();
3692            Ok(())
3693        })?
3694    }
3695
3696    async fn handle_remove_collaborator(
3697        this: Entity<Self>,
3698        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3699        mut cx: AsyncApp,
3700    ) -> Result<()> {
3701        this.update(&mut cx, |this, cx| {
3702            let peer_id = envelope
3703                .payload
3704                .peer_id
3705                .ok_or_else(|| anyhow!("invalid peer id"))?;
3706            let replica_id = this
3707                .collaborators
3708                .remove(&peer_id)
3709                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3710                .replica_id;
3711            this.buffer_store.update(cx, |buffer_store, cx| {
3712                buffer_store.forget_shared_buffers_for(&peer_id);
3713                for buffer in buffer_store.buffers() {
3714                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3715                }
3716            });
3717
3718            cx.emit(Event::CollaboratorLeft(peer_id));
3719            cx.notify();
3720            Ok(())
3721        })?
3722    }
3723
3724    async fn handle_update_project(
3725        this: Entity<Self>,
3726        envelope: TypedEnvelope<proto::UpdateProject>,
3727        mut cx: AsyncApp,
3728    ) -> Result<()> {
3729        this.update(&mut cx, |this, cx| {
3730            // Don't handle messages that were sent before the response to us joining the project
3731            if envelope.message_id > this.join_project_response_message_id {
3732                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3733            }
3734            Ok(())
3735        })?
3736    }
3737
3738    async fn handle_toast(
3739        this: Entity<Self>,
3740        envelope: TypedEnvelope<proto::Toast>,
3741        mut cx: AsyncApp,
3742    ) -> Result<()> {
3743        this.update(&mut cx, |_, cx| {
3744            cx.emit(Event::Toast {
3745                notification_id: envelope.payload.notification_id.into(),
3746                message: envelope.payload.message,
3747            });
3748            Ok(())
3749        })?
3750    }
3751
3752    async fn handle_language_server_prompt_request(
3753        this: Entity<Self>,
3754        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3755        mut cx: AsyncApp,
3756    ) -> Result<proto::LanguageServerPromptResponse> {
3757        let (tx, mut rx) = smol::channel::bounded(1);
3758        let actions: Vec<_> = envelope
3759            .payload
3760            .actions
3761            .into_iter()
3762            .map(|action| MessageActionItem {
3763                title: action,
3764                properties: Default::default(),
3765            })
3766            .collect();
3767        this.update(&mut cx, |_, cx| {
3768            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3769                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3770                message: envelope.payload.message,
3771                actions: actions.clone(),
3772                lsp_name: envelope.payload.lsp_name,
3773                response_channel: tx,
3774            }));
3775
3776            anyhow::Ok(())
3777        })??;
3778
3779        // We drop `this` to avoid holding a reference in this future for too
3780        // long.
3781        // If we keep the reference, we might not drop the `Project` early
3782        // enough when closing a window and it will only get releases on the
3783        // next `flush_effects()` call.
3784        drop(this);
3785
3786        let mut rx = pin!(rx);
3787        let answer = rx.next().await;
3788
3789        Ok(LanguageServerPromptResponse {
3790            action_response: answer.and_then(|answer| {
3791                actions
3792                    .iter()
3793                    .position(|action| *action == answer)
3794                    .map(|index| index as u64)
3795            }),
3796        })
3797    }
3798
3799    async fn handle_hide_toast(
3800        this: Entity<Self>,
3801        envelope: TypedEnvelope<proto::HideToast>,
3802        mut cx: AsyncApp,
3803    ) -> Result<()> {
3804        this.update(&mut cx, |_, cx| {
3805            cx.emit(Event::HideToast {
3806                notification_id: envelope.payload.notification_id.into(),
3807            });
3808            Ok(())
3809        })?
3810    }
3811
3812    // Collab sends UpdateWorktree protos as messages
3813    async fn handle_update_worktree(
3814        this: Entity<Self>,
3815        envelope: TypedEnvelope<proto::UpdateWorktree>,
3816        mut cx: AsyncApp,
3817    ) -> Result<()> {
3818        this.update(&mut cx, |this, cx| {
3819            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3820            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3821                worktree.update(cx, |worktree, _| {
3822                    let worktree = worktree.as_remote_mut().unwrap();
3823                    worktree.update_from_remote(envelope.payload);
3824                });
3825            }
3826            Ok(())
3827        })?
3828    }
3829
3830    async fn handle_update_buffer_from_ssh(
3831        this: Entity<Self>,
3832        envelope: TypedEnvelope<proto::UpdateBuffer>,
3833        cx: AsyncApp,
3834    ) -> Result<proto::Ack> {
3835        let buffer_store = this.read_with(&cx, |this, cx| {
3836            if let Some(remote_id) = this.remote_id() {
3837                let mut payload = envelope.payload.clone();
3838                payload.project_id = remote_id;
3839                cx.background_executor()
3840                    .spawn(this.client.request(payload))
3841                    .detach_and_log_err(cx);
3842            }
3843            this.buffer_store.clone()
3844        })?;
3845        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3846    }
3847
3848    async fn handle_update_buffer(
3849        this: Entity<Self>,
3850        envelope: TypedEnvelope<proto::UpdateBuffer>,
3851        cx: AsyncApp,
3852    ) -> Result<proto::Ack> {
3853        let buffer_store = this.read_with(&cx, |this, cx| {
3854            if let Some(ssh) = &this.ssh_client {
3855                let mut payload = envelope.payload.clone();
3856                payload.project_id = SSH_PROJECT_ID;
3857                cx.background_executor()
3858                    .spawn(ssh.read(cx).proto_client().request(payload))
3859                    .detach_and_log_err(cx);
3860            }
3861            this.buffer_store.clone()
3862        })?;
3863        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3864    }
3865
3866    fn retain_remotely_created_models(
3867        &mut self,
3868        cx: &mut Context<Self>,
3869    ) -> RemotelyCreatedModelGuard {
3870        {
3871            let mut remotely_create_models = self.remotely_created_models.lock();
3872            if remotely_create_models.retain_count == 0 {
3873                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3874                remotely_create_models.worktrees =
3875                    self.worktree_store.read(cx).worktrees().collect();
3876            }
3877            remotely_create_models.retain_count += 1;
3878        }
3879        RemotelyCreatedModelGuard {
3880            remote_models: Arc::downgrade(&self.remotely_created_models),
3881        }
3882    }
3883
3884    async fn handle_create_buffer_for_peer(
3885        this: Entity<Self>,
3886        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3887        mut cx: AsyncApp,
3888    ) -> Result<()> {
3889        this.update(&mut cx, |this, cx| {
3890            this.buffer_store.update(cx, |buffer_store, cx| {
3891                buffer_store.handle_create_buffer_for_peer(
3892                    envelope,
3893                    this.replica_id(),
3894                    this.capability(),
3895                    cx,
3896                )
3897            })
3898        })?
3899    }
3900
3901    async fn handle_synchronize_buffers(
3902        this: Entity<Self>,
3903        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3904        mut cx: AsyncApp,
3905    ) -> Result<proto::SynchronizeBuffersResponse> {
3906        let response = this.update(&mut cx, |this, cx| {
3907            let client = this.client.clone();
3908            this.buffer_store.update(cx, |this, cx| {
3909                this.handle_synchronize_buffers(envelope, cx, client)
3910            })
3911        })??;
3912
3913        Ok(response)
3914    }
3915
3916    async fn handle_search_candidate_buffers(
3917        this: Entity<Self>,
3918        envelope: TypedEnvelope<proto::FindSearchCandidates>,
3919        mut cx: AsyncApp,
3920    ) -> Result<proto::FindSearchCandidatesResponse> {
3921        let peer_id = envelope.original_sender_id()?;
3922        let message = envelope.payload;
3923        let query = SearchQuery::from_proto(
3924            message
3925                .query
3926                .ok_or_else(|| anyhow!("missing query field"))?,
3927        )?;
3928        let results = this.update(&mut cx, |this, cx| {
3929            this.find_search_candidate_buffers(&query, message.limit as _, cx)
3930        })?;
3931
3932        let mut response = proto::FindSearchCandidatesResponse {
3933            buffer_ids: Vec::new(),
3934        };
3935
3936        while let Ok(buffer) = results.recv().await {
3937            this.update(&mut cx, |this, cx| {
3938                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3939                response.buffer_ids.push(buffer_id.to_proto());
3940            })?;
3941        }
3942
3943        Ok(response)
3944    }
3945
3946    async fn handle_open_buffer_by_id(
3947        this: Entity<Self>,
3948        envelope: TypedEnvelope<proto::OpenBufferById>,
3949        mut cx: AsyncApp,
3950    ) -> Result<proto::OpenBufferResponse> {
3951        let peer_id = envelope.original_sender_id()?;
3952        let buffer_id = BufferId::new(envelope.payload.id)?;
3953        let buffer = this
3954            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3955            .await?;
3956        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3957    }
3958
3959    async fn handle_open_buffer_by_path(
3960        this: Entity<Self>,
3961        envelope: TypedEnvelope<proto::OpenBufferByPath>,
3962        mut cx: AsyncApp,
3963    ) -> Result<proto::OpenBufferResponse> {
3964        let peer_id = envelope.original_sender_id()?;
3965        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3966        let open_buffer = this.update(&mut cx, |this, cx| {
3967            this.open_buffer(
3968                ProjectPath {
3969                    worktree_id,
3970                    path: PathBuf::from(envelope.payload.path).into(),
3971                },
3972                cx,
3973            )
3974        })?;
3975
3976        let buffer = open_buffer.await?;
3977        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3978    }
3979
3980    async fn handle_open_new_buffer(
3981        this: Entity<Self>,
3982        envelope: TypedEnvelope<proto::OpenNewBuffer>,
3983        mut cx: AsyncApp,
3984    ) -> Result<proto::OpenBufferResponse> {
3985        let buffer = this
3986            .update(&mut cx, |this, cx| this.create_buffer(cx))?
3987            .await?;
3988        let peer_id = envelope.original_sender_id()?;
3989
3990        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3991    }
3992
3993    async fn handle_stage(
3994        this: Entity<Self>,
3995        envelope: TypedEnvelope<proto::Stage>,
3996        mut cx: AsyncApp,
3997    ) -> Result<proto::Ack> {
3998        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3999        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4000        let repository_handle =
4001            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4002
4003        let entries = envelope
4004            .payload
4005            .paths
4006            .into_iter()
4007            .map(PathBuf::from)
4008            .map(RepoPath::new)
4009            .collect();
4010
4011        repository_handle
4012            .update(&mut cx, |repository_handle, _| {
4013                repository_handle.stage_entries(entries)
4014            })?
4015            .await??;
4016        Ok(proto::Ack {})
4017    }
4018
4019    async fn handle_unstage(
4020        this: Entity<Self>,
4021        envelope: TypedEnvelope<proto::Unstage>,
4022        mut cx: AsyncApp,
4023    ) -> Result<proto::Ack> {
4024        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4025        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4026        let repository_handle =
4027            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4028
4029        let entries = envelope
4030            .payload
4031            .paths
4032            .into_iter()
4033            .map(PathBuf::from)
4034            .map(RepoPath::new)
4035            .collect();
4036
4037        repository_handle
4038            .update(&mut cx, |repository_handle, _| {
4039                repository_handle.unstage_entries(entries)
4040            })?
4041            .await??;
4042        Ok(proto::Ack {})
4043    }
4044
4045    async fn handle_commit(
4046        this: Entity<Self>,
4047        envelope: TypedEnvelope<proto::Commit>,
4048        mut cx: AsyncApp,
4049    ) -> Result<proto::Ack> {
4050        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4051        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4052        let repository_handle =
4053            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4054
4055        let message = SharedString::from(envelope.payload.message);
4056        let name = envelope.payload.name.map(SharedString::from);
4057        let email = envelope.payload.email.map(SharedString::from);
4058        repository_handle
4059            .update(&mut cx, |repository_handle, _| {
4060                repository_handle.commit(message, name.zip(email))
4061            })?
4062            .await??;
4063        Ok(proto::Ack {})
4064    }
4065
4066    async fn handle_open_commit_message_buffer(
4067        this: Entity<Self>,
4068        envelope: TypedEnvelope<proto::OpenCommitMessageBuffer>,
4069        mut cx: AsyncApp,
4070    ) -> Result<proto::OpenBufferResponse> {
4071        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4072        let work_directory_id = ProjectEntryId::from_proto(envelope.payload.work_directory_id);
4073        let repository_handle =
4074            Self::repository_for_request(&this, worktree_id, work_directory_id, &mut cx)?;
4075        let buffer = repository_handle
4076            .update(&mut cx, |repository_handle, cx| {
4077                repository_handle.open_commit_buffer(None, this.read(cx).buffer_store.clone(), cx)
4078            })?
4079            .await?;
4080
4081        let peer_id = envelope.original_sender_id()?;
4082        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4083    }
4084
4085    fn repository_for_request(
4086        this: &Entity<Self>,
4087        worktree_id: WorktreeId,
4088        work_directory_id: ProjectEntryId,
4089        cx: &mut AsyncApp,
4090    ) -> Result<Entity<Repository>> {
4091        this.update(cx, |project, cx| {
4092            let repository_handle = project
4093                .git_state()
4094                .read(cx)
4095                .all_repositories()
4096                .into_iter()
4097                .find(|repository_handle| {
4098                    let repository_handle = repository_handle.read(cx);
4099                    repository_handle.worktree_id == worktree_id
4100                        && repository_handle.repository_entry.work_directory_id()
4101                            == work_directory_id
4102                })
4103                .context("missing repository handle")?;
4104            anyhow::Ok(repository_handle)
4105        })?
4106    }
4107
4108    fn respond_to_open_buffer_request(
4109        this: Entity<Self>,
4110        buffer: Entity<Buffer>,
4111        peer_id: proto::PeerId,
4112        cx: &mut AsyncApp,
4113    ) -> Result<proto::OpenBufferResponse> {
4114        this.update(cx, |this, cx| {
4115            let is_private = buffer
4116                .read(cx)
4117                .file()
4118                .map(|f| f.is_private())
4119                .unwrap_or_default();
4120            if is_private {
4121                Err(anyhow!(ErrorCode::UnsharedItem))
4122            } else {
4123                Ok(proto::OpenBufferResponse {
4124                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4125                })
4126            }
4127        })?
4128    }
4129
4130    fn create_buffer_for_peer(
4131        &mut self,
4132        buffer: &Entity<Buffer>,
4133        peer_id: proto::PeerId,
4134        cx: &mut App,
4135    ) -> BufferId {
4136        self.buffer_store
4137            .update(cx, |buffer_store, cx| {
4138                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4139            })
4140            .detach_and_log_err(cx);
4141        buffer.read(cx).remote_id()
4142    }
4143
4144    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4145        let project_id = match self.client_state {
4146            ProjectClientState::Remote {
4147                sharing_has_stopped,
4148                remote_id,
4149                ..
4150            } => {
4151                if sharing_has_stopped {
4152                    return Task::ready(Err(anyhow!(
4153                        "can't synchronize remote buffers on a readonly project"
4154                    )));
4155                } else {
4156                    remote_id
4157                }
4158            }
4159            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4160                return Task::ready(Err(anyhow!(
4161                    "can't synchronize remote buffers on a local project"
4162                )))
4163            }
4164        };
4165
4166        let client = self.client.clone();
4167        cx.spawn(move |this, mut cx| async move {
4168            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4169                this.buffer_store.read(cx).buffer_version_info(cx)
4170            })?;
4171            let response = client
4172                .request(proto::SynchronizeBuffers {
4173                    project_id,
4174                    buffers,
4175                })
4176                .await?;
4177
4178            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4179                response
4180                    .buffers
4181                    .into_iter()
4182                    .map(|buffer| {
4183                        let client = client.clone();
4184                        let buffer_id = match BufferId::new(buffer.id) {
4185                            Ok(id) => id,
4186                            Err(e) => {
4187                                return Task::ready(Err(e));
4188                            }
4189                        };
4190                        let remote_version = language::proto::deserialize_version(&buffer.version);
4191                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4192                            let operations =
4193                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4194                            cx.background_executor().spawn(async move {
4195                                let operations = operations.await;
4196                                for chunk in split_operations(operations) {
4197                                    client
4198                                        .request(proto::UpdateBuffer {
4199                                            project_id,
4200                                            buffer_id: buffer_id.into(),
4201                                            operations: chunk,
4202                                        })
4203                                        .await?;
4204                                }
4205                                anyhow::Ok(())
4206                            })
4207                        } else {
4208                            Task::ready(Ok(()))
4209                        }
4210                    })
4211                    .collect::<Vec<_>>()
4212            })?;
4213
4214            // Any incomplete buffers have open requests waiting. Request that the host sends
4215            // creates these buffers for us again to unblock any waiting futures.
4216            for id in incomplete_buffer_ids {
4217                cx.background_executor()
4218                    .spawn(client.request(proto::OpenBufferById {
4219                        project_id,
4220                        id: id.into(),
4221                    }))
4222                    .detach();
4223            }
4224
4225            futures::future::join_all(send_updates_for_buffers)
4226                .await
4227                .into_iter()
4228                .collect()
4229        })
4230    }
4231
4232    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4233        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4234    }
4235
4236    /// Iterator of all open buffers that have unsaved changes
4237    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4238        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4239            let buf = buf.read(cx);
4240            if buf.is_dirty() {
4241                buf.project_path(cx)
4242            } else {
4243                None
4244            }
4245        })
4246    }
4247
4248    fn set_worktrees_from_proto(
4249        &mut self,
4250        worktrees: Vec<proto::WorktreeMetadata>,
4251        cx: &mut Context<Project>,
4252    ) -> Result<()> {
4253        cx.notify();
4254        self.worktree_store.update(cx, |worktree_store, cx| {
4255            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4256        })
4257    }
4258
4259    fn set_collaborators_from_proto(
4260        &mut self,
4261        messages: Vec<proto::Collaborator>,
4262        cx: &mut Context<Self>,
4263    ) -> Result<()> {
4264        let mut collaborators = HashMap::default();
4265        for message in messages {
4266            let collaborator = Collaborator::from_proto(message)?;
4267            collaborators.insert(collaborator.peer_id, collaborator);
4268        }
4269        for old_peer_id in self.collaborators.keys() {
4270            if !collaborators.contains_key(old_peer_id) {
4271                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4272            }
4273        }
4274        self.collaborators = collaborators;
4275        Ok(())
4276    }
4277
4278    pub fn supplementary_language_servers<'a>(
4279        &'a self,
4280        cx: &'a App,
4281    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4282        self.lsp_store.read(cx).supplementary_language_servers()
4283    }
4284
4285    pub fn language_servers_for_local_buffer<'a>(
4286        &'a self,
4287        buffer: &'a Buffer,
4288        cx: &'a App,
4289    ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4290        self.lsp_store
4291            .read(cx)
4292            .language_servers_for_local_buffer(buffer, cx)
4293    }
4294
4295    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4296        &self.buffer_store
4297    }
4298
4299    pub fn git_state(&self) -> &Entity<GitState> {
4300        &self.git_state
4301    }
4302
4303    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4304        self.git_state.read(cx).active_repository()
4305    }
4306
4307    pub fn all_repositories(&self, cx: &App) -> Vec<Entity<Repository>> {
4308        self.git_state.read(cx).all_repositories()
4309    }
4310}
4311
4312fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4313    code_actions
4314        .iter()
4315        .flat_map(|(kind, enabled)| {
4316            if *enabled {
4317                Some(kind.clone().into())
4318            } else {
4319                None
4320            }
4321        })
4322        .collect()
4323}
4324
4325pub struct PathMatchCandidateSet {
4326    pub snapshot: Snapshot,
4327    pub include_ignored: bool,
4328    pub include_root_name: bool,
4329    pub candidates: Candidates,
4330}
4331
4332pub enum Candidates {
4333    /// Only consider directories.
4334    Directories,
4335    /// Only consider files.
4336    Files,
4337    /// Consider directories and files.
4338    Entries,
4339}
4340
4341impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4342    type Candidates = PathMatchCandidateSetIter<'a>;
4343
4344    fn id(&self) -> usize {
4345        self.snapshot.id().to_usize()
4346    }
4347
4348    fn len(&self) -> usize {
4349        match self.candidates {
4350            Candidates::Files => {
4351                if self.include_ignored {
4352                    self.snapshot.file_count()
4353                } else {
4354                    self.snapshot.visible_file_count()
4355                }
4356            }
4357
4358            Candidates::Directories => {
4359                if self.include_ignored {
4360                    self.snapshot.dir_count()
4361                } else {
4362                    self.snapshot.visible_dir_count()
4363                }
4364            }
4365
4366            Candidates::Entries => {
4367                if self.include_ignored {
4368                    self.snapshot.entry_count()
4369                } else {
4370                    self.snapshot.visible_entry_count()
4371                }
4372            }
4373        }
4374    }
4375
4376    fn prefix(&self) -> Arc<str> {
4377        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4378            self.snapshot.root_name().into()
4379        } else if self.include_root_name {
4380            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4381        } else {
4382            Arc::default()
4383        }
4384    }
4385
4386    fn candidates(&'a self, start: usize) -> Self::Candidates {
4387        PathMatchCandidateSetIter {
4388            traversal: match self.candidates {
4389                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4390                Candidates::Files => self.snapshot.files(self.include_ignored, start),
4391                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4392            },
4393        }
4394    }
4395}
4396
4397pub struct PathMatchCandidateSetIter<'a> {
4398    traversal: Traversal<'a>,
4399}
4400
4401impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4402    type Item = fuzzy::PathMatchCandidate<'a>;
4403
4404    fn next(&mut self) -> Option<Self::Item> {
4405        self.traversal
4406            .next()
4407            .map(|entry| fuzzy::PathMatchCandidate {
4408                is_dir: entry.kind.is_dir(),
4409                path: &entry.path,
4410                char_bag: entry.char_bag,
4411            })
4412    }
4413}
4414
4415impl EventEmitter<Event> for Project {}
4416
4417impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4418    fn from(val: &'a ProjectPath) -> Self {
4419        SettingsLocation {
4420            worktree_id: val.worktree_id,
4421            path: val.path.as_ref(),
4422        }
4423    }
4424}
4425
4426impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4427    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4428        Self {
4429            worktree_id,
4430            path: path.as_ref().into(),
4431        }
4432    }
4433}
4434
4435pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4436    let mut path_components = path.components();
4437    let mut base_components = base.components();
4438    let mut components: Vec<Component> = Vec::new();
4439    loop {
4440        match (path_components.next(), base_components.next()) {
4441            (None, None) => break,
4442            (Some(a), None) => {
4443                components.push(a);
4444                components.extend(path_components.by_ref());
4445                break;
4446            }
4447            (None, _) => components.push(Component::ParentDir),
4448            (Some(a), Some(b)) if components.is_empty() && a == b => (),
4449            (Some(a), Some(Component::CurDir)) => components.push(a),
4450            (Some(a), Some(_)) => {
4451                components.push(Component::ParentDir);
4452                for _ in base_components {
4453                    components.push(Component::ParentDir);
4454                }
4455                components.push(a);
4456                components.extend(path_components.by_ref());
4457                break;
4458            }
4459        }
4460    }
4461    components.iter().map(|c| c.as_os_str()).collect()
4462}
4463
4464fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4465    let mut result = base.to_path_buf();
4466    for component in path.components() {
4467        match component {
4468            Component::ParentDir => {
4469                result.pop();
4470            }
4471            Component::CurDir => (),
4472            _ => result.push(component),
4473        }
4474    }
4475    result
4476}
4477
4478/// ResolvedPath is a path that has been resolved to either a ProjectPath
4479/// or an AbsPath and that *exists*.
4480#[derive(Debug, Clone)]
4481pub enum ResolvedPath {
4482    ProjectPath {
4483        project_path: ProjectPath,
4484        is_dir: bool,
4485    },
4486    AbsPath {
4487        path: PathBuf,
4488        is_dir: bool,
4489    },
4490}
4491
4492impl ResolvedPath {
4493    pub fn abs_path(&self) -> Option<&Path> {
4494        match self {
4495            Self::AbsPath { path, .. } => Some(path.as_path()),
4496            _ => None,
4497        }
4498    }
4499
4500    pub fn project_path(&self) -> Option<&ProjectPath> {
4501        match self {
4502            Self::ProjectPath { project_path, .. } => Some(&project_path),
4503            _ => None,
4504        }
4505    }
4506
4507    pub fn is_file(&self) -> bool {
4508        !self.is_dir()
4509    }
4510
4511    pub fn is_dir(&self) -> bool {
4512        match self {
4513            Self::ProjectPath { is_dir, .. } => *is_dir,
4514            Self::AbsPath { is_dir, .. } => *is_dir,
4515        }
4516    }
4517}
4518
4519impl ProjectItem for Buffer {
4520    fn try_open(
4521        project: &Entity<Project>,
4522        path: &ProjectPath,
4523        cx: &mut App,
4524    ) -> Option<Task<Result<Entity<Self>>>> {
4525        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4526    }
4527
4528    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4529        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4530    }
4531
4532    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4533        File::from_dyn(self.file()).map(|file| ProjectPath {
4534            worktree_id: file.worktree_id(cx),
4535            path: file.path().clone(),
4536        })
4537    }
4538
4539    fn is_dirty(&self) -> bool {
4540        self.is_dirty()
4541    }
4542}
4543
4544impl Completion {
4545    /// A key that can be used to sort completions when displaying
4546    /// them to the user.
4547    pub fn sort_key(&self) -> (usize, &str) {
4548        let kind_key = match self.lsp_completion.kind {
4549            Some(lsp::CompletionItemKind::KEYWORD) => 0,
4550            Some(lsp::CompletionItemKind::VARIABLE) => 1,
4551            _ => 2,
4552        };
4553        (kind_key, &self.label.text[self.label.filter_range.clone()])
4554    }
4555
4556    /// Whether this completion is a snippet.
4557    pub fn is_snippet(&self) -> bool {
4558        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4559    }
4560
4561    /// Returns the corresponding color for this completion.
4562    ///
4563    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4564    pub fn color(&self) -> Option<Hsla> {
4565        match self.lsp_completion.kind {
4566            Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4567            _ => None,
4568        }
4569    }
4570}
4571
4572pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
4573    entries.sort_by(|entry_a, entry_b| {
4574        let entry_a = entry_a.as_ref();
4575        let entry_b = entry_b.as_ref();
4576        compare_paths(
4577            (&entry_a.path, entry_a.is_file()),
4578            (&entry_b.path, entry_b.is_file()),
4579        )
4580    });
4581}
4582
4583fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4584    match level {
4585        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4586        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4587        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4588    }
4589}