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