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