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