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