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