project.rs

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