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