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