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