project.rs

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