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