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).next() 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 binary = adapter
1486 .get_binary(&delegate, &config, user_installed_path, cx)
1487 .await?;
1488
1489 let ret = this
1490 .update(cx, |project, cx| {
1491 project.dap_store.update(cx, |dap_store, cx| {
1492 dap_store.new_session(binary, config, None, cx)
1493 })
1494 })?
1495 .1
1496 .await;
1497 ret
1498 });
1499 result
1500 }
1501
1502 #[cfg(any(test, feature = "test-support"))]
1503 pub async fn example(
1504 root_paths: impl IntoIterator<Item = &Path>,
1505 cx: &mut AsyncApp,
1506 ) -> Entity<Project> {
1507 use clock::FakeSystemClock;
1508
1509 let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1510 let languages = LanguageRegistry::test(cx.background_executor().clone());
1511 let debug_adapters = DapRegistry::default().into();
1512 let clock = Arc::new(FakeSystemClock::new());
1513 let http_client = http_client::FakeHttpClient::with_404_response();
1514 let client = cx
1515 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1516 .unwrap();
1517 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1518 let project = cx
1519 .update(|cx| {
1520 Project::local(
1521 client,
1522 node_runtime::NodeRuntime::unavailable(),
1523 user_store,
1524 Arc::new(languages),
1525 debug_adapters,
1526 fs,
1527 None,
1528 cx,
1529 )
1530 })
1531 .unwrap();
1532 for path in root_paths {
1533 let (tree, _) = project
1534 .update(cx, |project, cx| {
1535 project.find_or_create_worktree(path, true, cx)
1536 })
1537 .unwrap()
1538 .await
1539 .unwrap();
1540 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1541 .unwrap()
1542 .await;
1543 }
1544 project
1545 }
1546
1547 #[cfg(any(test, feature = "test-support"))]
1548 pub async fn test(
1549 fs: Arc<dyn Fs>,
1550 root_paths: impl IntoIterator<Item = &Path>,
1551 cx: &mut gpui::TestAppContext,
1552 ) -> Entity<Project> {
1553 use clock::FakeSystemClock;
1554
1555 let languages = LanguageRegistry::test(cx.executor());
1556 let debug_adapters = DapRegistry::fake();
1557 let clock = Arc::new(FakeSystemClock::new());
1558 let http_client = http_client::FakeHttpClient::with_404_response();
1559 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1560 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1561 let project = cx.update(|cx| {
1562 Project::local(
1563 client,
1564 node_runtime::NodeRuntime::unavailable(),
1565 user_store,
1566 Arc::new(languages),
1567 Arc::new(debug_adapters),
1568 fs,
1569 None,
1570 cx,
1571 )
1572 });
1573 for path in root_paths {
1574 let (tree, _) = project
1575 .update(cx, |project, cx| {
1576 project.find_or_create_worktree(path, true, cx)
1577 })
1578 .await
1579 .unwrap();
1580
1581 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1582 .await;
1583 }
1584 project
1585 }
1586
1587 pub fn dap_store(&self) -> Entity<DapStore> {
1588 self.dap_store.clone()
1589 }
1590
1591 pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1592 self.breakpoint_store.clone()
1593 }
1594
1595 pub fn lsp_store(&self) -> Entity<LspStore> {
1596 self.lsp_store.clone()
1597 }
1598
1599 pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1600 self.worktree_store.clone()
1601 }
1602
1603 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1604 self.buffer_store.read(cx).get(remote_id)
1605 }
1606
1607 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1608 &self.languages
1609 }
1610
1611 pub fn debug_adapters(&self) -> &Arc<DapRegistry> {
1612 &self.debug_adapters
1613 }
1614
1615 pub fn client(&self) -> Arc<Client> {
1616 self.client.clone()
1617 }
1618
1619 pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1620 self.ssh_client.clone()
1621 }
1622
1623 pub fn user_store(&self) -> Entity<UserStore> {
1624 self.user_store.clone()
1625 }
1626
1627 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1628 self.node.as_ref()
1629 }
1630
1631 pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1632 self.buffer_store.read(cx).buffers().collect()
1633 }
1634
1635 pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1636 &self.environment
1637 }
1638
1639 pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1640 self.environment.read(cx).get_cli_environment()
1641 }
1642
1643 pub fn shell_environment_errors<'a>(
1644 &'a self,
1645 cx: &'a App,
1646 ) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
1647 self.environment.read(cx).environment_errors()
1648 }
1649
1650 pub fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
1651 self.environment.update(cx, |environment, cx| {
1652 environment.remove_environment_error(abs_path, cx);
1653 });
1654 }
1655
1656 #[cfg(any(test, feature = "test-support"))]
1657 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1658 self.buffer_store
1659 .read(cx)
1660 .get_by_path(&path.into(), cx)
1661 .is_some()
1662 }
1663
1664 pub fn fs(&self) -> &Arc<dyn Fs> {
1665 &self.fs
1666 }
1667
1668 pub fn remote_id(&self) -> Option<u64> {
1669 match self.client_state {
1670 ProjectClientState::Local => None,
1671 ProjectClientState::Shared { remote_id, .. }
1672 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1673 }
1674 }
1675
1676 pub fn supports_terminal(&self, _cx: &App) -> bool {
1677 if self.is_local() {
1678 return true;
1679 }
1680 if self.is_via_ssh() {
1681 return true;
1682 }
1683
1684 return false;
1685 }
1686
1687 pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1688 if let Some(ssh_state) = &self.ssh_client {
1689 return Some(ssh_state.read(cx).connection_string().into());
1690 }
1691
1692 return None;
1693 }
1694
1695 pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1696 self.ssh_client
1697 .as_ref()
1698 .map(|ssh| ssh.read(cx).connection_state())
1699 }
1700
1701 pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1702 self.ssh_client
1703 .as_ref()
1704 .map(|ssh| ssh.read(cx).connection_options())
1705 }
1706
1707 pub fn replica_id(&self) -> ReplicaId {
1708 match self.client_state {
1709 ProjectClientState::Remote { replica_id, .. } => replica_id,
1710 _ => {
1711 if self.ssh_client.is_some() {
1712 1
1713 } else {
1714 0
1715 }
1716 }
1717 }
1718 }
1719
1720 pub fn task_store(&self) -> &Entity<TaskStore> {
1721 &self.task_store
1722 }
1723
1724 pub fn snippets(&self) -> &Entity<SnippetProvider> {
1725 &self.snippets
1726 }
1727
1728 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1729 match kind {
1730 SearchInputKind::Query => &self.search_history,
1731 SearchInputKind::Include => &self.search_included_history,
1732 SearchInputKind::Exclude => &self.search_excluded_history,
1733 }
1734 }
1735
1736 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1737 match kind {
1738 SearchInputKind::Query => &mut self.search_history,
1739 SearchInputKind::Include => &mut self.search_included_history,
1740 SearchInputKind::Exclude => &mut self.search_excluded_history,
1741 }
1742 }
1743
1744 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1745 &self.collaborators
1746 }
1747
1748 pub fn host(&self) -> Option<&Collaborator> {
1749 self.collaborators.values().find(|c| c.is_host)
1750 }
1751
1752 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1753 self.worktree_store.update(cx, |store, _| {
1754 store.set_worktrees_reordered(worktrees_reordered);
1755 });
1756 }
1757
1758 /// Collect all worktrees, including ones that don't appear in the project panel
1759 pub fn worktrees<'a>(
1760 &self,
1761 cx: &'a App,
1762 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1763 self.worktree_store.read(cx).worktrees()
1764 }
1765
1766 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1767 pub fn visible_worktrees<'a>(
1768 &'a self,
1769 cx: &'a App,
1770 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1771 self.worktree_store.read(cx).visible_worktrees(cx)
1772 }
1773
1774 pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
1775 self.visible_worktrees(cx)
1776 .find(|tree| tree.read(cx).root_name() == root_name)
1777 }
1778
1779 pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1780 self.visible_worktrees(cx)
1781 .map(|tree| tree.read(cx).root_name())
1782 }
1783
1784 pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1785 self.worktree_store.read(cx).worktree_for_id(id, cx)
1786 }
1787
1788 pub fn worktree_for_entry(
1789 &self,
1790 entry_id: ProjectEntryId,
1791 cx: &App,
1792 ) -> Option<Entity<Worktree>> {
1793 self.worktree_store
1794 .read(cx)
1795 .worktree_for_entry(entry_id, cx)
1796 }
1797
1798 pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1799 self.worktree_for_entry(entry_id, cx)
1800 .map(|worktree| worktree.read(cx).id())
1801 }
1802
1803 /// Checks if the entry is the root of a worktree.
1804 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1805 self.worktree_for_entry(entry_id, cx)
1806 .map(|worktree| {
1807 worktree
1808 .read(cx)
1809 .root_entry()
1810 .is_some_and(|e| e.id == entry_id)
1811 })
1812 .unwrap_or(false)
1813 }
1814
1815 pub fn project_path_git_status(
1816 &self,
1817 project_path: &ProjectPath,
1818 cx: &App,
1819 ) -> Option<FileStatus> {
1820 self.git_store
1821 .read(cx)
1822 .project_path_git_status(project_path, cx)
1823 }
1824
1825 pub fn visibility_for_paths(
1826 &self,
1827 paths: &[PathBuf],
1828 metadatas: &[Metadata],
1829 exclude_sub_dirs: bool,
1830 cx: &App,
1831 ) -> Option<bool> {
1832 paths
1833 .iter()
1834 .zip(metadatas)
1835 .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1836 .max()
1837 .flatten()
1838 }
1839
1840 pub fn visibility_for_path(
1841 &self,
1842 path: &Path,
1843 metadata: &Metadata,
1844 exclude_sub_dirs: bool,
1845 cx: &App,
1846 ) -> Option<bool> {
1847 let sanitized_path = SanitizedPath::from(path);
1848 let path = sanitized_path.as_path();
1849 self.worktrees(cx)
1850 .filter_map(|worktree| {
1851 let worktree = worktree.read(cx);
1852 let abs_path = worktree.as_local()?.abs_path();
1853 let contains = path == abs_path
1854 || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1855 contains.then(|| worktree.is_visible())
1856 })
1857 .max()
1858 }
1859
1860 pub fn create_entry(
1861 &mut self,
1862 project_path: impl Into<ProjectPath>,
1863 is_directory: bool,
1864 cx: &mut Context<Self>,
1865 ) -> Task<Result<CreatedEntry>> {
1866 let project_path = project_path.into();
1867 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1868 return Task::ready(Err(anyhow!(format!(
1869 "No worktree for path {project_path:?}"
1870 ))));
1871 };
1872 worktree.update(cx, |worktree, cx| {
1873 worktree.create_entry(project_path.path, is_directory, cx)
1874 })
1875 }
1876
1877 pub fn copy_entry(
1878 &mut self,
1879 entry_id: ProjectEntryId,
1880 relative_worktree_source_path: Option<PathBuf>,
1881 new_path: impl Into<Arc<Path>>,
1882 cx: &mut Context<Self>,
1883 ) -> Task<Result<Option<Entry>>> {
1884 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1885 return Task::ready(Ok(None));
1886 };
1887 worktree.update(cx, |worktree, cx| {
1888 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1889 })
1890 }
1891
1892 /// Renames the project entry with given `entry_id`.
1893 ///
1894 /// `new_path` is a relative path to worktree root.
1895 /// If root entry is renamed then its new root name is used instead.
1896 pub fn rename_entry(
1897 &mut self,
1898 entry_id: ProjectEntryId,
1899 new_path: impl Into<Arc<Path>>,
1900 cx: &mut Context<Self>,
1901 ) -> Task<Result<CreatedEntry>> {
1902 let worktree_store = self.worktree_store.read(cx);
1903 let new_path = new_path.into();
1904 let Some((worktree, old_path, is_dir)) = worktree_store
1905 .worktree_and_entry_for_id(entry_id, cx)
1906 .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1907 else {
1908 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1909 };
1910
1911 let worktree_id = worktree.read(cx).id();
1912 let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1913
1914 let lsp_store = self.lsp_store().downgrade();
1915 cx.spawn(async move |_, cx| {
1916 let (old_abs_path, new_abs_path) = {
1917 let root_path = worktree.update(cx, |this, _| this.abs_path())?;
1918 let new_abs_path = if is_root_entry {
1919 root_path.parent().unwrap().join(&new_path)
1920 } else {
1921 root_path.join(&new_path)
1922 };
1923 (root_path.join(&old_path), new_abs_path)
1924 };
1925 LspStore::will_rename_entry(
1926 lsp_store.clone(),
1927 worktree_id,
1928 &old_abs_path,
1929 &new_abs_path,
1930 is_dir,
1931 cx.clone(),
1932 )
1933 .await;
1934
1935 let entry = worktree
1936 .update(cx, |worktree, cx| {
1937 worktree.rename_entry(entry_id, new_path.clone(), cx)
1938 })?
1939 .await?;
1940
1941 lsp_store
1942 .update(cx, |this, _| {
1943 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1944 })
1945 .ok();
1946 Ok(entry)
1947 })
1948 }
1949
1950 pub fn delete_file(
1951 &mut self,
1952 path: ProjectPath,
1953 trash: bool,
1954 cx: &mut Context<Self>,
1955 ) -> Option<Task<Result<()>>> {
1956 let entry = self.entry_for_path(&path, cx)?;
1957 self.delete_entry(entry.id, trash, cx)
1958 }
1959
1960 pub fn delete_entry(
1961 &mut self,
1962 entry_id: ProjectEntryId,
1963 trash: bool,
1964 cx: &mut Context<Self>,
1965 ) -> Option<Task<Result<()>>> {
1966 let worktree = self.worktree_for_entry(entry_id, cx)?;
1967 cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1968 worktree.update(cx, |worktree, cx| {
1969 worktree.delete_entry(entry_id, trash, cx)
1970 })
1971 }
1972
1973 pub fn expand_entry(
1974 &mut self,
1975 worktree_id: WorktreeId,
1976 entry_id: ProjectEntryId,
1977 cx: &mut Context<Self>,
1978 ) -> Option<Task<Result<()>>> {
1979 let worktree = self.worktree_for_id(worktree_id, cx)?;
1980 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1981 }
1982
1983 pub fn expand_all_for_entry(
1984 &mut self,
1985 worktree_id: WorktreeId,
1986 entry_id: ProjectEntryId,
1987 cx: &mut Context<Self>,
1988 ) -> Option<Task<Result<()>>> {
1989 let worktree = self.worktree_for_id(worktree_id, cx)?;
1990 let task = worktree.update(cx, |worktree, cx| {
1991 worktree.expand_all_for_entry(entry_id, cx)
1992 });
1993 Some(cx.spawn(async move |this, cx| {
1994 task.ok_or_else(|| anyhow!("no task"))?.await?;
1995 this.update(cx, |_, cx| {
1996 cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
1997 })?;
1998 Ok(())
1999 }))
2000 }
2001
2002 pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2003 if !matches!(self.client_state, ProjectClientState::Local) {
2004 return Err(anyhow!("project was already shared"));
2005 }
2006
2007 self.client_subscriptions.extend([
2008 self.client
2009 .subscribe_to_entity(project_id)?
2010 .set_entity(&cx.entity(), &mut cx.to_async()),
2011 self.client
2012 .subscribe_to_entity(project_id)?
2013 .set_entity(&self.worktree_store, &mut cx.to_async()),
2014 self.client
2015 .subscribe_to_entity(project_id)?
2016 .set_entity(&self.buffer_store, &mut cx.to_async()),
2017 self.client
2018 .subscribe_to_entity(project_id)?
2019 .set_entity(&self.lsp_store, &mut cx.to_async()),
2020 self.client
2021 .subscribe_to_entity(project_id)?
2022 .set_entity(&self.settings_observer, &mut cx.to_async()),
2023 self.client
2024 .subscribe_to_entity(project_id)?
2025 .set_entity(&self.dap_store, &mut cx.to_async()),
2026 self.client
2027 .subscribe_to_entity(project_id)?
2028 .set_entity(&self.breakpoint_store, &mut cx.to_async()),
2029 self.client
2030 .subscribe_to_entity(project_id)?
2031 .set_entity(&self.git_store, &mut cx.to_async()),
2032 ]);
2033
2034 self.buffer_store.update(cx, |buffer_store, cx| {
2035 buffer_store.shared(project_id, self.client.clone().into(), cx)
2036 });
2037 self.worktree_store.update(cx, |worktree_store, cx| {
2038 worktree_store.shared(project_id, self.client.clone().into(), cx);
2039 });
2040 self.lsp_store.update(cx, |lsp_store, cx| {
2041 lsp_store.shared(project_id, self.client.clone().into(), cx)
2042 });
2043 self.breakpoint_store.update(cx, |breakpoint_store, _| {
2044 breakpoint_store.shared(project_id, self.client.clone().into())
2045 });
2046 self.dap_store.update(cx, |dap_store, cx| {
2047 dap_store.shared(project_id, self.client.clone().into(), cx);
2048 });
2049 self.task_store.update(cx, |task_store, cx| {
2050 task_store.shared(project_id, self.client.clone().into(), cx);
2051 });
2052 self.settings_observer.update(cx, |settings_observer, cx| {
2053 settings_observer.shared(project_id, self.client.clone().into(), cx)
2054 });
2055 self.git_store.update(cx, |git_store, cx| {
2056 git_store.shared(project_id, self.client.clone().into(), cx)
2057 });
2058
2059 self.client_state = ProjectClientState::Shared {
2060 remote_id: project_id,
2061 };
2062
2063 cx.emit(Event::RemoteIdChanged(Some(project_id)));
2064 Ok(())
2065 }
2066
2067 pub fn reshared(
2068 &mut self,
2069 message: proto::ResharedProject,
2070 cx: &mut Context<Self>,
2071 ) -> Result<()> {
2072 self.buffer_store
2073 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2074 self.set_collaborators_from_proto(message.collaborators, cx)?;
2075
2076 self.worktree_store.update(cx, |worktree_store, cx| {
2077 worktree_store.send_project_updates(cx);
2078 });
2079 if let Some(remote_id) = self.remote_id() {
2080 self.git_store.update(cx, |git_store, cx| {
2081 git_store.shared(remote_id, self.client.clone().into(), cx)
2082 });
2083 }
2084 cx.emit(Event::Reshared);
2085 Ok(())
2086 }
2087
2088 pub fn rejoined(
2089 &mut self,
2090 message: proto::RejoinedProject,
2091 message_id: u32,
2092 cx: &mut Context<Self>,
2093 ) -> Result<()> {
2094 cx.update_global::<SettingsStore, _>(|store, cx| {
2095 self.worktree_store.update(cx, |worktree_store, cx| {
2096 for worktree in worktree_store.worktrees() {
2097 store
2098 .clear_local_settings(worktree.read(cx).id(), cx)
2099 .log_err();
2100 }
2101 });
2102 });
2103
2104 self.join_project_response_message_id = message_id;
2105 self.set_worktrees_from_proto(message.worktrees, cx)?;
2106 self.set_collaborators_from_proto(message.collaborators, cx)?;
2107 self.lsp_store.update(cx, |lsp_store, _| {
2108 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
2109 });
2110 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2111 .unwrap();
2112 cx.emit(Event::Rejoined);
2113 Ok(())
2114 }
2115
2116 pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2117 self.unshare_internal(cx)?;
2118 cx.emit(Event::RemoteIdChanged(None));
2119 Ok(())
2120 }
2121
2122 fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2123 if self.is_via_collab() {
2124 return Err(anyhow!("attempted to unshare a remote project"));
2125 }
2126
2127 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2128 self.client_state = ProjectClientState::Local;
2129 self.collaborators.clear();
2130 self.client_subscriptions.clear();
2131 self.worktree_store.update(cx, |store, cx| {
2132 store.unshared(cx);
2133 });
2134 self.buffer_store.update(cx, |buffer_store, cx| {
2135 buffer_store.forget_shared_buffers();
2136 buffer_store.unshared(cx)
2137 });
2138 self.task_store.update(cx, |task_store, cx| {
2139 task_store.unshared(cx);
2140 });
2141 self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2142 breakpoint_store.unshared(cx);
2143 });
2144 self.dap_store.update(cx, |dap_store, cx| {
2145 dap_store.unshared(cx);
2146 });
2147 self.settings_observer.update(cx, |settings_observer, cx| {
2148 settings_observer.unshared(cx);
2149 });
2150 self.git_store.update(cx, |git_store, cx| {
2151 git_store.unshared(cx);
2152 });
2153
2154 self.client
2155 .send(proto::UnshareProject {
2156 project_id: remote_id,
2157 })
2158 .ok();
2159 Ok(())
2160 } else {
2161 Err(anyhow!("attempted to unshare an unshared project"))
2162 }
2163 }
2164
2165 pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2166 if self.is_disconnected(cx) {
2167 return;
2168 }
2169 self.disconnected_from_host_internal(cx);
2170 cx.emit(Event::DisconnectedFromHost);
2171 }
2172
2173 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2174 let new_capability =
2175 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2176 Capability::ReadWrite
2177 } else {
2178 Capability::ReadOnly
2179 };
2180 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2181 if *capability == new_capability {
2182 return;
2183 }
2184
2185 *capability = new_capability;
2186 for buffer in self.opened_buffers(cx) {
2187 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2188 }
2189 }
2190 }
2191
2192 fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2193 if let ProjectClientState::Remote {
2194 sharing_has_stopped,
2195 ..
2196 } = &mut self.client_state
2197 {
2198 *sharing_has_stopped = true;
2199 self.collaborators.clear();
2200 self.worktree_store.update(cx, |store, cx| {
2201 store.disconnected_from_host(cx);
2202 });
2203 self.buffer_store.update(cx, |buffer_store, cx| {
2204 buffer_store.disconnected_from_host(cx)
2205 });
2206 self.lsp_store
2207 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2208 }
2209 }
2210
2211 pub fn close(&mut self, cx: &mut Context<Self>) {
2212 cx.emit(Event::Closed);
2213 }
2214
2215 pub fn is_disconnected(&self, cx: &App) -> bool {
2216 match &self.client_state {
2217 ProjectClientState::Remote {
2218 sharing_has_stopped,
2219 ..
2220 } => *sharing_has_stopped,
2221 ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
2222 _ => false,
2223 }
2224 }
2225
2226 fn ssh_is_disconnected(&self, cx: &App) -> bool {
2227 self.ssh_client
2228 .as_ref()
2229 .map(|ssh| ssh.read(cx).is_disconnected())
2230 .unwrap_or(false)
2231 }
2232
2233 pub fn capability(&self) -> Capability {
2234 match &self.client_state {
2235 ProjectClientState::Remote { capability, .. } => *capability,
2236 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2237 }
2238 }
2239
2240 pub fn is_read_only(&self, cx: &App) -> bool {
2241 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2242 }
2243
2244 pub fn is_local(&self) -> bool {
2245 match &self.client_state {
2246 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2247 self.ssh_client.is_none()
2248 }
2249 ProjectClientState::Remote { .. } => false,
2250 }
2251 }
2252
2253 pub fn is_via_ssh(&self) -> bool {
2254 match &self.client_state {
2255 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2256 self.ssh_client.is_some()
2257 }
2258 ProjectClientState::Remote { .. } => false,
2259 }
2260 }
2261
2262 pub fn is_via_collab(&self) -> bool {
2263 match &self.client_state {
2264 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2265 ProjectClientState::Remote { .. } => true,
2266 }
2267 }
2268
2269 pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2270 self.buffer_store
2271 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
2272 }
2273
2274 pub fn create_local_buffer(
2275 &mut self,
2276 text: &str,
2277 language: Option<Arc<Language>>,
2278 cx: &mut Context<Self>,
2279 ) -> Entity<Buffer> {
2280 if self.is_via_collab() || self.is_via_ssh() {
2281 panic!("called create_local_buffer on a remote project")
2282 }
2283 self.buffer_store.update(cx, |buffer_store, cx| {
2284 buffer_store.create_local_buffer(text, language, cx)
2285 })
2286 }
2287
2288 pub fn open_path(
2289 &mut self,
2290 path: ProjectPath,
2291 cx: &mut Context<Self>,
2292 ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
2293 let task = self.open_buffer(path.clone(), cx);
2294 cx.spawn(async move |_project, cx| {
2295 let buffer = task.await?;
2296 let project_entry_id = buffer.read_with(cx, |buffer, cx| {
2297 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
2298 })?;
2299
2300 let buffer: &AnyEntity = &buffer;
2301 Ok((project_entry_id, buffer.clone()))
2302 })
2303 }
2304
2305 pub fn open_local_buffer(
2306 &mut self,
2307 abs_path: impl AsRef<Path>,
2308 cx: &mut Context<Self>,
2309 ) -> Task<Result<Entity<Buffer>>> {
2310 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2311 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
2312 } else {
2313 Task::ready(Err(anyhow!("no such path")))
2314 }
2315 }
2316
2317 #[cfg(any(test, feature = "test-support"))]
2318 pub fn open_local_buffer_with_lsp(
2319 &mut self,
2320 abs_path: impl AsRef<Path>,
2321 cx: &mut Context<Self>,
2322 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2323 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2324 self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2325 } else {
2326 Task::ready(Err(anyhow!("no such path")))
2327 }
2328 }
2329
2330 pub fn open_buffer(
2331 &mut self,
2332 path: impl Into<ProjectPath>,
2333 cx: &mut App,
2334 ) -> Task<Result<Entity<Buffer>>> {
2335 if self.is_disconnected(cx) {
2336 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2337 }
2338
2339 self.buffer_store.update(cx, |buffer_store, cx| {
2340 buffer_store.open_buffer(path.into(), cx)
2341 })
2342 }
2343
2344 #[cfg(any(test, feature = "test-support"))]
2345 pub fn open_buffer_with_lsp(
2346 &mut self,
2347 path: impl Into<ProjectPath>,
2348 cx: &mut Context<Self>,
2349 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2350 let buffer = self.open_buffer(path, cx);
2351 cx.spawn(async move |this, cx| {
2352 let buffer = buffer.await?;
2353 let handle = this.update(cx, |project, cx| {
2354 project.register_buffer_with_language_servers(&buffer, cx)
2355 })?;
2356 Ok((buffer, handle))
2357 })
2358 }
2359
2360 pub fn register_buffer_with_language_servers(
2361 &self,
2362 buffer: &Entity<Buffer>,
2363 cx: &mut App,
2364 ) -> OpenLspBufferHandle {
2365 self.lsp_store.update(cx, |lsp_store, cx| {
2366 lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2367 })
2368 }
2369
2370 pub fn open_unstaged_diff(
2371 &mut self,
2372 buffer: Entity<Buffer>,
2373 cx: &mut Context<Self>,
2374 ) -> Task<Result<Entity<BufferDiff>>> {
2375 if self.is_disconnected(cx) {
2376 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2377 }
2378 self.git_store
2379 .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2380 }
2381
2382 pub fn open_uncommitted_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.update(cx, |git_store, cx| {
2391 git_store.open_uncommitted_diff(buffer, cx)
2392 })
2393 }
2394
2395 pub fn open_buffer_by_id(
2396 &mut self,
2397 id: BufferId,
2398 cx: &mut Context<Self>,
2399 ) -> Task<Result<Entity<Buffer>>> {
2400 if let Some(buffer) = self.buffer_for_id(id, cx) {
2401 Task::ready(Ok(buffer))
2402 } else if self.is_local() || self.is_via_ssh() {
2403 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2404 } else if let Some(project_id) = self.remote_id() {
2405 let request = self.client.request(proto::OpenBufferById {
2406 project_id,
2407 id: id.into(),
2408 });
2409 cx.spawn(async move |project, cx| {
2410 let buffer_id = BufferId::new(request.await?.buffer_id)?;
2411 project
2412 .update(cx, |project, cx| {
2413 project.buffer_store.update(cx, |buffer_store, cx| {
2414 buffer_store.wait_for_remote_buffer(buffer_id, cx)
2415 })
2416 })?
2417 .await
2418 })
2419 } else {
2420 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2421 }
2422 }
2423
2424 pub fn save_buffers(
2425 &self,
2426 buffers: HashSet<Entity<Buffer>>,
2427 cx: &mut Context<Self>,
2428 ) -> Task<Result<()>> {
2429 cx.spawn(async move |this, cx| {
2430 let save_tasks = buffers.into_iter().filter_map(|buffer| {
2431 this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2432 .ok()
2433 });
2434 try_join_all(save_tasks).await?;
2435 Ok(())
2436 })
2437 }
2438
2439 pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2440 self.buffer_store
2441 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2442 }
2443
2444 pub fn save_buffer_as(
2445 &mut self,
2446 buffer: Entity<Buffer>,
2447 path: ProjectPath,
2448 cx: &mut Context<Self>,
2449 ) -> Task<Result<()>> {
2450 self.buffer_store.update(cx, |buffer_store, cx| {
2451 buffer_store.save_buffer_as(buffer.clone(), path, cx)
2452 })
2453 }
2454
2455 pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2456 self.buffer_store.read(cx).get_by_path(path, cx)
2457 }
2458
2459 fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2460 {
2461 let mut remotely_created_models = self.remotely_created_models.lock();
2462 if remotely_created_models.retain_count > 0 {
2463 remotely_created_models.buffers.push(buffer.clone())
2464 }
2465 }
2466
2467 self.request_buffer_diff_recalculation(buffer, cx);
2468
2469 cx.subscribe(buffer, |this, buffer, event, cx| {
2470 this.on_buffer_event(buffer, event, cx);
2471 })
2472 .detach();
2473
2474 Ok(())
2475 }
2476
2477 pub fn open_image(
2478 &mut self,
2479 path: impl Into<ProjectPath>,
2480 cx: &mut Context<Self>,
2481 ) -> Task<Result<Entity<ImageItem>>> {
2482 if self.is_disconnected(cx) {
2483 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2484 }
2485
2486 let open_image_task = self.image_store.update(cx, |image_store, cx| {
2487 image_store.open_image(path.into(), cx)
2488 });
2489
2490 let weak_project = cx.entity().downgrade();
2491 cx.spawn(async move |_, cx| {
2492 let image_item = open_image_task.await?;
2493 let project = weak_project
2494 .upgrade()
2495 .ok_or_else(|| anyhow!("Project dropped"))?;
2496
2497 let metadata = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2498 image_item.update(cx, |image_item, cx| {
2499 image_item.image_metadata = Some(metadata);
2500 cx.emit(ImageItemEvent::MetadataUpdated);
2501 })?;
2502
2503 Ok(image_item)
2504 })
2505 }
2506
2507 async fn send_buffer_ordered_messages(
2508 this: WeakEntity<Self>,
2509 rx: UnboundedReceiver<BufferOrderedMessage>,
2510 cx: &mut AsyncApp,
2511 ) -> Result<()> {
2512 const MAX_BATCH_SIZE: usize = 128;
2513
2514 let mut operations_by_buffer_id = HashMap::default();
2515 async fn flush_operations(
2516 this: &WeakEntity<Project>,
2517 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2518 needs_resync_with_host: &mut bool,
2519 is_local: bool,
2520 cx: &mut AsyncApp,
2521 ) -> Result<()> {
2522 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2523 let request = this.update(cx, |this, _| {
2524 let project_id = this.remote_id()?;
2525 Some(this.client.request(proto::UpdateBuffer {
2526 buffer_id: buffer_id.into(),
2527 project_id,
2528 operations,
2529 }))
2530 })?;
2531 if let Some(request) = request {
2532 if request.await.is_err() && !is_local {
2533 *needs_resync_with_host = true;
2534 break;
2535 }
2536 }
2537 }
2538 Ok(())
2539 }
2540
2541 let mut needs_resync_with_host = false;
2542 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2543
2544 while let Some(changes) = changes.next().await {
2545 let is_local = this.update(cx, |this, _| this.is_local())?;
2546
2547 for change in changes {
2548 match change {
2549 BufferOrderedMessage::Operation {
2550 buffer_id,
2551 operation,
2552 } => {
2553 if needs_resync_with_host {
2554 continue;
2555 }
2556
2557 operations_by_buffer_id
2558 .entry(buffer_id)
2559 .or_insert(Vec::new())
2560 .push(operation);
2561 }
2562
2563 BufferOrderedMessage::Resync => {
2564 operations_by_buffer_id.clear();
2565 if this
2566 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2567 .await
2568 .is_ok()
2569 {
2570 needs_resync_with_host = false;
2571 }
2572 }
2573
2574 BufferOrderedMessage::LanguageServerUpdate {
2575 language_server_id,
2576 message,
2577 } => {
2578 flush_operations(
2579 &this,
2580 &mut operations_by_buffer_id,
2581 &mut needs_resync_with_host,
2582 is_local,
2583 cx,
2584 )
2585 .await?;
2586
2587 this.update(cx, |this, _| {
2588 if let Some(project_id) = this.remote_id() {
2589 this.client
2590 .send(proto::UpdateLanguageServer {
2591 project_id,
2592 language_server_id: language_server_id.0 as u64,
2593 variant: Some(message),
2594 })
2595 .log_err();
2596 }
2597 })?;
2598 }
2599 }
2600 }
2601
2602 flush_operations(
2603 &this,
2604 &mut operations_by_buffer_id,
2605 &mut needs_resync_with_host,
2606 is_local,
2607 cx,
2608 )
2609 .await?;
2610 }
2611
2612 Ok(())
2613 }
2614
2615 fn on_buffer_store_event(
2616 &mut self,
2617 _: Entity<BufferStore>,
2618 event: &BufferStoreEvent,
2619 cx: &mut Context<Self>,
2620 ) {
2621 match event {
2622 BufferStoreEvent::BufferAdded(buffer) => {
2623 self.register_buffer(buffer, cx).log_err();
2624 }
2625 BufferStoreEvent::BufferDropped(buffer_id) => {
2626 if let Some(ref ssh_client) = self.ssh_client {
2627 ssh_client
2628 .read(cx)
2629 .proto_client()
2630 .send(proto::CloseBuffer {
2631 project_id: 0,
2632 buffer_id: buffer_id.to_proto(),
2633 })
2634 .log_err();
2635 }
2636 }
2637 _ => {}
2638 }
2639 }
2640
2641 fn on_image_store_event(
2642 &mut self,
2643 _: Entity<ImageStore>,
2644 event: &ImageStoreEvent,
2645 cx: &mut Context<Self>,
2646 ) {
2647 match event {
2648 ImageStoreEvent::ImageAdded(image) => {
2649 cx.subscribe(image, |this, image, event, cx| {
2650 this.on_image_event(image, event, cx);
2651 })
2652 .detach();
2653 }
2654 }
2655 }
2656
2657 fn on_dap_store_event(
2658 &mut self,
2659 _: Entity<DapStore>,
2660 event: &DapStoreEvent,
2661 cx: &mut Context<Self>,
2662 ) {
2663 match event {
2664 DapStoreEvent::Notification(message) => {
2665 cx.emit(Event::Toast {
2666 notification_id: "dap".into(),
2667 message: message.clone(),
2668 });
2669 }
2670 _ => {}
2671 }
2672 }
2673
2674 fn on_lsp_store_event(
2675 &mut self,
2676 _: Entity<LspStore>,
2677 event: &LspStoreEvent,
2678 cx: &mut Context<Self>,
2679 ) {
2680 match event {
2681 LspStoreEvent::DiagnosticsUpdated {
2682 language_server_id,
2683 path,
2684 } => cx.emit(Event::DiagnosticsUpdated {
2685 path: path.clone(),
2686 language_server_id: *language_server_id,
2687 }),
2688 LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2689 Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2690 ),
2691 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2692 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2693 }
2694 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2695 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2696 ),
2697 LspStoreEvent::LanguageDetected {
2698 buffer,
2699 new_language,
2700 } => {
2701 let Some(_) = new_language else {
2702 cx.emit(Event::LanguageNotFound(buffer.clone()));
2703 return;
2704 };
2705 }
2706 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2707 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2708 LspStoreEvent::LanguageServerPrompt(prompt) => {
2709 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2710 }
2711 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2712 cx.emit(Event::DiskBasedDiagnosticsStarted {
2713 language_server_id: *language_server_id,
2714 });
2715 }
2716 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2717 cx.emit(Event::DiskBasedDiagnosticsFinished {
2718 language_server_id: *language_server_id,
2719 });
2720 }
2721 LspStoreEvent::LanguageServerUpdate {
2722 language_server_id,
2723 message,
2724 } => {
2725 if self.is_local() {
2726 self.enqueue_buffer_ordered_message(
2727 BufferOrderedMessage::LanguageServerUpdate {
2728 language_server_id: *language_server_id,
2729 message: message.clone(),
2730 },
2731 )
2732 .ok();
2733 }
2734 }
2735 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2736 notification_id: "lsp".into(),
2737 message: message.clone(),
2738 }),
2739 LspStoreEvent::SnippetEdit {
2740 buffer_id,
2741 edits,
2742 most_recent_edit,
2743 } => {
2744 if most_recent_edit.replica_id == self.replica_id() {
2745 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2746 }
2747 }
2748 }
2749 }
2750
2751 fn on_ssh_event(
2752 &mut self,
2753 _: Entity<SshRemoteClient>,
2754 event: &remote::SshRemoteEvent,
2755 cx: &mut Context<Self>,
2756 ) {
2757 match event {
2758 remote::SshRemoteEvent::Disconnected => {
2759 // if self.is_via_ssh() {
2760 // self.collaborators.clear();
2761 self.worktree_store.update(cx, |store, cx| {
2762 store.disconnected_from_host(cx);
2763 });
2764 self.buffer_store.update(cx, |buffer_store, cx| {
2765 buffer_store.disconnected_from_host(cx)
2766 });
2767 self.lsp_store.update(cx, |lsp_store, _cx| {
2768 lsp_store.disconnected_from_ssh_remote()
2769 });
2770 cx.emit(Event::DisconnectedFromSshRemote);
2771 }
2772 }
2773 }
2774
2775 fn on_settings_observer_event(
2776 &mut self,
2777 _: Entity<SettingsObserver>,
2778 event: &SettingsObserverEvent,
2779 cx: &mut Context<Self>,
2780 ) {
2781 match event {
2782 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2783 Err(InvalidSettingsError::LocalSettings { message, path }) => {
2784 let message = format!("Failed to set local settings in {path:?}:\n{message}");
2785 cx.emit(Event::Toast {
2786 notification_id: format!("local-settings-{path:?}").into(),
2787 message,
2788 });
2789 }
2790 Ok(path) => cx.emit(Event::HideToast {
2791 notification_id: format!("local-settings-{path:?}").into(),
2792 }),
2793 Err(_) => {}
2794 },
2795 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
2796 Err(InvalidSettingsError::Tasks { message, path }) => {
2797 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
2798 cx.emit(Event::Toast {
2799 notification_id: format!("local-tasks-{path:?}").into(),
2800 message,
2801 });
2802 }
2803 Ok(path) => cx.emit(Event::HideToast {
2804 notification_id: format!("local-tasks-{path:?}").into(),
2805 }),
2806 Err(_) => {}
2807 },
2808 }
2809 }
2810
2811 fn on_worktree_store_event(
2812 &mut self,
2813 _: Entity<WorktreeStore>,
2814 event: &WorktreeStoreEvent,
2815 cx: &mut Context<Self>,
2816 ) {
2817 match event {
2818 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2819 self.on_worktree_added(worktree, cx);
2820 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2821 }
2822 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2823 cx.emit(Event::WorktreeRemoved(*id));
2824 }
2825 WorktreeStoreEvent::WorktreeReleased(_, id) => {
2826 self.on_worktree_released(*id, cx);
2827 }
2828 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2829 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2830 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2831 self.client()
2832 .telemetry()
2833 .report_discovered_project_events(*worktree_id, changes);
2834 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2835 }
2836 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2837 cx.emit(Event::DeletedEntry(*worktree_id, *id))
2838 }
2839 // Listen to the GitStore instead.
2840 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
2841 }
2842 }
2843
2844 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2845 let mut remotely_created_models = self.remotely_created_models.lock();
2846 if remotely_created_models.retain_count > 0 {
2847 remotely_created_models.worktrees.push(worktree.clone())
2848 }
2849 }
2850
2851 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2852 if let Some(ssh) = &self.ssh_client {
2853 ssh.read(cx)
2854 .proto_client()
2855 .send(proto::RemoveWorktree {
2856 worktree_id: id_to_remove.to_proto(),
2857 })
2858 .log_err();
2859 }
2860 }
2861
2862 fn on_buffer_event(
2863 &mut self,
2864 buffer: Entity<Buffer>,
2865 event: &BufferEvent,
2866 cx: &mut Context<Self>,
2867 ) -> Option<()> {
2868 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2869 self.request_buffer_diff_recalculation(&buffer, cx);
2870 }
2871
2872 let buffer_id = buffer.read(cx).remote_id();
2873 match event {
2874 BufferEvent::ReloadNeeded => {
2875 if !self.is_via_collab() {
2876 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2877 .detach_and_log_err(cx);
2878 }
2879 }
2880 BufferEvent::Operation {
2881 operation,
2882 is_local: true,
2883 } => {
2884 let operation = language::proto::serialize_operation(operation);
2885
2886 if let Some(ssh) = &self.ssh_client {
2887 ssh.read(cx)
2888 .proto_client()
2889 .send(proto::UpdateBuffer {
2890 project_id: 0,
2891 buffer_id: buffer_id.to_proto(),
2892 operations: vec![operation.clone()],
2893 })
2894 .ok();
2895 }
2896
2897 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2898 buffer_id,
2899 operation,
2900 })
2901 .ok();
2902 }
2903
2904 _ => {}
2905 }
2906
2907 None
2908 }
2909
2910 fn on_image_event(
2911 &mut self,
2912 image: Entity<ImageItem>,
2913 event: &ImageItemEvent,
2914 cx: &mut Context<Self>,
2915 ) -> Option<()> {
2916 match event {
2917 ImageItemEvent::ReloadNeeded => {
2918 if !self.is_via_collab() {
2919 self.reload_images([image.clone()].into_iter().collect(), cx)
2920 .detach_and_log_err(cx);
2921 }
2922 }
2923 _ => {}
2924 }
2925
2926 None
2927 }
2928
2929 fn request_buffer_diff_recalculation(
2930 &mut self,
2931 buffer: &Entity<Buffer>,
2932 cx: &mut Context<Self>,
2933 ) {
2934 self.buffers_needing_diff.insert(buffer.downgrade());
2935 let first_insertion = self.buffers_needing_diff.len() == 1;
2936
2937 let settings = ProjectSettings::get_global(cx);
2938 let delay = if let Some(delay) = settings.git.gutter_debounce {
2939 delay
2940 } else {
2941 if first_insertion {
2942 let this = cx.weak_entity();
2943 cx.defer(move |cx| {
2944 if let Some(this) = this.upgrade() {
2945 this.update(cx, |this, cx| {
2946 this.recalculate_buffer_diffs(cx).detach();
2947 });
2948 }
2949 });
2950 }
2951 return;
2952 };
2953
2954 const MIN_DELAY: u64 = 50;
2955 let delay = delay.max(MIN_DELAY);
2956 let duration = Duration::from_millis(delay);
2957
2958 self.git_diff_debouncer
2959 .fire_new(duration, cx, move |this, cx| {
2960 this.recalculate_buffer_diffs(cx)
2961 });
2962 }
2963
2964 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2965 cx.spawn(async move |this, cx| {
2966 loop {
2967 let task = this
2968 .update(cx, |this, cx| {
2969 let buffers = this
2970 .buffers_needing_diff
2971 .drain()
2972 .filter_map(|buffer| buffer.upgrade())
2973 .collect::<Vec<_>>();
2974 if buffers.is_empty() {
2975 None
2976 } else {
2977 Some(this.git_store.update(cx, |git_store, cx| {
2978 git_store.recalculate_buffer_diffs(buffers, cx)
2979 }))
2980 }
2981 })
2982 .ok()
2983 .flatten();
2984
2985 if let Some(task) = task {
2986 task.await;
2987 } else {
2988 break;
2989 }
2990 }
2991 })
2992 }
2993
2994 pub fn set_language_for_buffer(
2995 &mut self,
2996 buffer: &Entity<Buffer>,
2997 new_language: Arc<Language>,
2998 cx: &mut Context<Self>,
2999 ) {
3000 self.lsp_store.update(cx, |lsp_store, cx| {
3001 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3002 })
3003 }
3004
3005 pub fn restart_language_servers_for_buffers(
3006 &mut self,
3007 buffers: Vec<Entity<Buffer>>,
3008 cx: &mut Context<Self>,
3009 ) {
3010 self.lsp_store.update(cx, |lsp_store, cx| {
3011 lsp_store.restart_language_servers_for_buffers(buffers, cx)
3012 })
3013 }
3014
3015 pub fn stop_language_servers_for_buffers(
3016 &mut self,
3017 buffers: Vec<Entity<Buffer>>,
3018 cx: &mut Context<Self>,
3019 ) {
3020 self.lsp_store.update(cx, |lsp_store, cx| {
3021 lsp_store.stop_language_servers_for_buffers(buffers, cx)
3022 })
3023 }
3024
3025 pub fn cancel_language_server_work_for_buffers(
3026 &mut self,
3027 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3028 cx: &mut Context<Self>,
3029 ) {
3030 self.lsp_store.update(cx, |lsp_store, cx| {
3031 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3032 })
3033 }
3034
3035 pub fn cancel_language_server_work(
3036 &mut self,
3037 server_id: LanguageServerId,
3038 token_to_cancel: Option<String>,
3039 cx: &mut Context<Self>,
3040 ) {
3041 self.lsp_store.update(cx, |lsp_store, cx| {
3042 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3043 })
3044 }
3045
3046 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3047 self.buffer_ordered_messages_tx
3048 .unbounded_send(message)
3049 .map_err(|e| anyhow!(e))
3050 }
3051
3052 pub fn available_toolchains(
3053 &self,
3054 path: ProjectPath,
3055 language_name: LanguageName,
3056 cx: &App,
3057 ) -> Task<Option<ToolchainList>> {
3058 if let Some(toolchain_store) = self.toolchain_store.clone() {
3059 cx.spawn(async move |cx| {
3060 cx.update(|cx| {
3061 toolchain_store
3062 .read(cx)
3063 .list_toolchains(path, language_name, cx)
3064 })
3065 .ok()?
3066 .await
3067 })
3068 } else {
3069 Task::ready(None)
3070 }
3071 }
3072
3073 pub async fn toolchain_term(
3074 languages: Arc<LanguageRegistry>,
3075 language_name: LanguageName,
3076 ) -> Option<SharedString> {
3077 languages
3078 .language_for_name(language_name.as_ref())
3079 .await
3080 .ok()?
3081 .toolchain_lister()
3082 .map(|lister| lister.term())
3083 }
3084
3085 pub fn activate_toolchain(
3086 &self,
3087 path: ProjectPath,
3088 toolchain: Toolchain,
3089 cx: &mut App,
3090 ) -> Task<Option<()>> {
3091 let Some(toolchain_store) = self.toolchain_store.clone() else {
3092 return Task::ready(None);
3093 };
3094 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3095 }
3096 pub fn active_toolchain(
3097 &self,
3098 path: ProjectPath,
3099 language_name: LanguageName,
3100 cx: &App,
3101 ) -> Task<Option<Toolchain>> {
3102 let Some(toolchain_store) = self.toolchain_store.clone() else {
3103 return Task::ready(None);
3104 };
3105 toolchain_store
3106 .read(cx)
3107 .active_toolchain(path, language_name, cx)
3108 }
3109 pub fn language_server_statuses<'a>(
3110 &'a self,
3111 cx: &'a App,
3112 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3113 self.lsp_store.read(cx).language_server_statuses()
3114 }
3115
3116 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3117 self.lsp_store.read(cx).last_formatting_failure()
3118 }
3119
3120 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3121 self.lsp_store
3122 .update(cx, |store, _| store.reset_last_formatting_failure());
3123 }
3124
3125 pub fn reload_buffers(
3126 &self,
3127 buffers: HashSet<Entity<Buffer>>,
3128 push_to_history: bool,
3129 cx: &mut Context<Self>,
3130 ) -> Task<Result<ProjectTransaction>> {
3131 self.buffer_store.update(cx, |buffer_store, cx| {
3132 buffer_store.reload_buffers(buffers, push_to_history, cx)
3133 })
3134 }
3135
3136 pub fn reload_images(
3137 &self,
3138 images: HashSet<Entity<ImageItem>>,
3139 cx: &mut Context<Self>,
3140 ) -> Task<Result<()>> {
3141 self.image_store
3142 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3143 }
3144
3145 pub fn format(
3146 &mut self,
3147 buffers: HashSet<Entity<Buffer>>,
3148 target: LspFormatTarget,
3149 push_to_history: bool,
3150 trigger: lsp_store::FormatTrigger,
3151 cx: &mut Context<Project>,
3152 ) -> Task<anyhow::Result<ProjectTransaction>> {
3153 self.lsp_store.update(cx, |lsp_store, cx| {
3154 lsp_store.format(buffers, target, push_to_history, trigger, cx)
3155 })
3156 }
3157
3158 #[inline(never)]
3159 fn definition_impl(
3160 &mut self,
3161 buffer: &Entity<Buffer>,
3162 position: PointUtf16,
3163 cx: &mut Context<Self>,
3164 ) -> Task<Result<Vec<LocationLink>>> {
3165 self.request_lsp(
3166 buffer.clone(),
3167 LanguageServerToQuery::FirstCapable,
3168 GetDefinition { position },
3169 cx,
3170 )
3171 }
3172 pub fn definition<T: ToPointUtf16>(
3173 &mut self,
3174 buffer: &Entity<Buffer>,
3175 position: T,
3176 cx: &mut Context<Self>,
3177 ) -> Task<Result<Vec<LocationLink>>> {
3178 let position = position.to_point_utf16(buffer.read(cx));
3179 self.definition_impl(buffer, position, cx)
3180 }
3181
3182 fn declaration_impl(
3183 &mut self,
3184 buffer: &Entity<Buffer>,
3185 position: PointUtf16,
3186 cx: &mut Context<Self>,
3187 ) -> Task<Result<Vec<LocationLink>>> {
3188 self.request_lsp(
3189 buffer.clone(),
3190 LanguageServerToQuery::FirstCapable,
3191 GetDeclaration { position },
3192 cx,
3193 )
3194 }
3195
3196 pub fn declaration<T: ToPointUtf16>(
3197 &mut self,
3198 buffer: &Entity<Buffer>,
3199 position: T,
3200 cx: &mut Context<Self>,
3201 ) -> Task<Result<Vec<LocationLink>>> {
3202 let position = position.to_point_utf16(buffer.read(cx));
3203 self.declaration_impl(buffer, position, cx)
3204 }
3205
3206 fn type_definition_impl(
3207 &mut self,
3208 buffer: &Entity<Buffer>,
3209 position: PointUtf16,
3210 cx: &mut Context<Self>,
3211 ) -> Task<Result<Vec<LocationLink>>> {
3212 self.request_lsp(
3213 buffer.clone(),
3214 LanguageServerToQuery::FirstCapable,
3215 GetTypeDefinition { position },
3216 cx,
3217 )
3218 }
3219
3220 pub fn type_definition<T: ToPointUtf16>(
3221 &mut self,
3222 buffer: &Entity<Buffer>,
3223 position: T,
3224 cx: &mut Context<Self>,
3225 ) -> Task<Result<Vec<LocationLink>>> {
3226 let position = position.to_point_utf16(buffer.read(cx));
3227 self.type_definition_impl(buffer, position, cx)
3228 }
3229
3230 pub fn implementation<T: ToPointUtf16>(
3231 &mut self,
3232 buffer: &Entity<Buffer>,
3233 position: T,
3234 cx: &mut Context<Self>,
3235 ) -> Task<Result<Vec<LocationLink>>> {
3236 let position = position.to_point_utf16(buffer.read(cx));
3237 self.request_lsp(
3238 buffer.clone(),
3239 LanguageServerToQuery::FirstCapable,
3240 GetImplementation { position },
3241 cx,
3242 )
3243 }
3244
3245 pub fn references<T: ToPointUtf16>(
3246 &mut self,
3247 buffer: &Entity<Buffer>,
3248 position: T,
3249 cx: &mut Context<Self>,
3250 ) -> Task<Result<Vec<Location>>> {
3251 let position = position.to_point_utf16(buffer.read(cx));
3252 self.request_lsp(
3253 buffer.clone(),
3254 LanguageServerToQuery::FirstCapable,
3255 GetReferences { position },
3256 cx,
3257 )
3258 }
3259
3260 fn document_highlights_impl(
3261 &mut self,
3262 buffer: &Entity<Buffer>,
3263 position: PointUtf16,
3264 cx: &mut Context<Self>,
3265 ) -> Task<Result<Vec<DocumentHighlight>>> {
3266 self.request_lsp(
3267 buffer.clone(),
3268 LanguageServerToQuery::FirstCapable,
3269 GetDocumentHighlights { position },
3270 cx,
3271 )
3272 }
3273
3274 pub fn document_highlights<T: ToPointUtf16>(
3275 &mut self,
3276 buffer: &Entity<Buffer>,
3277 position: T,
3278 cx: &mut Context<Self>,
3279 ) -> Task<Result<Vec<DocumentHighlight>>> {
3280 let position = position.to_point_utf16(buffer.read(cx));
3281 self.document_highlights_impl(buffer, position, cx)
3282 }
3283
3284 pub fn document_symbols(
3285 &mut self,
3286 buffer: &Entity<Buffer>,
3287 cx: &mut Context<Self>,
3288 ) -> Task<Result<Vec<DocumentSymbol>>> {
3289 self.request_lsp(
3290 buffer.clone(),
3291 LanguageServerToQuery::FirstCapable,
3292 GetDocumentSymbols,
3293 cx,
3294 )
3295 }
3296
3297 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3298 self.lsp_store
3299 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3300 }
3301
3302 pub fn open_buffer_for_symbol(
3303 &mut self,
3304 symbol: &Symbol,
3305 cx: &mut Context<Self>,
3306 ) -> Task<Result<Entity<Buffer>>> {
3307 self.lsp_store.update(cx, |lsp_store, cx| {
3308 lsp_store.open_buffer_for_symbol(symbol, cx)
3309 })
3310 }
3311
3312 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3313 let guard = self.retain_remotely_created_models(cx);
3314 let Some(ssh_client) = self.ssh_client.as_ref() else {
3315 return Task::ready(Err(anyhow!("not an ssh project")));
3316 };
3317
3318 let proto_client = ssh_client.read(cx).proto_client();
3319
3320 cx.spawn(async move |project, cx| {
3321 let buffer = proto_client
3322 .request(proto::OpenServerSettings {
3323 project_id: SSH_PROJECT_ID,
3324 })
3325 .await?;
3326
3327 let buffer = project
3328 .update(cx, |project, cx| {
3329 project.buffer_store.update(cx, |buffer_store, cx| {
3330 anyhow::Ok(
3331 buffer_store
3332 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3333 )
3334 })
3335 })??
3336 .await;
3337
3338 drop(guard);
3339 buffer
3340 })
3341 }
3342
3343 pub fn open_local_buffer_via_lsp(
3344 &mut self,
3345 abs_path: lsp::Url,
3346 language_server_id: LanguageServerId,
3347 language_server_name: LanguageServerName,
3348 cx: &mut Context<Self>,
3349 ) -> Task<Result<Entity<Buffer>>> {
3350 self.lsp_store.update(cx, |lsp_store, cx| {
3351 lsp_store.open_local_buffer_via_lsp(
3352 abs_path,
3353 language_server_id,
3354 language_server_name,
3355 cx,
3356 )
3357 })
3358 }
3359
3360 pub fn signature_help<T: ToPointUtf16>(
3361 &self,
3362 buffer: &Entity<Buffer>,
3363 position: T,
3364 cx: &mut Context<Self>,
3365 ) -> Task<Vec<SignatureHelp>> {
3366 self.lsp_store.update(cx, |lsp_store, cx| {
3367 lsp_store.signature_help(buffer, position, cx)
3368 })
3369 }
3370
3371 pub fn hover<T: ToPointUtf16>(
3372 &self,
3373 buffer: &Entity<Buffer>,
3374 position: T,
3375 cx: &mut Context<Self>,
3376 ) -> Task<Vec<Hover>> {
3377 let position = position.to_point_utf16(buffer.read(cx));
3378 self.lsp_store
3379 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3380 }
3381
3382 pub fn linked_edit(
3383 &self,
3384 buffer: &Entity<Buffer>,
3385 position: Anchor,
3386 cx: &mut Context<Self>,
3387 ) -> Task<Result<Vec<Range<Anchor>>>> {
3388 self.lsp_store.update(cx, |lsp_store, cx| {
3389 lsp_store.linked_edit(buffer, position, cx)
3390 })
3391 }
3392
3393 pub fn completions<T: ToOffset + ToPointUtf16>(
3394 &self,
3395 buffer: &Entity<Buffer>,
3396 position: T,
3397 context: CompletionContext,
3398 cx: &mut Context<Self>,
3399 ) -> Task<Result<Option<Vec<Completion>>>> {
3400 let position = position.to_point_utf16(buffer.read(cx));
3401 self.lsp_store.update(cx, |lsp_store, cx| {
3402 lsp_store.completions(buffer, position, context, cx)
3403 })
3404 }
3405
3406 pub fn code_actions<T: Clone + ToOffset>(
3407 &mut self,
3408 buffer_handle: &Entity<Buffer>,
3409 range: Range<T>,
3410 kinds: Option<Vec<CodeActionKind>>,
3411 cx: &mut Context<Self>,
3412 ) -> Task<Result<Vec<CodeAction>>> {
3413 let buffer = buffer_handle.read(cx);
3414 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3415 self.lsp_store.update(cx, |lsp_store, cx| {
3416 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3417 })
3418 }
3419
3420 pub fn code_lens<T: Clone + ToOffset>(
3421 &mut self,
3422 buffer_handle: &Entity<Buffer>,
3423 range: Range<T>,
3424 cx: &mut Context<Self>,
3425 ) -> Task<Result<Vec<CodeAction>>> {
3426 let snapshot = buffer_handle.read(cx).snapshot();
3427 let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3428 let code_lens_actions = self
3429 .lsp_store
3430 .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3431
3432 cx.background_spawn(async move {
3433 let mut code_lens_actions = code_lens_actions.await?;
3434 code_lens_actions.retain(|code_lens_action| {
3435 range
3436 .start
3437 .cmp(&code_lens_action.range.start, &snapshot)
3438 .is_ge()
3439 && range
3440 .end
3441 .cmp(&code_lens_action.range.end, &snapshot)
3442 .is_le()
3443 });
3444 Ok(code_lens_actions)
3445 })
3446 }
3447
3448 pub fn apply_code_action(
3449 &self,
3450 buffer_handle: Entity<Buffer>,
3451 action: CodeAction,
3452 push_to_history: bool,
3453 cx: &mut Context<Self>,
3454 ) -> Task<Result<ProjectTransaction>> {
3455 self.lsp_store.update(cx, |lsp_store, cx| {
3456 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3457 })
3458 }
3459
3460 pub fn apply_code_action_kind(
3461 &self,
3462 buffers: HashSet<Entity<Buffer>>,
3463 kind: CodeActionKind,
3464 push_to_history: bool,
3465 cx: &mut Context<Self>,
3466 ) -> Task<Result<ProjectTransaction>> {
3467 self.lsp_store.update(cx, |lsp_store, cx| {
3468 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3469 })
3470 }
3471
3472 fn prepare_rename_impl(
3473 &mut self,
3474 buffer: Entity<Buffer>,
3475 position: PointUtf16,
3476 cx: &mut Context<Self>,
3477 ) -> Task<Result<PrepareRenameResponse>> {
3478 self.request_lsp(
3479 buffer,
3480 LanguageServerToQuery::FirstCapable,
3481 PrepareRename { position },
3482 cx,
3483 )
3484 }
3485 pub fn prepare_rename<T: ToPointUtf16>(
3486 &mut self,
3487 buffer: Entity<Buffer>,
3488 position: T,
3489 cx: &mut Context<Self>,
3490 ) -> Task<Result<PrepareRenameResponse>> {
3491 let position = position.to_point_utf16(buffer.read(cx));
3492 self.prepare_rename_impl(buffer, position, cx)
3493 }
3494
3495 pub fn perform_rename<T: ToPointUtf16>(
3496 &mut self,
3497 buffer: Entity<Buffer>,
3498 position: T,
3499 new_name: String,
3500 cx: &mut Context<Self>,
3501 ) -> Task<Result<ProjectTransaction>> {
3502 let push_to_history = true;
3503 let position = position.to_point_utf16(buffer.read(cx));
3504 self.request_lsp(
3505 buffer,
3506 LanguageServerToQuery::FirstCapable,
3507 PerformRename {
3508 position,
3509 new_name,
3510 push_to_history,
3511 },
3512 cx,
3513 )
3514 }
3515
3516 pub fn on_type_format<T: ToPointUtf16>(
3517 &mut self,
3518 buffer: Entity<Buffer>,
3519 position: T,
3520 trigger: String,
3521 push_to_history: bool,
3522 cx: &mut Context<Self>,
3523 ) -> Task<Result<Option<Transaction>>> {
3524 self.lsp_store.update(cx, |lsp_store, cx| {
3525 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3526 })
3527 }
3528
3529 pub fn inlay_hints<T: ToOffset>(
3530 &mut self,
3531 buffer_handle: Entity<Buffer>,
3532 range: Range<T>,
3533 cx: &mut Context<Self>,
3534 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3535 let buffer = buffer_handle.read(cx);
3536 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3537 self.lsp_store.update(cx, |lsp_store, cx| {
3538 lsp_store.inlay_hints(buffer_handle, range, cx)
3539 })
3540 }
3541
3542 pub fn resolve_inlay_hint(
3543 &self,
3544 hint: InlayHint,
3545 buffer_handle: Entity<Buffer>,
3546 server_id: LanguageServerId,
3547 cx: &mut Context<Self>,
3548 ) -> Task<anyhow::Result<InlayHint>> {
3549 self.lsp_store.update(cx, |lsp_store, cx| {
3550 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3551 })
3552 }
3553
3554 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3555 let (result_tx, result_rx) = smol::channel::unbounded();
3556
3557 let matching_buffers_rx = if query.is_opened_only() {
3558 self.sort_search_candidates(&query, cx)
3559 } else {
3560 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3561 };
3562
3563 cx.spawn(async move |_, cx| {
3564 let mut range_count = 0;
3565 let mut buffer_count = 0;
3566 let mut limit_reached = false;
3567 let query = Arc::new(query);
3568 let mut chunks = matching_buffers_rx.ready_chunks(64);
3569
3570 // Now that we know what paths match the query, we will load at most
3571 // 64 buffers at a time to avoid overwhelming the main thread. For each
3572 // opened buffer, we will spawn a background task that retrieves all the
3573 // ranges in the buffer matched by the query.
3574 let mut chunks = pin!(chunks);
3575 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3576 let mut chunk_results = Vec::new();
3577 for buffer in matching_buffer_chunk {
3578 let buffer = buffer.clone();
3579 let query = query.clone();
3580 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3581 chunk_results.push(cx.background_spawn(async move {
3582 let ranges = query
3583 .search(&snapshot, None)
3584 .await
3585 .iter()
3586 .map(|range| {
3587 snapshot.anchor_before(range.start)
3588 ..snapshot.anchor_after(range.end)
3589 })
3590 .collect::<Vec<_>>();
3591 anyhow::Ok((buffer, ranges))
3592 }));
3593 }
3594
3595 let chunk_results = futures::future::join_all(chunk_results).await;
3596 for result in chunk_results {
3597 if let Some((buffer, ranges)) = result.log_err() {
3598 range_count += ranges.len();
3599 buffer_count += 1;
3600 result_tx
3601 .send(SearchResult::Buffer { buffer, ranges })
3602 .await?;
3603 if buffer_count > MAX_SEARCH_RESULT_FILES
3604 || range_count > MAX_SEARCH_RESULT_RANGES
3605 {
3606 limit_reached = true;
3607 break 'outer;
3608 }
3609 }
3610 }
3611 }
3612
3613 if limit_reached {
3614 result_tx.send(SearchResult::LimitReached).await?;
3615 }
3616
3617 anyhow::Ok(())
3618 })
3619 .detach();
3620
3621 result_rx
3622 }
3623
3624 fn find_search_candidate_buffers(
3625 &mut self,
3626 query: &SearchQuery,
3627 limit: usize,
3628 cx: &mut Context<Project>,
3629 ) -> Receiver<Entity<Buffer>> {
3630 if self.is_local() {
3631 let fs = self.fs.clone();
3632 self.buffer_store.update(cx, |buffer_store, cx| {
3633 buffer_store.find_search_candidates(query, limit, fs, cx)
3634 })
3635 } else {
3636 self.find_search_candidates_remote(query, limit, cx)
3637 }
3638 }
3639
3640 fn sort_search_candidates(
3641 &mut self,
3642 search_query: &SearchQuery,
3643 cx: &mut Context<Project>,
3644 ) -> Receiver<Entity<Buffer>> {
3645 let worktree_store = self.worktree_store.read(cx);
3646 let mut buffers = search_query
3647 .buffers()
3648 .into_iter()
3649 .flatten()
3650 .filter(|buffer| {
3651 let b = buffer.read(cx);
3652 if let Some(file) = b.file() {
3653 if !search_query.file_matches(file.path()) {
3654 return false;
3655 }
3656 if let Some(entry) = b
3657 .entry_id(cx)
3658 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3659 {
3660 if entry.is_ignored && !search_query.include_ignored() {
3661 return false;
3662 }
3663 }
3664 }
3665 true
3666 })
3667 .collect::<Vec<_>>();
3668 let (tx, rx) = smol::channel::unbounded();
3669 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3670 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3671 (None, Some(_)) => std::cmp::Ordering::Less,
3672 (Some(_), None) => std::cmp::Ordering::Greater,
3673 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3674 });
3675 for buffer in buffers {
3676 tx.send_blocking(buffer.clone()).unwrap()
3677 }
3678
3679 rx
3680 }
3681
3682 fn find_search_candidates_remote(
3683 &mut self,
3684 query: &SearchQuery,
3685 limit: usize,
3686 cx: &mut Context<Project>,
3687 ) -> Receiver<Entity<Buffer>> {
3688 let (tx, rx) = smol::channel::unbounded();
3689
3690 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3691 (ssh_client.read(cx).proto_client(), 0)
3692 } else if let Some(remote_id) = self.remote_id() {
3693 (self.client.clone().into(), remote_id)
3694 } else {
3695 return rx;
3696 };
3697
3698 let request = client.request(proto::FindSearchCandidates {
3699 project_id: remote_id,
3700 query: Some(query.to_proto()),
3701 limit: limit as _,
3702 });
3703 let guard = self.retain_remotely_created_models(cx);
3704
3705 cx.spawn(async move |project, cx| {
3706 let response = request.await?;
3707 for buffer_id in response.buffer_ids {
3708 let buffer_id = BufferId::new(buffer_id)?;
3709 let buffer = project
3710 .update(cx, |project, cx| {
3711 project.buffer_store.update(cx, |buffer_store, cx| {
3712 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3713 })
3714 })?
3715 .await?;
3716 let _ = tx.send(buffer).await;
3717 }
3718
3719 drop(guard);
3720 anyhow::Ok(())
3721 })
3722 .detach_and_log_err(cx);
3723 rx
3724 }
3725
3726 pub fn request_lsp<R: LspCommand>(
3727 &mut self,
3728 buffer_handle: Entity<Buffer>,
3729 server: LanguageServerToQuery,
3730 request: R,
3731 cx: &mut Context<Self>,
3732 ) -> Task<Result<R::Response>>
3733 where
3734 <R::LspRequest as lsp::request::Request>::Result: Send,
3735 <R::LspRequest as lsp::request::Request>::Params: Send,
3736 {
3737 let guard = self.retain_remotely_created_models(cx);
3738 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3739 lsp_store.request_lsp(buffer_handle, server, request, cx)
3740 });
3741 cx.spawn(async move |_, _| {
3742 let result = task.await;
3743 drop(guard);
3744 result
3745 })
3746 }
3747
3748 /// Move a worktree to a new position in the worktree order.
3749 ///
3750 /// The worktree will moved to the opposite side of the destination worktree.
3751 ///
3752 /// # Example
3753 ///
3754 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3755 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3756 ///
3757 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3758 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3759 ///
3760 /// # Errors
3761 ///
3762 /// An error will be returned if the worktree or destination worktree are not found.
3763 pub fn move_worktree(
3764 &mut self,
3765 source: WorktreeId,
3766 destination: WorktreeId,
3767 cx: &mut Context<Self>,
3768 ) -> Result<()> {
3769 self.worktree_store.update(cx, |worktree_store, cx| {
3770 worktree_store.move_worktree(source, destination, cx)
3771 })
3772 }
3773
3774 pub fn find_or_create_worktree(
3775 &mut self,
3776 abs_path: impl AsRef<Path>,
3777 visible: bool,
3778 cx: &mut Context<Self>,
3779 ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3780 self.worktree_store.update(cx, |worktree_store, cx| {
3781 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3782 })
3783 }
3784
3785 pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3786 self.worktree_store.read_with(cx, |worktree_store, cx| {
3787 worktree_store.find_worktree(abs_path, cx)
3788 })
3789 }
3790
3791 pub fn is_shared(&self) -> bool {
3792 match &self.client_state {
3793 ProjectClientState::Shared { .. } => true,
3794 ProjectClientState::Local => false,
3795 ProjectClientState::Remote { .. } => true,
3796 }
3797 }
3798
3799 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3800 pub fn resolve_path_in_buffer(
3801 &self,
3802 path: &str,
3803 buffer: &Entity<Buffer>,
3804 cx: &mut Context<Self>,
3805 ) -> Task<Option<ResolvedPath>> {
3806 let path_buf = PathBuf::from(path);
3807 if path_buf.is_absolute() || path.starts_with("~") {
3808 self.resolve_abs_path(path, cx)
3809 } else {
3810 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3811 }
3812 }
3813
3814 pub fn resolve_abs_file_path(
3815 &self,
3816 path: &str,
3817 cx: &mut Context<Self>,
3818 ) -> Task<Option<ResolvedPath>> {
3819 let resolve_task = self.resolve_abs_path(path, cx);
3820 cx.background_spawn(async move {
3821 let resolved_path = resolve_task.await;
3822 resolved_path.filter(|path| path.is_file())
3823 })
3824 }
3825
3826 pub fn resolve_abs_path(
3827 &self,
3828 path: &str,
3829 cx: &mut Context<Self>,
3830 ) -> Task<Option<ResolvedPath>> {
3831 if self.is_local() {
3832 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3833 let fs = self.fs.clone();
3834 cx.background_spawn(async move {
3835 let path = expanded.as_path();
3836 let metadata = fs.metadata(path).await.ok().flatten();
3837
3838 metadata.map(|metadata| ResolvedPath::AbsPath {
3839 path: expanded,
3840 is_dir: metadata.is_dir,
3841 })
3842 })
3843 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3844 let request_path = Path::new(path);
3845 let request = ssh_client
3846 .read(cx)
3847 .proto_client()
3848 .request(proto::GetPathMetadata {
3849 project_id: SSH_PROJECT_ID,
3850 path: request_path.to_proto(),
3851 });
3852 cx.background_spawn(async move {
3853 let response = request.await.log_err()?;
3854 if response.exists {
3855 Some(ResolvedPath::AbsPath {
3856 path: PathBuf::from_proto(response.path),
3857 is_dir: response.is_dir,
3858 })
3859 } else {
3860 None
3861 }
3862 })
3863 } else {
3864 return Task::ready(None);
3865 }
3866 }
3867
3868 fn resolve_path_in_worktrees(
3869 &self,
3870 path: PathBuf,
3871 buffer: &Entity<Buffer>,
3872 cx: &mut Context<Self>,
3873 ) -> Task<Option<ResolvedPath>> {
3874 let mut candidates = vec![path.clone()];
3875
3876 if let Some(file) = buffer.read(cx).file() {
3877 if let Some(dir) = file.path().parent() {
3878 let joined = dir.to_path_buf().join(path);
3879 candidates.push(joined);
3880 }
3881 }
3882
3883 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3884 let worktrees_with_ids: Vec<_> = self
3885 .worktrees(cx)
3886 .map(|worktree| {
3887 let id = worktree.read(cx).id();
3888 (worktree, id)
3889 })
3890 .collect();
3891
3892 cx.spawn(async move |_, mut cx| {
3893 if let Some(buffer_worktree_id) = buffer_worktree_id {
3894 if let Some((worktree, _)) = worktrees_with_ids
3895 .iter()
3896 .find(|(_, id)| *id == buffer_worktree_id)
3897 {
3898 for candidate in candidates.iter() {
3899 if let Some(path) =
3900 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3901 {
3902 return Some(path);
3903 }
3904 }
3905 }
3906 }
3907 for (worktree, id) in worktrees_with_ids {
3908 if Some(id) == buffer_worktree_id {
3909 continue;
3910 }
3911 for candidate in candidates.iter() {
3912 if let Some(path) =
3913 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3914 {
3915 return Some(path);
3916 }
3917 }
3918 }
3919 None
3920 })
3921 }
3922
3923 fn resolve_path_in_worktree(
3924 worktree: &Entity<Worktree>,
3925 path: &PathBuf,
3926 cx: &mut AsyncApp,
3927 ) -> Option<ResolvedPath> {
3928 worktree
3929 .update(cx, |worktree, _| {
3930 let root_entry_path = &worktree.root_entry()?.path;
3931 let resolved = resolve_path(root_entry_path, path);
3932 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3933 worktree.entry_for_path(stripped).map(|entry| {
3934 let project_path = ProjectPath {
3935 worktree_id: worktree.id(),
3936 path: entry.path.clone(),
3937 };
3938 ResolvedPath::ProjectPath {
3939 project_path,
3940 is_dir: entry.is_dir(),
3941 }
3942 })
3943 })
3944 .ok()?
3945 }
3946
3947 pub fn list_directory(
3948 &self,
3949 query: String,
3950 cx: &mut Context<Self>,
3951 ) -> Task<Result<Vec<DirectoryItem>>> {
3952 if self.is_local() {
3953 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3954 } else if let Some(session) = self.ssh_client.as_ref() {
3955 let path_buf = PathBuf::from(query);
3956 let request = proto::ListRemoteDirectory {
3957 dev_server_id: SSH_PROJECT_ID,
3958 path: path_buf.to_proto(),
3959 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
3960 };
3961
3962 let response = session.read(cx).proto_client().request(request);
3963 cx.background_spawn(async move {
3964 let proto::ListRemoteDirectoryResponse {
3965 entries,
3966 entry_info,
3967 } = response.await?;
3968 Ok(entries
3969 .into_iter()
3970 .zip(entry_info)
3971 .map(|(entry, info)| DirectoryItem {
3972 path: PathBuf::from(entry),
3973 is_dir: info.is_dir,
3974 })
3975 .collect())
3976 })
3977 } else {
3978 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3979 }
3980 }
3981
3982 pub fn create_worktree(
3983 &mut self,
3984 abs_path: impl AsRef<Path>,
3985 visible: bool,
3986 cx: &mut Context<Self>,
3987 ) -> Task<Result<Entity<Worktree>>> {
3988 self.worktree_store.update(cx, |worktree_store, cx| {
3989 worktree_store.create_worktree(abs_path, visible, cx)
3990 })
3991 }
3992
3993 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3994 self.worktree_store.update(cx, |worktree_store, cx| {
3995 worktree_store.remove_worktree(id_to_remove, cx);
3996 });
3997 }
3998
3999 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4000 self.worktree_store.update(cx, |worktree_store, cx| {
4001 worktree_store.add(worktree, cx);
4002 });
4003 }
4004
4005 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4006 let new_active_entry = entry.and_then(|project_path| {
4007 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4008 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4009 Some(entry.id)
4010 });
4011 if new_active_entry != self.active_entry {
4012 self.active_entry = new_active_entry;
4013 self.lsp_store.update(cx, |lsp_store, _| {
4014 lsp_store.set_active_entry(new_active_entry);
4015 });
4016 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4017 }
4018 }
4019
4020 pub fn language_servers_running_disk_based_diagnostics<'a>(
4021 &'a self,
4022 cx: &'a App,
4023 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4024 self.lsp_store
4025 .read(cx)
4026 .language_servers_running_disk_based_diagnostics()
4027 }
4028
4029 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4030 self.lsp_store
4031 .read(cx)
4032 .diagnostic_summary(include_ignored, cx)
4033 }
4034
4035 pub fn diagnostic_summaries<'a>(
4036 &'a self,
4037 include_ignored: bool,
4038 cx: &'a App,
4039 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4040 self.lsp_store
4041 .read(cx)
4042 .diagnostic_summaries(include_ignored, cx)
4043 }
4044
4045 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4046 self.active_entry
4047 }
4048
4049 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4050 self.worktree_store.read(cx).entry_for_path(path, cx)
4051 }
4052
4053 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4054 let worktree = self.worktree_for_entry(entry_id, cx)?;
4055 let worktree = worktree.read(cx);
4056 let worktree_id = worktree.id();
4057 let path = worktree.entry_for_id(entry_id)?.path.clone();
4058 Some(ProjectPath { worktree_id, path })
4059 }
4060
4061 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4062 self.worktree_for_id(project_path.worktree_id, cx)?
4063 .read(cx)
4064 .absolutize(&project_path.path)
4065 .ok()
4066 }
4067
4068 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4069 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4070 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4071 /// the first visible worktree that has an entry for that relative path.
4072 ///
4073 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4074 /// root name from paths.
4075 ///
4076 /// # Arguments
4077 ///
4078 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4079 /// relative path within a visible worktree.
4080 /// * `cx` - A reference to the `AppContext`.
4081 ///
4082 /// # Returns
4083 ///
4084 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4085 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4086 let path = path.as_ref();
4087 let worktree_store = self.worktree_store.read(cx);
4088
4089 for worktree in worktree_store.visible_worktrees(cx) {
4090 let worktree_root_name = worktree.read(cx).root_name();
4091 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4092 return Some(ProjectPath {
4093 worktree_id: worktree.read(cx).id(),
4094 path: relative_path.into(),
4095 });
4096 }
4097 }
4098
4099 for worktree in worktree_store.visible_worktrees(cx) {
4100 let worktree = worktree.read(cx);
4101 if let Some(entry) = worktree.entry_for_path(path) {
4102 return Some(ProjectPath {
4103 worktree_id: worktree.id(),
4104 path: entry.path.clone(),
4105 });
4106 }
4107 }
4108
4109 None
4110 }
4111
4112 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4113 self.find_worktree(abs_path, cx)
4114 .map(|(worktree, relative_path)| ProjectPath {
4115 worktree_id: worktree.read(cx).id(),
4116 path: relative_path.into(),
4117 })
4118 }
4119
4120 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4121 Some(
4122 self.worktree_for_id(project_path.worktree_id, cx)?
4123 .read(cx)
4124 .abs_path()
4125 .to_path_buf(),
4126 )
4127 }
4128
4129 pub fn blame_buffer(
4130 &self,
4131 buffer: &Entity<Buffer>,
4132 version: Option<clock::Global>,
4133 cx: &mut App,
4134 ) -> Task<Result<Option<Blame>>> {
4135 self.git_store.update(cx, |git_store, cx| {
4136 git_store.blame_buffer(buffer, version, cx)
4137 })
4138 }
4139
4140 pub fn get_permalink_to_line(
4141 &self,
4142 buffer: &Entity<Buffer>,
4143 selection: Range<u32>,
4144 cx: &mut App,
4145 ) -> Task<Result<url::Url>> {
4146 self.git_store.update(cx, |git_store, cx| {
4147 git_store.get_permalink_to_line(buffer, selection, cx)
4148 })
4149 }
4150
4151 // RPC message handlers
4152
4153 async fn handle_unshare_project(
4154 this: Entity<Self>,
4155 _: TypedEnvelope<proto::UnshareProject>,
4156 mut cx: AsyncApp,
4157 ) -> Result<()> {
4158 this.update(&mut cx, |this, cx| {
4159 if this.is_local() || this.is_via_ssh() {
4160 this.unshare(cx)?;
4161 } else {
4162 this.disconnected_from_host(cx);
4163 }
4164 Ok(())
4165 })?
4166 }
4167
4168 async fn handle_add_collaborator(
4169 this: Entity<Self>,
4170 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4171 mut cx: AsyncApp,
4172 ) -> Result<()> {
4173 let collaborator = envelope
4174 .payload
4175 .collaborator
4176 .take()
4177 .ok_or_else(|| anyhow!("empty collaborator"))?;
4178
4179 let collaborator = Collaborator::from_proto(collaborator)?;
4180 this.update(&mut cx, |this, cx| {
4181 this.buffer_store.update(cx, |buffer_store, _| {
4182 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4183 });
4184 this.breakpoint_store.read(cx).broadcast();
4185 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4186 this.collaborators
4187 .insert(collaborator.peer_id, collaborator);
4188 })?;
4189
4190 Ok(())
4191 }
4192
4193 async fn handle_update_project_collaborator(
4194 this: Entity<Self>,
4195 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4196 mut cx: AsyncApp,
4197 ) -> Result<()> {
4198 let old_peer_id = envelope
4199 .payload
4200 .old_peer_id
4201 .ok_or_else(|| anyhow!("missing old peer id"))?;
4202 let new_peer_id = envelope
4203 .payload
4204 .new_peer_id
4205 .ok_or_else(|| anyhow!("missing new peer id"))?;
4206 this.update(&mut cx, |this, cx| {
4207 let collaborator = this
4208 .collaborators
4209 .remove(&old_peer_id)
4210 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4211 let is_host = collaborator.is_host;
4212 this.collaborators.insert(new_peer_id, collaborator);
4213
4214 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4215 this.buffer_store.update(cx, |buffer_store, _| {
4216 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4217 });
4218
4219 if is_host {
4220 this.buffer_store
4221 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4222 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4223 .unwrap();
4224 cx.emit(Event::HostReshared);
4225 }
4226
4227 cx.emit(Event::CollaboratorUpdated {
4228 old_peer_id,
4229 new_peer_id,
4230 });
4231 Ok(())
4232 })?
4233 }
4234
4235 async fn handle_remove_collaborator(
4236 this: Entity<Self>,
4237 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4238 mut cx: AsyncApp,
4239 ) -> Result<()> {
4240 this.update(&mut cx, |this, cx| {
4241 let peer_id = envelope
4242 .payload
4243 .peer_id
4244 .ok_or_else(|| anyhow!("invalid peer id"))?;
4245 let replica_id = this
4246 .collaborators
4247 .remove(&peer_id)
4248 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4249 .replica_id;
4250 this.buffer_store.update(cx, |buffer_store, cx| {
4251 buffer_store.forget_shared_buffers_for(&peer_id);
4252 for buffer in buffer_store.buffers() {
4253 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4254 }
4255 });
4256 this.git_store.update(cx, |git_store, _| {
4257 git_store.forget_shared_diffs_for(&peer_id);
4258 });
4259
4260 cx.emit(Event::CollaboratorLeft(peer_id));
4261 Ok(())
4262 })?
4263 }
4264
4265 async fn handle_update_project(
4266 this: Entity<Self>,
4267 envelope: TypedEnvelope<proto::UpdateProject>,
4268 mut cx: AsyncApp,
4269 ) -> Result<()> {
4270 this.update(&mut cx, |this, cx| {
4271 // Don't handle messages that were sent before the response to us joining the project
4272 if envelope.message_id > this.join_project_response_message_id {
4273 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4274 }
4275 Ok(())
4276 })?
4277 }
4278
4279 async fn handle_toast(
4280 this: Entity<Self>,
4281 envelope: TypedEnvelope<proto::Toast>,
4282 mut cx: AsyncApp,
4283 ) -> Result<()> {
4284 this.update(&mut cx, |_, cx| {
4285 cx.emit(Event::Toast {
4286 notification_id: envelope.payload.notification_id.into(),
4287 message: envelope.payload.message,
4288 });
4289 Ok(())
4290 })?
4291 }
4292
4293 async fn handle_language_server_prompt_request(
4294 this: Entity<Self>,
4295 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4296 mut cx: AsyncApp,
4297 ) -> Result<proto::LanguageServerPromptResponse> {
4298 let (tx, mut rx) = smol::channel::bounded(1);
4299 let actions: Vec<_> = envelope
4300 .payload
4301 .actions
4302 .into_iter()
4303 .map(|action| MessageActionItem {
4304 title: action,
4305 properties: Default::default(),
4306 })
4307 .collect();
4308 this.update(&mut cx, |_, cx| {
4309 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4310 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4311 message: envelope.payload.message,
4312 actions: actions.clone(),
4313 lsp_name: envelope.payload.lsp_name,
4314 response_channel: tx,
4315 }));
4316
4317 anyhow::Ok(())
4318 })??;
4319
4320 // We drop `this` to avoid holding a reference in this future for too
4321 // long.
4322 // If we keep the reference, we might not drop the `Project` early
4323 // enough when closing a window and it will only get releases on the
4324 // next `flush_effects()` call.
4325 drop(this);
4326
4327 let mut rx = pin!(rx);
4328 let answer = rx.next().await;
4329
4330 Ok(LanguageServerPromptResponse {
4331 action_response: answer.and_then(|answer| {
4332 actions
4333 .iter()
4334 .position(|action| *action == answer)
4335 .map(|index| index as u64)
4336 }),
4337 })
4338 }
4339
4340 async fn handle_hide_toast(
4341 this: Entity<Self>,
4342 envelope: TypedEnvelope<proto::HideToast>,
4343 mut cx: AsyncApp,
4344 ) -> Result<()> {
4345 this.update(&mut cx, |_, cx| {
4346 cx.emit(Event::HideToast {
4347 notification_id: envelope.payload.notification_id.into(),
4348 });
4349 Ok(())
4350 })?
4351 }
4352
4353 // Collab sends UpdateWorktree protos as messages
4354 async fn handle_update_worktree(
4355 this: Entity<Self>,
4356 envelope: TypedEnvelope<proto::UpdateWorktree>,
4357 mut cx: AsyncApp,
4358 ) -> Result<()> {
4359 this.update(&mut cx, |this, cx| {
4360 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4361 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4362 worktree.update(cx, |worktree, _| {
4363 let worktree = worktree.as_remote_mut().unwrap();
4364 worktree.update_from_remote(envelope.payload);
4365 });
4366 }
4367 Ok(())
4368 })?
4369 }
4370
4371 async fn handle_update_buffer_from_ssh(
4372 this: Entity<Self>,
4373 envelope: TypedEnvelope<proto::UpdateBuffer>,
4374 cx: AsyncApp,
4375 ) -> Result<proto::Ack> {
4376 let buffer_store = this.read_with(&cx, |this, cx| {
4377 if let Some(remote_id) = this.remote_id() {
4378 let mut payload = envelope.payload.clone();
4379 payload.project_id = remote_id;
4380 cx.background_spawn(this.client.request(payload))
4381 .detach_and_log_err(cx);
4382 }
4383 this.buffer_store.clone()
4384 })?;
4385 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4386 }
4387
4388 async fn handle_update_buffer(
4389 this: Entity<Self>,
4390 envelope: TypedEnvelope<proto::UpdateBuffer>,
4391 cx: AsyncApp,
4392 ) -> Result<proto::Ack> {
4393 let buffer_store = this.read_with(&cx, |this, cx| {
4394 if let Some(ssh) = &this.ssh_client {
4395 let mut payload = envelope.payload.clone();
4396 payload.project_id = SSH_PROJECT_ID;
4397 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4398 .detach_and_log_err(cx);
4399 }
4400 this.buffer_store.clone()
4401 })?;
4402 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4403 }
4404
4405 fn retain_remotely_created_models(
4406 &mut self,
4407 cx: &mut Context<Self>,
4408 ) -> RemotelyCreatedModelGuard {
4409 {
4410 let mut remotely_create_models = self.remotely_created_models.lock();
4411 if remotely_create_models.retain_count == 0 {
4412 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4413 remotely_create_models.worktrees =
4414 self.worktree_store.read(cx).worktrees().collect();
4415 }
4416 remotely_create_models.retain_count += 1;
4417 }
4418 RemotelyCreatedModelGuard {
4419 remote_models: Arc::downgrade(&self.remotely_created_models),
4420 }
4421 }
4422
4423 async fn handle_create_buffer_for_peer(
4424 this: Entity<Self>,
4425 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4426 mut cx: AsyncApp,
4427 ) -> Result<()> {
4428 this.update(&mut cx, |this, cx| {
4429 this.buffer_store.update(cx, |buffer_store, cx| {
4430 buffer_store.handle_create_buffer_for_peer(
4431 envelope,
4432 this.replica_id(),
4433 this.capability(),
4434 cx,
4435 )
4436 })
4437 })?
4438 }
4439
4440 async fn handle_synchronize_buffers(
4441 this: Entity<Self>,
4442 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4443 mut cx: AsyncApp,
4444 ) -> Result<proto::SynchronizeBuffersResponse> {
4445 let response = this.update(&mut cx, |this, cx| {
4446 let client = this.client.clone();
4447 this.buffer_store.update(cx, |this, cx| {
4448 this.handle_synchronize_buffers(envelope, cx, client)
4449 })
4450 })??;
4451
4452 Ok(response)
4453 }
4454
4455 async fn handle_search_candidate_buffers(
4456 this: Entity<Self>,
4457 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4458 mut cx: AsyncApp,
4459 ) -> Result<proto::FindSearchCandidatesResponse> {
4460 let peer_id = envelope.original_sender_id()?;
4461 let message = envelope.payload;
4462 let query = SearchQuery::from_proto(
4463 message
4464 .query
4465 .ok_or_else(|| anyhow!("missing query field"))?,
4466 )?;
4467 let results = this.update(&mut cx, |this, cx| {
4468 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4469 })?;
4470
4471 let mut response = proto::FindSearchCandidatesResponse {
4472 buffer_ids: Vec::new(),
4473 };
4474
4475 while let Ok(buffer) = results.recv().await {
4476 this.update(&mut cx, |this, cx| {
4477 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4478 response.buffer_ids.push(buffer_id.to_proto());
4479 })?;
4480 }
4481
4482 Ok(response)
4483 }
4484
4485 async fn handle_open_buffer_by_id(
4486 this: Entity<Self>,
4487 envelope: TypedEnvelope<proto::OpenBufferById>,
4488 mut cx: AsyncApp,
4489 ) -> Result<proto::OpenBufferResponse> {
4490 let peer_id = envelope.original_sender_id()?;
4491 let buffer_id = BufferId::new(envelope.payload.id)?;
4492 let buffer = this
4493 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4494 .await?;
4495 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4496 }
4497
4498 async fn handle_open_buffer_by_path(
4499 this: Entity<Self>,
4500 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4501 mut cx: AsyncApp,
4502 ) -> Result<proto::OpenBufferResponse> {
4503 let peer_id = envelope.original_sender_id()?;
4504 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4505 let open_buffer = this.update(&mut cx, |this, cx| {
4506 this.open_buffer(
4507 ProjectPath {
4508 worktree_id,
4509 path: Arc::<Path>::from_proto(envelope.payload.path),
4510 },
4511 cx,
4512 )
4513 })?;
4514
4515 let buffer = open_buffer.await?;
4516 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4517 }
4518
4519 async fn handle_open_new_buffer(
4520 this: Entity<Self>,
4521 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4522 mut cx: AsyncApp,
4523 ) -> Result<proto::OpenBufferResponse> {
4524 let buffer = this
4525 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4526 .await?;
4527 let peer_id = envelope.original_sender_id()?;
4528
4529 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4530 }
4531
4532 fn respond_to_open_buffer_request(
4533 this: Entity<Self>,
4534 buffer: Entity<Buffer>,
4535 peer_id: proto::PeerId,
4536 cx: &mut AsyncApp,
4537 ) -> Result<proto::OpenBufferResponse> {
4538 this.update(cx, |this, cx| {
4539 let is_private = buffer
4540 .read(cx)
4541 .file()
4542 .map(|f| f.is_private())
4543 .unwrap_or_default();
4544 if is_private {
4545 Err(anyhow!(ErrorCode::UnsharedItem))
4546 } else {
4547 Ok(proto::OpenBufferResponse {
4548 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4549 })
4550 }
4551 })?
4552 }
4553
4554 fn create_buffer_for_peer(
4555 &mut self,
4556 buffer: &Entity<Buffer>,
4557 peer_id: proto::PeerId,
4558 cx: &mut App,
4559 ) -> BufferId {
4560 self.buffer_store
4561 .update(cx, |buffer_store, cx| {
4562 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4563 })
4564 .detach_and_log_err(cx);
4565 buffer.read(cx).remote_id()
4566 }
4567
4568 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4569 let project_id = match self.client_state {
4570 ProjectClientState::Remote {
4571 sharing_has_stopped,
4572 remote_id,
4573 ..
4574 } => {
4575 if sharing_has_stopped {
4576 return Task::ready(Err(anyhow!(
4577 "can't synchronize remote buffers on a readonly project"
4578 )));
4579 } else {
4580 remote_id
4581 }
4582 }
4583 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4584 return Task::ready(Err(anyhow!(
4585 "can't synchronize remote buffers on a local project"
4586 )));
4587 }
4588 };
4589
4590 let client = self.client.clone();
4591 cx.spawn(async move |this, cx| {
4592 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4593 this.buffer_store.read(cx).buffer_version_info(cx)
4594 })?;
4595 let response = client
4596 .request(proto::SynchronizeBuffers {
4597 project_id,
4598 buffers,
4599 })
4600 .await?;
4601
4602 let send_updates_for_buffers = this.update(cx, |this, cx| {
4603 response
4604 .buffers
4605 .into_iter()
4606 .map(|buffer| {
4607 let client = client.clone();
4608 let buffer_id = match BufferId::new(buffer.id) {
4609 Ok(id) => id,
4610 Err(e) => {
4611 return Task::ready(Err(e));
4612 }
4613 };
4614 let remote_version = language::proto::deserialize_version(&buffer.version);
4615 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4616 let operations =
4617 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4618 cx.background_spawn(async move {
4619 let operations = operations.await;
4620 for chunk in split_operations(operations) {
4621 client
4622 .request(proto::UpdateBuffer {
4623 project_id,
4624 buffer_id: buffer_id.into(),
4625 operations: chunk,
4626 })
4627 .await?;
4628 }
4629 anyhow::Ok(())
4630 })
4631 } else {
4632 Task::ready(Ok(()))
4633 }
4634 })
4635 .collect::<Vec<_>>()
4636 })?;
4637
4638 // Any incomplete buffers have open requests waiting. Request that the host sends
4639 // creates these buffers for us again to unblock any waiting futures.
4640 for id in incomplete_buffer_ids {
4641 cx.background_spawn(client.request(proto::OpenBufferById {
4642 project_id,
4643 id: id.into(),
4644 }))
4645 .detach();
4646 }
4647
4648 futures::future::join_all(send_updates_for_buffers)
4649 .await
4650 .into_iter()
4651 .collect()
4652 })
4653 }
4654
4655 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4656 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4657 }
4658
4659 /// Iterator of all open buffers that have unsaved changes
4660 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4661 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4662 let buf = buf.read(cx);
4663 if buf.is_dirty() {
4664 buf.project_path(cx)
4665 } else {
4666 None
4667 }
4668 })
4669 }
4670
4671 fn set_worktrees_from_proto(
4672 &mut self,
4673 worktrees: Vec<proto::WorktreeMetadata>,
4674 cx: &mut Context<Project>,
4675 ) -> Result<()> {
4676 self.worktree_store.update(cx, |worktree_store, cx| {
4677 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4678 })
4679 }
4680
4681 fn set_collaborators_from_proto(
4682 &mut self,
4683 messages: Vec<proto::Collaborator>,
4684 cx: &mut Context<Self>,
4685 ) -> Result<()> {
4686 let mut collaborators = HashMap::default();
4687 for message in messages {
4688 let collaborator = Collaborator::from_proto(message)?;
4689 collaborators.insert(collaborator.peer_id, collaborator);
4690 }
4691 for old_peer_id in self.collaborators.keys() {
4692 if !collaborators.contains_key(old_peer_id) {
4693 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4694 }
4695 }
4696 self.collaborators = collaborators;
4697 Ok(())
4698 }
4699
4700 pub fn supplementary_language_servers<'a>(
4701 &'a self,
4702 cx: &'a App,
4703 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4704 self.lsp_store.read(cx).supplementary_language_servers()
4705 }
4706
4707 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4708 self.lsp_store.update(cx, |this, cx| {
4709 this.language_servers_for_local_buffer(buffer, cx)
4710 .any(
4711 |(_, server)| match server.capabilities().inlay_hint_provider {
4712 Some(lsp::OneOf::Left(enabled)) => enabled,
4713 Some(lsp::OneOf::Right(_)) => true,
4714 None => false,
4715 },
4716 )
4717 })
4718 }
4719
4720 pub fn language_server_id_for_name(
4721 &self,
4722 buffer: &Buffer,
4723 name: &str,
4724 cx: &mut App,
4725 ) -> Task<Option<LanguageServerId>> {
4726 if self.is_local() {
4727 Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4728 lsp_store
4729 .language_servers_for_local_buffer(buffer, cx)
4730 .find_map(|(adapter, server)| {
4731 if adapter.name.0 == name {
4732 Some(server.server_id())
4733 } else {
4734 None
4735 }
4736 })
4737 }))
4738 } else if let Some(project_id) = self.remote_id() {
4739 let request = self.client.request(proto::LanguageServerIdForName {
4740 project_id,
4741 buffer_id: buffer.remote_id().to_proto(),
4742 name: name.to_string(),
4743 });
4744 cx.background_spawn(async move {
4745 let response = request.await.log_err()?;
4746 response.server_id.map(LanguageServerId::from_proto)
4747 })
4748 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4749 let request =
4750 ssh_client
4751 .read(cx)
4752 .proto_client()
4753 .request(proto::LanguageServerIdForName {
4754 project_id: SSH_PROJECT_ID,
4755 buffer_id: buffer.remote_id().to_proto(),
4756 name: name.to_string(),
4757 });
4758 cx.background_spawn(async move {
4759 let response = request.await.log_err()?;
4760 response.server_id.map(LanguageServerId::from_proto)
4761 })
4762 } else {
4763 Task::ready(None)
4764 }
4765 }
4766
4767 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4768 self.lsp_store.update(cx, |this, cx| {
4769 this.language_servers_for_local_buffer(buffer, cx)
4770 .next()
4771 .is_some()
4772 })
4773 }
4774
4775 pub fn git_init(
4776 &self,
4777 path: Arc<Path>,
4778 fallback_branch_name: String,
4779 cx: &App,
4780 ) -> Task<Result<()>> {
4781 self.git_store
4782 .read(cx)
4783 .git_init(path, fallback_branch_name, cx)
4784 }
4785
4786 pub fn buffer_store(&self) -> &Entity<BufferStore> {
4787 &self.buffer_store
4788 }
4789
4790 pub fn git_store(&self) -> &Entity<GitStore> {
4791 &self.git_store
4792 }
4793
4794 #[cfg(test)]
4795 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4796 cx.spawn(async move |this, cx| {
4797 let scans_complete = this
4798 .read_with(cx, |this, cx| {
4799 this.worktrees(cx)
4800 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4801 .collect::<Vec<_>>()
4802 })
4803 .unwrap();
4804 join_all(scans_complete).await;
4805 let barriers = this
4806 .update(cx, |this, cx| {
4807 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4808 repos
4809 .into_iter()
4810 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4811 .collect::<Vec<_>>()
4812 })
4813 .unwrap();
4814 join_all(barriers).await;
4815 })
4816 }
4817
4818 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4819 self.git_store.read(cx).active_repository()
4820 }
4821
4822 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4823 self.git_store.read(cx).repositories()
4824 }
4825
4826 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4827 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4828 }
4829}
4830
4831pub struct PathMatchCandidateSet {
4832 pub snapshot: Snapshot,
4833 pub include_ignored: bool,
4834 pub include_root_name: bool,
4835 pub candidates: Candidates,
4836}
4837
4838pub enum Candidates {
4839 /// Only consider directories.
4840 Directories,
4841 /// Only consider files.
4842 Files,
4843 /// Consider directories and files.
4844 Entries,
4845}
4846
4847impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4848 type Candidates = PathMatchCandidateSetIter<'a>;
4849
4850 fn id(&self) -> usize {
4851 self.snapshot.id().to_usize()
4852 }
4853
4854 fn len(&self) -> usize {
4855 match self.candidates {
4856 Candidates::Files => {
4857 if self.include_ignored {
4858 self.snapshot.file_count()
4859 } else {
4860 self.snapshot.visible_file_count()
4861 }
4862 }
4863
4864 Candidates::Directories => {
4865 if self.include_ignored {
4866 self.snapshot.dir_count()
4867 } else {
4868 self.snapshot.visible_dir_count()
4869 }
4870 }
4871
4872 Candidates::Entries => {
4873 if self.include_ignored {
4874 self.snapshot.entry_count()
4875 } else {
4876 self.snapshot.visible_entry_count()
4877 }
4878 }
4879 }
4880 }
4881
4882 fn prefix(&self) -> Arc<str> {
4883 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4884 self.snapshot.root_name().into()
4885 } else if self.include_root_name {
4886 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4887 } else {
4888 Arc::default()
4889 }
4890 }
4891
4892 fn candidates(&'a self, start: usize) -> Self::Candidates {
4893 PathMatchCandidateSetIter {
4894 traversal: match self.candidates {
4895 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4896 Candidates::Files => self.snapshot.files(self.include_ignored, start),
4897 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4898 },
4899 }
4900 }
4901}
4902
4903pub struct PathMatchCandidateSetIter<'a> {
4904 traversal: Traversal<'a>,
4905}
4906
4907impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4908 type Item = fuzzy::PathMatchCandidate<'a>;
4909
4910 fn next(&mut self) -> Option<Self::Item> {
4911 self.traversal
4912 .next()
4913 .map(|entry| fuzzy::PathMatchCandidate {
4914 is_dir: entry.kind.is_dir(),
4915 path: &entry.path,
4916 char_bag: entry.char_bag,
4917 })
4918 }
4919}
4920
4921impl EventEmitter<Event> for Project {}
4922
4923impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4924 fn from(val: &'a ProjectPath) -> Self {
4925 SettingsLocation {
4926 worktree_id: val.worktree_id,
4927 path: val.path.as_ref(),
4928 }
4929 }
4930}
4931
4932impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4933 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4934 Self {
4935 worktree_id,
4936 path: path.as_ref().into(),
4937 }
4938 }
4939}
4940
4941pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4942 let mut path_components = path.components();
4943 let mut base_components = base.components();
4944 let mut components: Vec<Component> = Vec::new();
4945 loop {
4946 match (path_components.next(), base_components.next()) {
4947 (None, None) => break,
4948 (Some(a), None) => {
4949 components.push(a);
4950 components.extend(path_components.by_ref());
4951 break;
4952 }
4953 (None, _) => components.push(Component::ParentDir),
4954 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4955 (Some(a), Some(Component::CurDir)) => components.push(a),
4956 (Some(a), Some(_)) => {
4957 components.push(Component::ParentDir);
4958 for _ in base_components {
4959 components.push(Component::ParentDir);
4960 }
4961 components.push(a);
4962 components.extend(path_components.by_ref());
4963 break;
4964 }
4965 }
4966 }
4967 components.iter().map(|c| c.as_os_str()).collect()
4968}
4969
4970fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4971 let mut result = base.to_path_buf();
4972 for component in path.components() {
4973 match component {
4974 Component::ParentDir => {
4975 result.pop();
4976 }
4977 Component::CurDir => (),
4978 _ => result.push(component),
4979 }
4980 }
4981 result
4982}
4983
4984/// ResolvedPath is a path that has been resolved to either a ProjectPath
4985/// or an AbsPath and that *exists*.
4986#[derive(Debug, Clone)]
4987pub enum ResolvedPath {
4988 ProjectPath {
4989 project_path: ProjectPath,
4990 is_dir: bool,
4991 },
4992 AbsPath {
4993 path: PathBuf,
4994 is_dir: bool,
4995 },
4996}
4997
4998impl ResolvedPath {
4999 pub fn abs_path(&self) -> Option<&Path> {
5000 match self {
5001 Self::AbsPath { path, .. } => Some(path.as_path()),
5002 _ => None,
5003 }
5004 }
5005
5006 pub fn project_path(&self) -> Option<&ProjectPath> {
5007 match self {
5008 Self::ProjectPath { project_path, .. } => Some(&project_path),
5009 _ => None,
5010 }
5011 }
5012
5013 pub fn is_file(&self) -> bool {
5014 !self.is_dir()
5015 }
5016
5017 pub fn is_dir(&self) -> bool {
5018 match self {
5019 Self::ProjectPath { is_dir, .. } => *is_dir,
5020 Self::AbsPath { is_dir, .. } => *is_dir,
5021 }
5022 }
5023}
5024
5025impl ProjectItem for Buffer {
5026 fn try_open(
5027 project: &Entity<Project>,
5028 path: &ProjectPath,
5029 cx: &mut App,
5030 ) -> Option<Task<Result<Entity<Self>>>> {
5031 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5032 }
5033
5034 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5035 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5036 }
5037
5038 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5039 self.file().map(|file| ProjectPath {
5040 worktree_id: file.worktree_id(cx),
5041 path: file.path().clone(),
5042 })
5043 }
5044
5045 fn is_dirty(&self) -> bool {
5046 self.is_dirty()
5047 }
5048}
5049
5050impl Completion {
5051 /// A key that can be used to sort completions when displaying
5052 /// them to the user.
5053 pub fn sort_key(&self) -> (usize, &str) {
5054 const DEFAULT_KIND_KEY: usize = 2;
5055 let kind_key = self
5056 .source
5057 // `lsp::CompletionListItemDefaults` has no `kind` field
5058 .lsp_completion(false)
5059 .and_then(|lsp_completion| lsp_completion.kind)
5060 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5061 lsp::CompletionItemKind::KEYWORD => Some(0),
5062 lsp::CompletionItemKind::VARIABLE => Some(1),
5063 _ => None,
5064 })
5065 .unwrap_or(DEFAULT_KIND_KEY);
5066 (kind_key, &self.label.text[self.label.filter_range.clone()])
5067 }
5068
5069 /// Whether this completion is a snippet.
5070 pub fn is_snippet(&self) -> bool {
5071 self.source
5072 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5073 .lsp_completion(true)
5074 .map_or(false, |lsp_completion| {
5075 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5076 })
5077 }
5078
5079 /// Returns the corresponding color for this completion.
5080 ///
5081 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5082 pub fn color(&self) -> Option<Hsla> {
5083 // `lsp::CompletionListItemDefaults` has no `kind` field
5084 let lsp_completion = self.source.lsp_completion(false)?;
5085 if lsp_completion.kind? == CompletionItemKind::COLOR {
5086 return color_extractor::extract_color(&lsp_completion);
5087 }
5088 None
5089 }
5090}
5091
5092pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5093 entries.sort_by(|entry_a, entry_b| {
5094 let entry_a = entry_a.as_ref();
5095 let entry_b = entry_b.as_ref();
5096 compare_paths(
5097 (&entry_a.path, entry_a.is_file()),
5098 (&entry_b.path, entry_b.is_file()),
5099 )
5100 });
5101}
5102
5103fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5104 match level {
5105 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5106 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5107 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5108 }
5109}