project.rs

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