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