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