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