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