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