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