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