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