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